Skip to content

feat(pi): bring the pi provider up to pi 1.6 - #2292

Merged
YishenTu merged 34 commits into
mainfrom
feat/pi-1-6-provider-update
Nov 25, 2026
Merged

YishenTu merged 34 commits into
mainfrom
feat/pi-1-6-provider-update

Conversation

@YishenTu

@YishenTu YishenTu commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Why

Claudian's pi provider was written against early pi 1.x, and pi is now at 1.6.0. Checked against pi 1.6.0's sources, docs and changelog, several behaviors were broken or missing:

  • prompts that time out while pi is still in preflight
  • dialogs left open after pi has already timed them out
  • history that misses sessions stored under a sessionDir set in pi's settings
  • effort levels pi clamps silently
  • retries and automatic compaction with no explanation

Two history bugs also live in code shared with Ardi, which fixed them in YishenTu/ardi#29: JSONL input finishing twice, and tool results from abandoned branches attaching to the active branch.

What Changed

History and forks

  • JSONL input finishes once when a stream both ends and closes.
  • A reply that ended on a tool batch with no later assistant message (a terminating batch) is checkpointed at its last tool result, so forks and replays keep those results.
  • Tool results from abandoned branches stay out of history.
  • Pending forks saved before this change follow the saved assistant entry's own unbranched chain of results, stepping over extension state, session metadata and usage (custom, session_info, label, usage, settings changes) recorded between them. Live turns, replay and these forks place a reply's checkpoint by one rule.
  • Edit alternatives stay grouped across system patches and extension state entries.
  • History finds native sessions under sessionDir from pi's project and user settings, searching pi's effective store first, as pi does. A pending fork's first send finds its source the same way.
  • Session files pi reports relative to a relative sessionDir resolve against pi's launch directory, and tree navigation (editing a prompt, switching branches) matches them. With no override, pi's default store is searched before an older vault-local store.
  • A reply that failed or was stopped replays its tool calls as failed, and starts no Peeps child. One helper decides this for live turns and replay.
  • Conversations without a stored model recover a virtual model the way pi's getBranchSelection does.

Runtime

  • The managed install marker accepts a UTF-8 BOM.
  • prompt waits for pi's reply instead of timing out after 30 s. Pi answers only after preflight, which includes extension commands and pre-run compaction.
  • Extension dialogs close when pi's own timeout expires.
  • Shutdown closes stdin before signalling the process.

Models and effort

  • Models pi marks reasoning: false offer only Off.
  • Provider ids containing / (for example URL-derived llama.cpp providers) can be selected.
  • An explicit effort is also checked against the model returned by set_model. The error suggests refreshing the catalog with Discover.
  • A discovered model's API name is never used as its provider. Models with no provider are dropped.

Turn reporting

  • Retry notices show the attempt, the maximum attempts and the error. Automatic compaction shows a notice. All notices go through t() in every locale.
  • Output pi reports before admitting a prompt, such as preflight compaction, waits for admission, and a preflight extension dialog opens without acknowledging the prompt, so a rejected prompt is never acknowledged as delivered.
  • A background run that pi settles with aborted: true completes as interrupted.
  • The context meter updates after a manual /compact, using pi's estimatedTokensAfter.
  • Tool calls are reported at toolcall_start, so the activity preview and session progress name a write while its arguments are still streaming. A streamed call in a reply that failed or was stopped settles as failed. A Peeps card built from that call follows the call's later arguments and result. A name that arrives after the call's id (OpenAI-compatible streams) replaces the placeholder.

Cleanup

  • Removed the unused launch model and thinkingLevel parameters.
  • Removed the session's unreachable extension-dialog branch. The test kernel now hands dialogs to the real PiExtensionUIBridge, which takes only the transport's send.

Why This Approach

Each change follows pi 1.6.0's own behavior and keeps the work inside the pi provider:

  • branch selection mirrors getBranchSelection
  • sessionDir is resolved in pi's order
  • turns settle from agent_settled

Shared chat code is unchanged.

