Skip to content

refactor: the bridge's pi adapters follow pi's docs, with explicit state - #29

Merged
YishenTu merged 6 commits into
mainfrom
refactor/pi-adapter-cleanup
Nov 25, 2026
Merged

YishenTu merged 6 commits into
mainfrom
refactor/pi-adapter-cleanup

Conversation

@YishenTu

Copy link
Copy Markdown
Owner

The bridge's pi adapters (src/bridge/runtime/, normalization/, history/) started as copies of Claudian's pi provider and kept its fallbacks for other formats and its scattered state. They are Ardi's own now. This reads pi's documented formats directly and makes each piece of state one explicit stage. It is separate from #28 and changes none of the same files.

Fixes:

  • History shows pi's active branch as its leaf-to-root path over id/parentId, as session-format.md defines it. The no-id fallback, the branch-graph guess and the tool-call-id rescue are gone. A tool result left on an abandoned branch no longer attaches to the active branch's call.
  • pi's JSONL reader finishes once. Streams emit both end and close, so it used to flush and report the end twice. Its error listener stays until it's unsubscribed.
  • A disposed RPC transport hands on no more lines from the read it was disposed in.

Simplifications:

  • Event normalization tracks each tool call as one stage: streaming its output, diverged once a snapshot stopped extending it, or done. This replaces three collections, one of which was never pruned. The state clears when the run settles, so a call is still reported once per run, and a missing result still falls back to the last snapshot.
  • PiRPCTransport takes its event handler when it's created and reads from then on. start(), the lazy start inside request(), the handler set and the cleanup closures are gone; request()'s signature is unchanged. The output's error and close listeners still outlive disposal, onAnswer still runs in order with events, and a timeout of 0 still means none.
  • src/bridge/AGENTS.md now says these files follow pi's docs (rpc.md, json.md, session-format.md) and needn't match Claudian.

Left as is, on purpose:

  • LineBuffer, which handles multi-megabyte lines (images); replacing it would need a timing check first.
  • spawnable.ts, PiProcess.ts and the helpers in piToolNormalization.ts, where changes would only be cosmetic.
  • Session files from before pi's session trees (v1) aren't read. Ardi resumes only sessions its own pi created, and that pi writes v3: session trees arrived in pi 0.31.0, and Ardi saves a session path only after get_commands, which arrived in 0.50.2.

Each fix has a test that failed first. New tests also cover a tool call id reused in a later run. Lint, tests (308, also randomized) and build pass. Reviewed by GPT-6.2-Astra over two rounds; the last found nothing blocking. Not yet tried with the loaded extension.

@YishenTu
YishenTu merged commit 2ca13a1 into main Nov 25, 2026
2 checks passed
@YishenTu
YishenTu deleted the refactor/pi-adapter-cleanup branch November 25, 2026 04:17
YishenTu added a commit to YishenTu/claudian that referenced this pull request Nov 25, 2026
* fix(rpc): finish JSONL input once when a stream ends and closes

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.

* fix(pi): fork a reply that ended on tool results from its last result

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.

* fix(pi): keep abandoned-branch tool results out of history

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.

* fix(pi): accept a managed install marker with a UTF-8 BOM

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.

* fix(pi): offer only Off to models pi marks non-reasoning

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.

* fix(pi): wait for the prompt reply instead of timing out after 30 s

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.

* fix(pi): keep edit alternatives across system patches and extension state

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.

* fix(pi): close extension dialogs when their native timeout expires

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.

* fix(pi): shut pi down by closing stdin before signalling it

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.

* fix(pi): find native history under the sessionDir from pi settings

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.

* fix(pi): select models whose provider id contains a slash

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.

* fix(pi): check an explicit effort against the model pi selects

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.

* fix(pi): show retry progress and automatic compaction

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.

* fix(pi): mark a background run pi reports as aborted interrupted

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.

* fix(pi): update the context meter after a manual compaction

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.

* fix(pi): recover a virtual model selection like pi does

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.

* feat(pi): report tool calls while pi streams them

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.

* refactor(pi): drop unused model and thinking launch parameters

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.

* refactor(pi): drop the session's unreachable extension dialog handler

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.

* fix(pi): never use a model's API name as its provider

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.

* fix(pi): replay a failed reply's tool calls as failed

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.

* refactor(pi): give the unrun-reply tool result one owner

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.

* refactor(pi): derive every reply checkpoint from one rule

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.

* fix(pi): hold preflight output until pi admits the prompt

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.

* fix(pi): follow fork checkpoints across session metadata

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.

* fix(pi): keep a streamed tool's name when it arrives late

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.

* fix(pi): resolve session files pi reports relative to its directory

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.

* fix(pi): look up a session ID in pi's configured store first

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.

* fix(pi): find a pending fork's source where its history was found

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.

* fix(pi): match a relative session file in tree navigation

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`.

* fix(pi): follow reply checkpoints across usage entries

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.

* fix(pi): search pi's default store before a vault-local copy

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.

* fix(pi): keep a preflight dialog from acknowledging the prompt

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.

* refactor(pi): drop superseded prompt acknowledgement and merge store-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>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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