Plan: the phone sees and sets the model, thinking, stats and compaction (#154, part 3)

Relates to: #154 (part 4 stays open there). Branch: feat/remote-rpc-state. Status: Done (2026-09-18) — shipped as pi-remote 0.6.0; part 4 stays on #154

TL;DR

Part 2 (plan Plan: the phone sends pi’s control commands (#154, part 2 + get_state)) made pi-remote the virtual RPC host for control: prompt, steer, follow_up, abort, get_commands, get_state. pivot shipped the PWA half (pivot#91) and opened the next two asks, both blocked on this package: model and thinking-level pickers (pivot#94: set_model, set_thinking_level, the two get_available_*) and the GADHS mode line beside the state (pivot#95). Those are #154’s part 3, together with get_session_stats, compact, and the compaction events. This plan lands them the way part 2 did: pi’s command and response records verbatim, pi’s own wording for refusals, and where the ExtensionAPI has no direct call, the same computation pi makes from the same inputs - never a guess.

Decisions

pi’s shapes, verbatim (docs/rpc.md at 0.85.1). Six commands, two events, one fire-and-forget request. Response envelope, field names and error texts are pi’s.

Reproduce, do not approximate. Two commands have no ExtensionAPI call: get_available_thinking_levels is getSupportedThinkingLevels(model) from @earendil-works/pi-ai (the function pi itself calls), or every level when no model is set; get_session_stats is pi’s AgentSession.getSessionStats fold - user/assistant/toolResult counts, tool calls, usage totals across assistant messages, tool results with usage, and compaction/branch-summary entries, over sessionManager.getEntries() - plus ctx.getContextUsage(). Both are pinned to pi’s algorithm by test.

Model lists follow #154’s rule. ctx.scopedModels when non-empty, else ctx.modelRegistry.getAvailable(); set_model finds its target in that same list, so a model the box cannot see is “Model not found: <provider>/<id>” (pi’s text), and one without credentials is “No API key for <provider>/<id>” (pi’s text) - pi.setModel returning false is the only way an extension learns that.

compact is answered with pi’s result, from the callback. ctx.compact({ customInstructions, onComplete, onError }) returns void and reports through callbacks; the response waits for one of them and carries CompactionResult verbatim (onError → success:false with the message). A compaction already running is pi’s own refusal through onError.

Compaction events translate from the session hooks. pi’s RPC emits compaction_start { reason } and compaction_end { reason, result?, aborted, errorMessage?, willRetry }; an extension sees session_before_compact, session_compact and session_compact_failed with the same fields. Translated one to one. auto_retry_start / auto_retry_end reach no extension and are not forwarded - said in the docs, not invented.

The mode line is pi’s setStatus. pi-modes publishes gadhs:status { …, text } on the bus (#155) and writes the same text to ctx.ui.setStatus("gadhs-mode", …). To a device it goes as pi’s own fire-and-forget record, { type: "extension_ui_request", id, method: "setStatus", statusKey: "gadhs-mode", statusText } on the session frame - the shape pi’s RPC would have emitted for that very call, no wire change. Broadcast on every status event; the latest is kept and sent to a device right after hello, as the state record is, so a late joiner has the line. The device already shows fire-and-forget requests (protocol.adoc § Asks).

Refusals stay honest. Anything a command needs before session_start is “no session”, as in part 2.

Design

Parse (mirror.ts)

PhoneCommand gains, each with id?: get_available_models, set_model { provider, modelId } (both strings, else unknown), get_available_thinking_levels, set_thinking_level { level } (one of pi’s seven, else unknown), get_session_stats, compact { customInstructions? } (a string when present).

Dispatch (commands.ts)

CommandHost.pi widens to setModel and setThinkingLevel. New cases:

  • get_available_models → { models: availableModels(ctx) }.

  • set_model → find in availableModels(ctx) by provider and id; not found → pi’s text; await pi.setModel(model) false → pi’s text; else data: model.

  • get_available_thinking_levels → { levels } as above.

  • set_thinking_level → pi.setThinkingLevel(level) → success:true (pi clamps to the model).

  • get_session_stats → sessionStats(ctx): the fold, sessionFile, sessionId, tokens { input, output, cacheRead, cacheWrite, total }, cost, and contextUsage when ctx.getContextUsage() returns one.

  • compact → a promise over `ctx.compact(…​)’s callbacks.

sessionStats and availableModels are small pure helpers in commands.ts; the fold is the one place with arithmetic and gets a property-style test over generated entry lists (totals equal the sum of the parts; counts equal the roles).

Forwarding (index.ts, peer.ts)

  • registerHooks: session_before_compact → broadcast compaction_start; session_compact → compaction_end with result from the CompactionEntry (summary, firstKeptEntryId, tokensBefore, usage?, details?), aborted: false, willRetry; session_compact_failed → compaction_end with aborted, errorMessage?, willRetry, no result. The existing compaction flag keeps its job.

  • pi.events.on("gadhs:status") → statusOf(data) parses text (a string, else ignored); kept in state.status; broadcast as the setStatus record with a fresh randomUUID() id.

  • Peer.greet() follows hello and state with the setStatus record when a status is known (session frame, this peer only).

  • MIRRORED_EVENTS is unchanged; the new records are built, not mirrored.

Package

@earendil-works/pi-ai becomes a peer of pi-remote (as it is of pi-modes) for getSupportedThinkingLevels; pi-remote 0.6.0.

Tests

  • commands.test.ts: each command’s response; set_model not-found and no-credentials texts and the data on success; scoped models win over the registry; thinking levels from a reasoning model, a non-reasoning model (["off"]), and no model; set_thinking_level passes the level through; get_session_stats against a hand-built entry list with the expected counts and totals, contextUsage present and absent; compact success and error through the callbacks.

  • units.test.ts: the parse variants and their malformed forms.

  • extension.test.ts (real wire): the three session hooks produce compaction_start / compaction_end records on the device with pi’s fields; a gadhs:status event becomes one setStatus record with the key and text, a reconnecting device gets it after hello and state, a malformed payload is ignored; set_model through the wire changes the fake ctx’s model.

  • link.test.ts: greet() order - hello, state, setStatus - and nothing for the two when unknown.

Coverage bars unchanged.

Docs

  • remote.adoc § What the phone can send: the six commands, the two events, the mode line, and what is not forwarded (auto_retry_*).

  • CHANGELOG.adoc: @gadhs/pi-remote 0.6.0, Added.

  • Notes on #154 (parts landed, part 4 remaining), pivot#94 and pivot#95 (unblocked, with the record shapes).

Scope

In

The six commands, the two events, the setStatus forward with its after-hello replay, the pi-ai peer, tests and docs above.

Out

  • Part 4 (get_messages, get_entries - pi-pivot#61): its own plan when pivot signals.

  • auto_retry_start / auto_retry_end: not visible to an extension.

  • Forwarding other extensions' notify / setWidget / setTitle: an extension cannot observe another’s UI calls; only the bus-published mode line is reachable.

  • set_steering_mode / set_follow_up_mode / get_available_* for queue modes: AgentSession-only, no bus, refused as unknown (dropped and logged, per the session-frame rule).

Errata

  • Erratum (2026-09-18): the dedupe on status text named under Risks as a follow-up landed in the change itself (a repeat sends nothing).

  • Erratum (2026-09-18): the stats test is a hand-built session with totals summed by hand, not a property-style test; the fold has one branch per entry kind and the hand-built case covers each.

  • Erratum (2026-09-18): compact.customInstructions is bounded like a prompt (MAX_PROMPT_CHARS), refused in words both ways; the plan did not say so.

Risks

  • getSessionStats drift. pi may change its fold; the test pins ours to the documented shape, and the code comment names the source method so a future diff is a one-place change.

  • compact never calling back. pi’s contract is one of the two callbacks; if neither fires the phone’s request has no response, as pi’s own RPC would hang. No timeout is added here: a false success:false during a long compaction would be worse than silence, and the compaction_end event arrives regardless.

  • Status replay on a busy box. One setStatus per status event; pi-modes recomputes on every ask verdict, so a busy turn produces a stream of identical-looking records. pi’s own RPC would too; a device coalesces by key. If it proves noisy, dedupe on text in a follow-up.

Edit this page · latest