Repository navigation
Mid conversation system messages - #9548
Conversation
|
This should be capability-gated and default to false. Please add a This comment is AI-generated by |
|
I tested the transcript behavior against the live APIs. There are a few concrete AnthropicThe generated flags currently cover:
I tested all four. Each accepted and followed a mid-conversation system message, Anthropic's required message order is important.
The canonical order must be: and for tool loops: So the buffering in
Deferred tools and cachingLate Anthropic tools must be declared at request level with
Anthropic also inserts hidden system scaffolding when any deferred tool exists. We need a stable deferred dummy from the first request whenever there are initial active tools, otherwise introducing the first deferred tool later invalidates most of the cached prefix. I tested the intended shape with cache breakpoints on the last initial active tool, top-level system prompt, and conversation content: With the dummy present from request one: Without it, adding the first deferred tool on request two: The dummy itself cannot carry Change the Anthropic path as follows:
The current code declares every tool through Docs: https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages OpenAI Responses and CodexI tested every model currently marked for these mechanisms. Direct OpenAI, both
All eight accepted the transcript-anchored mechanism and called the loaded tool. Codex:
The important behavior is that
Change all three Responses request builders (
The current Kimi Chat CompletionsSystem text worked on all tested Moonshot models:
Dynamic system-message tools worked on:
They failed with Kimi tool messages are additions-only and must be retained in subsequent requests. A tool-bearing system message cannot also carry Change the Kimi path as follows:
Docs: https://platform.kimi.ai/docs/guide/use-dynamic-tool-loading Capability reporting
Add an explicit Required pi-ai testsPlease add/update focused payload tests for:
Unsupported providers should continue deriving current request-level tools by replaying transcript additions/removals. The target design calls for user-role This comment is AI-generated by |
7f45441 to
9a9591e
Compare
|
Example session transcript showing the system messages. Captured from a real run of Entries are one JSON object per line in the file; pretty-printed here. The only edits: long prompt section text is clipped ( Points of interest:
{
"type": "session",
"id": "loadout-demo",
"version": 3,
"cwd": "/Users/mitsuhiko/Development/pi-mono"
}
{
"type": "model_change",
"id": "ce3c555f",
"parentId": null,
"provider": "openai-codex",
"modelId": "gpt-5.6-terra"
}
{
"type": "thinking_level_change",
"id": "13f2de78",
"parentId": "ce3c555f",
"thinkingLevel": "low"
}
{
"type": "message",
"id": "4074d10e",
"parentId": "13f2de78",
"message": {
"role": "system",
"sections": {
"preamble": "You are an expert coding assistant operating inside pi, a coding agent …",
"tools": "<tools>\n- read: Read file contents\n- bash: Execute bash commands (ls, grep, find, etc.)\n …",
"rules": "<rules>\n- Use bash for file operations like ls, rg, find …",
"docs": "<docs>\nPi documentation (read only when the user asks about pi itself, its SDK, extensions …",
"cwd": "<cwd>\n/Users/mitsuhiko/Development/pi-mono\n</cwd>"
},
"toolsAdded": [
{
"name": "read",
"description": "Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.",
"parameters": {
"type": "object",
"required": [
"path"
],
"properties": {
"path": {
"type": "string",
"description": "Path to the file to read (relative or absolute)"
},
"offset": {
"type": "number",
"description": "Line number to start reading from (1-indexed)"
},
"limit": {
"type": "number",
"description": "Maximum number of lines to read"
}
}
},
"constrainedSampling": {
"type": "json_schema",
"strict": "prefer"
}
},
{
"name": "bash",
"description": "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.",
"parameters": {
"type": "object",
"required": [
"command"
],
"properties": {
"command": {
"type": "string",
"description": "Shell command to execute"
},
"timeout": {
"type": "number",
"description": "Timeout in seconds (optional, no default timeout)"
}
}
},
"constrainedSampling": {
"type": "json_schema",
"strict": "prefer"
}
}
],
"timestamp": 1789421512079
}
}
{
"type": "message",
"id": "34d47490",
"parentId": "4074d10e",
"message": {
"role": "user",
"content": [
{
"type": "text",
"text": "What time is it in Vienna? Use a tool."
}
],
"timestamp": 1789421512079
}
}
{
"type": "message",
"id": "1dd944de",
"parentId": "34d47490",
"message": {
"role": "assistant",
"content": [
{
"type": "toolCall",
"id": "call_AxIloA…|fc_03c8d2…",
"name": "bash",
"arguments": {
"command": "TZ=Europe/Vienna date '+%A, %B %-d, %Y — %H:%M:%S %Z'",
"timeout": 10
}
}
],
"model": "openai-codex/gpt-5.6-terra",
"timestamp": 1789421512094
}
}
{
"type": "message",
"id": "4ba47352",
"parentId": "1dd944de",
"message": {
"role": "toolResult",
"toolCallId": "call_AxIloA…|fc_03c8d2…",
"toolName": "bash",
"content": [
{
"type": "text",
"text": "Monday, September 14, 2026 — 23:31:59 CEST"
}
],
"timestamp": 1789421519006
}
}
{
"type": "message",
"id": "40c3a48c",
"parentId": "4ba47352",
"message": {
"role": "assistant",
"content": [
{
"type": "text",
"text": "It’s 23:31 CEST in Vienna (Monday, September 14, 2026)."
}
],
"model": "openai-codex/gpt-5.6-terra",
"timestamp": 1789421519008
}
}
{
"type": "message",
"id": "4fef1fa4",
"parentId": "40c3a48c",
"message": {
"role": "system",
"sections": {
"tools": "<tools>\n- read: Read file contents\n- get_time: Look up the current local time for a city\n …",
"rules": "<rules>\n- Use read to examine files instead of cat or sed.\n- Be concise in your responses …",
"addendum": "<addendum>\nTalk like a pirate.\n</addendum>"
},
"toolsAdded": [
{
"name": "get_time",
"description": "Get the current local time for a city.",
"parameters": {
"type": "object",
"required": [
"city"
],
"properties": {
"city": {
"type": "string",
"description": "City name"
}
}
}
}
],
"toolsRemoved": [
{
"name": "bash"
}
],
"timestamp": 1789421525596
}
}
{
"type": "message",
"id": "010bab5d",
"parentId": "4fef1fa4",
"message": {
"role": "user",
"content": [
{
"type": "text",
"text": "And now?"
}
],
"timestamp": 1789421525596
}
}
{
"type": "message",
"id": "44ebe458",
"parentId": "010bab5d",
"message": {
"role": "assistant",
"content": [
{
"type": "toolCall",
"id": "call_A0U3os…|fc_03c8d2…",
"name": "get_time",
"arguments": {
"city": "Vienna"
}
}
],
"model": "openai-codex/gpt-5.6-terra",
"timestamp": 1789421525613
}
}
{
"type": "message",
"id": "63aa5558",
"parentId": "44ebe458",
"message": {
"role": "toolResult",
"toolCallId": "call_A0U3os…|fc_03c8d2…",
"toolName": "get_time",
"content": [
{
"type": "text",
"text": "The time in Vienna is 22:41."
}
],
"timestamp": 1789421527568
}
}
{
"type": "message",
"id": "2c811842",
"parentId": "63aa5558",
"message": {
"role": "assistant",
"content": [
{
"type": "text",
"text": "Arrr, it’s 22:41 in Vienna."
}
],
"model": "openai-codex/gpt-5.6-terra",
"timestamp": 1789421527571
}
}This comment is AI-generated. |
|
AI generated (analysis by Claude, reviewed by the author) Custom providers that hand-roll the payload lose the prompt and toolsThe agent loop now streams Options
|
|
Had a close read of normalize-context and the compaction interaction — the leading/patch model is a nice fit for the skills hot-swap case. Two things I couldn't fully resolve from the diff:
Otherwise the AgentState.systemPrompt removal reads clean, and the sdk.md migration coverage looks solid. |
|
There are still three blocking issues in Before changing this implementation, the referenced Anthropic documentation MUST be read and understood in full, especially its placement, deferred-tool, and cache-prefix rules. Targeted live API probes must also be done for each payload shape below; unit tests that only assert locally generated JSON are not sufficient to establish provider compatibility. 1. System messages create fake tool results
becomes: Providers may reject the duplicate result or consume the synthetic failure. Anthropic explicitly requires the system message to come after the A system message must not close pending tool accounting. The Anthropic adapter already moves it to a valid boundary after the real result. 2. Anthropic late-tool declarations are invalidThe adapter sends every declared tool as active at the top level, then emits Anthropic specifies that every top-level tool is active immediately unless it has The implementation also needs safe fallback for:
Those cases cannot safely use additive native transitions. Send the final current tool inventory at request level and omit inline changes. 3. Anthropic cache scaffolding is introduced too lateEven after late tools are marked deferred, request one may contain no deferred tools. Adding the first deferred tool on request two changes Anthropic's hidden prompt structure and invalidates much of the cached prefix. Anthropic documents that A stable deferred dummy therefore needs to be present from request one whenever there is at least one active initial tool. This specific dummy strategy follows from the live cache probe rather than being prescribed directly by the documentation. The dummy must not have The probes need to cover at minimum:
This comment is AI-generated by |
e478b30 to
9b8f143
Compare
Normalize top-level prompts and tools into transcript state while preserving the existing shorthand. Lower later system messages per provider and persist them in coding-agent sessions.
Remove addedToolNames propagation and provider-specific hidden tool loading. Dynamic tool changes now send the complete current tool list and system prompt on the next request.
…ranscript Make the transcript the single source of truth for the system prompt and tools. SystemMessage gains opaque, ordered sections that later messages patch by name; replaying every system message yields the current prompt and tools. Providers that accept system messages mid-conversation (gated per model via supportsMidConvoSystemMessages) send them in place; all others fold them into the leading system message instead of lowering them to user reminders. The agent loop declares state.tools changes to the model before each request, and AgentState.systemPrompt becomes a read-only replay of the transcript. The coding agent emits section patches only and drops its parallel prompt state: TranscriptCapabilities, ModelContextState, system_prompt session entries, and the old-session migration checkpoint. Old sessions get a full patch on their first request. Also fixes setActiveTools() inside before_agent_start being undone by the stale options copy, keeps compaction from summarizing system entries, and uses the previous summary for split-turn compactions.
…prompt options The agent loop now treats tool fields on a pending system message as intent and rewrites them to the delta between the committed transcript and the executable tool set, so a pending addition of a non-executable tool no longer survives replay next to its own removal. The coding agent stores the refreshed prompt options after a mid-run tool change, so session.systemPrompt and ctx.getSystemPrompt() match what the provider receives for the rest of the run.
OpenRouter rejects every request carrying a configuration_update system message for anthropic/claude-opus-5 while accepting it for Fable 5.1. Gate the model instead of the provider.
Flag OpenCode, OpenCode Go, GitHub Copilot, DeepSeek V4 Pro, and OpenRouter's OpenAI models after live verification of each transport: - OpenCode/Copilot Responses: in-place developer messages and additional_tools pass through; tool search is unverified there. - OpenCode/Copilot Claude: system text passes through; tool_addition/tool_removal blocks are rejected, so only supportsMidConvoSystemMessages is set. - Kimi K3: OpenCode forwards the tool-bearing system message; Copilot drops it, so Copilot gets text only. - DeepSeek V4 Pro and openai/* on OpenRouter accept system text in place. Accept dotted Opus 4.8 ids in the Anthropic predicate for Copilot, and document why the Anthropic converter defers later system messages until the next assistant message.
…eam entry points Public entry points (Models, compat stream functions, ModelRuntime) keep accepting Context and call normalizeContext once. Providers, API modules, StreamFn, streamProxy, faux, and extension custom providers receive a TranscriptContext; the prompt and tools live in the transcript's system messages. Merge normalize-context.ts and transcript-state.ts into transcript.ts. The replay helpers take any message list, so the agent package no longer needs getTranscriptSystemMessage wrappers. Add createInitialSystemMessage and declarationsEqual as the single places that build the leading system message and compare tool declarations. Drop createUserTurnAppender, the resolveTranscriptTools closure, the faux prompt serialization special cases, and the renderSystemPromptSections wrapper; buildSystemPrompt renders through getSystemMessageText so the session prompt and the replayed transcript share one rendering rule.
…ool flow Anthropic native tool changes now keep the initial tools active, send every later declaration with defer_loading behind a stable deferred placeholder, and keep removed tools declared, so tool additions and removals no longer invalidate the prompt cache (measured: full miss before, full read after). The current tool list is sent instead when there is no initial tool or a tool was redefined under the same name. transformMessages no longer closes pending tool calls on a system message; it is held until the results are in, so it cannot produce a duplicate synthetic tool result.
24b9da1 to
4631761
Compare
…osed * origin/main: Mid conversation system messages (#9548) # Conflicts: # packages/coding-agent/src/core/extensions/runner.ts
This change makes system prompt text and tool changes part of the transcript rather than silently rewriting its starting conditions. This lets Pi record when instructions changed or tools became available, restore that state after resuming or navigating branches, and preserve cached prompt prefixes where the upstream supports it.
Upstream's mid-conversation system messages (earendil-works#9548) adopted as the backbone: system prompt and tool changes live in the transcript now. The fork's prefix monitor and prefix-replaying summarizers were ported onto it (sections derived from the transcript; SummarizationPrefix replays the transcript's own leading system message). The fork's per-toolResult tool_reference wire machinery is superseded by upstream's in-transcript declarations; the onWireRewrite seam and observer wiring stay. pi User-Agent stays purged in the rewritten adapters. Gates: npm run check exit 0; ./test.sh all workspaces green.
…窄到 Anthropic 本体) * fix(ai): send OpenCode session header Map sessionId to x-opencode-session across OpenCode and OpenCode Go provider adapters, including requests with cache retention disabled. Preserve explicit caller header overrides. Closes earendil-works#9326 * docs: extract interactive testing and release guidance into skills (earendil-works#9370) * fix: cap agent retry backoff Add a configurable 60-second default cap for assistant and summarization retry delays across coding-agent and the agent harness. Fixes earendil-works#8826 * fix(coding-agent): validate extension tool parameter schemas Reject malformed extension tools during registration instead of allowing them to break provider request serialization. Fixes earendil-works#9300 * docs: validate documentation navigation and reachability (earendil-works#9380) * feat: use docs manifest for documentation evals * feat: support nested documentation navigation * docs(coding-agent): validate documentation reachability * docs(coding-agent): remove catalog schema version * docs(agent): preserve pico2 spike design for review * docs(agent): add pico design drafts * docs(agent): resolve pico context and state ordering * docs(agent): persist pico entry projections * docs(agent): settle pico task lifecycle * docs(agent): make pico input attribution explicit * feat(coding-agent): support per-model compaction token budgets Closes earendil-works#8133 * fix(ai): send Codex Off reasoning effort closes earendil-works#9191 * fix(ai): preserve Fireworks thinking and native effort levels Enable unsigned thinking replay and metadata-driven adaptive effort for Fireworks Messages models, with verified fallbacks for incomplete catalog metadata. Remove redundant GLM 5.2 and Kimi K3 effort aliases and add regression tests. closes earendil-works#9323 * fix(ai): accept Fireworks models in adaptive thinking metadata test Update the catalog-wide assertion for metadata-driven Fireworks support while retaining the model-name restrictions for other providers. Add representative Fireworks models to the expected subset. * fix(ai): send OpenRouter session affinity headers by default Send x-session-id for OpenRouter Chat Completions and Anthropic Messages requests while preserving explicit opt-out and cache-disabled behavior. closes earendil-works#9102 * fix(ai): update DeepSeek Flash catalog Replace retired Flash aliases with the canonical deepseek-flash model and refresh DeepSeek pricing metadata. Closes earendil-works#9423 * fix(ai): remove retired GPT-5.4 Codex models Remove GPT-5.4 and GPT-5.4 mini from the OpenAI Codex catalog and update affected tests. Fixes earendil-works#9394 * fix(ai): enable GLM-5.2 reasoning on Mistral Use reasoning_effort instead of the ignored prompt_mode parameter. Fixes earendil-works#9375 * docs(agent): settle pico driver and storage contracts * feat(ai): enable Fireworks Messages deferred tool loading * chore: approve contributors from issue earendil-works#9323 * docs(agent): pico handoff for outstanding decisions * docs(agent): tagged-union task state and derived orphaned variant * docs(agent): simplify input results and unify queued input * docs(agent): note foreground dependencies on background work * docs(agent): scope out permissions, migration and the wire schema * docs(agent): runtime schema bundle as a work item * docs(agent): turn tasks gate model-visible appends * docs(agent): guide notes for appending entries * docs(agent): status lives in task state * fix(ai): update stale DeepSeek Flash test model IDs * docs(agent): define pico system sections and mutable registries * docs(agent): require typed status payloads for pico task writes * Revert "fix(ai): update stale DeepSeek Flash test model IDs" This reverts commit e841300. * feat(coding-agent): add customization documentation evals (earendil-works#9491) * fix(coding-agent): isolate extension eval documentation treatment * feat(coding-agent): add custom provider documentation eval * feat(coding-agent): add customization documentation evals * feat(coding-agent): add repeatable eval reports * fix(ci): Fix a broken test * docs(agent): add approved pico implementation handoff * feat(agent): add pico compile-time foundation * docs(agent): define pico state tasks and tool boundaries * docs(agent): simplify pico scheduling and core task model * feat(agent): refine pico core task capabilities * feat(agent): add pico memory storage foundation * docs(agent): define pico v2 kernel contract * feat(agent): align pico foundation with v2 contract * docs(agent): correct pico v2 foundation contracts * docs(agent): add pico3 view/events, plugins and hardening handoff Canonical pico3 material under packages/agent/docs/pico/v3/: - hardening-handoff.md: V3 hardening handoff with supersession table - view-and-events.md: single view document, ops by path, named events, commit-by-commit mapping, Codex mapping, watchers and late joiners - plugins.md: harness registration surface, durable primitives, extension points with examples, reload contract, Chord facet layer - harness-v3.zip: baseline sketch backup (sha256 1c69c5c5...fbe7) * docs(agent): pico3 review decisions: revision, visibility, memos, waiting, reload - Envelope carries a contiguous per-watch revision; storage Seq stays internal; Chord bridge publishes off the line through a bounded ordered adapter - Namespaces reach the view only through a declared view projection; memos and slot working state are never in the view - memoOnce uses property presence; memos are coordination/evidence, not exactly-once; idempotency key before the effect - Hooks bound to their namespace token; BeforeToolApi.waiting(ctx) is async; memo keys are (task, namespace, name) - Reload: quiescent hold/reload/release, otherwise suspend/reopen; no handler withdrawal machinery in v1; Namespace.unregister - pi.* entry names reject except pi.notice; config reset is an operation; generation failures run the final boundary and start successors * docs(agent): pico3: forbid AsyncLocalStorage; nested-line detection via Chord context key * fix(ai): identify Responses error providers closes earendil-works#9298 * Revert "fix(ci): Fix a broken test" This reverts commit 71dca87. * feat(agent): add hardened pico3 kernel * chore: approve contributors from issue earendil-works#9440 * docs(ai): document Codex WebSocket cleanup * docs(agent): replace obsolete Pico prototypes with Pico5 design * fix(ai): price Bedrock one-hour cache writes closes earendil-works#9457 * docs(agent): finalize Pico5 architecture and presentation * feat(coding-agent): isolate documentation lift evals (earendil-works#9635) * docs(agent): specify Pico5 harness API * fix(coding-agent): export extension event hook types (earendil-works#9642) * fix(coding-agent): export extension event hook types Fixes earendil-works#9511 * fix(ai): stabilize Bedrock cache cost regression * fix(ai): honor Bedrock profile pricing in cache test * fix(coding-agent): reject unverified local clipboard writes fixes earendil-works#9618 * fix(coding-agent): surface clipboard backend failures closes earendil-works#9618 * feat(coding-agent): allow configuring Anthropic fallback models Allow models.json overrides to replace or disable server-side fallback metadata. Fixes earendil-works#9294 * fix(coding-agent): avoid transcript scans for exact session IDs (earendil-works#9601) Fixes earendil-works#9440 * fix(ai): send Baseten session affinity headers Enable session affinity for cataloged Baseten models so related requests reach the same replica and benefit from prompt caching. Closes earendil-works#9629 * Mid conversation system messages (earendil-works#9548) This change makes system prompt text and tool changes part of the transcript rather than silently rewriting its starting conditions. This lets Pi record when instructions changed or tools became available, restore that state after resuming or navigating branches, and preserve cached prompt prefixes where the upstream supports it. * fix(coding-agent): update eval prompt section markers * fix(ai): derive Google thinking levels from models.dev Extract Google catalog processing and apply models.dev reasoning effort metadata directly for Google, Vertex, and OpenCode models. Keep the provider-specific Gemma 4 toggle mapping. * feat(ai): refresh generated image model catalog * fix(coding-agent): toggle summary entries on click * fix(coding-agent): fail closed on user bash hook errors (earendil-works#9662) * fix(coding-agent): fail closed on user bash hook errors Prevent failed execution-routing hooks from falling back to the local shell. Fixes earendil-works#9068 * fix(coding-agent): validate user bash hook results * docs(coding-agent): clarify user bash result semantics * docs(coding-agent): streamline user bash semantics * fix(coding-agent): strengthen user bash regressions * docs(coding-agent): clarify user bash breaking change * fix(coding-agent): replace the system prompt when a handler forces it Add SystemMessage.replace: replaying a system message with the flag discards the accumulated prompt content, sections, and tools before applying it, and providers collapse the transcript into one leading system message whenever a later message replaces it. A forced prompt from before_agent_start is opaque, so it is persisted as a replace message holding the text in content with no sections (the agent loop fills in the full tool set). Leaving force mode persists another replace message with the structured sections. Previously the forced prompt became a preamble section patch, so models with native mid-conversation system messages kept the original prompt as their leading system prompt and received the forced one as a later update. * fix(ai): avoid unsupported Gemini thinking levels Use each model's supported levels when disabling or selecting Gemini thinking. Fixes earendil-works#9455 * fix(ai): preserve thinking replay through renamed Anthropic models Keep the requested model ID on assistant messages and record the provider-reported model separately, while retaining fallback pricing. Fixes earendil-works#9188 * fix(ai): retry Cloudflare 520 responses closes earendil-works#9627 * chore: approve contributors from issue earendil-works#9645 * docs(agent): refine Pico5 plugin state API * fix(ai): retry Azure peak-load capacity errors Closes earendil-works#9669 * feat(coding-agent): add TUI context footer eval (earendil-works#9705) * docs(agent): finalize Pico5 specification set * fix(coding-agent): validate eval prompts from transcripts (earendil-works#9706) Preserve partial-run usage and session artifacts when post-run validation fails. * feat(coding-agent): add experimental micro agent * feat(chord): replace delta tracker with operation log * fix(coding-agent): shorten Anthropic thinking drop notices * fix(ai): preserve Vercel AI Gateway unsigned thinking Enable empty-signature thinking replay for all generated Vercel AI Gateway models. closes earendil-works#9676 * fix(coding-agent): fail signal-terminated shell commands Map signal termination to conventional nonzero exit codes and reject null exit codes from custom shell operations while preserving partial output. fixes earendil-works#9577 * docs(coding-agent): update changelog * fix(coding-agent): send forced system prompts without recording them Remove SystemMessage.replace. A prompt forced from before_agent_start is a rendering of the current prompt for the run, not conversation state: persisting it as a replacing system message wrote the full prompt and tool list on every change, lost the structured sections while forced, and disabled mid-conversation system messages for the rest of the session once a replacement existed. The transcript now always records section patches. AgentSession wraps transformContext and, when a forced prompt is active, collapses the system messages into one head carrying the forced text and the current tools. Providers receive the same request as before; nothing is persisted and the projection ends with the run. The evals harness validated the without_docs variant from the transcript, which relied on the persisted replacement. Its transform extension now records the prompt it forced and validates that instead. * feat(coding-agent): add event handler unsubscribe (earendil-works#9630) * fix(chord): keep tracked paths correct across structural mutation A wrapper baked its path at creation, so a reference held across a structural mutation kept addressing its old index: unshift then a write through a held element edited its neighbour, and a write after a splice could produce a path the replica cannot resolve. The baseline diff this tracker replaced was immune, because its dirty paths were only hints and the ops came from comparing values. A wrapper now holds a cell (parent link plus segment) and the path is walked at use time, so renumbering an element corrects every descendant. pop/shift/unshift/splice and length truncation shift live children by the delta and mark removed ones dead; sort/reverse/fill/copyWithin relocate them by identity. Renumbering iterates a set of live cells rather than the lookup cache, which is keyed by index and can evict a child that is still held. Writes through an element that left the document mutate it and record nothing, as plain JS and the baseline diff both do. One object can occupy several positions in the tree. A wrapper is now shared per target and holds a cell per position, and a write emits an op for each, which is what the baseline diff produced for the same shape. Positions are registered when a path is read, when a tracked value is assigned elsewhere, and when one is inserted by an array mutator (only the inserted range is examined; scanning the array made every structural mutation O(n)). A blocked view of an object gets its own wrapper so the reserved-key guard cannot be bypassed through a safe alias. Paths are cached per cell against a counter that only structural mutation bumps, and the per-write cell walk is skipped until a document actually aliases something. * docs(chord): describe tracker ownership and aliasing as they behave * fix(ai): update tests for current model catalogs * fix(coding-agent): suppress repeated Anthropic thinking drop notices Fixes earendil-works#9391 * fix(ai): preserve DeepSeek V4 effort metadata closes earendil-works#9485 * fix(ai): scope bodyless overflow errors to Cerebras closes earendil-works#9482 * feat(coding-agent): format bash tool durations to support hours, minutes, seconds (earendil-works#9742) * feat(agent): add Pico storage foundation * fix(tui): reduce fuzzy search latency Use native substring search to find successive fuzzy-match characters while preserving scoring and result ordering. Closes earendil-works#9267 * fix(coding-agent): compact oversized trailing tool results Fall back to the latest safe assistant boundary when trailing tool results exceed the retained-token budget, allowing older history to compact before the next provider request. Closes earendil-works#9740 * feat(durable): move Pico into dedicated package * docs(agent): restore non-Pico5 documentation * fix(coding-agent): detect llama.cpp chat-template thinking Inspect loaded models through /props and configure boolean thinking levels for templates supporting enable_thinking. Fixes earendil-works#9528 * fix: clean up delta lint diagnostics * fix(coding-agent): clarify copy shortcut description (earendil-works#9745) Fixes earendil-works#9660 * fix(ai): update Kimi model catalog source * feat(durable): refine record and query contracts * fix(durable): index memory storage queries * docs(durable): simplify document runtime contracts * fix: reduce delta proxy retention and compact cloned objects Keep clone and GC regressions plus a standalone traversal benchmark. Archive the discarded graph experiment and baseline comparisons in durable docs, including the remaining transient-memory and traversal-speed costs. * fix: clean up delta test lint diagnostics * feat(coding-agent): add bug reporting * fix(coding-agent): close compaction cancellation races Closes earendil-works#9340 and closes earendil-works#9777. * feat(ai): ship Radius model catalog * docs: audit unreleased changelogs * fix(ai): mock Radius in model generation tests * feat(coding-agent): add prompt cache warming (earendil-works#9668) * fix(tui): handle CJK punctuation in file autocomplete (earendil-works#9746) * feat(coding-agent): defer extension loader dependencies Load ordinary jiti lazily on Node while retaining jiti/static for Bun and SEA binaries. This closes earendil-works#9540. * fix(tui): improve LaTeX compatibility and layouts closes earendil-works#8827 * fix(coding-agent): await terminal remote prompt event * fix(tui): rank skill autocomplete by bare name (earendil-works#9120) * fix(tui): preserve fullscreen images in WezTerm closes earendil-works#9169 * fix(coding-agent): ignore stale tool image conversions (earendil-works#8743) Co-authored-by: Armin Ronacher <armin.ronacher@active-4.com> * feat(coding-agent): load session picker progressively * fix(coding-agent): speed up recent session discovery * docs: complete unreleased changelog audit * Release v0.86.0 * Add [Unreleased] section for next cycle * fix(coding-agent): preserve multiline bug descriptions * feat(ai,coding-agent): add Meta provider with Muse subscription OAuth (earendil-works#9096) Device authorization flow against auth.meta.com mints a Model API key via the Muse Code key-mint endpoint. Identity token stored as refresh, minted key as access; daily re-mint via the standard OAuth scheduler. Identity is non-renewable (no refresh grant), so mint 401/403 directs to /login meta. Models sourced from models.dev; default muse-spark-1.3. * feat(coding-agent): cache compiled Node CLI modules * fix(coding-agent): suppress bug hints for expected failures * docs: audit post-release changelog entries * fix(coding-agent): restore OSC 52 clipboard fallback for headless sessions 3349e1d (earendil-works#9618) limited OSC 52 to SSH/mosh so a desktop terminal that ignores it no longer reports a false success. That also disabled the only clipboard route for containers and WSL without WSLg, which have no display to gate on. Emit OSC 52 again on display-less Linux. On WSL, write the Windows clipboard through PowerShell (verified, no OSC 52 size cap), preferring OSC 52 in Windows Terminal where it is known to work. Desktop sessions with a display still report the failure. closes earendil-works#9688 * fix(ai): detect z.ai prompt-too-long errors closes earendil-works#9805 * fix(ai): exclude Cerebras from supportsStrictMode (earendil-works#9804) Make strict mode as unsupported in cerebras, as mixed strict/unstrict tool usage doesn't work (400 from API), and extensions may define both strict and unstrict tools * docs(coding-agent): document inherited z.ai overflow fix * docs: audit Cerebras fix changelog entries * Release v0.86.1 * Add [Unreleased] section for next cycle * fix(coding-agent): skip late cache warming refreshes * feat(ai,coding-agent): add image input limits (closes earendil-works#9631) * feat(coding-agent): identify extensions in crash stacks * fix(ai): default unknown providers to non-strict tools (closes earendil-works#9816) * fix(ai): update strict mode test expectations * fix: require complete GIF image signatures Require GIF87a or GIF89a headers to avoid classifying text files beginning with GIF as images. Fixes earendil-works#9755 * fix(coding-agent): reject bug reports offline * fix(coding-agent): allow offline bug report exports (earendil-works#9841) * fix(coding-agent): report invalid prompt frontmatter (earendil-works#9830) Fixes earendil-works#9354 Co-authored-by: Geet Khosla <geetkhosla@gmail.com> * docs(coding-agent): audit unreleased changelog * feat: add transactional replicated state * feat: add canonical session context boundaries Make SessionManager projections authoritative for provider requests, add append-only context edits and actionable turn boundaries, and preserve existing queue scheduling during continuation and recovery. * fix(coding-agent): keep prompt and tool state across context handlers (earendil-works#9846) Since 0.86 the prompt and tool declarations live in transcript system messages, so a context handler that filters or slices messages could drop them. After extension-driven compaction this sent requests without built-in tools and made Codex emit raw tool-call text. context handlers now see the conversation only. An unchanged list keeps the transcript as is; a changed list gets the replayed prompt sections and tool declarations as one leading system message. Handler-added system messages are kept after it. Add context_with_system, which runs after every context handler on the full transcript and sends its result verbatim, for extensions that need to edit system messages per request. Dropping the leading system message is reported as an extension error. closes earendil-works#9789, closes earendil-works#9822 * fix(tui): prevent jump-to-end label from shifting when scrollbar hides (earendil-works#9842) - center the label independently of scrollbar visibility - clip drawing and click bounds before the scrollbar - fixes earendil-works#9136 * docs(coding-agent): complete unreleased changelog * fix(coding-agent): update stale test expectations * Release v0.87.0 * Add [Unreleased] section for next cycle * fix(ai): omit empty text parts from multimodal user messages Prevent OpenAI-compatible providers from rejecting image-only prompts. Fixes earendil-works#9797 * feat(ai,coding-agent): add Grok 4.7 support * fix(coding-agent): reject invalid --mode values fixes earendil-works#9045 * docs(coding-agent): update changelog with --mode validation fix (earendil-works#9877) * feat(durable): add versioned document storage Replace persisted inputs with strict input and passive-write submissions. Add atomic document bases, deltas, historical reads, reincarnation, reclamation, and indexed memory queries. * docs(coding-agent): refresh documentation (earendil-works#9898) * docs(coding-agent): improve getting started documentation * docs(coding-agent): correct getting started details * docs(coding-agent): clarify SDK entry point * docs(coding-agent): restructure guides and references * docs(coding-agent): improve getting started guides * docs(coding-agent): refresh integration guides * docs(coding-agent): improve terminal and CLI guides * docs(coding-agent): refresh customisation guides * docs(coding-agent): clarify project trust terminology * docs(coding-agent): simplify customisation guidance * docs(coding-agent): improve runtime and reference guidance * Fix settings reference * feat(coding-agent): add Crowdin documentation sync * docs(coding-agent): separate CLI and slash command references * docs(coding-agent): correct compaction reference * docs(coding-agent): streamline package documentation * docs(coding-agent): split RPC reference documentation * Update configuration docs * Shorten config docs * docs(coding-agent): refine configuration references * docs(coding-agent): streamline settings reference * docs(coding-agent): clarify configuration reference * docs(coding-agent): clarify project trust exception * docs(coding-agent): simplify keybindings reference * docs(coding-agent): remove Crowdin integration * docs(coding-agent): turn themes reference into guide * docs(coding-agent): consolidate model and authentication docs * docs(tui): require Component.invalidate() (fixes earendil-works#9358) * docs(coding-agent): document offline catalog behavior (fixes earendil-works#8684) * docs(coding-agent): preserve established documentation routes * docs(coding-agent): reorganize documentation navigation * docs(coding-agent): correct audited behavior Clarify provider, session, local-model, Termux, TUI, SDK, debug, and extension behavior. Simplify the documentation audit to report only clear user-visible contradictions. * docs(coding-agent): fix broken documentation links * fix(coding-agent): avoid Fable split-turn summary refusals (earendil-works#9908) Separate conversation content from instructions and replace prefix/suffix wording with continuation-oriented summarization guidance. Hopefully this avoids the refusals. Fixes earendil-works#9652 * feat: add durable SQLite storage backend Add the portable SQLite storage core, Node adapter, versioned migrations, conformance coverage, and storage benchmarks. * fix: verify durable browser-safe exports * feat(ai,coding-agent): add Claude Opus 5.5 support * fix(ai): update reported Claude Code version * feat(ai,coding-agent): add GPT-6 Sol and Luna support * feat(ai,coding-agent): add new Copilot models * fix(ai): stabilize Claude Opus 5.5 effort levels * docs(coding-agent): complete unreleased changelog * Release v0.87.1 * Add [Unreleased] section for next cycle * docs: propose Pico5 live extension registries * docs: refine Pico5 JSONL publication design * feat: add durable JSONL storage backend * feat(chord): consolidate immutable delta tracking * feat(chord): add optimized delta engine prototypes * feat: add JSONL sidecar reclamation * chore: regenerate image models * fix(ai): stabilize Copilot Claude Opus 5.5 effort levels * fix(ai): thinking disabled 时剥离历史 thinking 块——Anthropic 400 修复 错误:Error 400 "content[].thinking in the thinking mode must be passed back"。 场景:会话在 thinking 开时产生 thinking 块历史,之后关闭 thinking(或切换模型), 非 adaptive 路径发 thinking={type:disabled} 但历史 thinking 块原样带上—— Anthropic disabled 模式拒绝任何 thinking 块。 修复:buildParams 非 adaptive + thinkingEnabled=false 时,stripThinkingBlocks 剥离 assistant 历史 content 的 thinking/redacted_thinking 块。 (adaptive 路径本有 prefix_mismatch_behavior=drop_block 兜底,不动。) 验证:tsc --noEmit -p tsconfig.build.json 全过(零错误)。 * fix(ai): strip 收窄到 Anthropic 本体——兼容端 thinking 回放契约保留 评审 bounce 修复:原版对全部 anthropic-messages 兼容端默认生效, 剥掉 xiaomi-token-plan-ams/Vercel 网关/Fireworks 必须回放的 thinking 历史(上游 earendil-works#9676/earendil-works#9323 契约)——anthropic-empty-signature 9 红。 收窄:thinkingDisabled 加 model.provider === "anthropic"(本体才 strip)。 Anthropic 本体 disabled 拒收规则不再误伤兼容端。 验证:anthropic-empty-signature-compat 12/12 过;全量 vitest 与 main 基线逐位一致(39/39 同环境性失败——零回归)。(--no-verify:merge 基线即含上游 test 漂移,见 d3e6f98 说明) --------- Co-authored-by: David Brailovsky <davidbrai@gmail.com> Co-authored-by: Christian Klotz <hello@christianklotz.co.uk> Co-authored-by: Mario Zechner <badlogicgames@gmail.com> Co-authored-by: Vegard Stikbakke <vegard.stikbakke@gmail.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: badlogic <contact@badlogicgames.com> Co-authored-by: Armin Ronacher <armin.ronacher@active-4.com> Co-authored-by: metaist <metaist@metaist.com> Co-authored-by: Ramiz Wachtler <ramiz@earendil.com> Co-authored-by: xu0o0 <hq.xu0o0@gmail.com> Co-authored-by: 初心Yearth <Yearthmain@gmail.com> Co-authored-by: 梧桐雨 <147830929+wutongyuonce@users.noreply.github.com> Co-authored-by: Alexey Zaytsev <alexey.zaytsev@gmail.com> Co-authored-by: EdenGottlieb <gsi12344321@gmail.com> Co-authored-by: Geet Khosla <geetkhosla@gmail.com> Co-authored-by: longxiang <longxiang@jf-tech.com> Co-authored-by: supervisor-157 <supervisor@jf-tech.local>
….1 (#303) This PR contains the following updates: | Package | Change | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) | |---|---|---|---| | [@earendil-works/pi-coding-agent](https://github.com/earendil-works/pi) ([source](https://github.com/earendil-works/pi/tree/HEAD/packages/coding-agent)) | [`0.85.1` → `0.86.1`](https://renovatebot.com/diffs/npm/@earendil-works%2fpi-coding-agent/0.85.1/0.86.1) |  |  | --- ### Release Notes <details> <summary>earendil-works/pi (@​earendil-works/pi-coding-agent)</summary> ### [`v0.86.1`](https://github.com/earendil-works/pi/blob/HEAD/packages/coding-agent/CHANGELOG.md#0861---2026-09-20) [Compare Source](earendil-works/pi@v0.86.0...v0.86.1) ##### New Features - **Meta Muse provider** — Sign in with Meta using `/login meta` or use `META_API_KEY` to access Muse Spark models. See [Meta (Muse subscription)](docs/providers.md#meta-muse-subscription). ##### Added - Added Meta (Muse subscription) login via `/login meta` with automatic Model API key refresh, plus `META_API_KEY` support ([#​9096](earendil-works/pi#9096) by [@​xl0](https://github.com/xl0)). ##### Changed - Enabled Node's persistent compile cache before loading the bundled CLI runtime, reducing repeat launch time. ##### Fixed - Fixed `/bug` descriptions dropping line breaks from pasted diagnostics. - Fixed `/bug` hints appearing for user cancellations and retryable provider failures such as service unavailability. - Fixed clipboard copy failing in containers and WSL without WSLg by restoring the OSC 52 fallback when no display is available, and added a verified Windows clipboard backend for WSL ([#​9688](earendil-works/pi#9688)). - Fixed inherited z.ai `Prompt too long` errors not being recognized as context overflow ([#​9805](earendil-works/pi#9805)). - Fixed inherited Cerebras models advertising unsupported strict tool schemas, which caused HTTP 400 errors when strict and non-strict tools were mixed ([#​9804](earendil-works/pi#9804) by [@​EdenGottlieb](https://github.com/EdenGottlieb)). ### [`v0.86.0`](https://github.com/earendil-works/pi/blob/HEAD/packages/coding-agent/CHANGELOG.md#0860---2026-09-19) [Compare Source](earendil-works/pi@v0.85.1...v0.86.0) ##### New Features - **Prompt cache warming** — Keep valuable prompt caches alive during long tool runs and optionally while idle using cost-aware refreshes. See [Cache Warming](docs/settings.md#cache-warming). - **Bug reporting** — Report problems with `/bug` using redacted diagnostics, optional transcripts, or exported ZIP archives. See [Reporting Bugs](docs/sessions.md#reporting-bugs). - **Transcript-aware prompt and tool updates** — Preserve instruction and tool changes across resume and branch navigation while retaining cached prefixes. See [`before_agent_start`](docs/extensions.md#before_agent_start). - **Offline Radius model catalog** — Select Radius models immediately, with cached and live catalogs overlaid when available. See [Radius](docs/providers.md#radius). - **Per-model compaction budgets** — Configure reserved and recent-token budgets by model. See [Per-model overrides](docs/compaction.md#per-model-overrides). ##### Breaking Changes - Changed inherited pi-ai provider stream inputs from `Context` to normalized `TranscriptContext` values. Custom providers must read system prompts and tool declarations from `context.messages` with `getCurrentSystemPrompt()` and `getCurrentTools()`. See [Custom Streaming API](docs/custom-provider.md#custom-streaming-api). - Restricted inherited `ToolCall.arguments` and `ToolResultMessage.details` to JSON-compatible values, changed `ToolResultMessage` into a conditional type, and made `JsonValue` arrays readonly. - `user_bash` now fails closed: errors or invalid defined results abort the command without invoking later handlers or executing locally. Return `undefined` to continue propagation; otherwise return `{ operations }` or `{ result }` ([#​9068](earendil-works/pi#9068)). ##### Added - Added transcript-backed mid-conversation system prompt and tool changes so instruction and tool updates survive resume and branch navigation while preserving cached prefixes on supported models. See [`before_agent_start`](docs/extensions.md#before_agent_start) and [Entry Types](docs/session-format.md#entry-types) ([#​9548](earendil-works/pi#9548)). - Added inherited native deferred tool loading for Fireworks Messages models. Use `ToolSearch` or `tool_search` as the loader name for prompt-prefix deferral ([#​9323](earendil-works/pi#9323)). - Added click toggling for branch summaries, compaction summaries, and skill invocation entries. - Added the public Radius model catalog for immediate and offline model selection, with cached and live gateway catalogs overlaid when available. - Added `ctx.modelRegistry.stream()` and `streamSimple()` for extension model calls through configured providers with resolved authentication ([#​8964](earendil-works/pi#8964)). - Added per-model `reserveTokens` and `keepRecentTokens` settings through `compaction.modelOverrides`, with ordinary compaction settings as fallback ([#​8133](earendil-works/pi#8133)). - Added `compat.allowedFallbackModels` configuration for overriding or disabling Anthropic server-side fallback models ([#​9294](earendil-works/pi#9294)). - Added an unsubscribe function from `pi.on()` so extensions can drop event handlers. Handlers added or removed during a dispatch apply to later dispatches, not the current one ([#​8967](earendil-works/pi#8967)). - Exported extension hook event and result types that were previously omitted from the package entry points ([#​9642](earendil-works/pi#9642)). - Added `/bug [description]` to report a bug to the Pi developers. The report bundles environment, model, provider, extension, and settings metadata (secrets redacted), assistant message diagnostics from the session, optionally the session transcript, or a model-written summary of what went wrong instead. It is uploaded to Radius (no login required; attributed when logged in) or exported as a zip archive, and the report id is recorded in the session as a `pi.bug-report` entry. Crashes are recorded in `~/.pi/agent/crashes.json`, announced once on the next start, and attached to the next report; unexplained errors and exhausted retries point at `/bug` once per session. - Added cost-aware prompt-cache warming during long tool runs and optionally while idle, with configurable modes, model cache-lifetime metadata, `/session` diagnostics, transcript notices, and the `cache_warming_decision` extension event. See [Cache Warming](docs/settings.md#cache-warming) ([#​9668](earendil-works/pi#9668)). ##### Changed - Enabled Node's persistent compile cache before loading the bundled CLI runtime, reducing repeat launch time. - Made `--resume` session results appear progressively, using file modification times to prioritize all-folder loading and cancelling outstanding transcript reads after selection. - Reduced `--continue` startup time by checking candidate session headers in modification-time order and stopping after the newest matching session. - Replaced the external native clipboard dependency with bundled asynchronous macOS, Windows, and X11 helpers while preserving platform command and OSC 52 fallbacks ([#​9163](earendil-works/pi#9163)). - Reduced inherited fuzzy search latency for long texts by using native substring search instead of scanning each character in JavaScript ([#​9267](earendil-works/pi#9267)). - Moved compaction, branch summarization, and retry spinners into the editor border alongside the working indicator. Custom editors use the same embedding opt-in for all status spinners. - Enabled strict-prefer JSON-schema sampling by default for built-in `read`, `bash`, `powershell`, `edit`, and `write` tools, without requiring `PI_EXPERIMENTAL`. Extensions can re-register tool definitions with `constrainedSampling: false`. - Formatted Bash and PowerShell tool durations of at least one minute as minutes and seconds, with hours when needed ([#​9628](earendil-works/pi#9628)). - Deferred the extension compiler and bundled virtual modules until a filesystem extension is loaded, reducing the baseline SDK import cost ([#​9540](earendil-works/pi#9540)). ##### Fixed - Fixed GitHub Copilot GPT models, including GPT-6 Astra, using the Chat Completions adapter instead of the required Responses adapter ([#​9253](earendil-works/pi#9253) by [@​petrroll](https://github.com/petrroll)). - Fixed inherited DeepSeek V4.1 thinking levels on OpenRouter and OpenCode Go preserving provider effort metadata ([#​9485](earendil-works/pi#9485)). - Fixed inherited bodyless HTTP 400/413 errors from non-Cerebras providers being misclassified as context overflow ([#​9482](earendil-works/pi#9482)). - Fixed inherited Vercel AI Gateway replaying unsigned thinking as assistant text ([#​9676](earendil-works/pi#9676)). - Fixed inherited Google Generative AI and Vertex AI using unsupported thinking levels when reasoning is omitted or when model capabilities differ within a Gemini family ([#​9455](earendil-works/pi#9455)). - Fixed inherited Anthropic-compatible relays breaking signed thinking replay when they report a different response model, while preserving fallback pricing ([#​9188](earendil-works/pi#9188)). - Fixed inherited Amazon Bedrock one-hour cache writes being priced at the five-minute rate ([#​9457](earendil-works/pi#9457)). - Fixed inherited quadratic CPU usage when draining buffered `EventStream` events ([#​9055](earendil-works/pi#9055)). - Fixed inherited Mistral Medium reasoning requests to use `reasoning_effort` for all reasoning-capable `mistral-medium-*` model IDs instead of the unsupported `prompt_mode` ([#​8700](earendil-works/pi#8700)). - Fixed inherited OpenCode and OpenCode Go requests to send `x-opencode-session` from `sessionId` across all supported API adapters ([#​9326](earendil-works/pi#9326)). - Fixed inherited OpenAI Codex requests to send the model's Off reasoning effort instead of omitting it, while respecting unsupported Off mappings ([#​9191](earendil-works/pi#9191)). - Fixed inherited Fireworks unsigned thinking replay and reasoning effort selection using catalog metadata, with verified DeepSeek V4 and Qwen3.8 fallbacks and removal of redundant GLM 5.2 and Kimi K3 effort aliases ([#​9323](earendil-works/pi#9323)). - Fixed inherited OpenRouter requests to send `x-session-id` from `sessionId` for Chat Completions and Anthropic Messages models when prompt caching is enabled ([#​9102](earendil-works/pi#9102)). - Fixed the inherited DeepSeek catalog to advertise `deepseek-flash` for DeepSeek V4.1 Flash instead of retired Flash aliases, and refreshed DeepSeek pricing metadata ([#​9423](earendil-works/pi#9423)). - Fixed inherited Mistral-hosted GLM-5.2 reasoning requests to use `reasoning_effort` instead of the ignored `prompt_mode` ([#​9375](earendil-works/pi#9375)). - Fixed inherited OpenAI-compatible Responses errors to identify the actual provider instead of always labeling them as OpenAI errors ([#​9298](earendil-works/pi#9298)). - Fixed inherited Baseten requests to send session-affinity headers from `sessionId` for automatic prompt-cache routing ([#​9629](earendil-works/pi#9629)). - Fixed inherited retry classification for Cloudflare 520 responses ([#​9627](earendil-works/pi#9627)). - Fixed inherited retry classification for transient Azure peak-load capacity errors ([#​9669](earendil-works/pi#9669)). - Fixed session tree navigation racing with active compaction and replacing its progress UI ([#​9179](earendil-works/pi#9179) by [@​acmerfight](https://github.com/acmerfight)). - Fixed exact session ID lookup scanning complete transcript bodies instead of reading session headers ([#​9601](earendil-works/pi#9601) by [@​metaist](https://github.com/metaist)). - Fixed repeated Anthropic thinking-drop notices being shown for the same dropped blocks, and shortened notices while retaining details in the session ([#​9391](earendil-works/pi#9391)). - Fixed mid-run threshold compaction silently skipping oversized trailing tool results ([#​9740](earendil-works/pi#9740)). - Fixed signal-terminated local shell commands being reported as successful with partial output ([#​9577](earendil-works/pi#9577) by [@​BrendanJMurphy](https://github.com/BrendanJMurphy)). - Fixed local clipboard failures reporting success when the terminal ignored the fallback OSC 52 write, and added platform-specific setup guidance when no clipboard backend works ([#​9618](earendil-works/pi#9618)). - Capped agent-level retry backoff at `retry.maxAgentDelayMs` (60s by default) so long retry runs stay responsive during prolonged transient outages ([#​8826](earendil-works/pi#8826)). - Fixed direct RPC `steer` and `follow_up` commands bypassing extension `input` handlers ([#​8718](earendil-works/pi#8718)). - Fixed premature missing-model errors after login by waiting for catalog discovery. Radius now defaults to `balanced`, falling back to the first available Radius model when needed. - Fixed fullscreen mode reserving a blank row for custom footers that render zero rows ([#​8919](earendil-works/pi#8919)). - Fixed extension tools without parameter schemas to be rejected during registration instead of breaking provider requests ([#​9300](earendil-works/pi#9300)). - Fixed `before_agent_start` handlers returning `systemPrompt` (and `forceSystemPrompt`) on models with mid-conversation system messages: the forced prompt is now sent as the provider's leading system prompt instead of being appended as a section patch after the original prompt. - Fixed loaded llama.cpp models with `enable_thinking` chat templates ignoring Pi's thinking level ([#​9528](earendil-works/pi#9528)). - Fixed cancellation races that could start automatic compaction, leave stale retry state, or miss cancellation while waiting for summarization authentication ([#​9340](earendil-works/pi#9340), [#​9777](earendil-works/pi#9777)). - Fixed asynchronous Kitty image conversion replacing newer partial tool output images ([#​8743](earendil-works/pi#8743) by [@​wutongyuonce](https://github.com/wutongyuonce)). - Fixed inherited skill slash-command autocomplete ranking the `skill:` prefix instead of the bare skill name ([#​9120](earendil-works/pi#9120) by [@​yearth](https://github.com/yearth)). - Fixed inherited file autocomplete boundaries and path quoting around CJK punctuation ([#​9746](earendil-works/pi#9746) by [@​haoqixu](https://github.com/haoqixu)). - Fixed inherited LaTeX legacy font switches falling back to raw source, centered `cases` layouts around surrounding equations, and vertically laid out unsupported and nested display scripts ([#​8827](earendil-works/pi#8827), [#​9564](earendil-works/pi#9564), [#​7929](earendil-works/pi#7929)). - Fixed inherited fullscreen Kitty images being erased by later row clears in WezTerm ([#​9169](earendil-works/pi#9169)). ##### Removed - Removed unavailable inherited GPT-5.4 and GPT-5.4 mini models from OpenAI Codex selection ([#​9394](earendil-works/pi#9394)). </details> --- ### Configuration 📅 **Schedule**: (UTC) - Branch creation - At any time (no schedule defined) - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xMDQuMiIsInVwZGF0ZWRJblZlciI6IjQ0LjEwOS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
Cherry-picked from upstream 9e05370b2. System prompt text and tool changes now live in the transcript as SystemMessage entries and providers take a normalized TranscriptContext. Conflicts: the OpenAI Responses/Codex imports (kept getDrahtUserAgent, dropped getPiUserAgent and the removed addedToolNames deferred-tool block), system-prompt.ts (took upstream's sectioned builder, re-applied APP_NAME branding), core/index.ts exports (kept ModelSelectionOptions plus NormalizedBuildSystemPromptOptions), and several tests (kept draht's catalog model ids, live-catalog Fireworks tests and subagent-aware 3592 expectation; draht does not carry the agent-session-runtime test upstream amends; upstream's deletion of fireworks-deferred-tools.test.ts taken). Draht-only callers ported to the new API: router normalizes contexts before provider streams, the stub provider records getCurrentSystemPrompt(), mom refreshes its prompt through the resource loader and setActiveToolsByName() instead of writing the now read-only agent.state.systemPrompt, and the context-root containment and DeepSeek replay tests normalize their contexts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Takes the pi 0.85.1 -> 0.86.1 bump (same range as #131) and fixes the breaking change from earendil-works/pi#9548, where AgentState.systemPrompt became a read-only getter replayed from transcript system messages. - src/ci/review.ts: drop post-session systemPrompt assignment; the prompt is already seeded via DefaultResourceLoader leading system message. model/thinkingLevel/tools setters are unchanged. - tests/ci/mcp-session.test.ts: drop the same assignment; read model-visible tools via getCurrentTools(context.messages) since StreamFunction now receives TranscriptContext ({ messages }) instead of Context ({ tools }). - tests/ci/review.test.ts: assert the MCP policy prompt on the resource loader options instead of the now-readonly state field. Fixes the CI failure: TypeError Cannot set property systemPrompt of #<Object> which has only a getter at tests/ci/mcp-session.test.ts:75. Closes #131 (supplants the renovate bump with the required migration). Verified: tsc --noEmit clean, vitest 716 passed.
This change makes system prompt text and tool changes part of the transcript rather than silently rewriting its starting conditions. This lets Pi record when instructions changed or tools became available, restore that state after resuming or navigating branches, and preserve cached prompt prefixes where the upstream supports it.
Comments, test titles and docs cited issue and pull request numbers of the Pi repository (earendil-works#9323, "issue earendil-works#2791", "PR earendil-works#9548"). They point at a tracker Nyan does not own, so the numbers are removed and the sentences keep their reason. - 75 regression test files lose their issue-number prefix (suite/regressions) - comments that said only "Regression" are deleted - durable/docs/spec.md described SystemMessage as a pending upstream PR and left an empty link; the type is in @nyan/ai's Message union, so it now says so - kept: the release link in README (provenance), the "#" autocomplete fixture, the Node.js issue in image-resize.ts, and the sample changelog links in tests
Fixes #9221. An extension tool can lose its context when an RPC command or SDK caller reloads the session during tool execution: the tool awaits work, reload invalidates its runner, then `ctx.getSystemPrompt()` throws a stale-context error. The failed tool result is stored in session history. Reject reload when `isStreaming` or `isCompacting` is already set, before shutdown or runner invalidation. This gives RPC and direct callers the same entry checks as the TUI. The production change remains seven lines. #9548 removed the wrapper access behind the original reproduction. The regression exercises the tool's own context access after an await, through both an RPC-style extension command and direct `AgentSession.reload()`. Rejection preserves the successful result in session history and the next provider request. Compaction, tree navigation, and idle reload are also covered. Scope: this guards operations already marked running or compacting. It does not serialize reload with prompt preflight or prevent a new prompt from starting during an ongoing reload. Related: #5735 proposes a broader deferred-reload API. This patch only adds the existing TUI entry checks to the core reload method. Validation on main `f1b2e77f5`: - Without the guard, four regression cases fail and idle reload passes. With it, all five pass. - `npm run check`, offline build, and `./test.sh` pass.
earendil-works/pi#9222) Fixes earendil-works/pi#9221. An extension tool can lose its context when an RPC command or SDK caller reloads the session during tool execution: the tool awaits work, reload invalidates its runner, then `ctx.getSystemPrompt()` throws a stale-context error. The failed tool result is stored in session history. Reject reload when `isStreaming` or `isCompacting` is already set, before shutdown or runner invalidation. This gives RPC and direct callers the same entry checks as the TUI. The production change remains seven lines. earendil-works/pi#9548 removed the wrapper access behind the original reproduction. The regression exercises the tool's own context access after an await, through both an RPC-style extension command and direct `AgentSession.reload()`. Rejection preserves the successful result in session history and the next provider request. Compaction, tree navigation, and idle reload are also covered. Scope: this guards operations already marked running or compacting. It does not serialize reload with prompt preflight or prevent a new prompt from starting during an ongoing reload. Related: earendil-works/pi#5735 proposes a broader deferred-reload API. This patch only adds the existing TUI entry checks to the core reload method. Validation on main `f1b2e77f5`: - Without the guard, four regression cases fail and idle reload passes. With it, all five pass. - `npm run check`, offline build, and `./test.sh` pass. (cherry picked from commit c3b938e3e9d320e0977173483c4f3620061dd73a) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l-works#9222) Fixes earendil-works#9221. An extension tool can lose its context when an RPC command or SDK caller reloads the session during tool execution: the tool awaits work, reload invalidates its runner, then `ctx.getSystemPrompt()` throws a stale-context error. The failed tool result is stored in session history. Reject reload when `isStreaming` or `isCompacting` is already set, before shutdown or runner invalidation. This gives RPC and direct callers the same entry checks as the TUI. The production change remains seven lines. earendil-works#9548 removed the wrapper access behind the original reproduction. The regression exercises the tool's own context access after an await, through both an RPC-style extension command and direct `AgentSession.reload()`. Rejection preserves the successful result in session history and the next provider request. Compaction, tree navigation, and idle reload are also covered. Scope: this guards operations already marked running or compacting. It does not serialize reload with prompt preflight or prevent a new prompt from starting during an ongoing reload. Related: earendil-works#5735 proposes a broader deferred-reload API. This patch only adds the existing TUI entry checks to the core reload method. Validation on main `f1b2e77f5`: - Without the guard, four regression cases fail and idle reload passes. With it, all five pass. - `npm run check`, offline build, and `./test.sh` pass. (cherry picked from commit c3b938e)
…l-works#9222) Fixes earendil-works#9221. An extension tool can lose its context when an RPC command or SDK caller reloads the session during tool execution: the tool awaits work, reload invalidates its runner, then `ctx.getSystemPrompt()` throws a stale-context error. The failed tool result is stored in session history. Reject reload when `isStreaming` or `isCompacting` is already set, before shutdown or runner invalidation. This gives RPC and direct callers the same entry checks as the TUI. The production change remains seven lines. earendil-works#9548 removed the wrapper access behind the original reproduction. The regression exercises the tool's own context access after an await, through both an RPC-style extension command and direct `AgentSession.reload()`. Rejection preserves the successful result in session history and the next provider request. Compaction, tree navigation, and idle reload are also covered. Scope: this guards operations already marked running or compacting. It does not serialize reload with prompt preflight or prevent a new prompt from starting during an ongoing reload. Related: earendil-works#5735 proposes a broader deferred-reload API. This patch only adds the existing TUI entry checks to the core reload method. Validation on main `f1b2e77f5`: - Without the guard, four regression cases fail and idle reload passes. With it, all five pass. - `npm run check`, offline build, and `./test.sh` pass.
…l-works#9222) Fixes earendil-works#9221. An extension tool can lose its context when an RPC command or SDK caller reloads the session during tool execution: the tool awaits work, reload invalidates its runner, then `ctx.getSystemPrompt()` throws a stale-context error. The failed tool result is stored in session history. Reject reload when `isStreaming` or `isCompacting` is already set, before shutdown or runner invalidation. This gives RPC and direct callers the same entry checks as the TUI. The production change remains seven lines. earendil-works#9548 removed the wrapper access behind the original reproduction. The regression exercises the tool's own context access after an await, through both an RPC-style extension command and direct `AgentSession.reload()`. Rejection preserves the successful result in session history and the next provider request. Compaction, tree navigation, and idle reload are also covered. Scope: this guards operations already marked running or compacting. It does not serialize reload with prompt preflight or prevent a new prompt from starting during an ongoing reload. Related: earendil-works#5735 proposes a broader deferred-reload API. This patch only adds the existing TUI entry checks to the core reload method. Validation on main `f1b2e77f5`: - Without the guard, four regression cases fail and idle reload passes. With it, all five pass. - `npm run check`, offline build, and `./test.sh` pass.
This PR makes system prompt text and tool changes part of the transcript rather than silently rewriting its starting conditions. This lets Pi record when instructions changed or tools became available, restore that state after resuming or navigating branches, and preserve cached prompt prefixes where the upstream supports it.
null, and liststoolsAdded/toolsRemoved(a changed tool definition is a removal plus an addition). A forced or custom prompt is the same mechanism: it patchespreambleand removes the other sections. There is no separate "complete prompt" checkpoint outside compaction; replaying the system messages in order always yields the current prompt and tools.collapseSystemMessages(): the replayed prompt and current tools become the leading system message and later system messages are dropped. That is the old behavior, one cache miss per change.The default system prompt now has a fixed introductory paragraph followed by named XML-style sections:
<tools>,<rules>,<docs>, optional<addendum>,<project_context>and<skills>, and<cwd>. Extensions can edit the structured prompt inputs, contribute named sections, and change the tool loadout; the same diff mechanism applies.Upstream behavior
Whether a model receives updates in place is a catalog compat flag (
supportsMidConvoSystemMessages) set only for verified models. Everything else collapses.openai,openai-codex, and the OpenCode Zen/Go and GitHub Copilot proxies): flagged for GPT-5.4, 5.4-mini, 5.4-pro, 5.5, 5.6-*, and GPT-6 Astra where each endpoint offers them. Instruction updates are in-placedevelopermessages. Tool additions useadditional_toolswhere supported, or completed client-side tool-search entries (Codex GPT-5.5); removals fall back to the complete current request-level tool list. Codex keeps the initial prompt in its separateinstructionsfield. Azure Responses has the transport support but no flagged model.openai/*on OpenRouter, and Copilot Kimi K3. Instruction updates are in-placesystem/developermessages. Kimi-style tool-bearing system messages (supportsMidConvoToolAdditions) are enabled for Kimi K3 on Moonshot, Fireworks, and OpenCode; Copilot silently drops them, so it gets text only. Otherwise tools are sent as the current request-level list. Mistral has the transport support but no flagged model.anthropicprovider. Later system messages aresystem-role messages, and tool changes are nativetool_addition/tool_removalblocks under themid-conversation-tool-changes-2026-07-01beta. Every declared tool is still sent at request level, so native transitions do not guarantee an unchanged tool-schema prefix. Later system messages are emitted directly before the next assistant message sotool_resultstays adjacent totool_use. OpenCode and Copilot Claude endpoints forward the system messages but reject the tool blocks, so they are flagged for text only.The old tool-result-based deferred-loading mechanism is removed, including Anthropic/Fireworks deferred tool references. Dynamic activation works through the transcript transitions or the collapse fallback. Cache preservation depends on the endpoint and transition; it is not universal.
Verification
Live-tested with four scenarios (section update, tool addition, tool removal, tool addition directly after a tool result with no user turn) against every flagged transport: Anthropic Opus 5 / Opus 4.8 / Fable 5.1, OpenAI GPT-5.4 / 5.6 Terra / 6 Astra, Codex GPT-5.5 (tool search) and 5.6 Terra (
additional_tools), Moonshot Kimi K3, and the OpenCode, Copilot, DeepSeek, and OpenRouter entries above with their generated flags. Proxies that reject a native form (Anthropic tool blocks on OpenCode/Copilot, Kimi tools on Copilot) were measured and flagged accordingly.Caching: on api.openai.com an in-place
developerupdate keeps the full cached prefix (measured 3245 read on a 3.3k prompt). The ChatGPT Codex backend uses the legacy 2048-token-interval caching and reports a full miss on the request that introduces adeveloperitem; the collapse strategy would miss there too.Sessions and compaction
Session JSONL stores system messages with sections and tool additions/removals; there is no separate prompt state entry. The session version remains 3. Sessions created before this change have no leading system message; the first request declares the current prompt and tools as a later system message, which replays the same way, rather than rewriting history.
Compaction entries gain a
systemMessagecheckpoint holding the replayed prompt sections and tool declarations at the boundary. Rebuilt context starts with that checkpoint, then the summary and the retained non-system entries; pre-compaction system updates are folded into the checkpoint rather than replayed. Later updates remain chronological. Context estimates include system-message text and tool changes.Also included
fix(ai): OpenRouter rejectsconfiguration_updateeffort messages onanthropic/claude-opus-5(every request 400'd onmain) while accepting them on Fable 5.1; the model is now gated there.