Skip to content

Mid conversation system messages - #9548

Merged
mitsuhiko merged 12 commits into
mainfrom
mid-conversation-system-messages
Sep 16, 2026
Merged

mitsuhiko merged 12 commits into
mainfrom
mid-conversation-system-messages

Conversation

@mitsuhiko

@mitsuhiko mitsuhiko commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

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.

  • Pi records the initial system prompt and complete tool definitions in the transcript's first system message. Later changes are appended as system messages before the next model response, including changes made by tools during a run.
  • Tool activation is no longer tied to a particular tool result.
  • Unchanged state produces no extra message. Every change is a section diff: an update repeats only changed prompt sections, marks removed sections with null, and lists toolsAdded/toolsRemoved (a changed tool definition is a removal plus an addition). A forced or custom prompt is the same mechanism: it patches preamble and 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.
  • Models without mid-conversation system message support get 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 Responses (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-place developer messages. Tool additions use additional_tools where 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 separate instructions field. Azure Responses has the transport support but no flagged model.
  • Chat Completions: flagged for Kimi K3 (Moonshot, Fireworks, OpenCode), DeepSeek V4 Pro, openai/* on OpenRouter, and Copilot Kimi K3. Instruction updates are in-place system/developer messages. 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.
  • Anthropic: flagged for Opus 4.8, Opus 5, and Fable 5/5.1 on the anthropic provider. Later system messages are system-role messages, and tool changes are native tool_addition/tool_removal blocks under the mid-conversation-tool-changes-2026-07-01 beta. 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 so tool_result stays adjacent to tool_use. OpenCode and Copilot Claude endpoints forward the system messages but reject the tool blocks, so they are flagged for text only.
  • Google/Gemini, Vertex, Bedrock Converse, and all unflagged models: collapse into the leading system prompt and send the current tool list.

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 developer update 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 a developer item; 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 systemMessage checkpoint 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 rejects configuration_update effort messages on anthropic/claude-opus-5 (every request 400'd on main) while accepting them on Fable 5.1; the model is now gated there.

@badlogic

Copy link
Copy Markdown
Collaborator

getTranscriptCapabilities() currently treats every openai-completions model as supporting native mid-conversation system messages. That also opts arbitrary OpenAI-compatible endpoints in when compat is missing.

This should be capability-gated and default to false. Please add a supportsMidConvoSystemMessages compat flag, enable it only for providers/models where we know this works, and lower later system messages to user messages for everything else.

This comment is AI-generated by /wr.

@badlogic

Copy link
Copy Markdown
Collaborator

I tested the transcript behavior against the live APIs. There are a few concrete packages/ai changes needed before this matches the intended design.

Anthropic

The generated flags currently cover:

  • claude-fable-5
  • claude-fable-5-1
  • claude-opus-4-8
  • claude-opus-5

I tested all four. Each accepted and followed a mid-conversation system message, tool_addition, and tool_removal. There is no separate documented Anthropic addition-only model set: additions and removals are the same beta capability on the same models.

Anthropic's required message order is important. user -> system -> user is rejected with:

role 'system' must precede an 'assistant' message or end the array

The canonical order must be:

user* -> system* -> assistant

and for tool loops:

assistant(tool_use*) -> user(tool_result*) -> system* -> assistant

So the buffering in convertMessages() that moves system directives to the next assistant boundary is correct. For example, user -> system -> user -> assistant must become user -> user -> system -> assistant.

transformMessages() currently does more than reshuffle at a system boundary inside a multi-tool batch: it synthesizes missing tool results. A system message should be transparent to pending tool-call accounting; do not produce No result provided merely because one appeared between tool results. The Anthropic converter should continue buffering that system message to the next assistant boundary. Providers such as OpenAI that accept it between tool outputs can keep its exact position.

Deferred tools and caching

Late Anthropic tools must be declared at request level with defer_loading: true and activated with tool_addition. Live behavior:

  • late tool deferred, before addition: not callable
  • late tool deferred, after addition: callable
  • late tool not deferred: callable before the transcript addition
  • removed request-level tool: no longer callable
  • all tools deferred: request rejected with At least one tool must have defer_loading=false

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:

initial active tools       // non-deferred
stable dummy tool          // defer_loading: true, never activated
later declared tools       // defer_loading: true, appended after dummy

With the dummy present from request one:

request 1: cache_write 16,556
request 2: cache_read  16,556
           cache_write  2,251

Without it, adding the first deferred tool on request two:

request 1: cache_write 16,463
request 2: cache_read   5,172
           cache_write 13,632

The dummy itself cannot carry cache_control; Anthropic rejects cache_control combined with defer_loading. Keep the tool cache breakpoint on the last initial active tool.

Change the Anthropic path as follows:

  1. Initial active tools remain non-deferred.
  2. If there is at least one initial active tool, inject one stable deferred dummy on every request and never activate it.
  3. Put later declarations after the dummy with defer_loading: true.
  4. Keep cache_control on the last initial active tool, not the last declared/deferred tool.
  5. Emit tool_addition / tool_removal blocks at the canonical assistant boundary.
  6. If the initial active set is empty, omit the dummy. A later addition cannot use the all-deferred native shape, so fall back to the current non-deferred request-level tool set and suppress inline tool-change blocks.
  7. A same-name definition replacement also needs that fallback because Anthropic's inline blocks only reference names; they do not carry replacement schemas.

The current code declares every tool through getDeclaredTools() but marks none of the late definitions deferred, so additions currently have the wrong semantics and do not get the intended cache behavior.

Docs: https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages

OpenAI Responses and Codex

I tested every model currently marked for these mechanisms.

Direct OpenAI, both additional_tools and completed client tool-search replay:

  • gpt-5.4
  • gpt-5.4-mini
  • gpt-5.4-pro
  • gpt-5.5
  • gpt-5.6-luna
  • gpt-5.6-sol
  • gpt-5.6-terra
  • gpt-6-astra

All eight accepted the transcript-anchored mechanism and called the loaded tool.

Codex:

  • gpt-5.5: completed client tool-search replay worked
  • gpt-5.6-luna, gpt-5.6-sol, gpt-5.6-terra, gpt-6-astra: both additional_tools and tool-search replay worked

The important behavior is that additional_tools is additive, not a snapshot:

  • I added [tool_a, tool_b], then [tool_b, tool_c], then requested tool_a. GPT still called tool_a; omission from the later item did not remove it.
  • I redeclared same_tool with a new required argument. GPT continued using the original schema. Redeclaration is not a schema replacement.
  • A developer message between two function outputs was accepted at its exact transcript position.

Change all three Responses request builders (openai-responses, Azure, Codex) as follows:

  1. For additions-only history, keep initial tools at request level and emit only newly added definitions at each additional_tools item. Do not emit cumulative snapshots or repeat already loaded names.
  2. Keep the existing tool-search behavior that emits only newly added tools.
  3. If any toolsRemoved occurs, disable all inline tool-transition items for that request and send getCurrentTools() at request level.
  4. Do the same for a repeated tool name / definition replacement.
  5. Keep system/developer text at its transcript position. Codex keeps only the leading system text in instructions; later text remains inline.

The current additionalToolsIncludeInitial snapshot path cannot remove tools and the removal test currently asserts behavior the API does not provide. Update that test to expect request-level fallback and no additional_tools items. Also update anchors OpenAI additions at their system message: its second item should contain only last_tool, not late_tool again.

Docs: https://developers.openai.com/api/docs/guides/tools-tool-search#add-tools-at-a-specific-point-in-the-input

Kimi Chat Completions

System text worked on all tested Moonshot models:

  • kimi-k2.6
  • kimi-k2.7-code
  • kimi-k2.7-code-highspeed
  • kimi-k3

Dynamic system-message tools worked on:

  • Moonshot kimi-k3
  • Fireworks accounts/fireworks/models/kimi-k3
  • Fireworks accounts/fireworks/routers/kimi-k3-fast

They failed with tokenization failed on Moonshot K2.6 and both K2.7 variants. The official documentation explicitly says dynamic tool loading is currently K3-only.

Kimi tool messages are additions-only and must be retained in subsequent requests. A tool-bearing system message cannot also carry content, so keep the current split of a pi SystemMessage containing both text and tool additions into two adjacent system messages:

{ role: "system", tools: [new complete definitions] }
{ role: "system", content: "instruction text" }

Change the Kimi path as follows:

  1. Restrict supportsMidConvoToolAdditions generation to K3. The current id.includes("kimi") check incorrectly marks K2.6 and K2.7.
  2. Keep the existing filtering that emits only newly added complete definitions; never redeclare a previously loaded name.
  3. Any removal or same-name replacement falls back to the current request-level tool set and suppresses all tool-bearing system messages. Keep system text inline.
  4. Keep the existing no-content tool-message wire shape.

Docs: https://platform.kimi.ai/docs/guide/use-dynamic-tool-loading

Capability reporting

getTranscriptCapabilities() currently treats every openai-completions model as supporting native mid-conversation system messages. In the generated catalog that is 684 models across unrelated compatible providers. Kimi working does not establish that blanket capability.

Add an explicit supportsMidConvoSystemMessages compat flag for OpenAI Chat-compatible models, default it to false, and mark only verified provider/model families. The deliberate trade-off is that unmarked endpoints use collapseSystemMessages() and lose inline system updates rather than being optimistically sent a wire shape we have not verified. Keep this independent from supportsMidConvoToolAdditions: K2.6/K2.7 support inline system text but not inline tools. mistral-conversations is also hard-coded as native, but that is a separate capability claim and should remain unchanged unless we verify it separately.

Required pi-ai tests

Please add/update focused payload tests for:

  • Anthropic canonical user/user/system/assistant and tool-result batching
  • no synthetic tool result when a system message is inside a tool-result batch
  • initial active tools + stable deferred dummy + late deferred definitions
  • no dummy/all-deferred shape when initial tools are empty, with request-level fallback
  • Anthropic removal and same-name replacement fallback
  • OpenAI additions emitting only new definitions
  • OpenAI removal/replacement producing current request-level tools and no inline transition items
  • tool-search removal fallback
  • Kimi K3 additions, K2.6/K2.7 capability disabled, and removal/replacement fallback
  • getTranscriptCapabilities() default false for an unmarked openai-completions model and true for explicitly marked models

Unsupported providers should continue deriving current request-level tools by replaying transcript additions/removals. The target design calls for user-role <system> lowering; the PR currently emits <system_reminder>, so change renderSystemMessageAsUserText() if <system> remains the agreed wire format.

This comment is AI-generated by /wr.

@mitsuhiko
mitsuhiko force-pushed the mid-conversation-system-messages branch from 7f45441 to 9a9591e Compare September 14, 2026 17:29
@mitsuhiko
mitsuhiko marked this pull request as ready for review September 14, 2026 21:29
@mitsuhiko

mitsuhiko commented Sep 14, 2026 •

Copy link
Copy Markdown
Member Author

Example session transcript showing the system messages. Captured from a real run of pi -p from this branch against openai-codex/gpt-5.6-terra with a small extension: turn 1 runs with read and bash; before turn 2 the extension sets an addendum section, activates its own get_time tool, and drops bash.

Entries are one JSON object per line in the file; pretty-printed here. The only edits: long prompt section text is clipped (…), tool-call ids are shortened, and assistant usage/thinking blocks are omitted. Tool declarations (toolsAdded) are verbatim: parameters is the JSON Schema object, and built-in tools also carry constrainedSampling.

Points of interest:

  • The first system message declares every prompt section and the complete tool definitions.
  • The second system message is the diff: only the tools, rules, and addendum sections are repeated, get_time is in toolsAdded, and bash is in toolsRemoved. The unchanged preamble, docs, and cwd sections are not resent.
  • The model calls get_time on the very next request and follows the addendum.
{
  "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.

@mitsuhiko

Copy link
Copy Markdown
Member Author

AI generated (analysis by Claude, reviewed by the author)

Custom providers that hand-roll the payload lose the prompt and tools

The agent loop now streams { messages } only (packages/agent/src/agent-loop.ts:362); the system prompt and tool definitions travel inside role: "system" messages. Built-in providers are fine because they all go through normalizeContext(), which accepts both the old top-level systemPrompt/tools shorthand and the transcript form, and custom providers that delegate to a built-in stream function (checked: pi-llamacpp, pi-ds4, pi-radius, and the bundled custom-provider-gitlab-duo example) inherit that. Custom providers that build the wire request themselves from context.systemPrompt and context.tools break silently: Context still declares both fields as optional so nothing fails to type-check, but at runtime they send no instructions and no tool definitions, and their message converters meet an unknown system role (the bundled custom-provider-anthropic example drops it; other implementations may throw). The dispatch point is provider-composer.ts:470, where extension.streamSimple(model, context, ...) receives the raw transcript context.

Options

  1. Legacy shape at the extension boundary, opt-in for the transcript. In provider-composer.ts, before calling an extension's streamSimple, convert with collapseSystemMessages(normalizeContext(ctx)) and hand over { systemPrompt, tools, messages } with the system messages removed. Add a ProviderConfig flag (e.g. transcriptSystemMessages: true) for providers that want the raw transcript. Existing extensions keep the old semantics unchanged (one cache miss per prompt change). Cost: a delegating wrapper around a flagged model (e.g. pi-ds4 over openai-codex) loses in-place updates until it sets the flag, since the built-in provider downstream only sees the collapsed shape.

  2. No shim; migrate the example and document the break. Update custom-provider-anthropic to read getInitialSystemMessage()/getCurrentTools() (or collapse first), show the transcript-aware pattern in docs/custom-provider.md, and add Breaking Changes entries to the pi-ai and pi-coding-agent changelogs. The helpers are already exported from @earendil-works/pi-ai. Cost: third-party hand-rolled providers fail at runtime until updated, and the failure is quiet.

  3. Carry both in Context: top-level systemPrompt/tools derived from the transcript plus the system messages in messages. Not recommended: a legacy provider would send the top-level prompt and also push system messages through its converter, so it double-instructs or crashes, and normalizeContext() would need a precedence rule between the two sources.

@holny

holny commented Sep 15, 2026

Copy link
Copy Markdown

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:

  1. When a mid-conversation patch (say a sections swap) falls inside the region that gets summarized, does the compaction entry replay fold it back into the reconstructed leading message? system-message-replay.test.ts didn't show a case for a patch landing in the summarized region — might be worth one if the folding happens at replay time.

  2. For adapters without native mid-conversation system support (the mistral/kimi paths render later system messages as role:"system" regardless) — have you confirmed those APIs tolerate a system message after the first user turn, or does the collapse path always run first for them? If the collapse always runs, fine; if a raw system role can reach them, that looks like a 400 waiting to happen.

Otherwise the AgentState.systemPrompt removal reads clean, and the sdk.md migration coverage looks solid.

@badlogic

Copy link
Copy Markdown
Collaborator

There are still three blocking issues in packages/ai.

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

transformMessages() treats a system message like a new user turn and closes pending tool calls.

assistant: tool_call(read, id=1)
system: update tools/instructions
toolResult: actual result for id=1

becomes:

assistant: tool_call(read, id=1)
toolResult: "No result provided" for id=1
system: update
toolResult: actual result for id=1

Providers may reject the duplicate result or consume the synthetic failure. Anthropic explicitly requires the system message to come after the tool_result, not between tool_use and its result:

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 invalid

The adapter sends every declared tool as active at the top level, then emits tool_addition for later tools. For an initial read followed by a later write, the payload effectively says:

top-level active tools: read, write
later system block: add write

Anthropic specifies that every top-level tool is active immediately unless it has defer_loading: true. A later tool_addition must reference a previously declared deferred tool:

The implementation also needs safe fallback for:

  • no initially active tools;
  • tool removals;
  • replacing an existing tool's schema.

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 late

Even 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 tools come first in the cached request prefix, cache hits require an exact matching prefix, changing tool definitions invalidates the cache, and deferred loading exists to preserve that cache:

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 cache_control. It also cannot be used when there are no active tools because Anthropic rejects all-deferred inventories; that case needs the fallback described above.

The probes need to cover at minimum:

  1. tool_use -> system -> real tool_result, confirming no synthetic duplicate;
  2. initial active tool followed by a deferred late addition;
  3. empty initial inventory followed by an addition;
  4. removal and same-name schema replacement fallback;
  5. two cached requests with a late addition, checking cache_creation_input_tokens and cache_read_input_tokens rather than only request success.

This comment is AI-generated by /wr

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.
@mitsuhiko
mitsuhiko force-pushed the mid-conversation-system-messages branch from 24b9da1 to 4631761 Compare September 16, 2026 13:53
@mitsuhiko
mitsuhiko merged commit 9e05370 into main Sep 16, 2026
2 of 3 checks passed
@mitsuhiko
mitsuhiko deleted the mid-conversation-system-messages branch September 16, 2026 13:54
christianklotz added a commit that referenced this pull request Sep 16, 2026
…osed

* origin/main:
  Mid conversation system messages (#9548)

# Conflicts:
#	packages/coding-agent/src/core/extensions/runner.ts
Chesszyh pushed a commit to Chesszyh/pi that referenced this pull request Sep 17, 2026
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.
R-Dson added a commit to R-Dson/pi that referenced this pull request Sep 19, 2026
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.
NelsonLongxiang added a commit to NelsonLongxiang/pi that referenced this pull request Sep 23, 2026
…窄到 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>
dadezzz pushed a commit to dadezzz/forgejo-agent that referenced this pull request Sep 24, 2026
….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) | ![age](https://developer.mend.io/api/mc/badges/age/npm/@earendil-works%2fpi-coding-agent/0.86.1?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/@earendil-works%2fpi-coding-agent/0.85.1/0.86.1?slim=true) |

---

### Release Notes

<details>
<summary>earendil-works/pi (@&#8203;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 ([#&#8203;9096](earendil-works/pi#9096) by [@&#8203;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 ([#&#8203;9688](earendil-works/pi#9688)).
- Fixed inherited z.ai `Prompt too long` errors not being recognized as context overflow ([#&#8203;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 ([#&#8203;9804](earendil-works/pi#9804) by [@&#8203;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 }` ([#&#8203;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) ([#&#8203;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 ([#&#8203;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 ([#&#8203;8964](earendil-works/pi#8964)).
- Added per-model `reserveTokens` and `keepRecentTokens` settings through `compaction.modelOverrides`, with ordinary compaction settings as fallback ([#&#8203;8133](earendil-works/pi#8133)).
- Added `compat.allowedFallbackModels` configuration for overriding or disabling Anthropic server-side fallback models ([#&#8203;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 ([#&#8203;8967](earendil-works/pi#8967)).
- Exported extension hook event and result types that were previously omitted from the package entry points ([#&#8203;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) ([#&#8203;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 ([#&#8203;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 ([#&#8203;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 ([#&#8203;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 ([#&#8203;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 ([#&#8203;9253](earendil-works/pi#9253) by [@&#8203;petrroll](https://github.com/petrroll)).
- Fixed inherited DeepSeek V4.1 thinking levels on OpenRouter and OpenCode Go preserving provider effort metadata ([#&#8203;9485](earendil-works/pi#9485)).
- Fixed inherited bodyless HTTP 400/413 errors from non-Cerebras providers being misclassified as context overflow ([#&#8203;9482](earendil-works/pi#9482)).
- Fixed inherited Vercel AI Gateway replaying unsigned thinking as assistant text ([#&#8203;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 ([#&#8203;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 ([#&#8203;9188](earendil-works/pi#9188)).
- Fixed inherited Amazon Bedrock one-hour cache writes being priced at the five-minute rate ([#&#8203;9457](earendil-works/pi#9457)).
- Fixed inherited quadratic CPU usage when draining buffered `EventStream` events ([#&#8203;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` ([#&#8203;8700](earendil-works/pi#8700)).
- Fixed inherited OpenCode and OpenCode Go requests to send `x-opencode-session` from `sessionId` across all supported API adapters ([#&#8203;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 ([#&#8203;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 ([#&#8203;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 ([#&#8203;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 ([#&#8203;9423](earendil-works/pi#9423)).
- Fixed inherited Mistral-hosted GLM-5.2 reasoning requests to use `reasoning_effort` instead of the ignored `prompt_mode` ([#&#8203;9375](earendil-works/pi#9375)).
- Fixed inherited OpenAI-compatible Responses errors to identify the actual provider instead of always labeling them as OpenAI errors ([#&#8203;9298](earendil-works/pi#9298)).
- Fixed inherited Baseten requests to send session-affinity headers from `sessionId` for automatic prompt-cache routing ([#&#8203;9629](earendil-works/pi#9629)).
- Fixed inherited retry classification for Cloudflare 520 responses ([#&#8203;9627](earendil-works/pi#9627)).
- Fixed inherited retry classification for transient Azure peak-load capacity errors ([#&#8203;9669](earendil-works/pi#9669)).
- Fixed session tree navigation racing with active compaction and replacing its progress UI ([#&#8203;9179](earendil-works/pi#9179) by [@&#8203;acmerfight](https://github.com/acmerfight)).
- Fixed exact session ID lookup scanning complete transcript bodies instead of reading session headers ([#&#8203;9601](earendil-works/pi#9601) by [@&#8203;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 ([#&#8203;9391](earendil-works/pi#9391)).
- Fixed mid-run threshold compaction silently skipping oversized trailing tool results ([#&#8203;9740](earendil-works/pi#9740)).
- Fixed signal-terminated local shell commands being reported as successful with partial output ([#&#8203;9577](earendil-works/pi#9577) by [@&#8203;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 ([#&#8203;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 ([#&#8203;8826](earendil-works/pi#8826)).
- Fixed direct RPC `steer` and `follow_up` commands bypassing extension `input` handlers ([#&#8203;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 ([#&#8203;8919](earendil-works/pi#8919)).
- Fixed extension tools without parameter schemas to be rejected during registration instead of breaking provider requests ([#&#8203;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 ([#&#8203;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 ([#&#8203;9340](earendil-works/pi#9340), [#&#8203;9777](earendil-works/pi#9777)).
- Fixed asynchronous Kitty image conversion replacing newer partial tool output images ([#&#8203;8743](earendil-works/pi#8743) by [@&#8203;wutongyuonce](https://github.com/wutongyuonce)).
- Fixed inherited skill slash-command autocomplete ranking the `skill:` prefix instead of the bare skill name ([#&#8203;9120](earendil-works/pi#9120) by [@&#8203;yearth](https://github.com/yearth)).
- Fixed inherited file autocomplete boundaries and path quoting around CJK punctuation ([#&#8203;9746](earendil-works/pi#9746) by [@&#8203;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 ([#&#8203;8827](earendil-works/pi#8827), [#&#8203;9564](earendil-works/pi#9564), [#&#8203;7929](earendil-works/pi#7929)).
- Fixed inherited fullscreen Kitty images being erased by later row clears in WezTerm ([#&#8203;9169](earendil-works/pi#9169)).

##### Removed

- Removed unavailable inherited GPT-5.4 and GPT-5.4 mini models from OpenAI Codex selection ([#&#8203;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-->
oskarfreye pushed a commit to draht-dev/draht that referenced this pull request Oct 1, 2026
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>
esafak added a commit to esafak/pi-reviewer that referenced this pull request Oct 4, 2026
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.
jyn514 pushed a commit to jyn514/pi that referenced this pull request Oct 9, 2026
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.
blxzer77 added a commit to blxzer77/nyan-legacy that referenced this pull request Oct 12, 2026
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
badlogic pushed a commit that referenced this pull request Nov 4, 2026
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.
oskarfreye added a commit to draht-dev/draht that referenced this pull request Nov 4, 2026
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>
subimpact pushed a commit to subimpact/e that referenced this pull request Nov 7, 2026
…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)
luw2007 pushed a commit to luw2007/pi that referenced this pull request Nov 11, 2026
…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.
sherocktong pushed a commit to roam-agent/roam that referenced this pull request Nov 12, 2026
…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.
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.

3 participants