maka-agent 0.2.0-dev.30.20260912 → 0.2.0-dev.32.20260914

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 (245) hide show
  1. package/THIRD_PARTY_NOTICES.txt +392 -0
  2. package/dist/acp/maka-acp-agent.js +8 -2
  3. package/dist/acp/prompt-content.js +225 -0
  4. package/dist/acp/session-event-mapper.js +103 -0
  5. package/dist/acp/session-registry.js +654 -17
  6. package/dist/acp/stdio-server.js +10 -1
  7. package/dist/cli-core.js +1 -1
  8. package/dist/pi-transcript-tools.js +3 -2
  9. package/dist/pi-transcript.js +15 -6
  10. package/dist/runtime-host-session-channel.js +63 -9
  11. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  12. package/node_modules/@maka/core/dist/agent-graph-schedule.js +15 -4
  13. package/node_modules/@maka/core/dist/artifacts.js +6 -0
  14. package/node_modules/@maka/core/dist/attachments.js +7 -2
  15. package/node_modules/@maka/core/dist/durable-tool-result-projection.js +3 -1
  16. package/node_modules/@maka/core/dist/events.js +21 -0
  17. package/node_modules/@maka/core/dist/executor-id.js +22 -0
  18. package/node_modules/@maka/core/dist/external-session.js +18 -0
  19. package/node_modules/@maka/core/dist/goal.js +44 -2
  20. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -13
  21. package/node_modules/@maka/core/dist/permission.js +0 -1
  22. package/node_modules/@maka/core/dist/runtime-boundary.js +73 -29
  23. package/node_modules/@maka/core/dist/runtime-event.js +25 -6
  24. package/node_modules/@maka/core/dist/runtime-handoff.js +10 -2
  25. package/node_modules/@maka/core/dist/runtime-logical-execution.js +39 -14
  26. package/node_modules/@maka/core/dist/session-send-projection.js +6 -3
  27. package/node_modules/@maka/core/dist/session.js +8 -2
  28. package/node_modules/@maka/core/dist/shell-run-result.js +1 -0
  29. package/node_modules/@maka/core/dist/shell-run.js +4 -0
  30. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +3 -1
  31. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  32. package/node_modules/@maka/core/dist/unified-diff.js +33 -26
  33. package/node_modules/@maka/core/dist/work-board.js +94 -1
  34. package/node_modules/@maka/core/package.json +1 -0
  35. package/node_modules/@maka/eval/dist/fleet-simulation.js +270 -0
  36. package/node_modules/@maka/eval/dist/fleet-store.js +243 -0
  37. package/node_modules/@maka/eval/dist/fleet-worker.js +125 -0
  38. package/node_modules/@maka/eval/dist/fleet.js +329 -0
  39. package/node_modules/@maka/eval/dist/index.js +3 -0
  40. package/node_modules/@maka/runtime/dist/agent-run.js +2 -17
  41. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +55 -180
  42. package/node_modules/@maka/runtime/dist/ai-sdk-message-projection.js +43 -26
  43. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +271 -382
  44. package/node_modules/@maka/runtime/dist/background-task-health-tool.js +104 -0
  45. package/node_modules/@maka/runtime/dist/bash-model-output.js +7 -1
  46. package/node_modules/@maka/runtime/dist/bash-tail-buffer.js +13 -52
  47. package/node_modules/@maka/runtime/dist/builtin-tools.js +59 -111
  48. package/node_modules/@maka/runtime/dist/child-fd-input.js +3 -2
  49. package/node_modules/@maka/runtime/dist/context-budget-policy.js +1 -11
  50. package/node_modules/@maka/runtime/dist/context-budget.js +12 -1
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +104 -9
  52. package/node_modules/@maka/runtime/dist/filesystem-executor.js +10 -6
  53. package/node_modules/@maka/runtime/dist/filesystem-worker/client.js +77 -19
  54. package/node_modules/@maka/runtime/dist/filesystem-worker/launch-spec.js +66 -55
  55. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +34 -97
  56. package/node_modules/@maka/runtime/dist/filesystem-worker/protocol.js +25 -10
  57. package/node_modules/@maka/runtime/dist/filesystem-worker/worker-entry.js +2 -0
  58. package/node_modules/@maka/runtime/dist/glob-search.js +74 -0
  59. package/node_modules/@maka/runtime/dist/goal-continuation.js +78 -8
  60. package/node_modules/@maka/runtime/dist/goal-state.js +7 -0
  61. package/node_modules/@maka/runtime/dist/grep-search.js +155 -0
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +3 -1
  63. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +84 -94
  64. package/node_modules/@maka/runtime/dist/local-web-fetch.js +1 -1
  65. package/node_modules/@maka/runtime/dist/model-adapter.js +62 -53
  66. package/node_modules/@maka/runtime/dist/model-history.js +26 -8
  67. package/node_modules/@maka/runtime/dist/pipe-tail-collector.js +6 -9
  68. package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +311 -0
  69. package/node_modules/@maka/runtime/dist/plugin-executor-service.js +344 -0
  70. package/node_modules/@maka/runtime/dist/provider-error-classification.js +7 -1
  71. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +35 -8
  72. package/node_modules/@maka/runtime/dist/read-page.js +231 -0
  73. package/node_modules/@maka/runtime/dist/request-projection.js +2 -15
  74. package/node_modules/@maka/runtime/dist/ripgrep-executable.js +62 -0
  75. package/node_modules/@maka/runtime/dist/ripgrep-guidance.js +81 -0
  76. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +7 -1
  77. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +188 -20
  78. package/node_modules/@maka/runtime/dist/runtime-invocation-route.js +49 -0
  79. package/node_modules/@maka/runtime/dist/runtime-kernel.js +72 -150
  80. package/node_modules/@maka/runtime/dist/runtime-read-model.js +2 -3
  81. package/node_modules/@maka/runtime/dist/sandbox/linux-profile-path.js +7 -1
  82. package/node_modules/@maka/runtime/dist/sandbox/linux-sandbox.js +20 -5
  83. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +3 -0
  84. package/node_modules/@maka/runtime/dist/session-manager.js +106 -64
  85. package/node_modules/@maka/runtime/dist/session-recap.js +9 -5
  86. package/node_modules/@maka/runtime/dist/shell-exec.js +7 -25
  87. package/node_modules/@maka/runtime/dist/shell-run-manager.js +10 -4
  88. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +2 -1
  89. package/node_modules/@maka/runtime/dist/shell-tools.js +6 -12
  90. package/node_modules/@maka/runtime/dist/stream-graph-schedule-reconcile.js +1 -0
  91. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +26 -4
  92. package/node_modules/@maka/runtime/dist/subagent-tools.js +7 -0
  93. package/node_modules/@maka/runtime/dist/tool-availability.js +0 -1
  94. package/node_modules/@maka/runtime/dist/tool-output.js +1 -1
  95. package/node_modules/@maka/runtime/dist/tool-result-archive-capability.js +24 -36
  96. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +32 -527
  97. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +17 -119
  98. package/node_modules/@maka/runtime/dist/tool-result-archive.js +7 -25
  99. package/node_modules/@maka/runtime/dist/tool-runtime.js +52 -471
  100. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +6933 -3681
  101. package/node_modules/@maka/runtime/dist/workspace-executor.js +20 -24
  102. package/node_modules/@maka/runtime/package.json +5 -0
  103. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +7 -2
  104. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +185 -191
  105. package/node_modules/@maka/runtime-host/dist/client/reconnecting-connection.js +3 -0
  106. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +1 -0
  107. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +24 -3
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +8 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/message.js +2 -2
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +42 -5
  112. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +31 -3
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +8 -2
  114. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +10 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +38 -0
  116. package/node_modules/@maka/runtime-host/dist/server/child-agent-composition.js +1 -0
  117. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +3 -30
  118. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +56 -8
  119. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +14 -1
  120. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +81 -7
  121. package/node_modules/@maka/runtime-host/dist/server/host-session-availability.js +10 -2
  122. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +13 -13
  123. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +65 -0
  124. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  125. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  126. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +1 -0
  127. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +56 -16
  128. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +9 -5
  129. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +4 -0
  130. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +88 -72
  131. package/node_modules/@maka/runtime-host/dist/server/web-fetch-tool.js +37 -1
  132. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +21 -4
  133. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +145 -1
  134. package/node_modules/@maka/storage/dist/agent-run-store.js +5 -2
  135. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +450 -234
  136. package/node_modules/@maka/storage/dist/claude-code-transcript-lineage.js +106 -77
  137. package/node_modules/@maka/storage/dist/execution-stores.js +2 -1
  138. package/node_modules/@maka/storage/dist/legacy-run-header.js +2 -2
  139. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +1 -1
  140. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +27 -14
  141. package/node_modules/@maka/storage/dist/session-store.js +12 -2
  142. package/node_modules/@maka/storage/dist/sqlite-long-term-memory-store.js +86 -12
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +69 -3
  144. package/node_modules/@maka/storage/dist/work-board-store.js +40 -1
  145. package/node_modules/balanced-match/LICENSE.md +23 -0
  146. package/node_modules/balanced-match/README.md +57 -0
  147. package/node_modules/balanced-match/dist/commonjs/index.js +59 -0
  148. package/node_modules/balanced-match/dist/commonjs/package.json +3 -0
  149. package/node_modules/balanced-match/dist/esm/index.js +54 -0
  150. package/node_modules/balanced-match/dist/esm/package.json +3 -0
  151. package/node_modules/balanced-match/package.json +68 -0
  152. package/node_modules/brace-expansion/LICENSE +23 -0
  153. package/node_modules/brace-expansion/README.md +105 -0
  154. package/node_modules/brace-expansion/dist/commonjs/index.js +289 -0
  155. package/node_modules/brace-expansion/dist/commonjs/package.json +3 -0
  156. package/node_modules/brace-expansion/dist/esm/index.js +285 -0
  157. package/node_modules/brace-expansion/dist/esm/package.json +3 -0
  158. package/node_modules/brace-expansion/package.json +64 -0
  159. package/node_modules/glob/LICENSE.md +63 -0
  160. package/node_modules/glob/README.md +1203 -0
  161. package/node_modules/glob/dist/commonjs/glob.js +248 -0
  162. package/node_modules/glob/dist/commonjs/has-magic.js +27 -0
  163. package/node_modules/glob/dist/commonjs/ignore.js +119 -0
  164. package/node_modules/glob/dist/commonjs/index.js +68 -0
  165. package/node_modules/glob/dist/commonjs/index.min.js +4 -0
  166. package/node_modules/glob/dist/commonjs/package.json +3 -0
  167. package/node_modules/glob/dist/commonjs/pattern.js +223 -0
  168. package/node_modules/glob/dist/commonjs/processor.js +301 -0
  169. package/node_modules/glob/dist/commonjs/walker.js +387 -0
  170. package/node_modules/glob/dist/esm/glob.js +244 -0
  171. package/node_modules/glob/dist/esm/has-magic.js +23 -0
  172. package/node_modules/glob/dist/esm/ignore.js +115 -0
  173. package/node_modules/glob/dist/esm/index.js +55 -0
  174. package/node_modules/glob/dist/esm/index.min.js +4 -0
  175. package/node_modules/glob/dist/esm/package.json +3 -0
  176. package/node_modules/glob/dist/esm/pattern.js +219 -0
  177. package/node_modules/glob/dist/esm/processor.js +294 -0
  178. package/node_modules/glob/dist/esm/walker.js +381 -0
  179. package/node_modules/glob/package.json +98 -0
  180. package/node_modules/minimatch/LICENSE.md +55 -0
  181. package/node_modules/minimatch/README.md +528 -0
  182. package/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js +14 -0
  183. package/node_modules/minimatch/dist/commonjs/ast.js +845 -0
  184. package/node_modules/minimatch/dist/commonjs/brace-expressions.js +150 -0
  185. package/node_modules/minimatch/dist/commonjs/escape.js +30 -0
  186. package/node_modules/minimatch/dist/commonjs/index.js +1127 -0
  187. package/node_modules/minimatch/dist/commonjs/package.json +3 -0
  188. package/node_modules/minimatch/dist/commonjs/unescape.js +38 -0
  189. package/node_modules/minimatch/dist/esm/assert-valid-pattern.js +10 -0
  190. package/node_modules/minimatch/dist/esm/ast.js +841 -0
  191. package/node_modules/minimatch/dist/esm/brace-expressions.js +146 -0
  192. package/node_modules/minimatch/dist/esm/escape.js +26 -0
  193. package/node_modules/minimatch/dist/esm/index.js +1114 -0
  194. package/node_modules/minimatch/dist/esm/package.json +3 -0
  195. package/node_modules/minimatch/dist/esm/unescape.js +34 -0
  196. package/node_modules/minimatch/package.json +73 -0
  197. package/node_modules/minipass/LICENSE.md +55 -0
  198. package/node_modules/minipass/README.md +825 -0
  199. package/node_modules/minipass/dist/commonjs/index.js +1038 -0
  200. package/node_modules/minipass/dist/commonjs/package.json +3 -0
  201. package/node_modules/minipass/dist/esm/index.js +1020 -0
  202. package/node_modules/minipass/dist/esm/package.json +3 -0
  203. package/node_modules/minipass/package.json +77 -0
  204. package/node_modules/path-scurry/LICENSE.md +55 -0
  205. package/node_modules/path-scurry/README.md +636 -0
  206. package/node_modules/path-scurry/dist/commonjs/index.js +2018 -0
  207. package/node_modules/path-scurry/dist/commonjs/package.json +3 -0
  208. package/node_modules/path-scurry/dist/esm/index.js +1983 -0
  209. package/node_modules/path-scurry/dist/esm/package.json +3 -0
  210. package/node_modules/path-scurry/node_modules/lru-cache/LICENSE.md +55 -0
  211. package/node_modules/path-scurry/node_modules/lru-cache/README.md +469 -0
  212. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/diagnostics-channel.js +7 -0
  213. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/index.js +1726 -0
  214. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/index.min.js +2 -0
  215. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/perf.js +10 -0
  216. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/diagnostics-channel-cjs.d.cts.map +1 -0
  217. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/diagnostics-channel.js +7 -0
  218. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/index.js +1726 -0
  219. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/index.min.js +2 -0
  220. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/diagnostics-channel.js +9 -0
  221. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/index.js +1726 -0
  222. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/index.min.js +2 -0
  223. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/perf.js +10 -0
  224. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/package.json +3 -0
  225. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/perf.js +10 -0
  226. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/diagnostics-channel.js +4 -0
  227. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/index.js +1722 -0
  228. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/index.min.js +2 -0
  229. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/perf.js +7 -0
  230. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/diagnostics-channel-esm.d.mts.map +1 -0
  231. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/diagnostics-channel.js +19 -0
  232. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/index.js +1722 -0
  233. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/index.min.js +2 -0
  234. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/diagnostics-channel.js +6 -0
  235. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/index.js +1722 -0
  236. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/index.min.js +2 -0
  237. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/perf.js +7 -0
  238. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/package.json +3 -0
  239. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/perf.js +7 -0
  240. package/node_modules/path-scurry/node_modules/lru-cache/package.json +154 -0
  241. package/node_modules/path-scurry/package.json +72 -0
  242. package/package.json +1 -1
  243. package/node_modules/@maka/runtime/dist/active-tool-result-prune.js +0 -248
  244. package/node_modules/@maka/runtime/dist/active-tool-result-working-set.js +0 -218
  245. package/node_modules/@maka/runtime/dist/archive-read-tool.js +0 -115
