@bastani/atomic 0.9.18-alpha.4 → 0.9.18-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +8 -0
  3. package/dist/builtin/intercom/README.md +1 -1
  4. package/dist/builtin/intercom/index.bundle.mjs +13 -4
  5. package/dist/builtin/intercom/package.json +1 -1
  6. package/dist/builtin/mcp/package.json +1 -1
  7. package/dist/builtin/subagents/package.json +1 -1
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/builtin/workflows/package.json +1 -1
  10. package/dist/core/agent-session-runtime.js +2 -2
  11. package/dist/core/agent-session-runtime.js.map +1 -1
  12. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  13. package/dist/core/anthropic-thinking-guard.js +71 -5
  14. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  15. package/dist/core/extensions/provider-types.d.ts +2 -2
  16. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  17. package/dist/core/extensions/provider-types.js.map +1 -1
  18. package/dist/core/model-config.d.ts +9 -4
  19. package/dist/core/model-config.d.ts.map +1 -1
  20. package/dist/core/model-config.js +3 -2
  21. package/dist/core/model-config.js.map +1 -1
  22. package/dist/core/provider-composer-internal.d.ts +1 -1
  23. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  24. package/dist/core/provider-composer-internal.js.map +1 -1
  25. package/dist/core/sdk.d.ts.map +1 -1
  26. package/dist/core/sdk.js +3 -0
  27. package/dist/core/sdk.js.map +1 -1
  28. package/dist/core/tools/bash.d.ts.map +1 -1
  29. package/dist/core/tools/bash.js +10 -7
  30. package/dist/core/tools/bash.js.map +1 -1
  31. package/dist/core/tools/edit.d.ts.map +1 -1
  32. package/dist/core/tools/edit.js +25 -5
  33. package/dist/core/tools/edit.js.map +1 -1
  34. package/dist/core/tools/find.d.ts.map +1 -1
  35. package/dist/core/tools/find.js +9 -8
  36. package/dist/core/tools/find.js.map +1 -1
  37. package/dist/core/tools/grep.d.ts.map +1 -1
  38. package/dist/core/tools/grep.js +4 -3
  39. package/dist/core/tools/grep.js.map +1 -1
  40. package/dist/core/tools/ls.d.ts.map +1 -1
  41. package/dist/core/tools/ls.js +2 -2
  42. package/dist/core/tools/ls.js.map +1 -1
  43. package/dist/core/tools/read.d.ts.map +1 -1
  44. package/dist/core/tools/read.js +12 -11
  45. package/dist/core/tools/read.js.map +1 -1
  46. package/dist/core/tools/search.d.ts.map +1 -1
  47. package/dist/core/tools/search.js +20 -19
  48. package/dist/core/tools/search.js.map +1 -1
  49. package/dist/core/tools/write.d.ts.map +1 -1
  50. package/dist/core/tools/write.js +19 -18
  51. package/dist/core/tools/write.js.map +1 -1
  52. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  53. package/dist/modes/interactive/components/model-selector.js +6 -14
  54. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  55. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  56. package/dist/modes/interactive/components/scoped-models-selector.js +13 -15
  57. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  58. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  59. package/dist/modes/interactive/components/settings-selector-items.js +9 -4
  60. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  61. package/dist/modes/interactive/components/settings-selector-submenus.d.ts +1 -1
  62. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  63. package/dist/modes/interactive/components/settings-selector-submenus.js +10 -7
  64. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  65. package/dist/modes/interactive/components/thinking-selector.js +2 -2
  66. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  67. package/dist/modes/interactive/components/trust-selector.js +2 -2
  68. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  69. package/docs/compaction.md +2 -0
  70. package/docs/custom-provider.md +2 -1
  71. package/docs/extensions.md +2 -0
  72. package/docs/intercom.md +1 -1
  73. package/docs/models/model-selection.md +9 -1
  74. package/docs/models/pareto-efficiency.md +2 -1
  75. package/docs/models.md +43 -0
  76. package/docs/terminal-setup.md +15 -0
  77. package/npm-shrinkwrap.json +32 -32
  78. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.18-alpha.5] - 2026-09-01