Alternatives not taken:

  • Calling clear_queue before stopping a background run. Pi's steer and follow-up queue also holds extension messages such as Peeps results, which this would discard.
  • Drawing tool cards while their arguments stream. The shared chat holds every provider's tool cards until a result or more text arrives. Changing that is a cross-provider decision outside this PR.
  • Silently clamping a stale effort as pi does. Claudian already treats an explicit effort as authoritative. A stale catalog now fails with a recovery hint instead of running at another level.

Validation

  • npm run typecheck && npm run lint && npm run test && npm run build && npm run check:performance passes: 11,032 tests. The performance check passes with its existing warning (cold module evaluation 55.2 ms; warning indicator 50 ms).
  • Each of the first 21 commits typechecks and passes the pi tests on its own.
  • Every bug fix and behavior change has a regression test that failed before its fix. The tests added during review were also checked against a deliberately reintroduced fault.
  • Protocol claims were checked against the installed pi 1.6.0 sources and docs.
  • On real pi 1.6.0, without any model call:
    • get_available_models and set_model both return pi's full model records, which carry the thinking-level metadata.
    • A scan of about 3,200 tool-calling assistant entries in local pi sessions found extension custom entries between an assistant entry and its results. The legacy fork walk steps over them.
    • Pi 1.6.0's RPC toolcall_start carries id and toolName, and an OpenAI-compatible stream can leave toolName empty there.
    • With sessionDir: ./sessions, pi reports a relative session file, and the embedded tree extension rejected the absolute path before the fix and accepts it after (an extension command, no model call).
  • Three external review rounds (one by GPT-6.2-Astra) covered the whole branch. Their findings were addressed, apart from the follow-ups listed below.
  • Not run:
    • npm run smoke:obsidian
    • a manual session in Obsidian
    • native Windows or WSL runs
  • No screenshots were taken of the new notice text.

Impact and Follow-ups

  • If the cached model catalog still offers an effort level the model no longer supports, sends with that model fail with the stale-catalog hint until the user clicks Discover.
  • Discovered models without a provider no longer appear.
  • The new notice translations were not reviewed by native speakers.
  • Existing behavior for every provider: pressing Stop drops tool cards the chat hasn't drawn yet, and the call stays running in that reply until the conversation is reopened. A streamed or executing pi call is affected the same way.
  • Known gaps left for follow-up:
    • If an extension starts a background run before the first prompt and pi aborts it, the run can show as completed.
    • A virtual router missing from Claudian's saved models is still recovered as the physical model, as before.
    • On native Windows, a WSL-style sessionDir (/mnt/d/...) is not mapped to its drive.

Checklist

  • This pull request addresses one focused problem, and I have explained why this change is necessary. It brings one provider up to date with pi 1.6. The maintainer chose a single PR over a stacked series.
  • I linked the relevant issue, or explained why no issue is needed. There is no issue: these changes come from the maintainer's audit against pi 1.6.0 and from refactor: the bridge's pi adapters follow pi's docs, with explicit state ardi#29.
  • I added or updated tests for behavior changes, or explained why tests are not applicable.
  • I ran the relevant typecheck, lint, test, and build commands.
  • I updated user-facing documentation when needed. None was needed.

Streams emit `end` and then `close`, and subscribeJSONLLines finished on
both, so PiRPCTransport and JSONRPCTransport received `onEnd` twice. The
first `end` or `close` now stops reading, flushes the last line and calls
`onEnd`; the `error` listener stays until unsubscribe so a late stream
error stays handled.

Same fix as YishenTu/ardi#29.
Pi can end a run right after a tool batch, when every tool in it
returns `terminate: true` or the turn's finish hook ends the run. The
reply's fork checkpoint was still the assistant entry that made the
calls, so forking or replaying from it left those calls unanswered once
history stops pulling in results that follow the leaf. Replay, requested
turns and background turns now checkpoint such a reply at its last tool
result, which is pi's own leaf; a later assistant entry still moves it on.

Prepares the branch-path fix ported from YishenTu/ardi#29.
In pi's tree sessions (v2+), tool results are ordinary id/parentId
entries, so the leaf-to-root walk already contains the ones that belong.
The graph path also kept a result whose toolCallId matched an active call
or whose parent was on the path, so after branching from an assistant
turn the abandoned branch's result attached to the active call. Entries
with an id are now kept only when that id is on the active path. Id-less
entries and linear (v1) sessions keep their existing rules.