@@ -33,16 +33,17 @@ import { composeRequestProjection, } from './request-projection.js';
33
33
  import { decodePlaintextResponsesReasoningState, responsesReasoningItemId, } from './responses-reasoning-state.js';
34
34
  import { finitePositive } from './context-budget-helpers.js';
35
35
  import { contextDiagnosticsCompactionOf, } from './context-diagnostics.js';
36
- import { hasActiveToolResultPruneDiagnosticPatch, hasBlockingReplayDiagnostics, } from './ai-sdk-compaction.js';
36
+ import { hasBlockingReplayDiagnostics } from './ai-sdk-compaction.js';
37
37
  import { RunTrace } from './run-trace.js';
38
38
  import { REQUEST_SANDBOX_BOUNDARY_TOOL_NAME, SANDBOX_BOUNDARY_DENIED_FOR_TURN, SANDBOX_BOUNDARY_FINALIZATION_PROMPT, } from './sandbox-boundary-tool.js';
39
39
  import { buildRuntimeEventModelReplayPlan, buildSteeringEnvelope, collectToolActivityTurnIds, compatibleProviderReasoningReplayEventIds, formatTextWithInlineRefs, steeringMessagesMissingFromBase, steeringModelMessage, } from './model-history.js';
40
40
  import { toolSchemaCharsForDiagnostics, requestCompositionToolSchemas, stableHash, toolCatalogHash, } from './request-shape.js';
41
41
  import { toolAvailabilityHash } from './tool-availability.js';
42
+ import { hasFinalizedReasoning } from './ai-sdk-message-projection.js';
42
43
  import { renderSwarmModePrompt } from './swarm-mode.js';
43
44
  import { renderGraphModePrompt } from './graph-mode.js';
44
45
  import { modelUsesNativeOpenAiResponses } from './model-runtime.js';
45
- import { applyRuntimeEventContextBudget, buildContextBudgetDiagnosticShell, mergeContextBudgetDiagnostic, mergeContextBudgetDiagnosticPatches, minimalContextBudgetDiagnostic, shouldAppendContextCompactedNote, shouldAppendContextCompactionFailedOpenNote, } from './context-budget.js';
46
+ import { applyRuntimeEventContextBudget, buildContextBudgetDiagnosticShell, mergeContextBudgetDiagnostic, addToolResultPruneStats, minimalContextBudgetDiagnostic, shouldAppendContextCompactedNote, shouldAppendContextCompactionFailedOpenNote, } from './context-budget.js';
46
47
  import { isHistoryCompactContentEvent } from './history-compaction.js';
