maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. 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';
@@ -44,7 +43,7 @@ import { renderGraphModePrompt } from './graph-mode.js';
44
43
  import { modelUsesNativeOpenAiResponses } from './model-runtime.js';
45
44
  import { applyRuntimeEventContextBudget, buildContextBudgetDiagnosticShell, mergeContextBudgetDiagnostic, mergeContextBudgetDiagnosticPatches, minimalContextBudgetDiagnostic, shouldAppendContextCompactedNote, shouldAppendContextCompactionFailedOpenNote, } from './context-budget.js';
46
45
  import { isHistoryCompactContentEvent } from './history-compaction.js';
47
- import { canContinueHistoryCompactCheckpointForModel, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
46
+ import { canContinueHistoryCompactCheckpointForModel, historyCompactSourceDigest, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
48
47
  import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
49
48
  import { INVALID_TOOL_NAME, isProviderSandboxBoundaryAttempt, repairMakaToolCall, } from './ai-sdk-tool-repair.js';
50
49
  const CHILD_STEP_BUDGET_FINALIZATION_PROMPT = [
@@ -375,6 +374,7 @@ function providerRetryDelayMs(failedAttempt, retryAfterMs) {
375
374
  }
376
375
  function providerRetryReason(kind) {
377
376
  switch (kind) {
377
+ case 'stream_truncated':
378
378
  case 'network':
379
379
  case 'provider_unavailable':
380
380
  case 'rate_limit':
@@ -410,6 +410,7 @@ export class AiSdkTurn {
410
410
  aborted = false;
411
411
  loopStopRequested = false;
412
412
  loopStopReason;
413
+ handoffPaused = false;
413
414
  watchdog = null;
414
415
  runTrace = null;
415
416
  imageBudget = { used: 0, decisions: new Map() };
@@ -585,12 +586,26 @@ export class AiSdkTurn {
585
586
  impl: (args, context) => this.executeCodeModeCell(eventSink, args.code, context),
586
587
  };
587
588
  }
589
+ /**
590
+ * A note about what happened inside this invocation, written to the
591
+ * invocation's own ledger. Fail-open: the note explains a turn, it is not
592
+ * what the turn did, so losing it must never end a send that is otherwise
593
+ * fine. Returns whether the note landed.
594
+ */
595
+ async recordSystemNote(kind, turnId, data) {
596
+ if (!this.deps.backend.recordSystemNote)
597
+ return false;
598
+ return await this.deps.backend
599
+ .recordSystemNote(kind, turnId, data)
600
+ .then(() => true)
601
+ .catch(() => false);
602
+ }
588
603
  // --------------------------------------------------------------------------
589
604
  // manual history compaction
590
605
  // --------------------------------------------------------------------------
591
606
  async *runWithinScope(input) {
592
607
  const turnId = input.turnId;
593
- const maxSteps = input.maxSteps ?? this.deps.maxSteps;
608
+ const maxSteps = input.maxSteps === null ? undefined : (input.maxSteps ?? this.deps.maxSteps);
594
609
  const toolRuntime = this.toolRuntime;
595
610
  const turnAbortController = this.abortController;
596
611
  const midTurnState = this.deps.compaction.buildMidTurnCapacityCompactState(input);
@@ -636,36 +651,6 @@ export class AiSdkTurn {
636
651
  return;
637
652
  }
638
653
  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
654
  if (hasThinking) {
670
655
  for (const part of stepThinkingParts) {
671
656
  queue.push({
@@ -735,6 +720,28 @@ export class AiSdkTurn {
735
720
  let contextReportedWindowNoteWritten = false;
736
721
  let contextOverflowAfterCompactionNoteWritten = false;
737
722
  let contextWindowSuggestionNoteWritten = false;
723
+ // A compaction decision is known the moment its stage reports it — the
724
+ // pre-turn replay resolves its fold before the first request goes out —
725
+ // while the settlement path is skipped entirely by a stop or a stream
726
+ // error. Write both notes when the decision is known, once per send,
727
+ // whichever stage reports first (#4850).
728
+ const appendCompactionDecisionNotes = async (contextBudget) => {
729
+ if (!contextCompactionFailedOpenNoteWritten &&
730
+ shouldAppendContextCompactionFailedOpenNote(contextBudget)) {
731
+ // The most recent stage that refused the fold: a send can carry both a
732
+ // priorReplay and an activeStep refusal after a diagnostic merge, and
733
+ // array order would pin the stale one.
734
+ const failOpenReason = contextBudget?.compactionDecisions
735
+ ?.filter((decision) => decision.boundaryKind === 'historyCompact' && decision.decision === 'failedOpen')
736
+ .at(-1)?.failOpenReason;
737
+ // Mark written only after the append lands: a failed write must leave
738
+ // the flag down so the settlement fallback can still record the note.
739
+ contextCompactionFailedOpenNoteWritten = await this.recordSystemNote('context_compaction_failed_open', turnId, failOpenReason !== undefined ? { failOpenReason } : undefined);
740
+ }
741
+ if (!contextCompactedNoteWritten && shouldAppendContextCompactedNote(contextBudget)) {
742
+ contextCompactedNoteWritten = await this.recordSystemNote('context_compacted', turnId);
743
+ }
744
+ };
738
745
  // Request index (0-based) at which the active prune last rewrote the
739
746
  // request. A step Maka pruned is not append-only, so usage may legitimately
740
747
  // shrink.
@@ -912,6 +919,10 @@ export class AiSdkTurn {
912
919
  yield* this.drain(queue);
913
920
  return;
914
921
  }
922
+ // The pre-turn replay's fold decision is final here: surface it now so a
923
+ // stop or stream error later in the send cannot keep it from the
924
+ // transcript (#4850).
925
+ await appendCompactionDecisionNotes(priorReplay.contextBudget);
915
926
  if (midTurnState) {
916
927
  // Roll-forward seed: the latest durable checkpoint (loaded or written at
917
928
  // turn start) so a mid-turn summary only re-reads the newly folded span.
@@ -958,6 +969,7 @@ export class AiSdkTurn {
958
969
  };
959
970
  let lastCompletedStepHadToolResult = false;
960
971
  let terminalProviderErrorReason;
972
+ let terminalRetry;
961
973
  try {
962
974
  const startWatchdog = () => {
963
975
  watchdogState.current?.stop();
@@ -1007,12 +1019,26 @@ export class AiSdkTurn {
1007
1019
  ]
1008
1020
  : turnEvents;
1009
1021
  let replayEvents = rawProjectionEvents;
1022
+ let effectiveProjectionCheckpoint = projectionCheckpoint;
1010
1023
  if (projectionCheckpoint) {
1011
1024
  const checkpointMatch = matchHistoryCompactCheckpointPrefix(projectionCheckpoint, rawProjectionEvents);
1012
1025
  if (checkpointMatch.reason) {
1013
1026
  throw new Error(`durable checkpoint projection mismatch: ${checkpointMatch.reason}`);
1014
1027
  }
1015
- replayEvents = projectHistoryCompactCheckpointReplay(projectionCheckpoint, checkpointMatch.coveredRuntimeEvents, checkpointMatch.successorRuntimeEvents);
1028
+ // Content-currency guard: the raw identity still matches, but a
1029
+ // transition committed after this fold (e.g. an active-turn prune
1030
+ // in this very send) changed the effective view the block was
1031
+ // built from. Replay without the stale block — the provider
1032
+ // decides fit and overflow recovery re-folds (#4845 review).
1033
+ const pinnedEffectiveDigest = projectionCheckpoint.coverage.effectiveSourceDigest;
1034
+ const coveredEffective = await this.deps.compaction.foldEffectiveModelHistory(checkpointMatch.coveredRuntimeEvents);
1035
+ if (pinnedEffectiveDigest === undefined ||
1036
+ historyCompactSourceDigest(coveredEffective) !== pinnedEffectiveDigest) {
1037
+ effectiveProjectionCheckpoint = undefined;
1038
+ }
1039
+ else {
1040
+ replayEvents = projectHistoryCompactCheckpointReplay(projectionCheckpoint, checkpointMatch.coveredRuntimeEvents, checkpointMatch.successorRuntimeEvents);
1041
+ }
1016
1042
  // The checkpoint was capacity-validated before it was persisted.
1017
1043
  // Do not re-run that gate against a later, larger successor tail:
1018
1044
  // the active-step shaper must see that growth so it can roll the
@@ -1034,8 +1060,8 @@ export class AiSdkTurn {
1034
1060
  !this.deps.messageProjection.canReplayProviderNative(replayPlan))) {
1035
1061
  throw new Error('durable current-run projection is not replayable');
1036
1062
  }
1037
- 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));
1038
- return projectionCheckpoint
1063
+ 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));
1064
+ return effectiveProjectionCheckpoint
1039
1065
  ? currentTurnMessages
1040
1066
  : [...priorReplay.messages, ...currentTurnMessages];
1041
1067
  };
@@ -1304,15 +1330,10 @@ export class AiSdkTurn {
1304
1330
  ? stepUsage.inputTokens === priorInput
1305
1331
  : stepUsage.inputTokens <= priorInput)) {
1306
1332
  this.deps.session.contextProviderDroppingReported = true;
1307
- const note = {
1308
- type: 'system_note',
1309
- id: this.deps.newId(),
1310
- turnId,
1311
- ts: this.deps.now(),
1312
- kind: 'context_provider_dropping',
1313
- data: { inputTokens: stepUsage.inputTokens, priorInputTokens: priorInput },
1314
- };
1315
- await this.deps.backend.appendMessage(note).catch(() => { });
1333
+ await this.recordSystemNote('context_provider_dropping', turnId, {
1334
+ inputTokens: stepUsage.inputTokens,
1335
+ priorInputTokens: priorInput,
1336
+ });
1316
1337
  }
1317
1338
  // Fail closed: reset on every step boundary so a missing final
1318
1339
  // step's usage does not leave a stale value from an earlier step.
@@ -1331,18 +1352,10 @@ export class AiSdkTurn {
1331
1352
  stepUsage.outputTokens > 0 &&
1332
1353
  stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity) {
1333
1354
  contextWindowOverrunNoteWritten = true;
1334
- const note = {
1335
- type: 'system_note',
1336
- id: this.deps.newId(),
1337
- turnId,
1338
- ts: this.deps.now(),
1339
- kind: 'context_window_overrun',
1340
- data: {
1341
- usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1342
- declaredContextWindow: midTurnState.capacity,
1343
- },
1344
- };
1345
- await this.deps.backend.appendMessage(note).catch(() => { });
1355
+ await this.recordSystemNote('context_window_overrun', turnId, {
1356
+ usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1357
+ declaredContextWindow: midTurnState.capacity,
1358
+ });
1346
1359
  }
1347
1360
  // Nothing declared, and the provider accepted a request past
1348
1361
  // the window this model reports. Every other signal in this
@@ -1378,15 +1391,10 @@ export class AiSdkTurn {
1378
1391
  (previousTotal === undefined || previousTotal <= reported);
1379
1392
  if (reported !== undefined && crossedNow) {
1380
1393
  contextReportedWindowNoteWritten = true;
1381
- const note = {
1382
- type: 'system_note',
1383
- id: this.deps.newId(),
1384
- turnId,
1385
- ts: this.deps.now(),
1386
- kind: 'context_reported_window_exceeded',
1387
- data: { usedTokens: used, reportedContextWindow: reported },
1388
- };
1389
- await this.deps.backend.appendMessage(note).catch(() => { });
1394
+ await this.recordSystemNote('context_reported_window_exceeded', turnId, {
1395
+ usedTokens: used,
1396
+ reportedContextWindow: reported,
1397
+ });
1390
1398
  }
1391
1399
  }
1392
1400
  lastStepInputTokens = stepUsage?.inputTokens;
@@ -1686,20 +1694,12 @@ export class AiSdkTurn {
1686
1694
  acceptedTotal !== undefined &&
1687
1695
  (midTurnState.capacity === undefined || acceptedTotal < midTurnState.capacity)) {
1688
1696
  contextWindowSuggestionNoteWritten = true;
1689
- const note = {
1690
- type: 'system_note',
1691
- id: this.deps.newId(),
1692
- turnId,
1693
- ts: this.deps.now(),
1694
- kind: 'context_window_suggestion',
1695
- data: {
1696
- suggestedContextWindow: acceptedTotal,
1697
- ...(midTurnState.capacity !== undefined
1698
- ? { declaredContextWindow: midTurnState.capacity }
1699
- : {}),
1700
- },
1701
- };
1702
- await this.deps.backend.appendMessage(note).catch(() => { });
1697
+ await this.recordSystemNote('context_window_suggestion', turnId, {
1698
+ suggestedContextWindow: acceptedTotal,
1699
+ ...(midTurnState.capacity !== undefined
1700
+ ? { declaredContextWindow: midTurnState.capacity }
1701
+ : {}),
1702
+ });
1703
1703
  }
1704
1704
  // A folded projection was selected in this send and the provider
1705
1705
  // still rejects the request. That is worth saying, because the
@@ -1713,14 +1713,7 @@ export class AiSdkTurn {
1713
1713
  failure.kind === 'context_overflow' &&
1714
1714
  midTurnState?.compactionAppliedThisSend === true) {
1715
1715
  contextOverflowAfterCompactionNoteWritten = true;
1716
- const note = {
1717
- type: 'system_note',
1718
- id: this.deps.newId(),
1719
- turnId,
1720
- ts: this.deps.now(),
1721
- kind: 'context_overflow_after_compaction',
1722
- };
1723
- await this.deps.backend.appendMessage(note).catch(() => { });
1716
+ await this.recordSystemNote('context_overflow_after_compaction', turnId);
1724
1717
  }
1725
1718
  const idleWatchdogRecovery = settledWatchdogTimeout?.phase === 'idle' &&
1726
1719
  idleWatchdogRetryCount < MAX_IDLE_WATCHDOG_RETRIES_PER_STEP &&
@@ -1739,14 +1732,35 @@ export class AiSdkTurn {
1739
1732
  sealedThinkingRetryCount < MAX_SEALED_THINKING_RETRIES_PER_STEP &&
1740
1733
  attemptCanRecoverWithSealedThinking() &&
1741
1734
  !attemptHasNoObservableOutput();
1742
- if ((failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery) &&
1743
- failure.kind !== 'context_overflow' &&
1744
- providerAttempt < MAX_PROVIDER_ATTEMPTS_PER_STEP &&
1745
- stepBudgetRemains &&
1746
- (attemptHasNoObservableOutput() ||
1747
- idleWatchdogRecovery ||
1748
- incompleteStreamRecovery ||
1749
- sealedThinkingRecovery)) {
1735
+ // The stopping gate also supplies the durable reason. An absent
1736
+ // decision means this attempt is allowed to retry.
1737
+ let retry;
1738
+ if (!(attemptHasNoObservableOutput() ||
1739
+ idleWatchdogRecovery ||
1740
+ incompleteStreamRecovery ||
1741
+ sealedThinkingRecovery)) {
1742
+ retry = {
1743
+ decision: 'declined',
1744
+ because: attemptSawToolActivity ? 'side_effects' : 'observable_output',
1745
+ };
1746
+ }
1747
+ else if (!stepBudgetRemains) {
1748
+ retry = { decision: 'declined', because: 'budget' };
1749
+ }
1750
+ else if (providerAttempt >= MAX_PROVIDER_ATTEMPTS_PER_STEP) {
1751
+ retry = { decision: 'exhausted', attempts: providerAttempt };
1752
+ }
1753
+ else if (failure.kind === 'context_overflow') {
1754
+ retry = { decision: 'declined', because: 'policy' };
1755
+ }
1756
+ else if (!(failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery)) {
1757
+ retry =
1758
+ incompleteStreamTerminal &&
1759
+ incompleteStreamRetryCount >= MAX_INCOMPLETE_STREAM_RETRIES_PER_STEP
1760
+ ? { decision: 'exhausted', attempts: providerAttempt }
1761
+ : { decision: 'declined', because: 'policy' };
1762
+ }
1763
+ if (!retry) {
1750
1764
  if (idleWatchdogRecovery)
1751
1765
  idleWatchdogRetryCount += 1;
1752
1766
  if (sealedThinkingRecovery)
@@ -1798,6 +1812,7 @@ export class AiSdkTurn {
1798
1812
  // handler after settling any authoritative usage — never a
1799
1813
  // fabricated success.
1800
1814
  terminalProviderError = settledWatchdogTimeout?.error ?? failure;
1815
+ terminalRetry = { error: terminalProviderError, retry };
1801
1816
  terminalProviderErrorReason =
1802
1817
  lastCompletedStepHadToolResult && failure.kind === 'timeout'
1803
1818
  ? 'model_after_tool_timeout'
@@ -1934,6 +1949,12 @@ export class AiSdkTurn {
1934
1949
  }
1935
1950
  const mayTakeAnotherStep = !stepLimitReached && !this.loopStopRequested && !this.aborted;
1936
1951
  if (returnedToolCalls.length > 0 && mayTakeAnotherStep) {
1952
+ if ((await input.handoffBoundary?.(turnAbortController.signal, maxSteps === undefined ? null : maxSteps - runtimeSteps)) === 'pause') {
1953
+ this.handoffPaused = true;
1954
+ break agentLoop;
1955
+ }
1956
+ if (this.aborted || this.loopStopRequested)
1957
+ break agentLoop;
1937
1958
  currentStepMessageId = this.deps.newId();
1938
1959
  continue agentLoop;
1939
1960
  }
@@ -1962,6 +1983,13 @@ export class AiSdkTurn {
1962
1983
  if (this.injectedSteeringMessages.length > injectedBefore &&
1963
1984
  !this.loopStopRequested &&
1964
1985
  !this.aborted) {
1986
+ await queue.waitUntilConsumedThroughCurrent();
1987
+ if ((await input.handoffBoundary?.(turnAbortController.signal, maxSteps === undefined ? null : maxSteps - runtimeSteps)) === 'pause') {
1988
+ this.handoffPaused = true;
1989
+ break agentLoop;
1990
+ }
1991
+ if (this.aborted || this.loopStopRequested)
1992
+ break agentLoop;
1965
1993
  currentStepMessageId = this.deps.newId();
1966
1994
  continue agentLoop;
1967
1995
  }
@@ -2050,38 +2078,10 @@ export class AiSdkTurn {
2050
2078
  }
2051
2079
  : {}),
2052
2080
  };
2053
- const tu = {
2054
- type: 'token_usage',
2055
- id: this.deps.newId(),
2056
- turnId,
2057
- ts: this.deps.now(),
2058
- ...usageFields,
2059
- };
2060
- await this.deps.backend.appendMessage(tu).catch(() => { });
2061
- if (!contextCompactionFailedOpenNoteWritten &&
2062
- shouldAppendContextCompactionFailedOpenNote(contextBudgetForUsage)) {
2063
- contextCompactionFailedOpenNoteWritten = true;
2064
- const note = {
2065
- type: 'system_note',
2066
- id: this.deps.newId(),
2067
- turnId,
2068
- ts: this.deps.now(),
2069
- kind: 'context_compaction_failed_open',
2070
- };
2071
- await this.deps.backend.appendMessage(note).catch(() => { });
2072
- }
2073
- if (!contextCompactedNoteWritten &&
2074
- shouldAppendContextCompactedNote(contextBudgetForUsage)) {
2075
- contextCompactedNoteWritten = true;
2076
- const note = {
2077
- type: 'system_note',
2078
- id: this.deps.newId(),
2079
- turnId,
2080
- ts: this.deps.now(),
2081
- kind: 'context_compacted',
2082
- };
2083
- await this.deps.backend.appendMessage(note).catch(() => { });
2084
- }
2081
+ // Settlement fallback: a mid-turn or request-hook fold is only
2082
+ // known here. Notes already written at decision time are skipped
2083
+ // by the flags inside.
2084
+ await appendCompactionDecisionNotes(contextBudgetForUsage);
2085
2085
  queue.push({
2086
2086
  type: 'token_usage',
2087
2087
  id: this.deps.newId(),
@@ -2100,6 +2100,10 @@ export class AiSdkTurn {
2100
2100
  throw Object.assign(new Error('aborted'), { name: 'AbortError' });
2101
2101
  if (terminalProviderError)
2102
2102
  throw terminalProviderError;
2103
+ // Usage above still belongs to this physical attempt. Its Runtime owner
2104
+ // seals the drained stream; no complete/abort event ends the logical Turn.
2105
+ if (this.handoffPaused)
2106
+ return;
2103
2107
  const stopReason = this.loopStopReason ??
2104
2108
  (maxSteps !== undefined && finishReason === 'tool-calls'
2105
2109
  ? 'step_limit'
@@ -2132,8 +2136,8 @@ export class AiSdkTurn {
2132
2136
  // Flush the in-flight step's partial text/thinking before the terminal
2133
2137
  // abort/error events. Earlier steps already flushed at their
2134
2138
  // `finish-step`; this keeps their and this step's streamed-out output on
2135
- // BOTH exits — user stop and provider error / watchdog timeout — so
2136
- // partialOutputRetained reflects what the user actually saw.
2139
+ // BOTH exits — user stop and provider error / watchdog timeout — so the
2140
+ // transcript keeps what the user actually saw.
2137
2141
  await flushStep().catch(() => { });
2138
2142
  if (this.aborted) {
2139
2143
  queue.push({
@@ -2153,7 +2157,12 @@ export class AiSdkTurn {
2153
2157
  }
2154
2158
  else {
2155
2159
  const terminalError = currentWatchdogTimeout()?.error ?? err;
2156
- queue.push(this.makeErrorEvent(turnId, terminalError, terminalProviderErrorReason));
2160
+ queue.push({
2161
+ ...this.makeErrorEvent(turnId, terminalError, terminalProviderErrorReason),
2162
+ ...(terminalRetry && terminalRetry.error === terminalError
2163
+ ? { retry: terminalRetry.retry }
2164
+ : {}),
2165
+ });
2157
2166
  trace.modelStreamFailed(streamErrorClass, terminalError, priorReplayFailureTrace(priorReplay));
2158
2167
  queue.push({
2159
2168
  type: 'complete',
@@ -2367,7 +2376,11 @@ export class AiSdkTurn {
2367
2376
  diagnostics: [],
2368
2377
  };
2369
2378
  }
2370
- const rawPriorRuntimeContext = input.runtimeContext.filter((event) => event.turnId !== input.turnId);
2379
+ // A handoff changes the physical Run, not the logical Turn. Its admitted
2380
+ // replay is all predecessor history, including events with this turnId.
2381
+ const rawPriorRuntimeContext = input.continuation
2382
+ ? input.runtimeContext
2383
+ : input.runtimeContext.filter((event) => event.turnId !== input.turnId);
2371
2384
  // Everything below reads EFFECTIVE model history: raw events folded through
2372
2385
  // the durable projection-transition reducer (#4283). Replay, budgeting and
2373
2386
  // compaction share one input, so no RuntimeEvent replay path can resurrect
@@ -2376,8 +2389,16 @@ export class AiSdkTurn {
2376
2389
  const priorRuntimeContext = preparedContextBudget.events;
2377
2390
  const providerReasoningReplayEventIds = compatibleProviderReasoningReplayEventIds(priorRuntimeContext, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId);
2378
2391
  let contextBudget = preparedContextBudget.policy;
2379
- const budgeted = applyRuntimeEventContextBudget(priorRuntimeContext, contextBudget);
2380
- let runtimeContext = budgeted?.events ?? priorRuntimeContext;
2392
+ // Match the durable checkpoint against the RAW ledger prefix: every
2393
+ // creation path (standalone compactHistory and the mid-turn state) pins
2394
+ // its coverage digest on raw events, so matching the folded view here
2395
+ // lets any durable projection transition inside the covered prefix orphan
2396
+ // the checkpoint and silently fail open into a full-history replay
2397
+ // (#4842). The projected [block, tail] is then folded through the
2398
+ // transition reducer before it becomes messages, so a committed
2399
+ // transition still cannot resurrect content for the model (#4283).
2400
+ const budgeted = applyRuntimeEventContextBudget(rawPriorRuntimeContext, contextBudget);
2401
+ let runtimeContext = await this.deps.compaction.foldEffectiveModelHistory(budgeted?.events ?? rawPriorRuntimeContext);
2381
2402
  let contextBudgetDiagnostic = budgeted?.diagnostic;
2382
2403
  let projectedHistoryCompactCheckpoint = budgeted?.historyCompactCheckpoint;
2383
2404
  if (preparedContextBudget.diagnosticPatch) {
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { EventEmitter } from 'node:events';
20
20
  import { hasBotChannelCredentials } from '@maka/core/bot-chat-settings';
21
+ import { classifyGeneralizedError, redactSecrets } from '@maka/core/redaction';
21
22
  export class BaseBotAdapter extends EventEmitter {
22
23
  platform;
23
24
  settings;
@@ -62,10 +63,26 @@ export class BaseBotAdapter extends EventEmitter {
62
63
  emitStatusChange() {
63
64
  this.emit('statusChange', this.getStatus());
64
65
  }
66
+ recordFailure(error, code) {
67
+ const diagnostic = botDiagnosticMessage(this.settings, error);
68
+ this.reason = code ?? classifyGeneralizedError(diagnostic) ?? 'connection_failed';
69
+ console.warn(`[bots:${this.platform}] ${this.reason}: ${diagnostic}`);
70
+ }
65
71
  connectionKind() {
66
72
  return 'none';
67
73
  }
68
74
  }
75
+ export function botDiagnosticMessage(settings, error) {
76
+ let message = error instanceof Error ? error.message : String(error);
77
+ for (const secret of [settings.token.trim(), settings.appSecret?.trim()]) {
78
+ if (!secret)
79
+ continue;
80
+ message = message
81
+ .replaceAll(secret, '[redacted]')
82
+ .replaceAll(encodeURIComponent(secret), '[redacted]');
83
+ }
84
+ return redactSecrets(message);
85
+ }
69
86
  export function botReadinessFromSettings(settings) {
70
87
  if (!settings.enabled)
71
88
  return 'scaffolded';