maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.25.20260908

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 (215) hide show
  1. package/README.md +38 -19
  2. package/README.zh-CN.md +34 -19
  3. package/dist/acp/maka-acp-agent.js +2 -1
  4. package/dist/acp/session-configuration.js +143 -0
  5. package/dist/acp/session-registry.js +90 -4
  6. package/dist/cli-core.js +2 -0
  7. package/dist/pi-transcript-tools.js +6 -0
  8. package/dist/pi-transcript.js +5 -12
  9. package/dist/pi-tui-layout.js +56 -10
  10. package/dist/pi-tui-pickers.js +102 -1
  11. package/dist/pi-tui-runner.js +230 -46
  12. package/dist/pi-tui-todo.js +221 -0
  13. package/dist/pi-tui-transcript-viewer.js +134 -7
  14. package/dist/runtime-host-cli-context.js +224 -78
  15. package/dist/runtime-host-cli-installation.js +8 -2
  16. package/dist/runtime-host-cli.js +31 -1
  17. package/dist/runtime-host-handoff-surface.js +106 -0
  18. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  19. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  20. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  21. package/dist/runtime-host-local-handoff.js +48 -5
  22. package/dist/runtime-host-local-managed-activation.js +84 -0
  23. package/dist/runtime-host-local-source-retirement.js +18 -2
  24. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  25. package/dist/runtime-host-operator-retirement.js +50 -0
  26. package/dist/runtime-host-service-manager.js +3 -3
  27. package/dist/runtime-host-session-channel.js +13 -0
  28. package/dist/runtime-host-session-driver.js +46 -26
  29. package/dist/runtime-host-session-update.js +62 -0
  30. package/dist/runtime-host-tui-command.js +38 -73
  31. package/dist/runtime-host-tui-context.js +1 -0
  32. package/dist/runtime-host-tui-owner.js +226 -0
  33. package/dist/tui-copy-catalog.js +219 -6
  34. package/dist/tui-host-owner-copy.js +24 -0
  35. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  36. package/node_modules/@maka/core/dist/agent-run.js +1 -0
  37. package/node_modules/@maka/core/dist/attachments.js +3 -0
  38. package/node_modules/@maka/core/dist/canonical-json.js +27 -0
  39. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  40. package/node_modules/@maka/core/dist/capabilities.js +35 -0
  41. package/node_modules/@maka/core/dist/computer-use.js +0 -1
  42. package/node_modules/@maka/core/dist/display-redaction.js +18 -0
  43. package/node_modules/@maka/core/dist/llm-connections.js +13 -0
  44. package/node_modules/@maka/core/dist/model-call-attempt.js +2 -0
  45. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  46. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  47. package/node_modules/@maka/core/dist/model-metadata.js +7 -3
  48. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  49. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  50. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  51. package/node_modules/@maka/core/dist/redaction.js +35 -0
  52. package/node_modules/@maka/core/dist/run-composition.js +77 -2
  53. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  54. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  55. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  56. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  57. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  58. package/node_modules/@maka/core/dist/session.js +84 -56
  59. package/node_modules/@maka/core/dist/slash-command-catalog.js +3 -0
  60. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  61. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  62. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  63. package/node_modules/@maka/core/package.json +5 -0
  64. package/node_modules/@maka/eval/dist/experiment-directory.js +4 -13
  65. package/node_modules/@maka/mcp/dist/index.js +131 -1
  66. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +0 -13
  67. package/node_modules/@maka/runtime/dist/agent-run.js +351 -105
  68. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +29 -13
  69. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  70. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +184 -183
  71. package/node_modules/@maka/runtime/dist/archive-read-tool.js +2 -2
  72. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +0 -16
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +158 -15
  75. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +3 -3
  76. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  77. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  78. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  79. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  80. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +174 -0
  81. package/node_modules/@maka/runtime/dist/mcp-tools.js +7 -2
  82. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  83. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  84. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  85. package/node_modules/@maka/runtime/dist/model-fetcher.js +49 -2
  86. package/node_modules/@maka/runtime/dist/model-history.js +0 -112
  87. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  88. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  89. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  90. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  91. package/node_modules/@maka/runtime/dist/plugin-runtime.js +20 -10
  92. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +205 -0
  93. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  94. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +76 -109
  95. package/node_modules/@maka/runtime/dist/request-shape.js +23 -0
  96. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  97. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +83 -55
  98. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +121 -159
  99. package/node_modules/@maka/runtime/dist/runtime-kernel.js +157 -112
  100. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  101. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  102. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  103. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  104. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  105. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  106. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +21 -0
  107. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +0 -5
  108. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  109. package/node_modules/@maka/runtime/dist/test-connection.js +16 -17
  110. package/node_modules/@maka/runtime/dist/tool-activation-identity.js +41 -0
  111. package/node_modules/@maka/runtime/dist/tool-availability.js +11 -1
  112. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  113. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +63 -1
  114. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +42 -12
  115. package/node_modules/@maka/runtime/dist/tool-result-archive.js +27 -4
  116. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  117. package/node_modules/@maka/runtime/package.json +2 -0
  118. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  119. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  120. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  121. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +179 -0
  122. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +275 -0
  123. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  124. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  125. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  126. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  127. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +46 -5
  128. package/node_modules/@maka/runtime-host/dist/control/endpoint.js +1 -3
  129. package/node_modules/@maka/runtime-host/dist/node-error.js +22 -0
  130. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  131. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +1 -3
  132. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  133. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +0 -1
  134. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +1 -1
  135. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +1 -3
  136. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  137. package/node_modules/@maka/runtime-host/dist/protocol/index.js +29 -1
  138. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  139. package/node_modules/@maka/runtime-host/dist/protocol/plan.js +1 -0
  140. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +27 -5
  141. package/node_modules/@maka/runtime-host/dist/protocol/project-catalog.js +2 -2
  142. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  143. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  144. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  145. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  146. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +31 -2
  147. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  148. package/node_modules/@maka/runtime-host/dist/server/agent-graph-coordinator.js +0 -3
  149. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  150. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  151. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +32 -32
  152. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +144 -33
  153. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  154. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +45 -16
  155. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  156. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  157. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  158. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  159. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  160. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +47 -22
  161. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  162. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  163. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  164. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  165. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  166. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  167. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  168. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  169. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +5 -2
  170. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +12 -55
  171. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  172. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  173. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  174. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  175. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  176. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +20 -2
  177. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +13 -4
  178. package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +46 -0
  179. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  180. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  181. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -5
  182. package/node_modules/@maka/storage/dist/codex-session-adapter.js +284 -198
  183. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  184. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  185. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  186. package/node_modules/@maka/storage/dist/git-exec.js +61 -0
  187. package/node_modules/@maka/storage/dist/git-worktree-child-executor.js +8 -35
  188. package/node_modules/@maka/storage/dist/goal-authority.js +2 -2
  189. package/node_modules/@maka/storage/dist/interaction-store.js +2 -2
  190. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  191. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  192. package/node_modules/@maka/storage/dist/project-catalog.js +2 -23
  193. package/node_modules/@maka/storage/dist/runtime-event-invariants.js +2 -2
  194. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  195. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +8 -3
  196. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  197. package/node_modules/@maka/storage/dist/scheduled-task-store.js +249 -283
  198. package/node_modules/@maka/storage/dist/session-bundle-manifest.js +5 -17
  199. package/node_modules/@maka/storage/dist/session-bundle-policy.js +26 -5
  200. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +2 -1
  201. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  202. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  203. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  204. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  205. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  206. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  207. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  208. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +130 -27
  209. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  210. package/node_modules/@maka/storage/dist/storage-id.js +28 -0
  211. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +138 -0
  212. package/node_modules/@maka/storage/dist/workspace-identity.js +2 -15
  213. package/node_modules/@maka/storage/dist/workspace-version-authority-internal.js +1 -8
  214. package/node_modules/@maka/storage/package.json +2 -0
  215. package/package.json +1 -1