6
+
7
+ ### Added
8
+
9
+ - Documented the Zed integrated-terminal `keymap.json` bindings that make Zed emit the Kitty-protocol sequences Atomic reads for `Shift+Enter` and friends ([#8828](https://github.com/earendil-works/pi/pull/8828)).
10
+ - Claude Fable 5.1 (`claude-fable-5-1`) is now selectable in Atomic on the providers it has a Claude runtime integration for — currently Anthropic, Amazon Bedrock, OpenRouter, and the Vercel AI Gateway, with a provider "latest" alias such as OpenRouter's `~anthropic/claude-fable-latest` also routing to it. It offers a 1M-token context window, 128K maximum output, always-on adaptive thinking at exactly `low`, `medium`, `high`, `xhigh`, or `max`, and a $0.25 per million cache read against Claude Fable 5's $1.00. Published catalogs also list the model on Google Vertex and Azure, which Atomic does not generate. Run `--list-models` for the current set; provider catalogs change independently of Atomic releases.
11
+
12
+ ### Changed
13
+
14
+ - Changed selectors in `/thinking`, `/model`, `/scoped-models`, `/trust`, per-model thinking settings, and theme settings to keep active options marked while browsing. `/scoped-models` now uses consistent per-item toggles and strikes through unavailable models ([#8900](https://github.com/earendil-works/pi/pull/8900), [#8950](https://github.com/earendil-works/pi/pull/8950)).
15
+ - The bundled model-selection and Pareto-efficiency reference pages now state that Claude Fable 5.1 is unmeasured in Atomic's August 26, 2026 DeepSWE snapshot, because the model was released after it. They record the model's source-backed limits, effort levels, and pricing, and state explicitly that Claude Fable 5's benchmark row must not be read as a Fable 5.1 result. Builtin agent and workflow model defaults are unchanged.
16
+ - Claude models on Anthropic and Amazon Bedrock now accept PDF input. Anthropic documents PDF as a platform capability handled through the same vision path as images, so Atomic enables it wherever it has a runtime that can serialize a document block — the Anthropic Messages and Bedrock Converse paths — and leaves every other Claude mirror at text and images. A PDF sent to a model without support is replaced by a visible placeholder instead of being dropped. Bedrock needs citations enabled for full visual understanding; without them it falls back to text extraction. Note that no interactive Atomic session produces a document block yet, so this is currently reachable through the bundled `@bastani/pi-ai` library.
17
+ - The compaction documentation now states that client-side `preserve_recent` compaction intentionally resets the signed reasoning chain: because the protected tail is serialized into the boundary message rather than replayed as structured messages, no thinking block crosses a boundary, while the tail's text, tool calls, and tool results cross losslessly.
18
+
19
+ ### Fixed
20
+
21
+ - Fixed forking an in-memory (`--no-session`) session while a tool call was still running appending the aborted turn to the replacement session. The active turn is now settled before the fork ([#8937](https://github.com/earendil-works/pi/pull/8937)).
22
+ - The built-in `read`, `write`, `edit`, `search`, `find`, `ls`, `bash`, and `powershell` tools now resolve relative paths against `ctx.cwd` when an extension supplies one, instead of the cwd captured when the tool was created ([#8627](https://github.com/earendil-works/pi/pull/8627)). Atomic's `search` wrapper has no upstream counterpart; without this it returned content from the extension cwd while stamping hashline tags from the tool's original cwd, so a search result could not be edited.
23
+ - Custom provider model configs accept a `supportsMaxOutputTokens` compat flag, so openai-responses gateways that reject `max_output_tokens` can opt out ([#8941](https://github.com/earendil-works/pi/pull/8941)).
24
+ - Fixed Claude Fable 5.1 sessions breaking on a mid-conversation model switch or a mid-session prefix change. Anthropic ties each thinking block to the model that produced it and, on Claude Fable 5.1, to the conversation it was produced in, and enforces the second check by default for organizations created on or after August 31, 2026. Atomic now sends the block-binding beta with `prefix_mismatch_behavior: "drop_block"` for that model on every request, including turns with no reasoning level, so a changed system prompt, a tool-set change, or a model switch drops the affected reasoning and still answers the turn instead of failing with a 400. Switching between first-party Anthropic models also keeps reasoning the target model is allowed to read — switching up to Claude Fable 5.1 preserves it, switching down has the API drop it — while assistant text, tool calls, and tool results survive the switch intact. Claude on Amazon Bedrock, Google Vertex, and Anthropic-compatible proxies is unchanged, including opencode zen and the Vercel AI Gateway; see [Preserved thinking and model switches](https://atomic.bastani.dev/models#preserved-thinking-and-model-switches).
25
+ - Fixed forced tool use reaching Claude Fable 5.1, which rejects it on every request whichever platform serves it. Atomic's agent loop only ever asks for `auto` or `none`, so no interactive session was affected, but the bundled `@bastani/pi-ai` library's Anthropic, Amazon Bedrock, and OpenAI-completions entry points all accept the wider tool-choice shape. Such a request now fails with an error naming the model and the remedy, rather than being sent or silently rewritten to `auto`. Through a gateway the old behavior was quieter and worse: OpenRouter drops parameters a model does not support, so the forced choice disappeared and the answer looked normal. On the OpenAI-completions path the check covers all four of OpenAI's forcing shapes, including a named `custom` tool and `allowed_tools` with `mode: "required"`; `allowed_tools` with `mode: "auto"` narrows the candidate set rather than forcing a call and is left alone. The guard matches the versioned Claude Fable 5.1 model id, so it covers whichever mirrors a provider currently publishes. Claude Fable 5 accepts forced tool use and is untouched, and an unversioned "latest" alias is not covered because its target cannot be known from its id.
26
+ - Fixed Claude Fable 5 and Claude Fable 5.1 sending `temperature` when used through Amazon Bedrock, OpenRouter, or GitHub Copilot. The Anthropic path already omitted it, but the Bedrock Converse and OpenAI-completions request builders emitted the field for every model, so every Claude Fable mirror on those providers sent a parameter the model rejects — including the OpenRouter "latest" alias. All Claude Fable entries on those APIs now omit it, matching what the Anthropic path already did. Models outside that family are unchanged.
27
+ - Fixed Claude Fable 5.1 offering a `minimal` thinking level in `/model` and `--list-models` that Anthropic does not publish for it. The model now offers exactly the five documented efforts.
28
+ - Fixed a model's `samplingParams` reopening sampling fields it rejects. Custom sampling keys are merged last so they can override Atomic's named fields, which meant `temperature`, `top_p`, or `top_k` set that way still reached a model that returns an error for them. Those three keys are now dropped for such models, including when they come from a model-level default. Every other custom key still overrides as before.
29
+ - Fixed a server-side fallback losing track of which model answered, and undercounting its cost. When Claude Fable 5.1 declines partway through a response and Anthropic retries on Claude Opus 4.8 or Opus 5 within the same stream, the handoff marker was discarded, the reply stayed labelled as Fable 5.1, and the turn was costed at Fable 5.1's rates rather than at those of the model that produced it. Atomic now records the marker, reports the serving model, prices the turn correctly, and also bills the earlier attempt when it produced output before declining — Anthropic charges that separately and Atomic was reporting it as free. Continuing the conversation follows Anthropic's replay rules, so a follow-up turn is not rejected for echoing reasoning from both sides of the handoff.
30
+ - Fixed a forced tool choice being ignored rather than rejected on Amazon Bedrock when the request carried no tools. The validation ran after an early return, so the instruction was discarded in silence; it now runs first.
31
+ - Fixed Atomic silently giving up on restoring exact Anthropic reasoning bytes for two kinds of turn it had not been taught about. Atomic re-inserts a replayed thinking block's original bytes after the provider payload is built, and verifies the message shape first so it can never splice reasoning into the wrong turn. That verification did not know that a model which delegates thinking-block binding replays another Claude model's signed reasoning even when its text is empty — Claude Fable 5.1's default, since its thinking display is `"omitted"` — nor that a server-side fallback marker is now sent on the wire. Either one made the check abandon repair for the whole request. No incorrect bytes were ever sent; the repair simply stopped running. Both shapes are now recognized, reasoning and unexecuted tool calls from before a fallback boundary stay dropped as Anthropic requires, and a genuinely mismatched turn is still left untouched.
32
+
33
+
5
34
  ## [0.9.18-alpha.4] - 2026-09-01
6
35
 
7
36
  ### Changed
@@ -4,6 +4,14 @@ All notable changes to the `pi-intercom` extension will be documented in this fi
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.18-alpha.5] - 2026-09-01
8
+
9
+ ### Fixed
10
+
11
+ - A failed background reconnect no longer strands a live Intercom session. The next attempt is now scheduled after reconnect ownership is released, so a session whose broker restarts recovers on its own with bounded backoff instead of staying invisible until the next explicit Intercom call. A failing explicit `intercom` or overlay connection now leaves the same background retry behind rather than cancelling the one already scheduled, and a connection attempt that fails before it suspends can no longer park a settled promise in the reconnect slot and block every later attempt.
12
+ - Running workflow stages regain `intercom list` visibility and live routing on both their `<runId>:<stageName>` and `<runId>:<stageId>` targets after broker churn, instead of returning `Session not found` until something forced the stage session to reconnect.
13
+ - A reconnect that fails *after* the broker accepted the connection now closes that connection before the next attempt is scheduled. Previously the failed client stayed registered, so each retry added another entry for the same session: `intercom list` showed duplicates, and a send addressed to one of the stale entries was reported as delivered while the session never received it.
14
+
7
15
  ## [0.9.18-alpha.3] - 2026-09-01
8
16
 
9
17
  ### Fixed
@@ -451,7 +451,7 @@ graph TB
451
451
  B2 <-->|Local Socket/Pipe| B3
452
452
  ```
453
453
 
454
- The broker is a standalone TypeScript process that manages session registration and message routing. It auto-spawns when the first session that invokes Intercom needs it and exits after 5 seconds when it last has no registered sessions, including brokers that never received a connection and sockets that close before register. Clients now reconnect automatically if the broker disappears and later comes back.
454
+ The broker is a standalone TypeScript process that manages session registration and message routing. It auto-spawns when the first session that invokes Intercom needs it and exits after 5 seconds when it last has no registered sessions, including brokers that never received a connection and sockets that close before register. Clients reconnect automatically if the broker disappears and later comes back. A failed reconnect schedules the next attempt on a bounded backoff (1s, 2s, 5s, 10s, then 30s) once it releases reconnect ownership, so a transient failure never leaves a live session with nothing owning recovery; a failed explicit tool or overlay connection still returns its error to the caller and leaves the retry behind. A reconnect that fails after the broker already accepted it closes that connection first, so a session never appears twice in `intercom list`.
455
455
 
456
456
  Messages use length-prefixed JSON over a local socket/pipe transport (4-byte length + JSON payload) to handle fragmentation properly. The protocol includes request correlation for session listing, explicit delivery failures, and validation for malformed or out-of-order messages.
457
457
 
@@ -5424,7 +5424,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
5424
5424
  nextClient.on("error", () => {});
5425
5425
  }
5426
5426
  function scheduleReconnect() {
5427
- if (disposed || shuttingDown || reconnectTimer || reconnectPromise || !getLiveContext()) {
5427
+ if (disposed || shuttingDown || reconnectTimer || reconnectPromise || client?.isConnected() || !getLiveContext()) {
5428
5428
  return;
5429
5429
  }
5430
5430
  const scheduledGeneration = runtimeGeneration;
@@ -5584,12 +5584,16 @@ function piIntercomExtension(pi, testOverrides = {}) {
5584
5584
  if (reconnectPromise && reconnectPromiseGeneration === generationAtStart) {
5585
5585
  return reconnectPromise;
5586
5586
  }
5587
+ const ownershipRecorded = Promise.withResolvers();
5587
5588
  const nextReconnectPromise = (async () => {
5589
+ let connectFailed = false;
5590
+ await ownershipRecorded.promise;
5588
5591
  const nextClient = new IntercomClient(currentSessionId);
5589
5592
  const registration = buildRegistration();
5590
5593
  client = nextClient;
5591
5594
  attachClientHandlers(nextClient);
5592
5595
  try {
5596
+ await testOverrides.beforeConnectAttempt?.(reason);
5593
5597
  await spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs);
5594
5598
  const childMetadata = currentChildOrchestratorMetadata();
5595
5599
  await nextClient.connect(registration, childMetadata?.supervisor, supervisorAuthorizations.ownerToken, readSubagentMessageSource(runtimeContext?.subagentPolicy));
@@ -5617,19 +5621,24 @@ function piIntercomExtension(pi, testOverrides = {}) {
5617
5621
  client = null;
5618
5622
  clientRegistrationGroup = null;
5619
5623
  }
5620
- if (reason === "background" && getLiveContext(contextAtStart, generationAtStart)) {
5621
- scheduleReconnect();
5622
- }
5624
+ connectFailed = true;
5625
+ try {
5626
+ await nextClient.disconnect();
5627
+ } catch {}
5623
5628
  throw toError3(error);
5624
5629
  } finally {
5625
5630
  if (reconnectPromiseGeneration === generationAtStart) {
5626
5631
  reconnectPromise = null;
5627
5632
  reconnectPromiseGeneration = null;
5628
5633
  }
5634
+ if (connectFailed && getLiveContext(contextAtStart, generationAtStart)) {
5635
+ scheduleReconnect();
5636
+ }
5629
5637
  }
5630
5638
  })();
5631
5639
  reconnectPromise = nextReconnectPromise;
5632
5640
  reconnectPromiseGeneration = generationAtStart;
5641
+ ownershipRecorded.resolve();
5633
5642
  return nextReconnectPromise;
5634
5643
  }
5635
5644
  pi.events.on(PENDING_STAGE_ROUTE_EVENT, (payload) => {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/intercom",
3
- "version": "0.9.18-alpha.4",
3
+ "version": "0.9.18-alpha.5",
4
4
  "private": true,
5
5
  "description": "Atomic extension providing a private coordination channel between parent and child agent sessions. Fork of: https://github.com/nicobailon/pi-intercom",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/mcp",
3
- "version": "0.9.18-alpha.4",
3
+ "version": "0.9.18-alpha.5",
4
4
  "private": true,
5
5
  "description": "Atomic extension that adapts MCP (Model Context Protocol) servers into the coding agent. Fork of: https://github.com/nicobailon/pi-mcp-adapter",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/subagents",
3
- "version": "0.9.18-alpha.4",
3
+ "version": "0.9.18-alpha.5",
4
4
  "private": true,
5
5
  "description": "Atomic extension for delegating tasks to subagents with parallel execution. Fork of: https://github.com/nicobailon/pi-subagents",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/web-access",
3
- "version": "0.9.18-alpha.4",
3
+ "version": "0.9.18-alpha.5",
4
4
  "private": true,
5
5
  "description": "Atomic extension for web search, URL fetching, GitHub repo cloning, PDF/video extraction. Fork of: https://github.com/nicobailon/pi-web-access",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/workflows",
3
- "version": "0.9.18-alpha.4",
3
+ "version": "0.9.18-alpha.5",
4
4
  "private": true,
5
5
  "description": "Atomic extension for multi-stage workflow authoring and execution.",
6
6
  "contributors": [
@@ -276,13 +276,13 @@ export class AgentSessionRuntime {
276
276
  return { cancelled: false, selectedText };
277
277
  }
278
278
  const sessionManager = this.session.sessionManager;
279
+ await this.teardownCurrent("fork", sessionManager.getSessionFile());
279
280
  if (!targetLeafId) {
280
- sessionManager.newSession({ parentSession: this.session.sessionFile });
281
+ sessionManager.newSession({ parentSession: previousSessionFile });
281
282
  }
282
283
  else {
283
284
  sessionManager.createBranchedSession(targetLeafId);
284
285
  }
285
- await this.teardownCurrent("fork", sessionManager.getSessionFile());
286
286
  this.apply(await this.createRuntime({
287
287
  cwd: this.cwd,
288
288
  agentDir: this.services.agentDir,
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names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,KAAK,UAAU,yBAAyB,CAC9C,aAA+C,EAC/C,OAKC;IAED,sBAAsB,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,IAAI,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,EAC3B,MAAM,CAAC,mBAAmB,CAC1B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { type Api, type Model, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionInternalSurface } from \"./agent-session-methods.ts\";\nimport { prepareProtectedStreamingCustomMessagesForDisposal } from \"./agent-session-persistent-custom-messages.ts\";\nimport { type AtomicOAuthLoginCallbacks, loginRuntimeOAuthProvider } from \"./agent-session-runtime-auth.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nimport type { AuthStatus } from \"./provider-composer.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nexport interface LogoutProviderResult {\n\tprovider: string;\n\tauthStatus: AuthStatus;\n\tmodels: Model<Api>[];\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\n\tprivate declare _session: AgentSession;\n\tprivate declare _services: AgentSessionServices;\n\tprivate declare readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tprivate declare _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tprivate declare _modelFallbackMessage?: string;\n\tprivate declare _modelFallbackReason?: ModelFallbackReason;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t\t_modelFallbackReason?: ModelFallbackReason,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t\tthis._modelFallbackReason = _modelFallbackReason;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tget modelFallbackReason(): ModelFallbackReason | undefined {\n\t\treturn this._modelFallbackReason;\n\t}\n\n\treplaceModelFallback(message?: string, reason?: ModelFallbackReason): void {\n\t\tthis._modelFallbackMessage = message;\n\t\tthis._modelFallbackReason = reason;\n\t}\n\n\tresolveModelFallback(): void {\n\t\tthis.replaceModelFallback();\n\t}\n\n\tresolveModelFallbackAfterExplicitModelSelection(\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tselectedModel: Model<Api> | null | undefined,\n\t): void {\n\t\tif (selectedModel && !modelsAreEqual(previousModel, selectedModel)) this.resolveModelFallback();\n\t}\n\n\tasync loginOAuthProvider(\n\t\tprovider: string,\n\t\tcallbacks: AtomicOAuthLoginCallbacks,\n\t): Promise<{ modelsRefreshed: boolean }> {\n\t\tawait loginRuntimeOAuthProvider(this.session, provider, callbacks);\n\t\treturn { modelsRefreshed: true };\n\t}\n\n\tasync logoutProvider(provider: string): Promise<LogoutProviderResult> {\n\t\tconst registry = this.session.modelRuntime;\n\t\tawait registry.logout(provider);\n\t\tconst availableIds = new Set(registry.getAvailableSnapshot().map((model) => `${model.provider}\\0${model.id}`));\n\t\tconst scopedModels = this.session.scopedModels.filter(({ model }) =>\n\t\t\tavailableIds.has(`${model.provider}\\0${model.id}`),\n\t\t);\n\t\tthis.session.setScopedModels([...scopedModels]);\n\t\tthis.session.refreshCurrentModelFromRegistry();\n\t\treturn {\n\t\t\tprovider,\n\t\t\tauthStatus: registry.getProviderAuthStatus(provider),\n\t\t\tmodels: [...registry.getAvailableSnapshot()],\n\t\t\tscopedModels: [...scopedModels],\n\t\t};\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate disposeCurrentSession(): void {\n\t\tprepareProtectedStreamingCustomMessagesForDisposal(this.session as unknown as AgentSessionInternalSurface);\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n\n\t/**\n\t * Settle an active response before the session it belongs to is replaced, so the\n\t * aborted turn (including its tool results) is persisted to the outgoing session\n\t * rather than stranded.\n\t *\n\t * Overridable because the isolated engine must not re-enter its cooperative\n\t * abort wait here: the child engine settles its own turn before it reports the\n\t * replacement, and the host facade's `abort()` is an unbounded round trip that\n\t * would hang teardown on an unresponsive or dead engine.\n\t */\n\tprotected async settleActiveResponseBeforeTeardown(): Promise<void> {\n\t\tif (!this.session.isStreaming) return;\n\t\tawait this.session.abort();\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\tawait this.settleActiveResponseBeforeTeardown();\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.disposeCurrentSession();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t\tthis._modelFallbackReason = result.modelFallbackReason;\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t\tprojectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\tif (options?.parentSession) {\n\t\t\tsessionManager.newSession({ parentSession: options.parentSession });\n\t\t}\n\n\t\tawait this.teardownCurrent(\"new\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"new\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.agent.state.messages = this.session.sessionManager.buildSessionContext().messages;\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\t\t\tsessionManager.newSession({ parentSession: currentSessionFile });\n\t\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\t\tthis.apply(\n\t\t\t\t\tawait this.createRuntime({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\t\tsessionManager,\n\t\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This session has not been saved yet. Wait for the first assistant response before cloning or forking it.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\tif (!forkedSessionPath) {\n\t\t\t\tthrow new Error(\"Failed to create forked session\");\n\t\t\t}\n\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t}),\n\t\t\t);\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: this.session.sessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tconst destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (resolve(destinationPath) !== resolvedPath) {\n\t\t\tcopyFileSync(resolvedPath, destinationPath);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.disposeCurrentSession();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t\tresult.modelFallbackReason,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\n"]}
1
+ {"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAwB,cA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I,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,EAC3B,MAAM,CAAC,mBAAmB,CAC1B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { type Api, type Model, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionInternalSurface } from \"./agent-session-methods.ts\";\nimport { prepareProtectedStreamingCustomMessagesForDisposal } from \"./agent-session-persistent-custom-messages.ts\";\nimport { type AtomicOAuthLoginCallbacks, loginRuntimeOAuthProvider } from \"./agent-session-runtime-auth.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nimport type { AuthStatus } from \"./provider-composer.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nexport interface LogoutProviderResult {\n\tprovider: string;\n\tauthStatus: AuthStatus;\n\tmodels: Model<Api>[];\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\n\tprivate declare _session: AgentSession;\n\tprivate declare _services: AgentSessionServices;\n\tprivate declare readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tprivate declare _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tprivate declare _modelFallbackMessage?: string;\n\tprivate declare _modelFallbackReason?: ModelFallbackReason;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t\t_modelFallbackReason?: ModelFallbackReason,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t\tthis._modelFallbackReason = _modelFallbackReason;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tget modelFallbackReason(): ModelFallbackReason | undefined {\n\t\treturn this._modelFallbackReason;\n\t}\n\n\treplaceModelFallback(message?: string, reason?: ModelFallbackReason): void {\n\t\tthis._modelFallbackMessage = message;\n\t\tthis._modelFallbackReason = reason;\n\t}\n\n\tresolveModelFallback(): void {\n\t\tthis.replaceModelFallback();\n\t}\n\n\tresolveModelFallbackAfterExplicitModelSelection(\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tselectedModel: Model<Api> | null | undefined,\n\t): void {\n\t\tif (selectedModel && !modelsAreEqual(previousModel, selectedModel)) this.resolveModelFallback();\n\t}\n\n\tasync loginOAuthProvider(\n\t\tprovider: string,\n\t\tcallbacks: AtomicOAuthLoginCallbacks,\n\t): Promise<{ modelsRefreshed: boolean }> {\n\t\tawait loginRuntimeOAuthProvider(this.session, provider, callbacks);\n\t\treturn { modelsRefreshed: true };\n\t}\n\n\tasync logoutProvider(provider: string): Promise<LogoutProviderResult> {\n\t\tconst registry = this.session.modelRuntime;\n\t\tawait registry.logout(provider);\n\t\tconst availableIds = new Set(registry.getAvailableSnapshot().map((model) => `${model.provider}\\0${model.id}`));\n\t\tconst scopedModels = this.session.scopedModels.filter(({ model }) =>\n\t\t\tavailableIds.has(`${model.provider}\\0${model.id}`),\n\t\t);\n\t\tthis.session.setScopedModels([...scopedModels]);\n\t\tthis.session.refreshCurrentModelFromRegistry();\n\t\treturn {\n\t\t\tprovider,\n\t\t\tauthStatus: registry.getProviderAuthStatus(provider),\n\t\t\tmodels: [...registry.getAvailableSnapshot()],\n\t\t\tscopedModels: [...scopedModels],\n\t\t};\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate disposeCurrentSession(): void {\n\t\tprepareProtectedStreamingCustomMessagesForDisposal(this.session as unknown as AgentSessionInternalSurface);\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n\n\t/**\n\t * Settle an active response before the session it belongs to is replaced, so the\n\t * aborted turn (including its tool results) is persisted to the outgoing session\n\t * rather than stranded.\n\t *\n\t * Overridable because the isolated engine must not re-enter its cooperative\n\t * abort wait here: the child engine settles its own turn before it reports the\n\t * replacement, and the host facade's `abort()` is an unbounded round trip that\n\t * would hang teardown on an unresponsive or dead engine.\n\t */\n\tprotected async settleActiveResponseBeforeTeardown(): Promise<void> {\n\t\tif (!this.session.isStreaming) return;\n\t\tawait this.session.abort();\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\tawait this.settleActiveResponseBeforeTeardown();\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.disposeCurrentSession();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t\tthis._modelFallbackReason = result.modelFallbackReason;\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t\tprojectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\tif (options?.parentSession) {\n\t\t\tsessionManager.newSession({ parentSession: options.parentSession });\n\t\t}\n\n\t\tawait this.teardownCurrent(\"new\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"new\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.agent.state.messages = this.session.sessionManager.buildSessionContext().messages;\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\t\t\tsessionManager.newSession({ parentSession: currentSessionFile });\n\t\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\t\tthis.apply(\n\t\t\t\t\tawait this.createRuntime({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\t\tsessionManager,\n\t\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This session has not been saved yet. Wait for the first assistant response before cloning or forking it.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\tif (!forkedSessionPath) {\n\t\t\t\tthrow new Error(\"Failed to create forked session\");\n\t\t\t}\n\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t}),\n\t\t\t);\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: previousSessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tconst destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (resolve(destinationPath) !== resolvedPath) {\n\t\t\tcopyFileSync(resolvedPath, destinationPath);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.disposeCurrentSession();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t\tresult.modelFallbackReason,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-thinking-guard.d.ts","sourceRoot":"","sources":["../../src/core/anthropic-thinking-guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAmMnF;;;;;;;;;;;GAWG;AACH,wBAAgB,oCAAoC,CACnD,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,SAAS,OAAO,EAAE,EAClC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GACf,OAAO,CA+CT"}
1
+ {"version":3,"file":"anthropic-thinking-guard.d.ts","sourceRoot":"","sources":["../../src/core/anthropic-thinking-guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAoQnF;;;;;;;;;;;GAWG;AACH,wBAAgB,oCAAoC,CACnD,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,SAAS,OAAO,EAAE,EAClC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GACf,OAAO,CA+CT"}
@@ -12,6 +12,38 @@ function isThinkingLikeAnthropicBlock(value) {
12
12
  function isSameModelAssistant(message, model) {
13
13
  return message.provider === model.provider && message.api === model.api && message.model === model.id;
14
14
  }
15
+ /**
16
+ * Mirrors `canReplayForeignThinking` in @bastani/pi-ai's `transformMessages`: a *different* model
17
+ * on the same provider and API whose API adjudicates thinking model binding itself. Its signed
18
+ * blocks replay unchanged — including redacted ones and signed blocks whose text is empty, which
19
+ * is Claude Fable 5.1's default shape because `thinking.display` defaults to `"omitted"`.
20
+ *
21
+ * This must stay conditional. For a model that does not delegate binding, pi-ai still drops or
22
+ * flattens foreign thinking, so accepting signature-only blocks unconditionally would misalign
23
+ * the ordinals in the opposite direction.
24
+ */
25
+ function delegatesForeignThinkingBinding(message, model) {
26
+ if (message.provider !== model.provider || message.api !== model.api)
27
+ return false;
28
+ return isObject(model.compat) && model.compat.delegatesThinkingModelBinding === true;
29
+ }
30
+ /**
31
+ * Index of the last server-side fallback marker, or -1.
32
+ *
33
+ * pi-ai drops `thinking`, `redacted_thinking`, and client-side `tool_use` that precede the final
34
+ * marker, because "a request that echoes thinking blocks from both sides of the boundary is
35
+ * rejected". Both the alignment check and the repair pass must apply the same rule, or repair
36
+ * would splice pre-boundary thinking back into a request the API rejects.
37
+ * https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
38
+ */
39
+ function finalFallbackBoundaryIndex(content) {
40
+ for (let index = content.length - 1; index >= 0; index -= 1) {
41
+ const block = content[index];
42
+ if (isObject(block) && block.type === "fallback")
43
+ return index;
44
+ }
45
+ return -1;
46
+ }
15
47
  function readReplayThinkingBlock(block, allowEmptySignature = false) {
16
48
  if (!isObject(block) || typeof block.type !== "string")
17
49
  return undefined;
@@ -60,7 +92,12 @@ function legacyProviderWouldEmitAssistant(message, model) {
60
92
  // This mirrors the relevant same-model branch in @bastani/pi-ai's
61
93
  // transformMessages() + Anthropic convertMessages() pipeline closely enough
62
94
  // to keep assistant ordinal mapping aligned with the provider payload.
63
- if (isSameModelAssistant(message, model)) {
95
+ //
96
+ // A cross-model turn on a model that delegates binding follows the *same* rule: pi-ai replays
97
+ // its foreign signed thinking unchanged, so a redacted or empty-text signed block is emitted
98
+ // there too. Without this branch, a Fable 5.1 turn whose thinking display is `"omitted"` looks
99
+ // non-emitting here, the ordinals desynchronise, and repair is abandoned for the whole request.
100
+ if (isSameModelAssistant(message, model) || delegatesForeignThinkingBinding(message, model)) {
64
101
  return message.content.some((block) => legacyProviderWouldEmitAssistantBlock(block));
65
102
  }
66
103
  return message.content.some((block) => {
@@ -95,12 +132,21 @@ function takeProviderBlock(providerBlocks, providerIndex, expectedType) {
95
132
  return { block: undefined, nextProviderIndex: providerIndex };
96
133
  }
97
134
  function nonThinkingBlocksAlign(message, providerBlocks) {
98
- const sourceTypes = message.content.flatMap((block) => {
135
+ const boundaryIndex = finalFallbackBoundaryIndex(message.content);
136
+ const sourceTypes = message.content.flatMap((block, index) => {
99
137
  if (!isObject(block) || typeof block.type !== "string")
100
138
  return [];
101
139
  if (block.type === "text")
102
140
  return typeof block.text === "string" && block.text.trim().length > 0 ? ["text"] : [];
103
- return block.type === "toolCall" ? ["tool_use"] : [];
141
+ // The marker is replayed in place and is not thinking-like, so it survives the provider-side
142
+ // filter below and both sides must count it.
143
+ if (block.type === "fallback")
144
+ return ["fallback"];
145
+ if (block.type !== "toolCall")
146
+ return [];
147
+ // A client-side tool call before the final marker was never executed by the model that
148
+ // continued the turn, so pi-ai drops it along with its tool result.
149
+ return boundaryIndex >= 0 && index < boundaryIndex ? [] : ["tool_use"];
104
150
  });
105
151
  const providerTypes = providerBlocks
106
152
  .filter((block) => !isThinkingLikeAnthropicBlock(block))
@@ -110,8 +156,14 @@ function nonThinkingBlocksAlign(message, providerBlocks) {
110
156
  function repairAssistantContent(originalMessage, providerBlocks, allowEmptySignature) {
111
157
  const repaired = [];
112
158
  let providerIndex = 0;
113
- for (const originalBlock of originalMessage.content) {
114
- const replayBlock = readReplayThinkingBlock(originalBlock, allowEmptySignature);
159
+ // `fallbackTextBlock`/`fallbackToolUseBlock` below mean "fallback value"; `boundaryIndex` is the
160
+ // unrelated Anthropic server-side fallback marker.
161
+ const boundaryIndex = finalFallbackBoundaryIndex(originalMessage.content);
162
+ for (const [index, originalBlock] of originalMessage.content.entries()) {
163
+ const precedesBoundary = boundaryIndex >= 0 && index < boundaryIndex;
164
+ // Thinking before the final marker is not in the payload and must not be restored into it:
165
+ // echoing thinking from both sides of the boundary is rejected outright.
166
+ const replayBlock = precedesBoundary ? undefined : readReplayThinkingBlock(originalBlock, allowEmptySignature);
115
167
  if (replayBlock) {
116
168
  if (isThinkingLikeAnthropicBlock(providerBlocks[providerIndex])) {
117
169
  providerIndex += 1;
@@ -121,6 +173,16 @@ function repairAssistantContent(originalMessage, providerBlocks, allowEmptySigna
121
173
  }
122
174
  if (!isObject(originalBlock) || typeof originalBlock.type !== "string")
123
175
  continue;
176
+ if (originalBlock.type === "fallback") {
177
+ // Replayed in place, straight from the payload: this guard only restores thinking, and
178
+ // the marker's position is what the API validates the surrounding thinking against.
179
+ const providerMarker = takeProviderBlock(providerBlocks, providerIndex, "fallback");
180
+ if (providerMarker.block) {
181
+ repaired.push(providerMarker.block);
182
+ providerIndex = providerMarker.nextProviderIndex;
183
+ }
184
+ continue;
185
+ }
124
186
  if (originalBlock.type === "text") {
125
187
  const providerText = takeProviderBlock(providerBlocks, providerIndex, "text");
126
188
  if (providerText.block) {
@@ -134,6 +196,10 @@ function repairAssistantContent(originalMessage, providerBlocks, allowEmptySigna
134
196
  continue;
135
197
  }
136
198
  if (originalBlock.type === "toolCall") {
199
+ // Dropped by pi-ai alongside its tool result, because the declining model's call was
200
+ // never executed by the model that continued.
201
+ if (precedesBoundary)
202
+ continue;
137
203
  const providerToolUse = takeProviderBlock(providerBlocks, providerIndex, "tool_use");
138
204
  if (providerToolUse.block) {
139
205
  repaired.push(providerToolUse.block);
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-thinking-guard.js","sourceRoot":"","sources":["../../src/core/anthropic-thinking-guard.ts"],"names":[],"mappings":"AAUA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAc;IAC9C,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC1D,CAAC;AAED,SAAS,4BAA4B,CAAC,KAAc;IACnD,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAClD,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,KAAK,CAAC,IAAI,KAAK,mBAAmB,CAAC;AACxE,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAyB,EAAE,KAAiB;IACzE,OAAO,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,IAAI,OAAO,CAAC,KAAK,KAAK,KAAK,CAAC,EAAE,CAAC;AACvG,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAc,EAAE,mBAAmB,GAAG,KAAK;IAC3E,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAEzE,IAAI,KAAK,CAAC,IAAI,KAAK,mBAAmB,EAAE,CAAC;QACxC,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AAI,wBAAwB,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3F,MAAM,gBAAgB,GAAG,iBAAiB,CAAC,uBAAuB,CAAC,CAAC;QAEpE,IAAI,CAAC,oBAAoB,CAAC,aAAa,EAAE,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,aAAa,EAAE,mBAAmB,CAAC;YAC7G,SAAS;QACV,8EAA8E;QAC9E,sEAAsE;QACtE,IAAI,CAAC,sBAAsB,CAAC,aAAa,EAAE,gBAAgB,CAAC,OAAO,CAAC;YAAE,SAAS;QAE/E,MAAM,eAAe,GAAG,sBAAsB,CAAC,aAAa,EAAE,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;QAC7G,IAAI,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAAE,SAAS;QAE3F,mBAAmB,KAAK,CAAC,GAAG,eAAe,CAAC,CAAC;QAC7C,mBAAmB,CAAC,gBAAgB,CAAC,KAAK,CAAC,GAAG;YAC7C,GAAG,gBAAgB,CAAC,OAAO;YAC3B,OAAO,EAAE,eAAe;SACxB,CAAC;IACH,CAAC;IAED,IAAI,CAAC,mBAAmB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAC;IAC/D,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import type { Api, AssistantMessage, Message, Model } from \"@bastani/pi-ai/compat\";\n\ntype JsonObject = Record<string, unknown>;\n\ntype AnthropicContentBlock = JsonObject & { type: string };\n\ntype ReplayThinkingBlock =\n\t| { type: \"thinking\"; thinking: string; signature: string }\n\t| { type: \"redacted_thinking\"; data: string };\n\nfunction isObject(value: unknown): value is JsonObject {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isAnthropicContentBlock(value: unknown): value is AnthropicContentBlock {\n\treturn isObject(value) && typeof value.type === \"string\";\n}\n\nfunction isThinkingLikeAnthropicBlock(value: unknown): boolean {\n\tif (!isAnthropicContentBlock(value)) return false;\n\treturn value.type === \"thinking\" || value.type === \"redacted_thinking\";\n}\n\nfunction isSameModelAssistant(message: AssistantMessage, model: Model<Api>): boolean {\n\treturn message.provider === model.provider && message.api === model.api && message.model === model.id;\n}\n\nfunction readReplayThinkingBlock(block: unknown, allowEmptySignature = false): ReplayThinkingBlock | undefined {\n\tif (!isObject(block) || typeof block.type !== \"string\") return undefined;\n\n\tif (block.type === \"redacted_thinking\") {\n\t\treturn typeof block.data === \"string\" ? { type: \"redacted_thinking\", data: block.data } : undefined;\n\t}\n\n\tif (block.type !== \"thinking\") return undefined;\n\n\tif (block.redacted === true) {\n\t\treturn typeof block.thinkingSignature === \"string\"\n\t\t\t? { type: \"redacted_thinking\", data: block.thinkingSignature }\n\t\t\t: undefined;\n\t}\n\n\tif (typeof block.thinking !== \"string\" || typeof block.thinkingSignature !== \"string\") return undefined;\n\tif (!allowEmptySignature && block.thinkingSignature.trim().length === 0) return undefined;\n\treturn { type: \"thinking\", thinking: block.thinking, signature: block.thinkingSignature };\n}\n\nfunction hasReplayThinkingBlock(message: AssistantMessage, allowEmptySignature: boolean): boolean {\n\treturn message.content.some((block) => readReplayThinkingBlock(block, allowEmptySignature) !== undefined);\n}\n\nfunction legacyProviderWouldEmitAssistantBlock(block: unknown): boolean {\n\tif (!isObject(block) || typeof block.type !== \"string\") return false;\n\n\tif (block.type === \"text\") {\n\t\treturn typeof block.text === \"string\" && block.text.trim().length > 0;\n\t}\n\n\tif (block.type === \"toolCall\") {\n\t\treturn true;\n\t}\n\n\tif (block.type !== \"thinking\") {\n\t\treturn false;\n\t}\n\n\tif (block.redacted === true) {\n\t\treturn true;\n\t}\n\n\tif (typeof block.thinking !== \"string\") return false;\n\tconst signature = typeof block.thinkingSignature === \"string\" ? block.thinkingSignature : undefined;\n\treturn block.thinking.trim().length > 0 || (signature !== undefined && signature.trim().length > 0);\n}\n\nfunction legacyProviderWouldEmitAssistant(message: AssistantMessage, model: Model<Api>): boolean {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return false;\n\n\t// This mirrors the relevant same-model branch in @bastani/pi-ai's\n\t// transformMessages() + Anthropic convertMessages() pipeline closely enough\n\t// to keep assistant ordinal mapping aligned with the provider payload.\n\tif (isSameModelAssistant(message, model)) {\n\t\treturn message.content.some((block) => legacyProviderWouldEmitAssistantBlock(block));\n\t}\n\n\treturn message.content.some((block) => {\n\t\tif (!isObject(block) || typeof block.type !== \"string\") return false;\n\t\tif (block.type === \"text\") return typeof block.text === \"string\" && block.text.trim().length > 0;\n\t\tif (block.type === \"toolCall\") return true;\n\t\tif (block.type !== \"thinking\") return false;\n\t\tif (block.redacted === true) return false;\n\t\treturn typeof block.thinking === \"string\" && block.thinking.trim().length > 0;\n\t});\n}\n\nfunction fallbackTextBlock(block: JsonObject): AnthropicContentBlock | undefined {\n\treturn typeof block.text === \"string\" && block.text.trim().length > 0\n\t\t? { type: \"text\", text: block.text }\n\t\t: undefined;\n}\n\nfunction fallbackToolUseBlock(block: JsonObject): AnthropicContentBlock | undefined {\n\tif (typeof block.id !== \"string\" || typeof block.name !== \"string\") return undefined;\n\treturn { type: \"tool_use\", id: block.id, name: block.name, input: block.arguments ?? {} };\n}\n\nfunction takeProviderBlock(\n\tproviderBlocks: readonly AnthropicContentBlock[],\n\tproviderIndex: number,\n\texpectedType: string,\n): { block: AnthropicContentBlock | undefined; nextProviderIndex: number } {\n\tconst providerBlock = providerBlocks[providerIndex];\n\tif (providerBlock?.type === expectedType) {\n\t\treturn { block: providerBlock, nextProviderIndex: providerIndex + 1 };\n\t}\n\treturn { block: undefined, nextProviderIndex: providerIndex };\n}\n\nfunction nonThinkingBlocksAlign(message: AssistantMessage, providerBlocks: readonly AnthropicContentBlock[]): boolean {\n\tconst sourceTypes = message.content.flatMap((block) => {\n\t\tif (!isObject(block) || typeof block.type !== \"string\") return [];\n\t\tif (block.type === \"text\") return typeof block.text === \"string\" && block.text.trim().length > 0 ? [\"text\"] : [];\n\t\treturn block.type === \"toolCall\" ? [\"tool_use\"] : [];\n\t});\n\tconst providerTypes = providerBlocks\n\t\t.filter((block) => !isThinkingLikeAnthropicBlock(block))\n\t\t.map((block) => block.type);\n\treturn (\n\t\tsourceTypes.length === providerTypes.length && sourceTypes.every((type, index) => type === providerTypes[index])\n\t);\n}\n\nfunction repairAssistantContent(\n\toriginalMessage: AssistantMessage,\n\tproviderBlocks: readonly AnthropicContentBlock[],\n\tallowEmptySignature: boolean,\n): AnthropicContentBlock[] {\n\tconst repaired: AnthropicContentBlock[] = [];\n\tlet providerIndex = 0;\n\n\tfor (const originalBlock of originalMessage.content) {\n\t\tconst replayBlock = readReplayThinkingBlock(originalBlock, allowEmptySignature);\n\t\tif (replayBlock) {\n\t\t\tif (isThinkingLikeAnthropicBlock(providerBlocks[providerIndex])) {\n\t\t\t\tproviderIndex += 1;\n\t\t\t}\n\t\t\trepaired.push({ ...replayBlock });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isObject(originalBlock) || typeof originalBlock.type !== \"string\") continue;\n\n\t\tif (originalBlock.type === \"text\") {\n\t\t\tconst providerText = takeProviderBlock(providerBlocks, providerIndex, \"text\");\n\t\t\tif (providerText.block) {\n\t\t\t\trepaired.push(providerText.block);\n\t\t\t\tproviderIndex = providerText.nextProviderIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fallback = fallbackTextBlock(originalBlock);\n\t\t\tif (fallback) repaired.push(fallback);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (originalBlock.type === \"toolCall\") {\n\t\t\tconst providerToolUse = takeProviderBlock(providerBlocks, providerIndex, \"tool_use\");\n\t\t\tif (providerToolUse.block) {\n\t\t\t\trepaired.push(providerToolUse.block);\n\t\t\t\tproviderIndex = providerToolUse.nextProviderIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fallback = fallbackToolUseBlock(originalBlock);\n\t\t\tif (fallback) repaired.push(fallback);\n\t\t}\n\t}\n\n\tfor (; providerIndex < providerBlocks.length; providerIndex += 1) {\n\t\trepaired.push(providerBlocks[providerIndex]);\n\t}\n\n\treturn repaired;\n}\n\nfunction getAnthropicMessages(payload: unknown): unknown[] | undefined {\n\tif (!isObject(payload)) return undefined;\n\treturn Array.isArray(payload.messages) ? payload.messages : undefined;\n}\n\nfunction getAnthropicAssistantContent(message: unknown): AnthropicContentBlock[] | undefined {\n\tif (!isObject(message) || message.role !== \"assistant\") return undefined;\n\tif (!Array.isArray(message.content)) return undefined;\n\tconst content = message.content.filter(isAnthropicContentBlock);\n\treturn content.length === message.content.length ? content : undefined;\n}\n\n/**\n * Restore same-model Anthropic replay thinking blocks after provider payload\n * construction and extension payload hooks.\n *\n * Anthropic requires thinking/redacted_thinking blocks from replayed assistant\n * messages to remain byte-for-byte identical to the original response. The\n * upstream pi-ai Anthropic converter can sanitize thinking text and drop signed\n * empty thinking. convertToLlm normalizes raw redacted_thinking blocks in its\n * transient, non-mutating LLM-compatible messages before this hook, then this guard\n * restores exact same-model payloads while leaving non-Anthropic and cross-model\n * payloads unchanged.\n */\nexport function restoreAnthropicReplayThinkingBlocks(\n\tpayload: unknown,\n\tsourceMessages: readonly Message[],\n\tmodel: Model<Api>,\n): unknown {\n\tif (model.api !== \"anthropic-messages\") return payload;\n\n\tconst payloadMessages = getAnthropicMessages(payload);\n\tif (!payloadMessages) return payload;\n\n\tconst assistantPayloads = payloadMessages\n\t\t.map((message, index) => ({ message, index, content: getAnthropicAssistantContent(message) }))\n\t\t.filter(\n\t\t\t(entry): entry is { message: JsonObject; index: number; content: AnthropicContentBlock[] } =>\n\t\t\t\tentry.content !== undefined && isObject(entry.message),\n\t\t);\n\n\tif (assistantPayloads.length === 0) return payload;\n\n\tconst emittingSourceAssistants = sourceMessages.filter(\n\t\t(message): message is AssistantMessage =>\n\t\t\tmessage.role === \"assistant\" && legacyProviderWouldEmitAssistant(message, model),\n\t);\n\t// Fail closed if pi-ai's converter emission behavior drifts from the model above;\n\t// ordinal restoration must never splice thinking into a different assistant.\n\tif (emittingSourceAssistants.length !== assistantPayloads.length) return payload;\n\n\tconst allowEmptySignature = isObject(model.compat) && model.compat.allowEmptySignature === true;\n\tlet nextPayloadMessages: unknown[] | undefined;\n\n\tfor (const [assistantPayloadOrdinal, sourceMessage] of emittingSourceAssistants.entries()) {\n\t\tconst payloadAssistant = assistantPayloads[assistantPayloadOrdinal];\n\n\t\tif (!isSameModelAssistant(sourceMessage, model) || !hasReplayThinkingBlock(sourceMessage, allowEmptySignature))\n\t\t\tcontinue;\n\t\t// A second fail-closed guard verifies the non-thinking shape before replacing\n\t\t// signed blocks, protecting against equal-count ordinal misalignment.\n\t\tif (!nonThinkingBlocksAlign(sourceMessage, payloadAssistant.content)) continue;\n\n\t\tconst repairedContent = repairAssistantContent(sourceMessage, payloadAssistant.content, allowEmptySignature);\n\t\tif (JSON.stringify(repairedContent) === JSON.stringify(payloadAssistant.content)) continue;\n\n\t\tnextPayloadMessages ??= [...payloadMessages];\n\t\tnextPayloadMessages[payloadAssistant.index] = {\n\t\t\t...payloadAssistant.message,\n\t\t\tcontent: repairedContent,\n\t\t};\n\t}\n\n\tif (!nextPayloadMessages || !isObject(payload)) return payload;\n\treturn { ...payload, messages: nextPayloadMessages };\n}\n"]}
1
+ {"version":3,"file":"anthropic-thinking-guard.js","sourceRoot":"","sources":["../../src/core/anthropic-thinking-guard.ts"],"names":[],"mappings":"AAUA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAc;IAC9C,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC1D,CAAC;AA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I,wBAAwB,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3F,MAAM,gBAAgB,GAAG,iBAAiB,CAAC,uBAAuB,CAAC,CAAC;QAEpE,IAAI,CAAC,oBAAoB,CAAC,aAAa,EAAE,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,aAAa,EAAE,mBAAmB,CAAC;YAC7G,SAAS;QACV,8EAA8E;QAC9E,sEAAsE;QACtE,IAAI,CAAC,sBAAsB,CAAC,aAAa,EAAE,gBAAgB,CAAC,OAAO,CAAC;YAAE,SAAS;QAE/E,MAAM,eAAe,GAAG,sBAAsB,CAAC,aAAa,EAAE,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;QAC7G,IAAI,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAAE,SAAS;QAE3F,mBAAmB,KAAK,CAAC,GAAG,eAAe,CAAC,CAAC;QAC7C,mBAAmB,CAAC,gBAAgB,CAAC,KAAK,CAAC,GAAG;YAC7C,GAAG,gBAAgB,CAAC,OAAO;YAC3B,OAAO,EAAE,eAAe;SACxB,CAAC;IACH,CAAC;IAED,IAAI,CAAC,mBAAmB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAC;IAC/D,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import type { Api, AssistantMessage, Message, Model } from \"@bastani/pi-ai/compat\";\n\ntype JsonObject = Record<string, unknown>;\n\ntype AnthropicContentBlock = JsonObject & { type: string };\n\ntype ReplayThinkingBlock =\n\t| { type: \"thinking\"; thinking: string; signature: string }\n\t| { type: \"redacted_thinking\"; data: string };\n\nfunction isObject(value: unknown): value is JsonObject {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isAnthropicContentBlock(value: unknown): value is AnthropicContentBlock {\n\treturn isObject(value) && typeof value.type === \"string\";\n}\n\nfunction isThinkingLikeAnthropicBlock(value: unknown): boolean {\n\tif (!isAnthropicContentBlock(value)) return false;\n\treturn value.type === \"thinking\" || value.type === \"redacted_thinking\";\n}\n\nfunction isSameModelAssistant(message: AssistantMessage, model: Model<Api>): boolean {\n\treturn message.provider === model.provider && message.api === model.api && message.model === model.id;\n}\n\n/**\n * Mirrors `canReplayForeignThinking` in @bastani/pi-ai's `transformMessages`: a *different* model\n * on the same provider and API whose API adjudicates thinking model binding itself. Its signed\n * blocks replay unchanged — including redacted ones and signed blocks whose text is empty, which\n * is Claude Fable 5.1's default shape because `thinking.display` defaults to `\"omitted\"`.\n *\n * This must stay conditional. For a model that does not delegate binding, pi-ai still drops or\n * flattens foreign thinking, so accepting signature-only blocks unconditionally would misalign\n * the ordinals in the opposite direction.\n */\nfunction delegatesForeignThinkingBinding(message: AssistantMessage, model: Model<Api>): boolean {\n\tif (message.provider !== model.provider || message.api !== model.api) return false;\n\treturn isObject(model.compat) && model.compat.delegatesThinkingModelBinding === true;\n}\n\n/**\n * Index of the last server-side fallback marker, or -1.\n *\n * pi-ai drops `thinking`, `redacted_thinking`, and client-side `tool_use` that precede the final\n * marker, because \"a request that echoes thinking blocks from both sides of the boundary is\n * rejected\". Both the alignment check and the repair pass must apply the same rule, or repair\n * would splice pre-boundary thinking back into a request the API rejects.\n * https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n */\nfunction finalFallbackBoundaryIndex(content: readonly unknown[]): number {\n\tfor (let index = content.length - 1; index >= 0; index -= 1) {\n\t\tconst block = content[index];\n\t\tif (isObject(block) && block.type === \"fallback\") return index;\n\t}\n\treturn -1;\n}\n\nfunction readReplayThinkingBlock(block: unknown, allowEmptySignature = false): ReplayThinkingBlock | undefined {\n\tif (!isObject(block) || typeof block.type !== \"string\") return undefined;\n\n\tif (block.type === \"redacted_thinking\") {\n\t\treturn typeof block.data === \"string\" ? { type: \"redacted_thinking\", data: block.data } : undefined;\n\t}\n\n\tif (block.type !== \"thinking\") return undefined;\n\n\tif (block.redacted === true) {\n\t\treturn typeof block.thinkingSignature === \"string\"\n\t\t\t? { type: \"redacted_thinking\", data: block.thinkingSignature }\n\t\t\t: undefined;\n\t}\n\n\tif (typeof block.thinking !== \"string\" || typeof block.thinkingSignature !== \"string\") return undefined;\n\tif (!allowEmptySignature && block.thinkingSignature.trim().length === 0) return undefined;\n\treturn { type: \"thinking\", thinking: block.thinking, signature: block.thinkingSignature };\n}\n\nfunction hasReplayThinkingBlock(message: AssistantMessage, allowEmptySignature: boolean): boolean {\n\treturn message.content.some((block) => readReplayThinkingBlock(block, allowEmptySignature) !== undefined);\n}\n\nfunction legacyProviderWouldEmitAssistantBlock(block: unknown): boolean {\n\tif (!isObject(block) || typeof block.type !== \"string\") return false;\n\n\tif (block.type === \"text\") {\n\t\treturn typeof block.text === \"string\" && block.text.trim().length > 0;\n\t}\n\n\tif (block.type === \"toolCall\") {\n\t\treturn true;\n\t}\n\n\tif (block.type !== \"thinking\") {\n\t\treturn false;\n\t}\n\n\tif (block.redacted === true) {\n\t\treturn true;\n\t}\n\n\tif (typeof block.thinking !== \"string\") return false;\n\tconst signature = typeof block.thinkingSignature === \"string\" ? block.thinkingSignature : undefined;\n\treturn block.thinking.trim().length > 0 || (signature !== undefined && signature.trim().length > 0);\n}\n\nfunction legacyProviderWouldEmitAssistant(message: AssistantMessage, model: Model<Api>): boolean {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") return false;\n\n\t// This mirrors the relevant same-model branch in @bastani/pi-ai's\n\t// transformMessages() + Anthropic convertMessages() pipeline closely enough\n\t// to keep assistant ordinal mapping aligned with the provider payload.\n\t//\n\t// A cross-model turn on a model that delegates binding follows the *same* rule: pi-ai replays\n\t// its foreign signed thinking unchanged, so a redacted or empty-text signed block is emitted\n\t// there too. Without this branch, a Fable 5.1 turn whose thinking display is `\"omitted\"` looks\n\t// non-emitting here, the ordinals desynchronise, and repair is abandoned for the whole request.\n\tif (isSameModelAssistant(message, model) || delegatesForeignThinkingBinding(message, model)) {\n\t\treturn message.content.some((block) => legacyProviderWouldEmitAssistantBlock(block));\n\t}\n\n\treturn message.content.some((block) => {\n\t\tif (!isObject(block) || typeof block.type !== \"string\") return false;\n\t\tif (block.type === \"text\") return typeof block.text === \"string\" && block.text.trim().length > 0;\n\t\tif (block.type === \"toolCall\") return true;\n\t\tif (block.type !== \"thinking\") return false;\n\t\tif (block.redacted === true) return false;\n\t\treturn typeof block.thinking === \"string\" && block.thinking.trim().length > 0;\n\t});\n}\n\nfunction fallbackTextBlock(block: JsonObject): AnthropicContentBlock | undefined {\n\treturn typeof block.text === \"string\" && block.text.trim().length > 0\n\t\t? { type: \"text\", text: block.text }\n\t\t: undefined;\n}\n\nfunction fallbackToolUseBlock(block: JsonObject): AnthropicContentBlock | undefined {\n\tif (typeof block.id !== \"string\" || typeof block.name !== \"string\") return undefined;\n\treturn { type: \"tool_use\", id: block.id, name: block.name, input: block.arguments ?? {} };\n}\n\nfunction takeProviderBlock(\n\tproviderBlocks: readonly AnthropicContentBlock[],\n\tproviderIndex: number,\n\texpectedType: string,\n): { block: AnthropicContentBlock | undefined; nextProviderIndex: number } {\n\tconst providerBlock = providerBlocks[providerIndex];\n\tif (providerBlock?.type === expectedType) {\n\t\treturn { block: providerBlock, nextProviderIndex: providerIndex + 1 };\n\t}\n\treturn { block: undefined, nextProviderIndex: providerIndex };\n}\n\nfunction nonThinkingBlocksAlign(message: AssistantMessage, providerBlocks: readonly AnthropicContentBlock[]): boolean {\n\tconst boundaryIndex = finalFallbackBoundaryIndex(message.content);\n\tconst sourceTypes = message.content.flatMap((block, index) => {\n\t\tif (!isObject(block) || typeof block.type !== \"string\") return [];\n\t\tif (block.type === \"text\") return typeof block.text === \"string\" && block.text.trim().length > 0 ? [\"text\"] : [];\n\t\t// The marker is replayed in place and is not thinking-like, so it survives the provider-side\n\t\t// filter below and both sides must count it.\n\t\tif (block.type === \"fallback\") return [\"fallback\"];\n\t\tif (block.type !== \"toolCall\") return [];\n\t\t// A client-side tool call before the final marker was never executed by the model that\n\t\t// continued the turn, so pi-ai drops it along with its tool result.\n\t\treturn boundaryIndex >= 0 && index < boundaryIndex ? [] : [\"tool_use\"];\n\t});\n\tconst providerTypes = providerBlocks\n\t\t.filter((block) => !isThinkingLikeAnthropicBlock(block))\n\t\t.map((block) => block.type);\n\treturn (\n\t\tsourceTypes.length === providerTypes.length && sourceTypes.every((type, index) => type === providerTypes[index])\n\t);\n}\n\nfunction repairAssistantContent(\n\toriginalMessage: AssistantMessage,\n\tproviderBlocks: readonly AnthropicContentBlock[],\n\tallowEmptySignature: boolean,\n): AnthropicContentBlock[] {\n\tconst repaired: AnthropicContentBlock[] = [];\n\tlet providerIndex = 0;\n\n\t// `fallbackTextBlock`/`fallbackToolUseBlock` below mean \"fallback value\"; `boundaryIndex` is the\n\t// unrelated Anthropic server-side fallback marker.\n\tconst boundaryIndex = finalFallbackBoundaryIndex(originalMessage.content);\n\n\tfor (const [index, originalBlock] of originalMessage.content.entries()) {\n\t\tconst precedesBoundary = boundaryIndex >= 0 && index < boundaryIndex;\n\t\t// Thinking before the final marker is not in the payload and must not be restored into it:\n\t\t// echoing thinking from both sides of the boundary is rejected outright.\n\t\tconst replayBlock = precedesBoundary ? undefined : readReplayThinkingBlock(originalBlock, allowEmptySignature);\n\t\tif (replayBlock) {\n\t\t\tif (isThinkingLikeAnthropicBlock(providerBlocks[providerIndex])) {\n\t\t\t\tproviderIndex += 1;\n\t\t\t}\n\t\t\trepaired.push({ ...replayBlock });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isObject(originalBlock) || typeof originalBlock.type !== \"string\") continue;\n\n\t\tif (originalBlock.type === \"fallback\") {\n\t\t\t// Replayed in place, straight from the payload: this guard only restores thinking, and\n\t\t\t// the marker's position is what the API validates the surrounding thinking against.\n\t\t\tconst providerMarker = takeProviderBlock(providerBlocks, providerIndex, \"fallback\");\n\t\t\tif (providerMarker.block) {\n\t\t\t\trepaired.push(providerMarker.block);\n\t\t\t\tproviderIndex = providerMarker.nextProviderIndex;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (originalBlock.type === \"text\") {\n\t\t\tconst providerText = takeProviderBlock(providerBlocks, providerIndex, \"text\");\n\t\t\tif (providerText.block) {\n\t\t\t\trepaired.push(providerText.block);\n\t\t\t\tproviderIndex = providerText.nextProviderIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fallback = fallbackTextBlock(originalBlock);\n\t\t\tif (fallback) repaired.push(fallback);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (originalBlock.type === \"toolCall\") {\n\t\t\t// Dropped by pi-ai alongside its tool result, because the declining model's call was\n\t\t\t// never executed by the model that continued.\n\t\t\tif (precedesBoundary) continue;\n\t\t\tconst providerToolUse = takeProviderBlock(providerBlocks, providerIndex, \"tool_use\");\n\t\t\tif (providerToolUse.block) {\n\t\t\t\trepaired.push(providerToolUse.block);\n\t\t\t\tproviderIndex = providerToolUse.nextProviderIndex;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fallback = fallbackToolUseBlock(originalBlock);\n\t\t\tif (fallback) repaired.push(fallback);\n\t\t}\n\t}\n\n\tfor (; providerIndex < providerBlocks.length; providerIndex += 1) {\n\t\trepaired.push(providerBlocks[providerIndex]);\n\t}\n\n\treturn repaired;\n}\n\nfunction getAnthropicMessages(payload: unknown): unknown[] | undefined {\n\tif (!isObject(payload)) return undefined;\n\treturn Array.isArray(payload.messages) ? payload.messages : undefined;\n}\n\nfunction getAnthropicAssistantContent(message: unknown): AnthropicContentBlock[] | undefined {\n\tif (!isObject(message) || message.role !== \"assistant\") return undefined;\n\tif (!Array.isArray(message.content)) return undefined;\n\tconst content = message.content.filter(isAnthropicContentBlock);\n\treturn content.length === message.content.length ? content : undefined;\n}\n\n/**\n * Restore same-model Anthropic replay thinking blocks after provider payload\n * construction and extension payload hooks.\n *\n * Anthropic requires thinking/redacted_thinking blocks from replayed assistant\n * messages to remain byte-for-byte identical to the original response. The\n * upstream pi-ai Anthropic converter can sanitize thinking text and drop signed\n * empty thinking. convertToLlm normalizes raw redacted_thinking blocks in its\n * transient, non-mutating LLM-compatible messages before this hook, then this guard\n * restores exact same-model payloads while leaving non-Anthropic and cross-model\n * payloads unchanged.\n */\nexport function restoreAnthropicReplayThinkingBlocks(\n\tpayload: unknown,\n\tsourceMessages: readonly Message[],\n\tmodel: Model<Api>,\n): unknown {\n\tif (model.api !== \"anthropic-messages\") return payload;\n\n\tconst payloadMessages = getAnthropicMessages(payload);\n\tif (!payloadMessages) return payload;\n\n\tconst assistantPayloads = payloadMessages\n\t\t.map((message, index) => ({ message, index, content: getAnthropicAssistantContent(message) }))\n\t\t.filter(\n\t\t\t(entry): entry is { message: JsonObject; index: number; content: AnthropicContentBlock[] } =>\n\t\t\t\tentry.content !== undefined && isObject(entry.message),\n\t\t);\n\n\tif (assistantPayloads.length === 0) return payload;\n\n\tconst emittingSourceAssistants = sourceMessages.filter(\n\t\t(message): message is AssistantMessage =>\n\t\t\tmessage.role === \"assistant\" && legacyProviderWouldEmitAssistant(message, model),\n\t);\n\t// Fail closed if pi-ai's converter emission behavior drifts from the model above;\n\t// ordinal restoration must never splice thinking into a different assistant.\n\tif (emittingSourceAssistants.length !== assistantPayloads.length) return payload;\n\n\tconst allowEmptySignature = isObject(model.compat) && model.compat.allowEmptySignature === true;\n\tlet nextPayloadMessages: unknown[] | undefined;\n\n\tfor (const [assistantPayloadOrdinal, sourceMessage] of emittingSourceAssistants.entries()) {\n\t\tconst payloadAssistant = assistantPayloads[assistantPayloadOrdinal];\n\n\t\tif (!isSameModelAssistant(sourceMessage, model) || !hasReplayThinkingBlock(sourceMessage, allowEmptySignature))\n\t\t\tcontinue;\n\t\t// A second fail-closed guard verifies the non-thinking shape before replacing\n\t\t// signed blocks, protecting against equal-count ordinal misalignment.\n\t\tif (!nonThinkingBlocksAlign(sourceMessage, payloadAssistant.content)) continue;\n\n\t\tconst repairedContent = repairAssistantContent(sourceMessage, payloadAssistant.content, allowEmptySignature);\n\t\tif (JSON.stringify(repairedContent) === JSON.stringify(payloadAssistant.content)) continue;\n\n\t\tnextPayloadMessages ??= [...payloadMessages];\n\t\tnextPayloadMessages[payloadAssistant.index] = {\n\t\t\t...payloadAssistant.message,\n\t\t\tcontent: repairedContent,\n\t\t};\n\t}\n\n\tif (!nextPayloadMessages || !isObject(payload)) return payload;\n\treturn { ...payload, messages: nextPayloadMessages };\n}\n"]}
@@ -59,8 +59,8 @@ export interface ProviderModelConfig {
59
59
  reasoning: boolean;
60
60
  /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */
61
61
  thinkingLevelMap?: Model<Api>["thinkingLevelMap"];
62
- /** Supported input types. */
63
- input: ("text" | "image")[];
62
+ /** Supported input types. `"pdf"` only on runtimes that can serialize a document block. */
63
+ input: Model<Api>["input"];
64
64
  /** Request pricing, including optional request-wide long-context tiers. */
65
65
  cost: Model<Api>["cost"];
66
66
  /** Default/effective context window size in tokens. */