The other callers of resolvePiActivePath/resolvePiEntryPath read user
and assistant ids, the last id, models or ancestry, and none of them
relies on off-path results. Forks at a reply that ended on tool results
keep them, because the previous commit checkpoints such a reply at its
last result. A pending fork saved before that commit still names the
assistant entry that made the calls, so forking and showing it follow
that entry's unbranched chain of results for those calls, stepping over
the custom and settings entries recorded between them; when the chain
branches, the checkpoint stays at the last result before it.

Same fix as YishenTu/ardi#29.
Windows PowerShell 5.1 adds a BOM when it rewrites managed-install.json,
which pi itself accepts since 1.4.0. Claudian's JSON.parse rejected it,
so a pi.dev managed launcher failed to resolve to its Node.js entry.
Pi 1.x reports some non-reasoning models with a thinkingLevelMap, such
as openai/gpt-5-chat-latest with `{off: null}`. Claudian treated any map
as reasoning support and offered Minimal to High, which pi then clamped
to off without an error. A model with `reasoning: false` now gets only
Off, matching pi-ai's getSupportedThinkingLevels; already discovered
models change on the next model refresh.
Pi sends the `prompt` response only after preflight: extension commands,
input handlers and the compaction that runs before a run starts. The
30 s control deadline turned a slow extension command, a dialog the
user answered late, or a long pre-prompt compaction into "Request
timeout: prompt" and killed the process mid-work. Like manual
compaction, the prompt now waits with no deadline; Stop still aborts
the native run and fences the process.
…tate

Pi 1.x persists prompt-section and tool changes as `system` messages
before the next prompt, and extensions persist state as `custom`
entries. Prompt grouping stopped at both, so an edited prompt written
after either lost its branch switcher. Both are now skipped like model
changes. A custom entry's `data` is no longer read as a message, which
also kept extension state whose data held a `role` from replaying as a
chat message. Sessions with entries such as `peeps/run` between prompts
now show their edit alternatives.
A select, confirm or input request with `timeout` is resolved by pi with
its default when the time runs out, and pi drops any later response.
Claudian ignored the field, so the modal stayed open and the user's
later choice did nothing. The bridge now closes the dialog unanswered
at the deadline, through the same abort path as a cancelled run.
Pi's RPC docs ask clients to close stdin and give pi time to finish:
since 1.5.1 its shutdown waits for credential refresh saves and for
aborted tool results to be recorded. Claudian sent SIGTERM at once and
SIGKILL 3 s later, which cut that work short and, on Windows, killed
the process outright. Pi now gets stdin EOF and 5 s to exit before the
existing SIGTERM/SIGKILL escalation; an idle pi exits within
milliseconds. The shared fake pi process now exits on stdin EOF like
the real one.
Pi reads `sessionDir` from the user settings (<agent dir>/settings.json)
and from the working directory's .pi/settings.json, which it reads even
before project trust. Claudian only followed the environment variables,
so sessions stored under a configured sessionDir were outside every
trusted root: history showed nothing and fork and resume lookups failed.