@@ -29,7 +29,6 @@ import { DEFAULT_CODE_MODE_EXECUTION_POLICY, executeCodeCell, } from './code-mod
29
29
  import { StreamWatchdog, formatStreamWatchdogError, } from './stream-watchdog.js';
30
30
  import { isRuntimeCommitBoundaryError, } from './tool-runtime.js';
31
31
  import { persistedOpenAiResponsesStepMessages } from './openai-responses-continuation.js';
32
- import { nonCanonicalContentOrder } from './runtime-event-read-model.js';
33
32
  import { composeRequestProjection, } from './request-projection.js';
34
33
  import { decodePlaintextResponsesReasoningState, responsesReasoningItemId, } from './responses-reasoning-state.js';
35
34
  import { finitePositive } from './context-budget-helpers.js';
@@ -38,13 +37,14 @@ import { hasActiveToolResultPruneDiagnosticPatch, hasBlockingReplayDiagnostics,
38
37
  import { RunTrace } from './run-trace.js';
39
38
  import { REQUEST_SANDBOX_BOUNDARY_TOOL_NAME, SANDBOX_BOUNDARY_DENIED_FOR_TURN, SANDBOX_BOUNDARY_FINALIZATION_PROMPT, } from './sandbox-boundary-tool.js';
40
39
  import { buildRuntimeEventModelReplayPlan, buildSteeringEnvelope, collectToolActivityTurnIds, compatibleProviderReasoningReplayEventIds, formatTextWithInlineRefs, steeringMessagesMissingFromBase, steeringModelMessage, } from './model-history.js';
41
- import { toolSchemaCharsForDiagnostics } from './request-shape.js';
40
+ import { toolSchemaCharsForDiagnostics, requestCompositionToolSchemas, stableHash, toolCatalogHash, } from './request-shape.js';
41
+ import { toolAvailabilityHash } from './tool-availability.js';
42
42
  import { renderSwarmModePrompt } from './swarm-mode.js';
43
43
  import { renderGraphModePrompt } from './graph-mode.js';
44
44
  import { modelUsesNativeOpenAiResponses } from './model-runtime.js';
45
45
  import { applyRuntimeEventContextBudget, buildContextBudgetDiagnosticShell, mergeContextBudgetDiagnostic, mergeContextBudgetDiagnosticPatches, minimalContextBudgetDiagnostic, shouldAppendContextCompactedNote, shouldAppendContextCompactionFailedOpenNote, } from './context-budget.js';
46
46
  import { isHistoryCompactContentEvent } from './history-compaction.js';
47
- import { canContinueHistoryCompactCheckpointForModel, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
47
+ import { canContinueHistoryCompactCheckpointForModel, historyCompactSourceDigest, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
48
48
  import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
49
49
  import { INVALID_TOOL_NAME, isProviderSandboxBoundaryAttempt, repairMakaToolCall, } from './ai-sdk-tool-repair.js';
50
50
  const CHILD_STEP_BUDGET_FINALIZATION_PROMPT = [
@@ -375,6 +375,7 @@ function providerRetryDelayMs(failedAttempt, retryAfterMs) {
375
375
  }
376
376
  function providerRetryReason(kind) {
377
377
  switch (kind) {
378
+ case 'stream_truncated':
378
379
  case 'network':
379
380
  case 'provider_unavailable':
380
381
  case 'rate_limit':
@@ -410,6 +411,7 @@ export class AiSdkTurn {
410
411
  aborted = false;
411
412
  loopStopRequested = false;
412
413
  loopStopReason;
414
+ handoffPaused = false;
413
415
  watchdog = null;
414
416
  runTrace = null;
415
417
  imageBudget = { used: 0, decisions: new Map() };
@@ -585,12 +587,26 @@ export class AiSdkTurn {
585
587
  impl: (args, context) => this.executeCodeModeCell(eventSink, args.code, context),
586
588
  };
587
589
  }
590
+ /**
591
+ * A note about what happened inside this invocation, written to the
592
+ * invocation's own ledger. Fail-open: the note explains a turn, it is not
593
+ * what the turn did, so losing it must never end a send that is otherwise
594
+ * fine. Returns whether the note landed.
595
+ */
596
+ async recordSystemNote(kind, turnId, data) {
597
+ if (!this.deps.backend.recordSystemNote)
598
+ return false;
599
+ return await this.deps.backend
600
+ .recordSystemNote(kind, turnId, data)
601
+ .then(() => true)
602
+ .catch(() => false);
603
+ }
588
604
  // --------------------------------------------------------------------------
589
605
  // manual history compaction
590
606
  // --------------------------------------------------------------------------
591
607
  async *runWithinScope(input) {
592
608
  const turnId = input.turnId;
593
- const maxSteps = input.maxSteps ?? this.deps.maxSteps;
609
+ const maxSteps = input.maxSteps === null ? undefined : (input.maxSteps ?? this.deps.maxSteps);
594
610
  const toolRuntime = this.toolRuntime;
595
611
  const turnAbortController = this.abortController;
596
612
  const midTurnState = this.deps.compaction.buildMidTurnCapacityCompactState(input);
@@ -636,36 +652,6 @@ export class AiSdkTurn {
636
652
  return;
637
653
  }
638
654
  const stepId = currentStepMessageId;
639
- const thinkingText = stepThinkingParts.map((part) => part.text).join('');
640
- const contentOrder = nonCanonicalContentOrder(stepContentOrder);
641
- const msg = {
642
- type: 'assistant',
643
- id: stepId,
644
- turnId,
645
- ts: this.deps.now(),
646
- text: stepText,
647
- ...(stepTextProviderOptions !== undefined
648
- ? { providerOptions: stepTextProviderOptions }
649
- : {}),
650
- ...(contentOrder ? { contentOrder } : {}),
651
- modelId: this.deps.backend.modelId,
652
- ...(hasThinking
653
- ? {
654
- thinking: {
655
- text: thinkingText,
656
- ...(stepThinkingParts.length === 1 && stepThinkingParts[0].signature !== undefined
657
- ? { signature: stepThinkingParts[0].signature }
658
- : {}),
659
- ...(stepThinkingParts.length === 1 &&
660
- stepThinkingParts[0].providerOptions !== undefined
661
- ? { providerOptions: stepThinkingParts[0].providerOptions }
662
- : {}),
663
- ...(stepThinkingParts.length > 1 ? { parts: stepThinkingParts } : {}),
664
- },
665
- }
666
- : {}),
667
- };
668
- await this.deps.backend.appendMessage(msg);
669
655
  if (hasThinking) {
670
656
  for (const part of stepThinkingParts) {
671
657
  queue.push({
@@ -749,33 +735,12 @@ export class AiSdkTurn {
749
735
  const failOpenReason = contextBudget?.compactionDecisions
750
736
  ?.filter((decision) => decision.boundaryKind === 'historyCompact' && decision.decision === 'failedOpen')
751
737
  .at(-1)?.failOpenReason;
752
- const note = {
753
- type: 'system_note',
754
- id: this.deps.newId(),
755
- turnId,
756
- ts: this.deps.now(),
757
- kind: 'context_compaction_failed_open',
758
- ...(failOpenReason !== undefined ? { data: { failOpenReason } } : {}),
759
- };
760
738
  // Mark written only after the append lands: a failed write must leave
761
739
  // the flag down so the settlement fallback can still record the note.
762
- contextCompactionFailedOpenNoteWritten = await this.deps.backend
763
- .appendMessage(note)
764
- .then(() => true)
765
- .catch(() => false);
740
+ contextCompactionFailedOpenNoteWritten = await this.recordSystemNote('context_compaction_failed_open', turnId, failOpenReason !== undefined ? { failOpenReason } : undefined);
766
741
  }
767
742
  if (!contextCompactedNoteWritten && shouldAppendContextCompactedNote(contextBudget)) {
768
- const note = {
769
- type: 'system_note',
770
- id: this.deps.newId(),
771
- turnId,
772
- ts: this.deps.now(),
773
- kind: 'context_compacted',
774
- };
775
- contextCompactedNoteWritten = await this.deps.backend
776
- .appendMessage(note)
777
- .then(() => true)
778
- .catch(() => false);
743
+ contextCompactedNoteWritten = await this.recordSystemNote('context_compacted', turnId);
779
744
  }
780
745
  };
781
746
  // Request index (0-based) at which the active prune last rewrote the
@@ -836,8 +801,8 @@ export class AiSdkTurn {
836
801
  return;
837
802
  }
838
803
  // --- Build the provider-visible schema set. Tool execution stays in Runtime. ---
839
- // One immutable runtime owns the bound search catalog and cached index.
840
- // Mutable activation belongs to this turn.
804
+ // Each logical step freezes its own scoped catalog and search projection.
805
+ // Mutable activation belongs to this turn and follows contribution identity.
841
806
  const requiredOrchestrationTools = this.orchestration.mode === 'swarm'
842
807
  ? new Set([
843
808
  'agent_list',
@@ -861,11 +826,22 @@ export class AiSdkTurn {
861
826
  throw new Error(`Invalid tool mode: ${String(requestedToolMode)}`);
862
827
  }
863
828
  const toolMode = requestedToolMode;
864
- if (toolMode === 'code_mode' && this.deps.backend.tools.some((tool) => tool.name === 'exec')) {
865
- throw new Error('Tool name "exec" is reserved for Code Mode.');
866
- }
867
- const plan = projectToolModePlan(this.deps.toolAvailabilityRuntime.prepare(this.activeTools, requiredOrchestrationTools), toolMode, codeModeExecTool);
868
- const providerTools = plan.providerTools;
829
+ const snapshotStepTools = () => {
830
+ const snapshot = this.deps.snapshotToolAvailability();
831
+ if (toolMode === 'code_mode' && snapshot.hostTools.some((tool) => tool.name === 'exec')) {
832
+ throw new Error('Tool name "exec" is reserved for Code Mode.');
833
+ }
834
+ const plan = projectToolModePlan(snapshot.runtime.prepare(this.activeTools, requiredOrchestrationTools), toolMode, codeModeExecTool);
835
+ const modelTools = {};
836
+ for (const tool of plan.providerTools) {
837
+ modelTools[tool.name] = tool.providerTool
838
+ ? { kind: 'provider', providerTool: tool.providerTool }
839
+ : { kind: 'function', description: tool.description, inputSchema: tool.parameters };
840
+ }
841
+ toolRuntime.setGating(plan.gating);
842
+ return { plan, providerTools: plan.providerTools, modelTools };
843
+ };
844
+ let { plan, providerTools, modelTools } = snapshotStepTools();
869
845
  let activeToolResultPruneDiagnosticPatch = {};
870
846
  let midTurnCompactDiagnosticPatch;
871
847
  // Tool names the repair path matches a mis-cased call against — follows the
@@ -879,44 +855,8 @@ export class AiSdkTurn {
879
855
  : [...names];
880
856
  };
881
857
  const currentRepairToolNames = () => boundaryAwareToolNames(plan.currentRepairToolNames());
882
- if (plan.gating) {
883
- toolRuntime.setGating(plan.gating);
884
- }
885
- const modelTools = {};
886
- for (const t of providerTools) {
887
- modelTools[t.name] = t.providerTool
888
- ? { kind: 'provider', providerTool: t.providerTool }
889
- : {
890
- kind: 'function',
891
- description: t.description,
892
- inputSchema: t.parameters,
893
- };
894
- }
895
- // Resolve the stable Provider envelope before automatic Compaction freezes
896
- // its source. The same value is reused by the primary request; Memory does
897
- // not resolve or mutate Agent configuration after the checkpoint commits.
858
+ let resolvedSystemPrompt = { sourceRevisions: [] };
898
859
  let systemPrompt;
899
- try {
900
- systemPrompt = joinPromptFragments([
901
- await this.resolveSystemPrompt(),
902
- this.orchestration?.mode === 'swarm' ? renderSwarmModePrompt() : undefined,
903
- this.orchestration?.mode === 'graph' ? renderGraphModePrompt() : undefined,
904
- ]);
905
- }
906
- catch (err) {
907
- trace.modelStreamFailed(this.deps.modelAdapter.classifyError(err), err);
908
- queue.push(this.makeErrorEvent(turnId, err));
909
- queue.push({
910
- type: 'complete',
911
- id: this.deps.newId(),
912
- turnId,
913
- ts: this.deps.now(),
914
- stopReason: 'error',
915
- });
916
- queue.close();
917
- yield* this.drain(queue);
918
- return;
919
- }
920
860
  // --- Build messages from RuntimeEvent history and its compatibility projection. ---
921
861
  const priorReplayResult = await this.buildPriorMessages(input);
922
862
  if (this.aborted) {
@@ -1005,6 +945,7 @@ export class AiSdkTurn {
1005
945
  };
1006
946
  let lastCompletedStepHadToolResult = false;
1007
947
  let terminalProviderErrorReason;
948
+ let terminalRetry;
1008
949
  try {
1009
950
  const startWatchdog = () => {
1010
951
  watchdogState.current?.stop();
@@ -1054,12 +995,26 @@ export class AiSdkTurn {
1054
995
  ]
1055
996
  : turnEvents;
1056
997
  let replayEvents = rawProjectionEvents;
998
+ let effectiveProjectionCheckpoint = projectionCheckpoint;
1057
999
  if (projectionCheckpoint) {
1058
1000
  const checkpointMatch = matchHistoryCompactCheckpointPrefix(projectionCheckpoint, rawProjectionEvents);
1059
1001
  if (checkpointMatch.reason) {
1060
1002
  throw new Error(`durable checkpoint projection mismatch: ${checkpointMatch.reason}`);
1061
1003
  }
1062
- replayEvents = projectHistoryCompactCheckpointReplay(projectionCheckpoint, checkpointMatch.coveredRuntimeEvents, checkpointMatch.successorRuntimeEvents);
1004
+ // Content-currency guard: the raw identity still matches, but a
1005
+ // transition committed after this fold (e.g. an active-turn prune
1006
+ // in this very send) changed the effective view the block was
1007
+ // built from. Replay without the stale block — the provider
1008
+ // decides fit and overflow recovery re-folds (#4845 review).
1009
+ const pinnedEffectiveDigest = projectionCheckpoint.coverage.effectiveSourceDigest;
1010
+ const coveredEffective = await this.deps.compaction.foldEffectiveModelHistory(checkpointMatch.coveredRuntimeEvents);
1011
+ if (pinnedEffectiveDigest === undefined ||
1012
+ historyCompactSourceDigest(coveredEffective) !== pinnedEffectiveDigest) {
1013
+ effectiveProjectionCheckpoint = undefined;
1014
+ }
1015
+ else {
1016
+ replayEvents = projectHistoryCompactCheckpointReplay(projectionCheckpoint, checkpointMatch.coveredRuntimeEvents, checkpointMatch.successorRuntimeEvents);
1017
+ }
1063
1018
  // The checkpoint was capacity-validated before it was persisted.
1064
1019
  // Do not re-run that gate against a later, larger successor tail:
1065
1020
  // the active-step shaper must see that growth so it can roll the
@@ -1081,8 +1036,8 @@ export class AiSdkTurn {
1081
1036
  !this.deps.messageProjection.canReplayProviderNative(replayPlan))) {
1082
1037
  throw new Error('durable current-run projection is not replayable');
1083
1038
  }
1084
- const currentTurnMessages = await this.deps.messageProjection.materializeRuntimeReplayPlan(replayPlan, this.imageBudget, projectionCheckpoint, compatibleProviderReasoningReplayEventIds(replayEvents, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId, this.runId));
1085
- return projectionCheckpoint
1039
+ const currentTurnMessages = await this.deps.messageProjection.materializeRuntimeReplayPlan(replayPlan, this.imageBudget, effectiveProjectionCheckpoint, compatibleProviderReasoningReplayEventIds(replayEvents, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId, this.runId));
1040
+ return effectiveProjectionCheckpoint
1086
1041
  ? currentTurnMessages
1087
1042
  : [...priorReplay.messages, ...currentTurnMessages];
1088
1043
  };
@@ -1104,7 +1059,8 @@ export class AiSdkTurn {
1104
1059
  const onMidTurnDiagnosticPatch = (patch) => {
1105
1060
  midTurnCompactDiagnosticPatch = mergeContextBudgetDiagnosticPatches(midTurnCompactDiagnosticPatch, patch);
1106
1061
  };
1107
- const midTurnCapacityHook = this.deps.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, providerTools, onMidTurnDiagnosticPatch, this, this.automaticMemoryCompactionSupported()
1062
+ const capacityProviderTools = [...providerTools];
1063
+ const midTurnCapacityHook = this.deps.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, capacityProviderTools, onMidTurnDiagnosticPatch, this, this.automaticMemoryCompactionSupported()
1108
1064
  ? () => this.automaticMemoryCompactionDecision()
1109
1065
  : undefined, this.automaticMemoryCompactionSupported()
1110
1066
  ? (dispatch) => this.dispatchAutomaticMemoryCompaction(dispatch)
@@ -1116,7 +1072,8 @@ export class AiSdkTurn {
1116
1072
  pruneAppliedAtStep = runtimeSteps;
1117
1073
  activeToolResultPruneDiagnosticPatch = mergeActiveToolResultPruneDiagnosticPatches(activeToolResultPruneDiagnosticPatch, patch);
1118
1074
  });
1119
- const shapedProjection = composeRequestProjection(plan.projectActiveTools, midTurnCapacityHook, activeToolResultPruneHook);
1075
+ const projectCurrentToolAvailability = (options) => plan.projectActiveTools?.(options);
1076
+ const shapedProjection = composeRequestProjection(projectCurrentToolAvailability, midTurnCapacityHook, activeToolResultPruneHook);
1120
1077
  // Hooks shape; nothing measures the final payload. Whether it fits is
1121
1078
  // the provider's answer (#4559).
1122
1079
  const requestProjection = shapedProjection;
@@ -1132,6 +1089,14 @@ export class AiSdkTurn {
1132
1089
  let finishReason = 'stop';
1133
1090
  let terminalProviderError;
1134
1091
  agentLoop: for (;;) {
1092
+ ({ plan, providerTools, modelTools } = snapshotStepTools());
1093
+ resolvedSystemPrompt = await this.resolveSystemPrompt();
1094
+ systemPrompt = joinPromptFragments([
1095
+ resolvedSystemPrompt.text,
1096
+ this.orchestration.mode === 'swarm' ? renderSwarmModePrompt() : undefined,
1097
+ this.orchestration.mode === 'graph' ? renderGraphModePrompt() : undefined,
1098
+ ]);
1099
+ capacityProviderTools.splice(0, capacityProviderTools.length, ...providerTools);
1135
1100
  await this.drainSteeringInto(input, queue);
1136
1101
  if (this.deps.backend.loadTurnRuntimeEvents) {
1137
1102
  requestMessages = await loadDurableTurnProjection();
@@ -1180,7 +1145,20 @@ export class AiSdkTurn {
1180
1145
  : undefined;
1181
1146
  const projectedMessages = shaped?.messages ?? requestMessages;
1182
1147
  const activeToolsForRequest = resolveDispatch(shaped?.activeTools).activeTools;
1183
- providerRequestTracker?.setStep(runtimeSteps);
1148
+ const requestCompositionId = this.runId && this.deps.backend.recordRequestComposition
1149
+ ? await this.deps.backend.recordRequestComposition(this.runId, {
1150
+ compositionId: this.deps.newId(),
1151
+ step: runtimeSteps,
1152
+ sourceRevisions: resolvedSystemPrompt.sourceRevisions,
1153
+ systemPromptHash: stableHash(requestSystemPrompt ?? ''),
1154
+ toolCatalogHash: toolCatalogHash(providerTools),
1155
+ toolAvailabilityHash: toolAvailabilityHash(this.deps.backend.toolAvailability),
1156
+ providerOptionsHash: stableHash(this.deps.resolvedProviderOptions),
1157
+ toolNames: activeToolsForRequest,
1158
+ toolSchemas: requestCompositionToolSchemas(providerTools, activeToolsForRequest),
1159
+ })
1160
+ : undefined;
1161
+ providerRequestTracker?.setStep(runtimeSteps, requestCompositionId);
1184
1162
  let attemptMessages = projectedMessages;
1185
1163
  let providerAttempt = 1;
1186
1164
  let idleWatchdogRetryCount = 0;
@@ -1351,15 +1329,10 @@ export class AiSdkTurn {
1351
1329
  ? stepUsage.inputTokens === priorInput
1352
1330
  : stepUsage.inputTokens <= priorInput)) {
1353
1331
  this.deps.session.contextProviderDroppingReported = true;
1354
- const note = {
1355
- type: 'system_note',
1356
- id: this.deps.newId(),
1357
- turnId,
1358
- ts: this.deps.now(),
1359
- kind: 'context_provider_dropping',
1360
- data: { inputTokens: stepUsage.inputTokens, priorInputTokens: priorInput },
1361
- };
1362
- await this.deps.backend.appendMessage(note).catch(() => { });
1332
+ await this.recordSystemNote('context_provider_dropping', turnId, {
1333
+ inputTokens: stepUsage.inputTokens,
1334
+ priorInputTokens: priorInput,
1335
+ });
1363
1336
  }
1364
1337
  // Fail closed: reset on every step boundary so a missing final
1365
1338
  // step's usage does not leave a stale value from an earlier step.
@@ -1378,18 +1351,10 @@ export class AiSdkTurn {
1378
1351
  stepUsage.outputTokens > 0 &&
1379
1352
  stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity) {
1380
1353
  contextWindowOverrunNoteWritten = true;
1381
- const note = {
1382
- type: 'system_note',
1383
- id: this.deps.newId(),
1384
- turnId,
1385
- ts: this.deps.now(),
1386
- kind: 'context_window_overrun',
1387
- data: {
1388
- usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1389
- declaredContextWindow: midTurnState.capacity,
1390
- },
1391
- };
1392
- await this.deps.backend.appendMessage(note).catch(() => { });
1354
+ await this.recordSystemNote('context_window_overrun', turnId, {
1355
+ usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1356
+ declaredContextWindow: midTurnState.capacity,
1357
+ });
1393
1358
  }
1394
1359
  // Nothing declared, and the provider accepted a request past
1395
1360
  // the window this model reports. Every other signal in this
@@ -1425,15 +1390,10 @@ export class AiSdkTurn {
1425
1390
  (previousTotal === undefined || previousTotal <= reported);
1426
1391
  if (reported !== undefined && crossedNow) {
1427
1392
  contextReportedWindowNoteWritten = true;
1428
- const note = {
1429
- type: 'system_note',
1430
- id: this.deps.newId(),
1431
- turnId,
1432
- ts: this.deps.now(),
1433
- kind: 'context_reported_window_exceeded',
1434
- data: { usedTokens: used, reportedContextWindow: reported },
1435
- };
1436
- await this.deps.backend.appendMessage(note).catch(() => { });
1393
+ await this.recordSystemNote('context_reported_window_exceeded', turnId, {
1394
+ usedTokens: used,
1395
+ reportedContextWindow: reported,
1396
+ });
1437
1397
  }
1438
1398
  }
1439
1399
  lastStepInputTokens = stepUsage?.inputTokens;
@@ -1733,20 +1693,12 @@ export class AiSdkTurn {
1733
1693
  acceptedTotal !== undefined &&
1734
1694
  (midTurnState.capacity === undefined || acceptedTotal < midTurnState.capacity)) {
1735
1695
  contextWindowSuggestionNoteWritten = true;
1736
- const note = {
1737
- type: 'system_note',
1738
- id: this.deps.newId(),
1739
- turnId,
1740
- ts: this.deps.now(),
1741
- kind: 'context_window_suggestion',
1742
- data: {
1743
- suggestedContextWindow: acceptedTotal,
1744
- ...(midTurnState.capacity !== undefined
1745
- ? { declaredContextWindow: midTurnState.capacity }
1746
- : {}),
1747
- },
1748
- };
1749
- await this.deps.backend.appendMessage(note).catch(() => { });
1696
+ await this.recordSystemNote('context_window_suggestion', turnId, {
1697
+ suggestedContextWindow: acceptedTotal,
1698
+ ...(midTurnState.capacity !== undefined
1699
+ ? { declaredContextWindow: midTurnState.capacity }
1700
+ : {}),
1701
+ });
1750
1702
  }
1751
1703
  // A folded projection was selected in this send and the provider
1752
1704
  // still rejects the request. That is worth saying, because the
@@ -1760,14 +1712,7 @@ export class AiSdkTurn {
1760
1712
  failure.kind === 'context_overflow' &&
1761
1713
  midTurnState?.compactionAppliedThisSend === true) {
1762
1714
  contextOverflowAfterCompactionNoteWritten = true;
1763
- const note = {
1764
- type: 'system_note',
1765
- id: this.deps.newId(),
1766
- turnId,
1767
- ts: this.deps.now(),
1768
- kind: 'context_overflow_after_compaction',
1769
- };
1770
- await this.deps.backend.appendMessage(note).catch(() => { });
1715
+ await this.recordSystemNote('context_overflow_after_compaction', turnId);
1771
1716
  }
1772
1717
  const idleWatchdogRecovery = settledWatchdogTimeout?.phase === 'idle' &&
1773
1718
  idleWatchdogRetryCount < MAX_IDLE_WATCHDOG_RETRIES_PER_STEP &&
@@ -1786,14 +1731,35 @@ export class AiSdkTurn {
1786
1731
  sealedThinkingRetryCount < MAX_SEALED_THINKING_RETRIES_PER_STEP &&
1787
1732
  attemptCanRecoverWithSealedThinking() &&
1788
1733
  !attemptHasNoObservableOutput();
1789
- if ((failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery) &&
1790
- failure.kind !== 'context_overflow' &&
1791
- providerAttempt < MAX_PROVIDER_ATTEMPTS_PER_STEP &&
1792
- stepBudgetRemains &&
1793
- (attemptHasNoObservableOutput() ||
1794
- idleWatchdogRecovery ||
1795
- incompleteStreamRecovery ||
1796
- sealedThinkingRecovery)) {
1734
+ // The stopping gate also supplies the durable reason. An absent
1735
+ // decision means this attempt is allowed to retry.
1736
+ let retry;
1737
+ if (!(attemptHasNoObservableOutput() ||
1738
+ idleWatchdogRecovery ||
1739
+ incompleteStreamRecovery ||
1740
+ sealedThinkingRecovery)) {
1741
+ retry = {
1742
+ decision: 'declined',
1743
+ because: attemptSawToolActivity ? 'side_effects' : 'observable_output',
1744
+ };
1745
+ }
1746
+ else if (!stepBudgetRemains) {
1747
+ retry = { decision: 'declined', because: 'budget' };
1748
+ }
1749
+ else if (providerAttempt >= MAX_PROVIDER_ATTEMPTS_PER_STEP) {
1750
+ retry = { decision: 'exhausted', attempts: providerAttempt };
1751
+ }
1752
+ else if (failure.kind === 'context_overflow') {
1753
+ retry = { decision: 'declined', because: 'policy' };
1754
+ }
1755
+ else if (!(failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery)) {
1756
+ retry =
1757
+ incompleteStreamTerminal &&
1758
+ incompleteStreamRetryCount >= MAX_INCOMPLETE_STREAM_RETRIES_PER_STEP
1759
+ ? { decision: 'exhausted', attempts: providerAttempt }
1760
+ : { decision: 'declined', because: 'policy' };
1761
+ }
1762
+ if (!retry) {
1797
1763
  if (idleWatchdogRecovery)
1798
1764
  idleWatchdogRetryCount += 1;
1799
1765
  if (sealedThinkingRecovery)
@@ -1845,6 +1811,7 @@ export class AiSdkTurn {
1845
1811
  // handler after settling any authoritative usage — never a
1846
1812
  // fabricated success.
1847
1813
  terminalProviderError = settledWatchdogTimeout?.error ?? failure;
1814
+ terminalRetry = { error: terminalProviderError, retry };
1848
1815
  terminalProviderErrorReason =
1849
1816
  lastCompletedStepHadToolResult && failure.kind === 'timeout'
1850
1817
  ? 'model_after_tool_timeout'
@@ -1981,6 +1948,12 @@ export class AiSdkTurn {
1981
1948
  }
1982
1949
  const mayTakeAnotherStep = !stepLimitReached && !this.loopStopRequested && !this.aborted;
1983
1950
  if (returnedToolCalls.length > 0 && mayTakeAnotherStep) {
1951
+ if ((await input.handoffBoundary?.(turnAbortController.signal, maxSteps === undefined ? null : maxSteps - runtimeSteps)) === 'pause') {
1952
+ this.handoffPaused = true;
1953
+ break agentLoop;
1954
+ }
1955
+ if (this.aborted || this.loopStopRequested)
1956
+ break agentLoop;
1984
1957
  currentStepMessageId = this.deps.newId();
1985
1958
  continue agentLoop;
1986
1959
  }
@@ -2009,6 +1982,13 @@ export class AiSdkTurn {
2009
1982
  if (this.injectedSteeringMessages.length > injectedBefore &&
2010
1983
  !this.loopStopRequested &&
2011
1984
  !this.aborted) {
1985
+ await queue.waitUntilConsumedThroughCurrent();
1986
+ if ((await input.handoffBoundary?.(turnAbortController.signal, maxSteps === undefined ? null : maxSteps - runtimeSteps)) === 'pause') {
1987
+ this.handoffPaused = true;
1988
+ break agentLoop;
1989
+ }
1990
+ if (this.aborted || this.loopStopRequested)
1991
+ break agentLoop;
2012
1992
  currentStepMessageId = this.deps.newId();
2013
1993
  continue agentLoop;
2014
1994
  }
@@ -2097,14 +2077,6 @@ export class AiSdkTurn {
2097
2077
  }
2098
2078
  : {}),
2099
2079
  };
2100
- const tu = {
2101
- type: 'token_usage',
2102
- id: this.deps.newId(),
2103
- turnId,
2104
- ts: this.deps.now(),
2105
- ...usageFields,
2106
- };
2107
- await this.deps.backend.appendMessage(tu).catch(() => { });
2108
2080
  // Settlement fallback: a mid-turn or request-hook fold is only
2109
2081
  // known here. Notes already written at decision time are skipped
2110
2082
  // by the flags inside.
@@ -2127,6 +2099,10 @@ export class AiSdkTurn {
2127
2099
  throw Object.assign(new Error('aborted'), { name: 'AbortError' });
2128
2100
  if (terminalProviderError)
2129
2101
  throw terminalProviderError;
2102
+ // Usage above still belongs to this physical attempt. Its Runtime owner
2103
+ // seals the drained stream; no complete/abort event ends the logical Turn.
2104
+ if (this.handoffPaused)
2105
+ return;
2130
2106
  const stopReason = this.loopStopReason ??
2131
2107
  (maxSteps !== undefined && finishReason === 'tool-calls'
2132
2108
  ? 'step_limit'
@@ -2159,8 +2135,8 @@ export class AiSdkTurn {
2159
2135
  // Flush the in-flight step's partial text/thinking before the terminal
2160
2136
  // abort/error events. Earlier steps already flushed at their
2161
2137
  // `finish-step`; this keeps their and this step's streamed-out output on
2162
- // BOTH exits — user stop and provider error / watchdog timeout — so
2163
- // partialOutputRetained reflects what the user actually saw.
2138
+ // BOTH exits — user stop and provider error / watchdog timeout — so the
2139
+ // transcript keeps what the user actually saw.
2164
2140
  await flushStep().catch(() => { });
2165
2141
  if (this.aborted) {
2166
2142
  queue.push({
@@ -2180,7 +2156,12 @@ export class AiSdkTurn {
2180
2156
  }
2181
2157
  else {
2182
2158
  const terminalError = currentWatchdogTimeout()?.error ?? err;
2183
- queue.push(this.makeErrorEvent(turnId, terminalError, terminalProviderErrorReason));
2159
+ queue.push({
2160
+ ...this.makeErrorEvent(turnId, terminalError, terminalProviderErrorReason),
2161
+ ...(terminalRetry && terminalRetry.error === terminalError
2162
+ ? { retry: terminalRetry.retry }
2163
+ : {}),
2164
+ });
2184
2165
  trace.modelStreamFailed(streamErrorClass, terminalError, priorReplayFailureTrace(priorReplay));
2185
2166
  queue.push({
2186
2167
  type: 'complete',
@@ -2394,7 +2375,11 @@ export class AiSdkTurn {
2394
2375
  diagnostics: [],
2395
2376
  };
2396
2377
  }
2397
- const rawPriorRuntimeContext = input.runtimeContext.filter((event) => event.turnId !== input.turnId);
2378
+ // A handoff changes the physical Run, not the logical Turn. Its admitted
2379
+ // replay is all predecessor history, including events with this turnId.
2380
+ const rawPriorRuntimeContext = input.continuation
2381
+ ? input.runtimeContext
2382
+ : input.runtimeContext.filter((event) => event.turnId !== input.turnId);
2398
2383
  // Everything below reads EFFECTIVE model history: raw events folded through
2399
2384
  // the durable projection-transition reducer (#4283). Replay, budgeting and
2400
2385
  // compaction share one input, so no RuntimeEvent replay path can resurrect
@@ -2403,8 +2388,16 @@ export class AiSdkTurn {
2403
2388
  const priorRuntimeContext = preparedContextBudget.events;
2404
2389
  const providerReasoningReplayEventIds = compatibleProviderReasoningReplayEventIds(priorRuntimeContext, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId);
2405
2390
  let contextBudget = preparedContextBudget.policy;
2406
- const budgeted = applyRuntimeEventContextBudget(priorRuntimeContext, contextBudget);
2407
- let runtimeContext = budgeted?.events ?? priorRuntimeContext;
2391
+ // Match the durable checkpoint against the RAW ledger prefix: every
2392
+ // creation path (standalone compactHistory and the mid-turn state) pins
2393
+ // its coverage digest on raw events, so matching the folded view here
2394
+ // lets any durable projection transition inside the covered prefix orphan
2395
+ // the checkpoint and silently fail open into a full-history replay
2396
+ // (#4842). The projected [block, tail] is then folded through the
2397
+ // transition reducer before it becomes messages, so a committed
2398
+ // transition still cannot resurrect content for the model (#4283).
2399
+ const budgeted = applyRuntimeEventContextBudget(rawPriorRuntimeContext, contextBudget);
2400
+ let runtimeContext = await this.deps.compaction.foldEffectiveModelHistory(budgeted?.events ?? rawPriorRuntimeContext);
2408
2401
  let contextBudgetDiagnostic = budgeted?.diagnostic;
2409
2402
  let projectedHistoryCompactCheckpoint = budgeted?.historyCompactCheckpoint;
2410
2403
  if (preparedContextBudget.diagnosticPatch) {
@@ -2494,14 +2487,22 @@ export class AiSdkTurn {
2494
2487
  async resolveSystemPrompt() {
2495
2488
  const turnId = this.turnId;
2496
2489
  if (typeof this.deps.backend.systemPrompt === 'function') {
2497
- return await this.deps.backend.systemPrompt({
2490
+ const resolved = await this.deps.backend.systemPrompt({
2498
2491
  sessionId: this.deps.backend.sessionId,
2499
2492
  turnId,
2500
2493
  cwd: this.deps.backend.header.cwd,
2501
2494
  emitSkillCatalogTrace: (message, data) => this.runTrace?.emit('skill', 'skill_catalog_built', message, data),
2502
2495
  });
2496
+ return typeof resolved === 'string' || resolved === undefined
2497
+ ? { ...(resolved === undefined ? {} : { text: resolved }), sourceRevisions: [] }
2498
+ : resolved;
2503
2499
  }
2504
- return this.deps.backend.systemPrompt;
2500
+ return {
2501
+ ...(this.deps.backend.systemPrompt === undefined
2502
+ ? {}
2503
+ : { text: this.deps.backend.systemPrompt }),
2504
+ sourceRevisions: [],
2505
+ };
2505
2506
  }
2506
2507
  async *drain(queue) {
2507
2508
  try {
@@ -25,7 +25,7 @@ export function buildArchiveReadTool(reader) {
25
25
  .object({
26
26
  ref: z
27
27
  .string()
28
- .describe('A maka://archive/... ref returned in an archived tool-result placeholder'),
28
+ .describe('The exact resourceRef returned in an archived tool-result placeholder (ledger or legacy archive)'),
29
29
  operation: z
30
30
  .enum(['inspect', 'read', 'query', 'search'])
31
31
  .default('inspect')
@@ -82,7 +82,7 @@ export function buildArchiveReadTool(reader) {
82
82
  name: ARCHIVE_READ_TOOL_NAME,
83
83
  displayName: 'Read archived result',
84
84
  activityKind: 'read',
85
- description: 'Inspect, search, or page through a tool-result archive returned as a maka://archive/... ref. Start with inspect for a preview and the char/line coordinate space. Use operation "search" with a pattern to locate text, operation "read" with unit "line" for line-oriented terminal output, or operation "query" with an itemId for one agent_swarm item. Results are strictly bounded so reading an archive cannot immediately trigger another archive.',
85
+ description: 'Inspect, search, or page through a tool-result archive using its exact resourceRef. Both ledger and legacy archive references are supported. Start with inspect for a preview and the char/line coordinate space. Use operation "search" with a pattern to locate text, operation "read" with unit "line" for line-oriented terminal output, or operation "query" with an itemId for one agent_swarm item. Results are strictly bounded so reading an archive cannot immediately trigger another archive.',
86
86
  parameters: jsonSchema(async () => await providerSchema.jsonSchema, {
87
87
  validate: async (value) => {
88
88
  const result = await parameters.safeParseAsync(value);