47
48
  import { canContinueHistoryCompactCheckpointForModel, historyCompactSourceDigest, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
48
49
  import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
@@ -345,13 +346,6 @@ function joinPromptFragments(fragments) {
345
346
  }
346
347
  const MAX_WAITING_CODE_MODE_CELLS = 1;
347
348
  const MAX_PROVIDER_ATTEMPTS_PER_STEP = 10;
348
- const MAX_IDLE_WATCHDOG_RETRIES_PER_STEP = 1;
349
- const MAX_INCOMPLETE_STREAM_RETRIES_PER_STEP = 1;
350
- // A mid-stream cut after partial thinking seals one transcript fragment per
351
- // retry. A gateway that systematically kills long thinking streams (the
352
- // 2026-08-28 incident shape) would otherwise spend the full attempt budget
353
- // accumulating fragments before failing anyway, so fail fast after one.
354
- const MAX_SEALED_THINKING_RETRIES_PER_STEP = 1;
355
349
  const PROVIDER_RETRY_BASE_DELAY_MS = 1_000;
356
350
  const PROVIDER_RETRY_MAX_DELAY_MS = 32_000;
357
351
  const PROVIDER_RETRY_JITTER_FACTOR = 0.25;
@@ -375,9 +369,6 @@ function providerRetryReason(kind) {
375
369
  return 'unknown';
376
370
  }
377
371
  }
378
- function isIncompleteProviderFinishReason(reason) {
379
- return reason === undefined || reason === 'other' || reason === 'unknown';
380
- }
381
372
  /**
382
373
  * The mutable state of ONE `send()`.
383
374
  *
@@ -611,11 +602,6 @@ export class AiSdkTurn {
611
602
  let stepTextPartStartOffset = 0;
612
603
  let stepThinkingParts = [];
613
604
  let stepThinkingPartsById = new Map();
614
- let stepContentOrder = [];
615
- const recordStepContent = (kind) => {
616
- if (!stepContentOrder.includes(kind))
617
- stepContentOrder.push(kind);
618
- };
619
605
  // Flush the current step's AssistantMessage (text + thinking) and the paired
620
606
  // terminal thinking/text events, then clear the per-step accumulators.
621
607
  // Persist when the step produced text OR reasoning — a thinking-only step
@@ -631,17 +617,37 @@ export class AiSdkTurn {
631
617
  stepTextPartStartOffset = 0;
632
618
  stepThinkingParts = [];
633
619
  stepThinkingPartsById = new Map();
634
- stepContentOrder = [];
635
620
  };
636
- const flushStep = async () => {
621
+ const flushStep = async (interrupted = false) => {
637
622
  const hasThinking = stepThinkingParts.length > 0;
638
623
  if (stepText.length === 0 && !hasThinking) {
639
624
  resetStep();
640
625
  return;
641
626
  }
642
- const stepId = currentStepMessageId;
643
- if (hasThinking) {
644
- for (const part of stepThinkingParts) {
627
+ // A provider may finalize one reasoning item before the next item fails.
628
+ // Keep completed and interrupted parts in separate transcript rows so
629
+ // missing-ledger recovery preserves the same model visibility.
630
+ const fragments = [];
631
+ for (const part of stepThinkingParts) {
632
+ const partInterrupted = interrupted && !hasFinalizedReasoning(part);
633
+ let fragment = fragments.at(-1);
634
+ if (!fragment || fragment.interrupted !== partInterrupted) {
635
+ fragment = { thinking: [], text: '', interrupted: partInterrupted };
636
+ fragments.push(fragment);
637
+ }
638
+ fragment.thinking.push(part);
639
+ }
640
+ if (stepText.length > 0) {
641
+ let fragment = fragments.at(-1);
642
+ if (!fragment || fragment.interrupted !== interrupted) {
643
+ fragment = { thinking: [], text: '', interrupted };
644
+ fragments.push(fragment);
645
+ }
646
+ fragment.text = stepText;
647
+ }
648
+ for (const [index, fragment] of fragments.entries()) {
649
+ const stepId = index === 0 ? currentStepMessageId : this.deps.newId();
650
+ for (const part of fragment.thinking) {
645
651
  queue.push({
646
652
  type: 'thinking_complete',
647
653
  id: this.deps.newId(),
@@ -649,6 +655,7 @@ export class AiSdkTurn {
649
655
  ts: this.deps.now(),
650
656
  messageId: stepId,
651
657
  text: part.text,
658
+ ...(fragment.interrupted ? { interrupted: true } : {}),
652
659
  ...(part.signature !== undefined ? { signature: part.signature } : {}),
653
660
  // No sanitiser here, unlike the tool call below: these options are
654
661
  // not the provider's object. `translateChunk` rebuilds reasoning
@@ -661,24 +668,25 @@ export class AiSdkTurn {
661
668
  : {}),
662
669
  });
663
670
  }
671
+ queue.push({
672
+ type: 'text_complete',
673
+ id: this.deps.newId(),
674
+ turnId,
675
+ ts: this.deps.now(),
676
+ messageId: stepId,
677
+ text: fragment.text,
678
+ ...(fragment.interrupted ? { interrupted: true } : {}),
679
+ ...(index === fragments.length - 1 && stepTextProviderOptions !== undefined
680
+ ? { providerOptions: stepTextProviderOptions }
681
+ : {}),
682
+ });
664
683
  }
665
- queue.push({
666
- type: 'text_complete',
667
- id: this.deps.newId(),
668
- turnId,
669
- ts: this.deps.now(),
670
- messageId: stepId,
671
- text: stepText,
672
- ...(stepTextProviderOptions !== undefined
673
- ? { providerOptions: stepTextProviderOptions }
674
- : {}),
675
- });
676
684
  this.finalAssistantText = stepText.length > 0 ? stepText : undefined;
677
685
  resetStep();
678
686
  };
679
687
  let tokenUsage;
680
688
  let tokenUsageCostUsd;
681
- // Per-send sum of every COMPLETED step's usage, merged at each finish-step
689
+ // Per-send sum of every completed step's usage, merged at settlement
682
690
  // boundary. When the send aborts (mid-turn exhaust, user stop, stream
683
691
  // error) the SDK's cumulative `usage` promise may not resolve, but this sum is
684
692
  // real provider-reported evidence for the steps that did finish — IF every
@@ -834,8 +842,6 @@ export class AiSdkTurn {
834
842
  return { plan, providerTools: plan.providerTools, modelTools, nestedTools };
835
843
  };
836
844
  let { plan, providerTools, modelTools, nestedTools } = snapshotStepTools();
837
- let activeToolResultPruneDiagnosticPatch = {};
838
- let midTurnCompactDiagnosticPatch;
839
845
  // Tool names the repair path matches a mis-cased call against — follows the
840
846
  // current step's snapshot so a tool activated mid-turn is repairable on the
841
847
  // step it becomes active, not routed to `invalid`.
@@ -947,7 +953,9 @@ export class AiSdkTurn {
947
953
  idleTimeoutMs: this.deps.backend.streamIdleTimeoutMs,
948
954
  ...this.deps.backend.streamWatchdogTimer,
949
955
  onTimeout: (timeout) => {
950
- const error = new Error(formatStreamWatchdogError(timeout));
956
+ const error = Object.assign(new Error(formatStreamWatchdogError(timeout)), {
957
+ code: 'MODEL_STREAM_TIMEOUT',
958
+ });
951
959
  watchdogTimeoutState.current = { phase: timeout.phase, error };
952
960
  providerRequestAbortController.abort(error);
953
961
  },
@@ -979,6 +987,12 @@ export class AiSdkTurn {
979
987
  };
980
988
  const loadDurableTurnProjection = async () => {
981
989
  const turnEvents = await loadDurableTurnEvents();
990
+ const pruned = await this.deps.compaction.pruneToolResults(turnEvents, turnId);
991
+ if (pruned.stats) {
992
+ if (pruned.stats.prunedToolResults > 0)
993
+ pruneAppliedAtStep = runtimeSteps;
994
+ contextBudgetForTelemetry = addToolResultPruneStats(contextBudgetForTelemetry ?? minimalContextBudgetDiagnostic(), pruned.stats);
995
+ }
982
996
  const projectionCheckpoint = midTurnState?.projectionCheckpoint;
983
997
  const rawProjectionEvents = projectionCheckpoint
984
998
  ? [
@@ -999,7 +1013,7 @@ export class AiSdkTurn {
999
1013
  // built from. Replay without the stale block — the provider
1000
1014
  // decides fit and overflow recovery re-folds (#4845 review).
1001
1015
  const pinnedEffectiveDigest = projectionCheckpoint.coverage.effectiveSourceDigest;
1002
- const coveredEffective = await this.deps.compaction.foldEffectiveModelHistory(checkpointMatch.coveredRuntimeEvents);
1016
+ const coveredEffective = await this.deps.compaction.foldEffectiveModelHistory(checkpointMatch.coveredRuntimeEvents, pruned.projectionSnapshot);
1003
1017
  if (pinnedEffectiveDigest === undefined ||
1004
1018
  historyCompactSourceDigest(coveredEffective) !== pinnedEffectiveDigest) {
1005
1019
  effectiveProjectionCheckpoint = undefined;
@@ -1016,7 +1030,9 @@ export class AiSdkTurn {
1016
1030
  // folded through the same reducer before it becomes messages. Without
1017
1031
  // this, a result archived at step N is rebuilt in full at step N+1 and
1018
1032
  // the ledger's account of what the model sees stops being true.
1019
- const foldedReplayEvents = await this.deps.compaction.foldEffectiveModelHistory(replayEvents);
1033
+ const foldedReplayEvents = projectionCheckpoint
1034
+ ? await this.deps.compaction.foldEffectiveModelHistory(replayEvents, pruned.projectionSnapshot)
1035
+ : pruned.events;
1020
1036
  const replayPlan = buildRuntimeEventModelReplayPlan(foldedReplayEvents, {
1021
1037
  toolActivityTurnIds: collectToolActivityTurnIds([
1022
1038
  ...(input.runtimeContext ?? []),
@@ -1049,7 +1065,7 @@ export class AiSdkTurn {
1049
1065
  ...(priorReplay.contextBudget ? { contextBudget: priorReplay.contextBudget } : {}),
1050
1066
  });
1051
1067
  const onMidTurnDiagnosticPatch = (patch) => {
1052
- midTurnCompactDiagnosticPatch = mergeContextBudgetDiagnosticPatches(midTurnCompactDiagnosticPatch, patch);
1068
+ contextBudgetForTelemetry = mergeContextBudgetDiagnostic(contextBudgetForTelemetry ?? minimalContextBudgetDiagnostic(), patch);
1053
1069
  };
1054
1070
  const capacityProviderTools = [...providerTools];
1055
1071
  const midTurnCapacityHook = this.deps.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, capacityProviderTools, onMidTurnDiagnosticPatch, this, this.automaticMemoryCompactionSupported()
@@ -1057,25 +1073,13 @@ export class AiSdkTurn {
1057
1073
  : undefined, this.automaticMemoryCompactionSupported()
1058
1074
  ? (dispatch) => this.dispatchAutomaticMemoryCompaction(dispatch)
1059
1075
  : undefined, turnAbortController.signal);
1060
- // When mid-turn capacity compaction is active, the prune must also cover
1061
- // the newest completed step; see collectPrunableCompletedStepToolCallIds.
1062
- const activeToolResultPruneIncludesNewestStep = midTurnState !== undefined;
1063
- const activeToolResultPruneHook = this.deps.compaction.buildActiveToolResultPruneProjection(turnId, activeToolResultPruneIncludesNewestStep, (patch) => {
1064
- pruneAppliedAtStep = runtimeSteps;
1065
- activeToolResultPruneDiagnosticPatch = mergeActiveToolResultPruneDiagnosticPatches(activeToolResultPruneDiagnosticPatch, patch);
1066
- });
1067
1076
  const projectCurrentToolAvailability = (options) => plan.projectActiveTools?.(options);
1068
- const shapedProjection = composeRequestProjection(projectCurrentToolAvailability, midTurnCapacityHook, activeToolResultPruneHook);
1077
+ const shapedProjection = composeRequestProjection(projectCurrentToolAvailability, midTurnCapacityHook);
1069
1078
  // Hooks shape; nothing measures the final payload. Whether it fits is
1070
1079
  // the provider's answer (#4559).
1071
1080
  const requestProjection = shapedProjection;
1072
1081
  const completedProviderSteps = [];
1073
1082
  let requestMessages = messages;
1074
- // The compaction module runs at most once per send. This tracks the
1075
- // reactive entry; the proactive one sets the same flag on the mid-turn
1076
- // state, and each consults the other, so a send that already folded
1077
- // reports the oversized message instead of folding again (#4559).
1078
- let overflowRetryUsed = false;
1079
1083
  let result;
1080
1084
  let providerOutcome;
1081
1085
  let finishReason = 'stop';
@@ -1156,41 +1160,27 @@ export class AiSdkTurn {
1156
1160
  : undefined;
1157
1161
  providerRequestTracker?.setStep(runtimeSteps, requestCompositionId);
1158
1162
  let attemptMessages = projectedMessages;
1159
- let providerAttempt = 1;
1160
- let idleWatchdogRetryCount = 0;
1161
- let incompleteStreamRetryCount = 0;
1162
- let sealedThinkingRetryCount = 0;
1163
+ let providerAttempt = 0;
1163
1164
  const returnedToolCalls = [];
1164
- let providerToolActivityCount = 0;
1165
1165
  const providerToolInputs = new Map();
1166
1166
  let providerStepUsage;
1167
1167
  for (;;) {
1168
+ providerAttempt += 1;
1169
+ // Local calls are only admitted after a successful provider outcome.
1170
+ // A new physical request must not inherit the failed one's intents.
1171
+ returnedToolCalls.length = 0;
1168
1172
  providerRequestAbortController = new AbortController();
1169
1173
  watchdogTimeoutState.current = null;
1170
1174
  startWatchdog();
1171
1175
  // Monotonic facts for this physical request. The step accumulators
1172
1176
  // are cleared after flushStep(), so they cannot decide whether a
1173
1177
  // later stream failure is safe to retry.
1174
- let attemptSawText = false;
1175
- let attemptSawThinking = false;
1178
+ let attemptSawVisibleContent = false;
1176
1179
  let attemptSawToolActivity = false;
1177
- let attemptSawContinuationMetadata = false;
1178
- let attemptReachedStepBoundary = false;
1179
- const attemptHasNoObservableOutput = () => !attemptSawText &&
1180
- !attemptSawThinking &&
1181
- !attemptSawToolActivity &&
1182
- !attemptSawContinuationMetadata &&
1183
- !attemptReachedStepBoundary;
1184
- // Thinking is the only output that can be sealed into its own
1185
- // message before a retry: flushStep() closes the fragment under
1186
- // the current message id and the retry streams into a fresh one,
1187
- // so the user never sees spliced or duplicated content. Text,
1188
- // tool activity, continuation metadata, and step boundaries stay
1189
- // non-recoverable for the reasons each of them is tracked.
1190
- const attemptCanRecoverWithSealedThinking = () => !attemptSawText &&
1191
- !attemptSawToolActivity &&
1192
- !attemptSawContinuationMetadata &&
1193
- !attemptReachedStepBoundary;
1180
+ let attemptSawToolInput = false;
1181
+ let attemptSawReplayBarrier = false;
1182
+ const attemptHasNoObservableOutput = () => !attemptSawVisibleContent && !attemptSawToolActivity && !attemptSawReplayBarrier;
1183
+ const attemptCanReplay = () => !attemptSawToolActivity && !attemptSawReplayBarrier;
1194
1184
  this.memorySourceMessages = [...attemptMessages];
1195
1185
  this.memorySourceEventMessagePositions =
1196
1186
  this.deps.messageProjection.memoryEventMessagePositions(attemptMessages);
@@ -1243,185 +1233,18 @@ export class AiSdkTurn {
1243
1233
  // trailer and consume the one authoritative outcome below.
1244
1234
  break;
1245
1235
  }
1246
- const incompleteFinish = (event.kind === 'finish' || event.kind === 'step-finish') &&
1247
- isIncompleteProviderFinishReason(event.finishReason);
1248
- if ((event.kind === 'finish' || event.kind === 'step-finish') && !incompleteFinish) {
1249
- attemptReachedStepBoundary = true;
1250
- }
1251
- if (event.kind === 'step-finish') {
1252
- // AI SDK can synthesize `finish-step(other)` when the provider
1253
- // stream reaches EOF without a terminal frame. That is not a
1254
- // completed model step and must not consume the step budget or
1255
- // checkpoint imaginary usage before the safe retry below.
1256
- if (!incompleteFinish) {
1257
- // Step boundary: AI SDK 7 delimits steps with `finish-step`
1258
- // (and `step-finish` for legacy replay fixtures); the adapter
1259
- // reduces both to this event. A duplicate boundary is harmless:
1260
- // the second flush no-ops (accumulators already cleared) and one
1261
- // extra id rotation just discards an unused id.
1262
- runtimeSteps += 1;
1263
- const stepUsage = event.usage;
1264
- providerStepUsage = stepUsage;
1265
- if (!stepUsage)
1266
- sawUnusableStepUsage = true;
1267
- // Silent eviction / rewrite check (#4559): this step only
1268
- // appended (no fold, no prune, no image omission) yet the
1269
- // provider counted no more input tokens than for the previous
1270
- // request. Not-greater, not strictly-fewer: a provider that
1271
- // truncates to a fixed window (Ollama's `num_ctx`) reports the
1272
- // same total on every later request while Maka keeps
1273
- // appending, so a plateau is the signal, and an equal count
1274
- // after an append is already impossible without provider-side
1275
- // eviction or rewriting. Input against input: the previous
1276
- // reply's reasoning may not be resent, so input + output is
1277
- // not the floor of the next input on every wire.
1278
- const completedRequestIndex = runtimeSteps - 1;
1279
- // A finalization step resolves an empty tool set, so its
1280
- // request legitimately drops several thousand schema tokens
1281
- // with no fold, prune or image omission. Maka shaped that
1282
- // request; the provider did not drop anything.
1283
- const toolSchemaShrank = lastStepActiveToolCount !== undefined &&
1284
- activeToolsForRequest.length < lastStepActiveToolCount;
1285
- // Across the send boundary the comparison is the same one,
1286
- // against the last request a provider accepted before this
1287
- // send. A provider that truncates to a fixed window reports
1288
- // the same input on every later request while the user keeps
1289
- // adding turns, and a send of one or two steps never sees
1290
- // that from the inside: the live evidence plateaus at 3,716
1291
- // input tokens across eight turns with nothing reported
1292
- // (#4623). The first request of a send therefore compares
1293
- // against the persisted anchor, which is route-validated
1294
- // where it is read; a fold before that request would explain
1295
- // a smaller input by itself, so it disables the comparison.
1296
- const acrossSends = completedRequestIndex === 0;
1297
- const priorInput = acrossSends
1298
- ? midTurnState?.compactionAppliedThisSend === true
1299
- ? undefined
1300
- : midTurnState?.priorAcceptedInputTokens
1301
- : lastStepInputTokens;
1302
- if (!this.deps.session.contextProviderDroppingReported &&
1303
- !toolSchemaShrank &&
1304
- midTurnState &&
1305
- priorInput !== undefined &&
1306
- midTurnState.replacedStepNumber !== completedRequestIndex &&
1307
- pruneAppliedAtStep !== completedRequestIndex &&
1308
- midTurnState.omittedImageToolResults.size === 0 &&
1309
- stepUsage !== undefined &&
1310
- Number.isFinite(stepUsage.inputTokens) &&
1311
- stepUsage.inputTokens > 0 &&
1312
- // Across sends the test is equality, not "did not grow".
1313
- // Inside a send Maka knows it only appended, so any
1314
- // shortfall is the provider's. Across the boundary it does
1315
- // not: a manual compaction leaves the pre-compaction anchor
1316
- // behind, a turn can carry a smaller tool set, and a user
1317
- // can edit or branch history. All three shrink the input
1318
- // legitimately, and none of them lands on exactly the same
1319
- // count. A provider truncating to a fixed window does, on
1320
- // every later request.
1321
- (acrossSends
1322
- ? stepUsage.inputTokens === priorInput
1323
- : stepUsage.inputTokens <= priorInput)) {
1324
- this.deps.session.contextProviderDroppingReported = true;
1325
- await this.recordSystemNote('context_provider_dropping', turnId, {
1326
- inputTokens: stepUsage.inputTokens,
1327
- priorInputTokens: priorInput,
1328
- });
1329
- }
1330
- // Fail closed: reset on every step boundary so a missing final
1331
- // step's usage does not leave a stale value from an earlier step.
1332
- // The reply needed more room than the declared window had
1333
- // left after this request's own input. Both halves are the
1334
- // provider's numbers, read after the fact: the reserve that
1335
- // should have kept them apart was measured from a smaller
1336
- // previous reply. Say so once per send; the next request
1337
- // folds anyway because the baseline now exceeds the window.
1338
- if (!contextWindowOverrunNoteWritten &&
1339
- midTurnState?.capacity !== undefined &&
1340
- stepUsage !== undefined &&
1341
- Number.isFinite(stepUsage.inputTokens) &&
1342
- stepUsage.inputTokens > 0 &&
1343
- Number.isFinite(stepUsage.outputTokens) &&
1344
- stepUsage.outputTokens > 0 &&
1345
- stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity) {
1346
- contextWindowOverrunNoteWritten = true;
1347
- await this.recordSystemNote('context_window_overrun', turnId, {
1348
- usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1349
- declaredContextWindow: midTurnState.capacity,
1350
- });
1351
- }
1352
- // Nothing declared, and the provider accepted a request past
1353
- // the window this model reports. Every other signal in this
1354
- // design stays dark there: no rejection to recover from, no
1355
- // plateau to read, and no declaration to arm the proactive
1356
- // threshold, so the session degrades quietly and
1357
- // indefinitely (#4634). Report the two real numbers and
1358
- // leave the decision with the user: a reported window is a
1359
- // hint, and Maka still declares nothing on their behalf.
1360
- //
1361
- // Once per crossing, not once per send. On these providers
1362
- // usage keeps growing past the line (305K → 322K observed),
1363
- // so the note fires on the transition: the previous accepted
1364
- // total was still inside the reported window and this one is
1365
- // not. The baseline carries that previous total across
1366
- // sessions through the persisted anchor, so a resumed
1367
- // session does not repeat a crossing it already reported.
1368
- if (!contextReportedWindowNoteWritten &&
1369
- midTurnState !== undefined &&
1370
- midTurnState.capacity === undefined &&
1371
- stepUsage !== undefined &&
1372
- Number.isFinite(stepUsage.inputTokens) &&
1373
- stepUsage.inputTokens > 0 &&
1374
- Number.isFinite(stepUsage.outputTokens)) {
1375
- const reported = resolveSelectedModelContextWindow(this.deps.backend.connection, this.deps.backend.modelId);
1376
- const used = stepUsage.inputTokens + Math.max(0, stepUsage.outputTokens);
1377
- // `baselineTokens` still describes the request before this
1378
- // one: the capacity hook sets it from the previous step, or
1379
- // from the persisted anchor on a send's first request.
1380
- const previousTotal = midTurnState.baselineTokens;
1381
- const crossedNow = reported !== undefined &&
1382
- used > reported &&
1383
- (previousTotal === undefined || previousTotal <= reported);
1384
- if (reported !== undefined && crossedNow) {
1385
- contextReportedWindowNoteWritten = true;
1386
- await this.recordSystemNote('context_reported_window_exceeded', turnId, {
1387
- usedTokens: used,
1388
- reportedContextWindow: reported,
1389
- });
1390
- }
1391
- }
1392
- lastStepInputTokens = stepUsage?.inputTokens;
1393
- lastStepOutputTokens = stepUsage?.outputTokens;
1394
- lastStepActiveToolCount = activeToolsForRequest.length;
1395
- // A `finishReason: length` is deliberately not a trigger. The
1396
- // reply may have been cut because the provider ran out of
1397
- // window room, or because the provider's own output cap is
1398
- // lower than the one Maka sends. Those are indistinguishable
1399
- // from outside, and an indistinguishable signal must not
1400
- // drive an action; the cut reply is visible to the user
1401
- // either way (#4559).
1402
- if (stepUsage) {
1403
- completedStepUsage = mergeNormalizedUsage(completedStepUsage, stepUsage);
1404
- this.deps.session.cumulativeUsageCheckpoint = mergeNormalizedUsage(this.deps.session.cumulativeUsageCheckpoint, stepUsage);
1405
- await this.deps.backend.recordUsageCheckpoint?.({
1406
- ...this.deps.session.cumulativeUsageCheckpoint,
1407
- costUsd: this.deps.providerTelemetry.normalizedUsageCostUsd(this.deps.session.cumulativeUsageCheckpoint),
1408
- });
1409
- }
1410
- }
1411
- }
1412
1236
  if (event.kind === 'text-start') {
1413
1237
  if (stepText.length > 0 && event.providerItemBoundary === true) {
1238
+ attemptSawReplayBarrier = true;
1414
1239
  await flushStep();
1415
1240
  currentStepMessageId = this.deps.newId();
1416
1241
  }
1417
1242
  stepTextPartStartOffset = stepText.length;
1418
1243
  }
1419
1244
  else if (event.kind === 'text') {
1420
- if (event.text.length > 0)
1421
- recordStepContent('text');
1422
1245
  stepText += event.text;
1423
1246
  if (event.text.length > 0)
1424
- attemptSawText = true;
1247
+ attemptSawVisibleContent = true;
1425
1248
  queue.push({
1426
1249
  type: 'text_delta',
1427
1250
  id: this.deps.newId(),
@@ -1433,7 +1256,7 @@ export class AiSdkTurn {
1433
1256
  }
1434
1257
  else if (event.kind === 'text-end') {
1435
1258
  if (event.providerOptions !== undefined) {
1436
- attemptSawContinuationMetadata = true;
1259
+ attemptSawReplayBarrier = true;
1437
1260
  stepTextProviderOptions = mergeTextProviderOptions(stepTextProviderOptions, stripUndefinedDeep(event.providerOptions), stepTextPartStartOffset);
1438
1261
  }
1439
1262
  if (event.providerItemBoundary === true) {
@@ -1443,7 +1266,7 @@ export class AiSdkTurn {
1443
1266
  }
1444
1267
  else if (event.kind === 'thinking-start') {
1445
1268
  if (event.providerOptions !== undefined) {
1446
- attemptSawContinuationMetadata = true;
1269
+ attemptSawReplayBarrier = true;
1447
1270
  }
1448
1271
  const part = {
1449
1272
  text: '',
@@ -1458,12 +1281,10 @@ export class AiSdkTurn {
1458
1281
  }
1459
1282
  else if (event.kind === 'thinking') {
1460
1283
  if (event.text.length > 0)
1461
- recordStepContent('thinking');
1462
- if (event.text.length > 0)
1463
- attemptSawThinking = true;
1284
+ attemptSawVisibleContent = true;
1464
1285
  if (event.providerOptions !== undefined) {
1465
1286
  if (event.providerOptionsOrigin !== 'maka_transport') {
1466
- attemptSawContinuationMetadata = true;
1287
+ attemptSawReplayBarrier = true;
1467
1288
  }
1468
1289
  }
1469
1290
  const partId = event.reasoningPartId ?? responsesReasoningItemId(event.providerOptions);
@@ -1519,7 +1340,7 @@ export class AiSdkTurn {
1519
1340
  });
1520
1341
  }
1521
1342
  else if (event.kind === 'thinking-signature') {
1522
- attemptSawContinuationMetadata = true;
1343
+ attemptSawReplayBarrier = true;
1523
1344
  let part = event.reasoningPartId
1524
1345
  ? stepThinkingPartsById.get(event.reasoningPartId)
1525
1346
  : stepThinkingParts.at(-1);
@@ -1532,17 +1353,17 @@ export class AiSdkTurn {
1532
1353
  }
1533
1354
  part.signature = event.signature;
1534
1355
  }
1535
- else if (event.kind === 'provider-tool-input') {
1356
+ else if (event.kind === 'tool-input') {
1357
+ attemptSawToolInput = true;
1536
1358
  // The provider has started its own tool. Even without a
1537
1359
  // final tool-call/result event, retrying can repeat external
1538
1360
  // work that the Runtime cannot observe or reconcile.
1539
- attemptSawToolActivity = true;
1361
+ if (event.providerExecuted)
1362
+ attemptSawToolActivity = true;
1540
1363
  }
1541
1364
  else if (event.kind === 'tool-call') {
1542
- attemptSawToolActivity = true;
1543
- recordStepContent('tools');
1544
1365
  if (event.toolCall.providerExecuted) {
1545
- providerToolActivityCount += 1;
1366
+ attemptSawToolActivity = true;
1546
1367
  providerToolInputs.set(event.toolCall.toolCallId, event.toolCall.input);
1547
1368
  queue.push({
1548
1369
  type: 'tool_start',
@@ -1569,7 +1390,6 @@ export class AiSdkTurn {
1569
1390
  }
1570
1391
  else if (event.kind === 'provider-tool-result') {
1571
1392
  attemptSawToolActivity = true;
1572
- providerToolActivityCount += 1;
1573
1393
  const providerOutput = stripUndefinedDeep(event.output);
1574
1394
  queue.push({
1575
1395
  type: 'tool_result',
@@ -1584,44 +1404,185 @@ export class AiSdkTurn {
1584
1404
  });
1585
1405
  providerToolInputs.delete(event.toolCallId);
1586
1406
  }
1587
- else if (event.kind === 'step-finish' && !incompleteFinish) {
1588
- // The step's text/thinking deltas are all in (the stream is
1589
- // drained in order), so flush this step's AssistantMessage and
1590
- // rotate to a fresh id for the next step. Tool settlement
1591
- // below receives this step's pre-rotation id, so durable replay
1592
- // can regroup calls with this reasoning/text.
1593
- await flushStep();
1594
- if (midTurnState) {
1595
- // Durability clock: step N's thinking/text completion events
1596
- // are enqueued by flushStep just above, so only after this
1597
- // boundary can a seq-ack wait for step N mean anything. Wake
1598
- // waiters AFTER the increment or they would re-check a stale
1599
- // count and sleep.
1600
- midTurnState.flushedSteps += 1;
1601
- queue.wake();
1602
- }
1603
- }
1604
1407
  }
1605
1408
  watchdogState.current?.stop();
1606
1409
  // This timeout belongs to the physical request that just settled.
1607
1410
  // Consume it before recovery/flush work: a later persistence error
1608
1411
  // must not be reported as the already-handled watchdog timeout.
1609
- const settledWatchdogTimeout = consumeWatchdogTimeout();
1412
+ consumeWatchdogTimeout();
1610
1413
  providerOutcome = await result.outcome;
1611
- const incompleteStreamTerminal = providerOutcome.kind === 'truncated';
1612
- const incompleteStreamHasNoObservableOutput = incompleteStreamTerminal &&
1613
- !attemptSawText &&
1614
- !attemptSawThinking &&
1615
- !attemptSawToolActivity &&
1616
- !attemptSawContinuationMetadata;
1617
- const attemptFailure = settledWatchdogTimeout?.error ??
1618
- (providerOutcome.kind === 'completed' ? undefined : providerOutcome.failure);
1619
- if (attemptFailure && !this.aborted) {
1620
- const failure = settledWatchdogTimeout || providerOutcome.kind === 'completed'
1621
- ? this.deps.modelAdapter.normalizeFailure(attemptFailure)
1622
- : providerOutcome.failure;
1414
+ if (providerOutcome.kind === 'completed') {
1415
+ runtimeSteps += 1;
1416
+ const stepUsage = providerOutcome.usage;
1417
+ providerStepUsage = stepUsage;
1418
+ if (!stepUsage)
1419
+ sawUnusableStepUsage = true;
1420
+ // Silent eviction / rewrite check (#4559): this step only
1421
+ // appended (no fold, no prune, no image omission) yet the
1422
+ // provider counted no more input tokens than for the previous
1423
+ // request. Not-greater, not strictly-fewer: a provider that
1424
+ // truncates to a fixed window (Ollama's `num_ctx`) reports the
1425
+ // same total on every later request while Maka keeps
1426
+ // appending, so a plateau is the signal, and an equal count
1427
+ // after an append is already impossible without provider-side
1428
+ // eviction or rewriting. Input against input: the previous
1429
+ // reply's reasoning may not be resent, so input + output is
1430
+ // not the floor of the next input on every wire.
1431
+ const completedRequestIndex = runtimeSteps - 1;
1432
+ // A finalization step resolves an empty tool set, so its
1433
+ // request legitimately drops several thousand schema tokens
1434
+ // with no fold, prune or image omission. Maka shaped that
1435
+ // request; the provider did not drop anything.
1436
+ const toolSchemaShrank = lastStepActiveToolCount !== undefined &&
1437
+ activeToolsForRequest.length < lastStepActiveToolCount;
1438
+ // Across the send boundary the comparison is the same one,
1439
+ // against the last request a provider accepted before this
1440
+ // send. A provider that truncates to a fixed window reports
1441
+ // the same input on every later request while the user keeps
1442
+ // adding turns, and a send of one or two steps never sees
1443
+ // that from the inside: the live evidence plateaus at 3,716
1444
+ // input tokens across eight turns with nothing reported
1445
+ // (#4623). The first request of a send therefore compares
1446
+ // against the persisted anchor, which is route-validated
1447
+ // where it is read; a fold before that request would explain
1448
+ // a smaller input by itself, so it disables the comparison.
1449
+ const acrossSends = completedRequestIndex === 0;
1450
+ const priorInput = acrossSends
1451
+ ? midTurnState?.compactionAppliedThisSend === true
1452
+ ? undefined
1453
+ : midTurnState?.priorAcceptedInputTokens
1454
+ : lastStepInputTokens;
1455
+ if (!this.deps.session.contextProviderDroppingReported &&
1456
+ !toolSchemaShrank &&
1457
+ midTurnState &&
1458
+ priorInput !== undefined &&
1459
+ midTurnState.replacedStepNumber !== completedRequestIndex &&
1460
+ pruneAppliedAtStep !== completedRequestIndex &&
1461
+ midTurnState.omittedImageToolResults.size === 0 &&
1462
+ stepUsage !== undefined &&
1463
+ Number.isFinite(stepUsage.inputTokens) &&
1464
+ stepUsage.inputTokens > 0 &&
1465
+ // Across sends the test is equality, not "did not grow".
1466
+ // Inside a send Maka knows it only appended, so any
1467
+ // shortfall is the provider's. Across the boundary it does
1468
+ // not: a manual compaction leaves the pre-compaction anchor
1469
+ // behind, a turn can carry a smaller tool set, and a user
1470
+ // can edit or branch history. All three shrink the input
1471
+ // legitimately, and none of them lands on exactly the same
1472
+ // count. A provider truncating to a fixed window does, on
1473
+ // every later request.
1474
+ (acrossSends
1475
+ ? stepUsage.inputTokens === priorInput
1476
+ : stepUsage.inputTokens <= priorInput)) {
1477
+ this.deps.session.contextProviderDroppingReported = true;
1478
+ await this.recordSystemNote('context_provider_dropping', turnId, {
1479
+ inputTokens: stepUsage.inputTokens,
1480
+ priorInputTokens: priorInput,
1481
+ });
1482
+ }
1483
+ // Fail closed: reset on every step boundary so a missing final
1484
+ // step's usage does not leave a stale value from an earlier step.
1485
+ // The reply needed more room than the declared window had
1486
+ // left after this request's own input. Both halves are the
1487
+ // provider's numbers, read after the fact: the reserve that
1488
+ // should have kept them apart was measured from a smaller
1489
+ // previous reply. Say so once per send; the next request
1490
+ // folds anyway because the baseline now exceeds the window.
1491
+ if (!contextWindowOverrunNoteWritten &&
1492
+ midTurnState?.capacity !== undefined &&
1493
+ stepUsage !== undefined &&
1494
+ Number.isFinite(stepUsage.inputTokens) &&
1495
+ stepUsage.inputTokens > 0 &&
1496
+ Number.isFinite(stepUsage.outputTokens) &&
1497
+ stepUsage.outputTokens > 0 &&
1498
+ stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity) {
1499
+ contextWindowOverrunNoteWritten = true;
1500
+ await this.recordSystemNote('context_window_overrun', turnId, {
1501
+ usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1502
+ declaredContextWindow: midTurnState.capacity,
1503
+ });
1504
+ }
1505
+ // Nothing declared, and the provider accepted a request past
1506
+ // the window this model reports. Every other signal in this
1507
+ // design stays dark there: no rejection to recover from, no
1508
+ // plateau to read, and no declaration to arm the proactive
1509
+ // threshold, so the session degrades quietly and
1510
+ // indefinitely (#4634). Report the two real numbers and
1511
+ // leave the decision with the user: a reported window is a
1512
+ // hint, and Maka still declares nothing on their behalf.
1513
+ //
1514
+ // Once per crossing, not once per send. On these providers
1515
+ // usage keeps growing past the line (305K → 322K observed),
1516
+ // so the note fires on the transition: the previous accepted
1517
+ // total was still inside the reported window and this one is
1518
+ // not. The baseline carries that previous total across
1519
+ // sessions through the persisted anchor, so a resumed
1520
+ // session does not repeat a crossing it already reported.
1521
+ if (!contextReportedWindowNoteWritten &&
1522
+ midTurnState !== undefined &&
1523
+ midTurnState.capacity === undefined &&
1524
+ stepUsage !== undefined &&
1525
+ Number.isFinite(stepUsage.inputTokens) &&
1526
+ stepUsage.inputTokens > 0 &&
1527
+ Number.isFinite(stepUsage.outputTokens)) {
1528
+ const reported = resolveSelectedModelContextWindow(this.deps.backend.connection, this.deps.backend.modelId);
1529
+ const used = stepUsage.inputTokens + Math.max(0, stepUsage.outputTokens);
1530
+ // `baselineTokens` still describes the request before this
1531
+ // one: the capacity hook sets it from the previous step, or
1532
+ // from the persisted anchor on a send's first request.
1533
+ const previousTotal = midTurnState.baselineTokens;
1534
+ const crossedNow = reported !== undefined &&
1535
+ used > reported &&
1536
+ (previousTotal === undefined || previousTotal <= reported);
1537
+ if (reported !== undefined && crossedNow) {
1538
+ contextReportedWindowNoteWritten = true;
1539
+ await this.recordSystemNote('context_reported_window_exceeded', turnId, {
1540
+ usedTokens: used,
1541
+ reportedContextWindow: reported,
1542
+ });
1543
+ }
1544
+ }
1545
+ lastStepInputTokens = stepUsage?.inputTokens;
1546
+ lastStepOutputTokens = stepUsage?.outputTokens;
1547
+ lastStepActiveToolCount = activeToolsForRequest.length;
1548
+ // A `finishReason: length` is deliberately not a trigger. The
1549
+ // reply may have been cut because the provider ran out of
1550
+ // window room, or because the provider's own output cap is
1551
+ // lower than the one Maka sends. Those are indistinguishable
1552
+ // from outside, and an indistinguishable signal must not
1553
+ // drive an action; the cut reply is visible to the user
1554
+ // either way (#4559).
1555
+ if (stepUsage) {
1556
+ completedStepUsage = mergeNormalizedUsage(completedStepUsage, stepUsage);
1557
+ this.deps.session.cumulativeUsageCheckpoint = mergeNormalizedUsage(this.deps.session.cumulativeUsageCheckpoint, stepUsage);
1558
+ await this.deps.backend.recordUsageCheckpoint?.({
1559
+ ...this.deps.session.cumulativeUsageCheckpoint,
1560
+ costUsd: this.deps.providerTelemetry.normalizedUsageCostUsd(this.deps.session.cumulativeUsageCheckpoint),
1561
+ });
1562
+ }
1563
+ await flushStep();
1564
+ if (midTurnState) {
1565
+ // Durability clock: step N's thinking/text completion events
1566
+ // are enqueued by flushStep just above, so only after this
1567
+ // boundary can a seq-ack wait for step N mean anything. Wake
1568
+ // waiters AFTER the increment or they would re-check a stale
1569
+ // count and sleep.
1570
+ midTurnState.flushedSteps += 1;
1571
+ queue.wake();
1572
+ }
1573
+ }
1574
+ if (providerOutcome.kind === 'failed' && !this.aborted) {
1575
+ const failure = providerOutcome.failure;
1576
+ // An output-free context rejection did not sample a response.
1577
+ // Preserve metering for completed steps across compaction recovery.
1578
+ if (!providerOutcome.usage &&
1579
+ !(failure.kind === 'context_overflow' &&
1580
+ attemptHasNoObservableOutput() &&
1581
+ !attemptSawToolInput &&
1582
+ returnedToolCalls.length === 0))
1583
+ sawUnusableStepUsage = true;
1623
1584
  if (this.loopStopRequested) {
1624
- terminalProviderError = settledWatchdogTimeout?.error ?? failure;
1585
+ terminalProviderError = failure;
1625
1586
  terminalProviderErrorReason =
1626
1587
  lastCompletedStepHadToolResult && failure.kind === 'timeout'
1627
1588
  ? 'model_after_tool_timeout'
@@ -1632,10 +1593,11 @@ export class AiSdkTurn {
1632
1593
  // more step; with the send-level budget already spent there is
1633
1594
  // nothing left to grant it, so the error is terminal.
1634
1595
  const stepBudgetRemains = maxSteps === undefined || runtimeSteps < maxSteps;
1635
- const recovered = stepBudgetRemains && attemptHasNoObservableOutput()
1596
+ const recovered = stepBudgetRemains &&
1597
+ providerAttempt < MAX_PROVIDER_ATTEMPTS_PER_STEP &&
1598
+ attemptHasNoObservableOutput()
1636
1599
  ? await this.deps.compaction.recoverFromOverflowError({
1637
- error: attemptFailure,
1638
- retryAlreadyUsed: overflowRetryUsed || (midTurnState?.compactionAttemptedThisSend ?? false),
1600
+ error: failure,
1639
1601
  midTurnState,
1640
1602
  turnId,
1641
1603
  stepNumber: runtimeSteps,
@@ -1654,22 +1616,7 @@ export class AiSdkTurn {
1654
1616
  })
1655
1617
  : undefined;
1656
1618
  if (recovered) {
1657
- overflowRetryUsed = true;
1658
- // Recovery rebuilds the request from the durable ledger, whose
1659
- // tool results intentionally retain their full bodies. Re-enter
1660
- // the active-result projection before dispatch so an archived
1661
- // result cannot reappear in provider context on the retry.
1662
- const recoveredProjection = activeToolResultPruneHook
1663
- ? await activeToolResultPruneHook({
1664
- completedSteps: completedProviderSteps,
1665
- stepNumber: runtimeSteps,
1666
- model,
1667
- messages: recovered.messages,
1668
- activeTools: activeToolsForRequest,
1669
- resolveDispatch,
1670
- })
1671
- : undefined;
1672
- attemptMessages = recoveredProjection?.messages ?? recovered.messages;
1619
+ attemptMessages = recovered.messages;
1673
1620
  continue;
1674
1621
  }
1675
1622
  // Window suggestion (#4559): the provider rejected a request and
@@ -1707,30 +1654,10 @@ export class AiSdkTurn {
1707
1654
  contextOverflowAfterCompactionNoteWritten = true;
1708
1655
  await this.recordSystemNote('context_overflow_after_compaction', turnId);
1709
1656
  }
1710
- const idleWatchdogRecovery = settledWatchdogTimeout?.phase === 'idle' &&
1711
- idleWatchdogRetryCount < MAX_IDLE_WATCHDOG_RETRIES_PER_STEP &&
1712
- attemptCanRecoverWithSealedThinking();
1713
- const incompleteStreamRecovery = incompleteStreamTerminal &&
1714
- incompleteStreamRetryCount < MAX_INCOMPLETE_STREAM_RETRIES_PER_STEP &&
1715
- incompleteStreamHasNoObservableOutput;
1716
- // Same seal-and-retry contract as the watchdog path, entered when
1717
- // the failure arrives as a retryable provider/network error
1718
- // instead of a local idle timeout. `!idleWatchdogRecovery` keeps
1719
- // every watchdog-shaped outcome on its existing path, and
1720
- // `!attemptHasNoObservableOutput()` keeps no-output retries on
1721
- // the plain budget so this one is spent only on sealed fragments.
1722
- const sealedThinkingRecovery = !idleWatchdogRecovery &&
1723
- failure.retryable &&
1724
- sealedThinkingRetryCount < MAX_SEALED_THINKING_RETRIES_PER_STEP &&
1725
- attemptCanRecoverWithSealedThinking() &&
1726
- !attemptHasNoObservableOutput();
1727
1657
  // The stopping gate also supplies the durable reason. An absent
1728
1658
  // decision means this attempt is allowed to retry.
1729
1659
  let retry;
1730
- if (!(attemptHasNoObservableOutput() ||
1731
- idleWatchdogRecovery ||
1732
- incompleteStreamRecovery ||
1733
- sealedThinkingRecovery)) {
1660
+ if (!attemptCanReplay()) {
1734
1661
  retry = {
1735
1662
  decision: 'declined',
1736
1663
  because: attemptSawToolActivity ? 'side_effects' : 'observable_output',
@@ -1745,33 +1672,20 @@ export class AiSdkTurn {
1745
1672
  else if (failure.kind === 'context_overflow') {
1746
1673
  retry = { decision: 'declined', because: 'policy' };
1747
1674
  }
1748
- else if (!(failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery)) {
1749
- retry =
1750
- incompleteStreamTerminal &&
1751
- incompleteStreamRetryCount >= MAX_INCOMPLETE_STREAM_RETRIES_PER_STEP
1752
- ? { decision: 'exhausted', attempts: providerAttempt }
1753
- : { decision: 'declined', because: 'policy' };
1675
+ else if (!failure.retryable) {
1676
+ retry = { decision: 'declined', because: 'policy' };
1754
1677
  }
1755
1678
  if (!retry) {
1756
- if (idleWatchdogRecovery)
1757
- idleWatchdogRetryCount += 1;
1758
- if (sealedThinkingRecovery)
1759
- sealedThinkingRetryCount += 1;
1760
- if (incompleteStreamRecovery)
1761
- incompleteStreamRetryCount += 1;
1762
- if ((idleWatchdogRecovery || sealedThinkingRecovery) &&
1763
- stepThinkingParts.length > 0) {
1764
- await flushStep();
1765
- currentStepMessageId = this.deps.newId();
1766
- }
1679
+ // Preserve the failed fragment for the transcript, but exclude
1680
+ // it from model history when a later tool step reloads the ledger.
1681
+ await flushStep(true);
1682
+ currentStepMessageId = this.deps.newId();
1767
1683
  // The failed request did not return authoritative usage. Keep
1768
1684
  // effectiveness recoverable, but fail final metering closed.
1769
1685
  sawUnusableStepUsage = true;
1770
1686
  const delayMs = providerRetryDelayMs(providerAttempt, failure.retryAfterMs);
1771
1687
  const nextAttempt = providerAttempt + 1;
1772
- const maxAttempts = idleWatchdogRecovery || incompleteStreamRecovery || sealedThinkingRecovery
1773
- ? nextAttempt
1774
- : MAX_PROVIDER_ATTEMPTS_PER_STEP;
1688
+ const maxAttempts = MAX_PROVIDER_ATTEMPTS_PER_STEP;
1775
1689
  const reason = providerRetryReason(failure.kind);
1776
1690
  queue.push({
1777
1691
  type: 'provider_retry',
@@ -1786,14 +1700,13 @@ export class AiSdkTurn {
1786
1700
  reason,
1787
1701
  });
1788
1702
  await this.deps.providerRetrySleep(delayMs, turnAbortController.signal);
1789
- providerAttempt = nextAttempt;
1790
1703
  queue.push({
1791
1704
  type: 'provider_retry',
1792
1705
  id: this.deps.newId(),
1793
1706
  turnId,
1794
1707
  ts: this.deps.now(),
1795
1708
  phase: 'started',
1796
- attempt: providerAttempt,
1709
+ attempt: nextAttempt,
1797
1710
  maxAttempts,
1798
1711
  reason,
1799
1712
  });
@@ -1803,7 +1716,7 @@ export class AiSdkTurn {
1803
1716
  // safe fold): surface the real provider error via the terminal
1804
1717
  // handler after settling any authoritative usage — never a
1805
1718
  // fabricated success.
1806
- terminalProviderError = settledWatchdogTimeout?.error ?? failure;
1719
+ terminalProviderError = failure;
1807
1720
  terminalRetry = { error: terminalProviderError, retry };
1808
1721
  terminalProviderErrorReason =
1809
1722
  lastCompletedStepHadToolResult && failure.kind === 'timeout'
@@ -1820,10 +1733,7 @@ export class AiSdkTurn {
1820
1733
  if (this.aborted) {
1821
1734
  throw Object.assign(new Error('aborted'), { name: 'AbortError' });
1822
1735
  }
1823
- // Catch-all: flush any residual step content if the provider closed the
1824
- // stream without a trailing `finish-step` for the last step.
1825
1736
  const providerStepId = currentStepMessageId;
1826
- await flushStep();
1827
1737
  if (providerOutcome.kind !== 'completed')
1828
1738
  throw providerOutcome.failure;
1829
1739
  finishReason = providerOutcome.finishReason;
@@ -2006,7 +1916,7 @@ export class AiSdkTurn {
2006
1916
  tokenUsage = sawUnusableStepUsage ? undefined : (completedStepUsage ?? attemptTotalUsage);
2007
1917
  if (tokenUsage) {
2008
1918
  tokenUsageCostUsd = this.deps.providerTelemetry.normalizedUsageCostUsd(tokenUsage);
2009
- const contextBudgetForUsage = contextBudgetWithRequestProjectionDiagnostics(contextBudgetForTelemetry, activeToolResultPruneDiagnosticPatch, midTurnCompactDiagnosticPatch);
1919
+ const contextBudgetForUsage = contextBudgetForTelemetry;
2010
1920
  // Persisted alongside the live event so transcript rebuilds from
2011
1921
  // stored messages keep the TUI ctx segment instead of degrading to
2012
1922
  // `?/<window>` (#4019). Computed once; both writers share it.
@@ -2126,11 +2036,11 @@ export class AiSdkTurn {
2126
2036
  streamStatus = this.aborted ? 'aborted' : 'error';
2127
2037
  streamErrorClass = this.deps.modelAdapter.classifyError(currentWatchdogTimeout()?.error ?? err);
2128
2038
  // Flush the in-flight step's partial text/thinking before the terminal
2129
- // abort/error events. Earlier steps already flushed at their
2130
- // `finish-step`; this keeps their and this step's streamed-out output on
2039
+ // abort/error events. Earlier steps already flushed at settlement;
2040
+ // this keeps their and this step's streamed-out output on
2131
2041
  // BOTH exits — user stop and provider error / watchdog timeout — so the
2132
2042
  // transcript keeps what the user actually saw.
2133
- await flushStep().catch(() => { });
2043
+ await flushStep(!this.aborted).catch(() => { });
2134
2044
  if (this.aborted) {
2135
2045
  queue.push({
2136
2046
  type: 'abort',
@@ -2169,7 +2079,6 @@ export class AiSdkTurn {
2169
2079
  watchdogState.current?.stop();
2170
2080
  if (this.watchdog === watchdogState.current)
2171
2081
  this.watchdog = null;
2172
- contextBudgetForTelemetry = contextBudgetWithRequestProjectionDiagnostics(contextBudgetForTelemetry, activeToolResultPruneDiagnosticPatch, midTurnCompactDiagnosticPatch);
2173
2082
  // `tokenUsage` still backfills from the completed steps when the send
2174
2083
  // ended without a final `usage`: the terminal outcome and the
2175
2084
  // `token_usage` SessionEvent below both read it. An unusable sample in
@@ -2393,7 +2302,7 @@ export class AiSdkTurn {
2393
2302
  // transition reducer before it becomes messages, so a committed
2394
2303
  // transition still cannot resurrect content for the model (#4283).
2395
2304
  const budgeted = applyRuntimeEventContextBudget(rawPriorRuntimeContext, contextBudget);
2396
- let runtimeContext = await this.deps.compaction.foldEffectiveModelHistory(budgeted?.events ?? rawPriorRuntimeContext);
2305
+ let runtimeContext = await this.deps.compaction.foldEffectiveModelHistory(budgeted?.events ?? rawPriorRuntimeContext, preparedContextBudget.projectionSnapshot);
2397
2306
  let contextBudgetDiagnostic = budgeted?.diagnostic;
2398
2307
  let projectedHistoryCompactCheckpoint = budgeted?.historyCompactCheckpoint;
2399
2308
  if (preparedContextBudget.diagnosticPatch) {
@@ -2656,15 +2565,6 @@ class ContinuationReplayEmptyError extends Error {
2656
2565
  this.name = 'ContinuationReplayEmptyError';
2657
2566
  }
2658
2567
  }
2659
- function mergeActiveToolResultPruneDiagnosticPatches(left, right) {
2660
- return {
2661
- ...sumOptionalCounts('activePrunedToolResults', left, right),
2662
- ...sumOptionalCounts('activeSupersededToolResults', left, right),
2663
- ...sumOptionalCounts('activeDuplicateToolResults', left, right),
2664
- ...sumOptionalCounts('activeArchiveFailures', left, right),
2665
- ...sumOptionalCounts('activeEstimatedTokensSaved', left, right),
2666
- };
2667
- }
2668
2568
  function mergeNormalizedUsage(current, next) {
2669
2569
  if (!current)
2670
2570
  return next;
@@ -2685,17 +2585,6 @@ function mergeNormalizedUsage(current, next) {
2685
2585
  cachedInputTokens: cacheHitInputTokens,
2686
2586
  };
2687
2587
  }
2688
- function sumOptionalCounts(key, left, right) {
2689
- const total = (left[key] ?? 0) + (right[key] ?? 0);
2690
- return total > 0 ? { [key]: total } : {};
2691
- }
2692
- function contextBudgetWithRequestProjectionDiagnostics(base, patch, compactionPatch) {
2693
- const prunePatch = hasActiveToolResultPruneDiagnosticPatch(patch) ? patch : undefined;
2694
- const mergedPatch = mergeContextBudgetDiagnosticPatches(prunePatch, compactionPatch);
2695
- if (!mergedPatch)
2696
- return base;
2697
- return mergeContextBudgetDiagnostic(base ?? minimalContextBudgetDiagnostic(), mergedPatch);
2698
- }
2699
2588
  function projectMemoryConversationPrefix(messages, eventMessagePositions) {
2700
2589
  // Context visibility and durable evidence authority are separate boundaries.
2701
2590
  // Keep the exact source prefix so the auxiliary request preserves referents