Native lookups now also trust the sessionDir from both settings files,
reading project settings only when the vault path is known; the existing
roots, including the default home store, are unchanged. WSL lookups,
which trust only the store pi would use, follow pi's order: the
session-directory variable, then project over user settings, then the
agent store. A WSL settings sessionDir therefore stops trust in the
default store, as PI_CODING_AGENT_SESSION_DIR already does.
Pi 1.5 accepts provider ids containing `/`, such as URL-derived
llama.cpp providers. Claudian built set_model by splitting its encoded
id at the first slash, so such a model was sent with the wrong provider
and pi rejected it. A discovered model now sends pi's own provider and
id; the split remains for models without discovery metadata.
Pi clamps set_thinking_level silently, and Claudian validated an
explicit effort only against cached discovery metadata, which pi
releases can change. A level the cache still lists could run at another
level without an error. Pi 1.x answers set_model with the full model, so
an explicit level is now also checked against that model's thinking
levels before set_thinking_level, using the same rule as the cached
check. Because every send repeats a level the stale cache offers, the
error adds the catalog's "click Discover to refresh it" hint. Pi
versions that answer without the model keep the cached check only.
Pi reports the attempt, the attempt limit and the error that caused an
automatic retry, but Claudian showed a generic "Pi is retrying the turn."
and then "Pi retry finished." even when the final attempt failed, next to
that failure's own error. The retry notice now names the attempt and
reason, a failed final retry is reported only by its terminal error, and
threshold or overflow compaction, which can take minutes, shows a notice
when it starts. Manual compaction stays silent; pi versions without the
retry fields keep the generic notice.
Pi 1.1 added `aborted` to agent_settled so clients can tell a cancelled
run from a finished one. Claudian decided only from its own Stop flag,
so a background run an extension aborted completed as finished while
history replays it as interrupted. An `aborted: true` settlement now
completes the background turn as interrupted; pi versions without the
flag behave as before.
Pi reports no context tokens right after compaction, until a fresh
response provides usage. After /compact no response follows, so
Claudian skipped the usage update and the meter kept its
pre-compaction value. The compact result's estimatedTokensAfter now
fills in while pi reports none; fresh native usage still wins, and
automatic compaction is followed by a response that reports it.
A virtual model routes each request to a physical model, and responses
name the physical one. Pi restores the virtual selection from its
model_change as long as that virtual model is registered, and skips
responses left on the virtual model by failed routing. Claudian's model
recovery took the last response's physical model instead. Recovery now
follows pi's rule, using the discovered models' `pi-virtual` API to
recognise registered virtual models. It applies only to conversations
without a stored model.
Pi streams each tool call inside message_update (toolcall_start with the
id and name, then toolcall_end with the complete arguments) before it
runs the call. Claudian read only text and thinking deltas and reported
a tool call only at tool_execution_start, so during a large write or
edit the turn's activity preview still showed the earlier step. The call
is now reported at toolcall_start, which updates the activity preview
and session progress, and gets its arguments at toolcall_end; the chat
still holds the card itself until its buffer flushes, as for every
provider. Execution updates the call only when pi runs it with different
arguments. A call streamed in a reply that ended in an error or abort
never runs, so it fails instead of spinning after a retry: with the
error of an errored reply, and without abort text for a stopped one. A
Peeps spawn's subagent card, built when the call starts streaming, now
follows the call's later arguments and result unless Peeps reported the
child itself.
Execution selects the model and thinking level over RPC, and the model
discovery and command metadata probes only query metadata, so
buildPiLaunchSpec's `model` and `thinkingLevel` parameters had no
caller outside tests. Their branch also dropped `--thinking off`, which
would have fallen back to pi's default level had anything used it.
PiRPCSessionKernel hands every extension_ui_request to its dialog
bridge, which cancels any dialog the session refuses or cannot render,
and never forwards the request as an event. The session's own
cancellation branch for that event type could not run. Tests reached it
only because the fake kernel forwarded dialogs as events; the fake now
hands them to the real dialog bridge, as the real kernel does. The
bridge now takes only the transport's send, which is all it uses, so the
fake passes a plain sender.
Model discovery fell back to a record's `api` when it had no provider,
so a model would be listed under its wire protocol (for example
openai-responses) and set_model would ask pi for a provider that does
not exist. Pi models always carry a provider; a record without one is
now skipped.
Pi never runs the tool calls of a reply that ended in an error or an
abort, and it keeps such a reply in raw history when it retries. History
replayed those calls as running cards, so a reloaded conversation kept a
spinner that the live turn had settled as failed. The calls now replay
as failed: an error reply attaches its error message, and a stopped
reply attaches no abort text, matching how history shows a stopped turn.
A Peeps spawn in such a reply no longer replays a running child.
Live streaming, history replay and the Peeps replay each decided which
replies pi never runs tool calls for (stopReason error or aborted), and
the first two also decided what result such calls show. A new stop
reason would have had to be added in three places. getPiUnrunToolResult
now owns both rules and all three use it. The normalizer's tool phases
also shrink to streamed and resolved, the only distinction any reader
makes.
Live turns, history replay and legacy pending forks each placed a
reply's fork checkpoint: at its assistant entry, or at the last result
of a tool batch that ended the run. Live turns took any trailing tool
result without checking that it answered the reply's calls, and only
the legacy fork walk stepped over extension state between results.
followPiReplyCheckpoint now owns the rule (move over the batch's own
results, pass recorded state, stop at anything else); live turns and
legacy forks walk with it, and replay applies the same step to each
reply.
Pi answers `prompt` only after preflight, which can compact the context
first. The automatic-compaction notice reached the turn before that
answer and acknowledged the prompt as delivered, so a prompt pi then
rejected still showed as started, and an inter-session message could be
marked delivered. Output pi reports before admitting the prompt now
waits and appears once it is admitted; a rejected prompt shows only its
error. The requested run's admission is one state that carries the held
output.
A tool can name the session (pi.setSessionName) or label an entry while
it runs, which records a session_info or label entry between its call
and its result. The checkpoint walk for legacy pending forks stopped
there, so the fork left the completed call without its result. Both
entry types now pass like other recorded state; branches and results of
other calls still end the walk.
OpenAI-compatible streams can start a tool call with its id before its
name, so pi reports toolcall_start with an empty toolName and the call
showed as the placeholder `tool`. A later report of the same call with
its name was dropped when its arguments were empty, as for `ls`, so the
placeholder stayed. A report that names the call differently now
updates it, whatever its arguments.
Pi keeps a relative `sessionDir` from its settings relative, so with
`sessionDir: ./sessions` get_state reports `sessions/<file>.jsonl`.
A WSL launch could not map that path and failed the turn, and a local
launch stored it as given, so later reads resolved it against
Obsidian's working directory. The session and parent files pi reports
now resolve against the directory pi was launched in, through the one
parser of get_state's session identity.
Native history searched the `sessionDir` roots from pi's settings after
the default and agent stores. When a session was copied into a newly
configured store and its old copy remained, a lookup by ID returned the
stale copy. The roots now follow pi's own order (the session-directory
variable, then project and user `sessionDir`, then the agent store),
and the older stores follow for sessions that remain there.
A pending fork saved with only its source session ID showed its history
through the settings-aware lookup, which includes the `sessionDir` from
pi's project and user settings. Its first send on a native launch used
a lookup that skips those settings, so it failed with "Pi fork source
session not found". Both now use the same lookup; a saved source path is
still used as saved.
With a relative `sessionDir`, pi names its session file relative to its
working directory while Claudian now holds the absolute path, so the
tree extension rejected every edit or branch switch with "Pi session
changed before tree navigation". The extension now compares both paths
through pi's real working directory, and reports the file as Claudian
names it when they match, which also covers a vault reached through a
symlink. Reproduced against pi 1.6.0 with `sessionDir: ./sessions`.
YishenTu and others added 4 commits November 25, 2026 16:12
Pi records model usage outside the conversation, such as cache warming,
as `usage` entries, and one can land between a tool call and its result.
The live checkpoint and the legacy fork walk stopped there, so a fork
left the completed call running without its result. Usage entries now
pass like other recorded state.
Without a session-directory override, pi's store is the home default
store, but ID lookup searched the vault's `.pi/agent/sessions` first.
With the same session ID in both, it returned the older vault copy.
The agent store pi uses now comes right after any configured
`sessionDir`, and the vault-local store is searched last.
Pi runs extension input hooks before its final checks, such as
authentication, and a hook can open a dialog. Opening that dialog
acknowledged the prompt as delivered, so a prompt pi then rejected
still showed as started and an inter-session message could be marked
delivered. Extension dialogs are standalone modals, so they now open
without acknowledging the prompt; pi's admission does that.
…order tests

A chunk reaches the requested stream only after admission flushed it, so the
extra acknowledgement there did nothing. parsePiSessionModel's sole caller
always passes its virtual-model check, so the parameter is required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@YishenTu
YishenTu merged commit 2fe7556 into main Nov 25, 2026
19 checks passed
@YishenTu
YishenTu deleted the feat/pi-1-6-provider-update branch November 25, 2026 08:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant