maka-agent 0.2.0-dev.23.20260906 → 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 (148) 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-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  28. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  29. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  30. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  31. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  32. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  33. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  34. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  35. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  36. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  37. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  38. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  39. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  40. package/node_modules/@maka/core/dist/session.js +54 -52
  41. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  42. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  43. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  44. package/node_modules/@maka/core/package.json +4 -0
  45. package/node_modules/@maka/mcp/dist/index.js +131 -1
  46. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  49. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +127 -133
  50. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  52. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  53. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  54. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  55. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  56. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  57. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  58. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  59. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  60. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  61. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  62. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  63. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  64. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  65. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  66. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  67. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  68. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  69. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  70. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  71. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  72. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  73. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  74. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  75. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  76. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  77. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  78. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  79. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  80. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  81. package/node_modules/@maka/runtime/package.json +1 -0
  82. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  83. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  84. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  86. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  87. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  88. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  89. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  90. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  91. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  92. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  93. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  94. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  95. package/node_modules/@maka/runtime-host/dist/protocol/index.js +25 -1
  96. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  97. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  98. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  99. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  100. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  101. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  102. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  103. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  104. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +100 -24
  105. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  106. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  107. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  108. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  109. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  110. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  111. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  112. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  113. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  114. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  115. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  116. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  117. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  118. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  119. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  120. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  121. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  122. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  123. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  124. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +0 -1
  125. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  126. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  127. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  128. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  129. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  130. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  131. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  132. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  133. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  134. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  135. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  136. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  137. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  138. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  139. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  140. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  141. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  142. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  144. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  145. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  146. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  147. package/node_modules/@maka/storage/package.json +2 -0
  148. 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({
@@ -749,33 +734,12 @@ export class AiSdkTurn {
749
734
  const failOpenReason = contextBudget?.compactionDecisions
750
735
  ?.filter((decision) => decision.boundaryKind === 'historyCompact' && decision.decision === 'failedOpen')
751
736
  .at(-1)?.failOpenReason;
752
- const note = {
753
- type: 'system_note',
754
- id: this.deps.newId(),
755
- turnId,
756
- ts: this.deps.now(),
757
- kind: 'context_compaction_failed_open',
758
- ...(failOpenReason !== undefined ? { data: { failOpenReason } } : {}),
759
- };
760
737
  // Mark written only after the append lands: a failed write must leave
761
738
  // the flag down so the settlement fallback can still record the note.
762
- contextCompactionFailedOpenNoteWritten = await this.deps.backend
763
- .appendMessage(note)
764
- .then(() => true)
765
- .catch(() => false);
739
+ contextCompactionFailedOpenNoteWritten = await this.recordSystemNote('context_compaction_failed_open', turnId, failOpenReason !== undefined ? { failOpenReason } : undefined);
766
740
  }
767
741
  if (!contextCompactedNoteWritten && shouldAppendContextCompactedNote(contextBudget)) {
768
- const note = {
769
- type: 'system_note',
770
- id: this.deps.newId(),
771
- turnId,
772
- ts: this.deps.now(),
773
- kind: 'context_compacted',
774
- };
775
- contextCompactedNoteWritten = await this.deps.backend
776
- .appendMessage(note)
777
- .then(() => true)
778
- .catch(() => false);
742
+ contextCompactedNoteWritten = await this.recordSystemNote('context_compacted', turnId);
779
743
  }
780
744
  };
781
745
  // Request index (0-based) at which the active prune last rewrote the
@@ -1005,6 +969,7 @@ export class AiSdkTurn {
1005
969
  };
1006
970
  let lastCompletedStepHadToolResult = false;
1007
971
  let terminalProviderErrorReason;
972
+ let terminalRetry;
1008
973
  try {
1009
974
  const startWatchdog = () => {
1010
975
  watchdogState.current?.stop();
@@ -1054,12 +1019,26 @@ export class AiSdkTurn {
1054
1019
  ]
1055
1020
  : turnEvents;
1056
1021
  let replayEvents = rawProjectionEvents;
1022
+ let effectiveProjectionCheckpoint = projectionCheckpoint;
1057
1023
  if (projectionCheckpoint) {
1058
1024
  const checkpointMatch = matchHistoryCompactCheckpointPrefix(projectionCheckpoint, rawProjectionEvents);
1059
1025
  if (checkpointMatch.reason) {
1060
1026
  throw new Error(`durable checkpoint projection mismatch: ${checkpointMatch.reason}`);
1061
1027
  }
1062
- 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
+ }
1063
1042
  // The checkpoint was capacity-validated before it was persisted.
1064
1043
  // Do not re-run that gate against a later, larger successor tail:
1065
1044
  // the active-step shaper must see that growth so it can roll the
@@ -1081,8 +1060,8 @@ export class AiSdkTurn {
1081
1060
  !this.deps.messageProjection.canReplayProviderNative(replayPlan))) {
1082
1061
  throw new Error('durable current-run projection is not replayable');
1083
1062
  }
1084
- const currentTurnMessages = await this.deps.messageProjection.materializeRuntimeReplayPlan(replayPlan, this.imageBudget, projectionCheckpoint, compatibleProviderReasoningReplayEventIds(replayEvents, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId, this.runId));
1085
- return projectionCheckpoint
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
1086
1065
  ? currentTurnMessages
1087
1066
  : [...priorReplay.messages, ...currentTurnMessages];
1088
1067
  };
@@ -1351,15 +1330,10 @@ export class AiSdkTurn {
1351
1330
  ? stepUsage.inputTokens === priorInput
1352
1331
  : stepUsage.inputTokens <= priorInput)) {
1353
1332
  this.deps.session.contextProviderDroppingReported = true;
1354
- const note = {
1355
- type: 'system_note',
1356
- id: this.deps.newId(),
1357
- turnId,
1358
- ts: this.deps.now(),
1359
- kind: 'context_provider_dropping',
1360
- data: { inputTokens: stepUsage.inputTokens, priorInputTokens: priorInput },
1361
- };
1362
- await this.deps.backend.appendMessage(note).catch(() => { });
1333
+ await this.recordSystemNote('context_provider_dropping', turnId, {
1334
+ inputTokens: stepUsage.inputTokens,
1335
+ priorInputTokens: priorInput,
1336
+ });
1363
1337
  }
1364
1338
  // Fail closed: reset on every step boundary so a missing final
1365
1339
  // step's usage does not leave a stale value from an earlier step.
@@ -1378,18 +1352,10 @@ export class AiSdkTurn {
1378
1352
  stepUsage.outputTokens > 0 &&
1379
1353
  stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity) {
1380
1354
  contextWindowOverrunNoteWritten = true;
1381
- const note = {
1382
- type: 'system_note',
1383
- id: this.deps.newId(),
1384
- turnId,
1385
- ts: this.deps.now(),
1386
- kind: 'context_window_overrun',
1387
- data: {
1388
- usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1389
- declaredContextWindow: midTurnState.capacity,
1390
- },
1391
- };
1392
- await this.deps.backend.appendMessage(note).catch(() => { });
1355
+ await this.recordSystemNote('context_window_overrun', turnId, {
1356
+ usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
1357
+ declaredContextWindow: midTurnState.capacity,
1358
+ });
1393
1359
  }
1394
1360
  // Nothing declared, and the provider accepted a request past
1395
1361
  // the window this model reports. Every other signal in this
@@ -1425,15 +1391,10 @@ export class AiSdkTurn {
1425
1391
  (previousTotal === undefined || previousTotal <= reported);
1426
1392
  if (reported !== undefined && crossedNow) {
1427
1393
  contextReportedWindowNoteWritten = true;
1428
- const note = {
1429
- type: 'system_note',
1430
- id: this.deps.newId(),
1431
- turnId,
1432
- ts: this.deps.now(),
1433
- kind: 'context_reported_window_exceeded',
1434
- data: { usedTokens: used, reportedContextWindow: reported },
1435
- };
1436
- await this.deps.backend.appendMessage(note).catch(() => { });
1394
+ await this.recordSystemNote('context_reported_window_exceeded', turnId, {
1395
+ usedTokens: used,
1396
+ reportedContextWindow: reported,
1397
+ });
1437
1398
  }
1438
1399
  }
1439
1400
  lastStepInputTokens = stepUsage?.inputTokens;
@@ -1733,20 +1694,12 @@ export class AiSdkTurn {
1733
1694
  acceptedTotal !== undefined &&
1734
1695
  (midTurnState.capacity === undefined || acceptedTotal < midTurnState.capacity)) {
1735
1696
  contextWindowSuggestionNoteWritten = true;
1736
- const note = {
1737
- type: 'system_note',
1738
- id: this.deps.newId(),
1739
- turnId,
1740
- ts: this.deps.now(),
1741
- kind: 'context_window_suggestion',
1742
- data: {
1743
- suggestedContextWindow: acceptedTotal,
1744
- ...(midTurnState.capacity !== undefined
1745
- ? { declaredContextWindow: midTurnState.capacity }
1746
- : {}),
1747
- },
1748
- };
1749
- await this.deps.backend.appendMessage(note).catch(() => { });
1697
+ await this.recordSystemNote('context_window_suggestion', turnId, {
1698
+ suggestedContextWindow: acceptedTotal,
1699
+ ...(midTurnState.capacity !== undefined
1700
+ ? { declaredContextWindow: midTurnState.capacity }
1701
+ : {}),
1702
+ });
1750
1703
  }
1751
1704
  // A folded projection was selected in this send and the provider
1752
1705
  // still rejects the request. That is worth saying, because the
@@ -1760,14 +1713,7 @@ export class AiSdkTurn {
1760
1713
  failure.kind === 'context_overflow' &&
1761
1714
  midTurnState?.compactionAppliedThisSend === true) {
1762
1715
  contextOverflowAfterCompactionNoteWritten = true;
1763
- const note = {
1764
- type: 'system_note',
1765
- id: this.deps.newId(),
1766
- turnId,
1767
- ts: this.deps.now(),
1768
- kind: 'context_overflow_after_compaction',
1769
- };
1770
- await this.deps.backend.appendMessage(note).catch(() => { });
1716
+ await this.recordSystemNote('context_overflow_after_compaction', turnId);
1771
1717
  }
1772
1718
  const idleWatchdogRecovery = settledWatchdogTimeout?.phase === 'idle' &&
1773
1719
  idleWatchdogRetryCount < MAX_IDLE_WATCHDOG_RETRIES_PER_STEP &&
@@ -1786,14 +1732,35 @@ export class AiSdkTurn {
1786
1732
  sealedThinkingRetryCount < MAX_SEALED_THINKING_RETRIES_PER_STEP &&
1787
1733
  attemptCanRecoverWithSealedThinking() &&
1788
1734
  !attemptHasNoObservableOutput();
1789
- if ((failure.retryable || idleWatchdogRecovery || incompleteStreamRecovery) &&
1790
- failure.kind !== 'context_overflow' &&
1791
- providerAttempt < MAX_PROVIDER_ATTEMPTS_PER_STEP &&
1792
- stepBudgetRemains &&
1793
- (attemptHasNoObservableOutput() ||
1794
- idleWatchdogRecovery ||
1795
- incompleteStreamRecovery ||
1796
- sealedThinkingRecovery)) {
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) {
1797
1764
  if (idleWatchdogRecovery)
1798
1765
  idleWatchdogRetryCount += 1;
1799
1766
  if (sealedThinkingRecovery)
@@ -1845,6 +1812,7 @@ export class AiSdkTurn {
1845
1812
  // handler after settling any authoritative usage — never a
1846
1813
  // fabricated success.
1847
1814
  terminalProviderError = settledWatchdogTimeout?.error ?? failure;
1815
+ terminalRetry = { error: terminalProviderError, retry };
1848
1816
  terminalProviderErrorReason =
1849
1817
  lastCompletedStepHadToolResult && failure.kind === 'timeout'
1850
1818
  ? 'model_after_tool_timeout'
@@ -1981,6 +1949,12 @@ export class AiSdkTurn {
1981
1949
  }
1982
1950
  const mayTakeAnotherStep = !stepLimitReached && !this.loopStopRequested && !this.aborted;
1983
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;
1984
1958
  currentStepMessageId = this.deps.newId();
1985
1959
  continue agentLoop;
1986
1960
  }
@@ -2009,6 +1983,13 @@ export class AiSdkTurn {
2009
1983
  if (this.injectedSteeringMessages.length > injectedBefore &&
2010
1984
  !this.loopStopRequested &&
2011
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;
2012
1993
  currentStepMessageId = this.deps.newId();
2013
1994
  continue agentLoop;
2014
1995
  }
@@ -2097,14 +2078,6 @@ export class AiSdkTurn {
2097
2078
  }
2098
2079
  : {}),
2099
2080
  };
2100
- const tu = {
2101
- type: 'token_usage',
2102
- id: this.deps.newId(),
2103
- turnId,
2104
- ts: this.deps.now(),
2105
- ...usageFields,
2106
- };
2107
- await this.deps.backend.appendMessage(tu).catch(() => { });
2108
2081
  // Settlement fallback: a mid-turn or request-hook fold is only
2109
2082
  // known here. Notes already written at decision time are skipped
2110
2083
  // by the flags inside.
@@ -2127,6 +2100,10 @@ export class AiSdkTurn {
2127
2100
  throw Object.assign(new Error('aborted'), { name: 'AbortError' });
2128
2101
  if (terminalProviderError)
2129
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;
2130
2107
  const stopReason = this.loopStopReason ??
2131
2108
  (maxSteps !== undefined && finishReason === 'tool-calls'
2132
2109
  ? 'step_limit'
@@ -2159,8 +2136,8 @@ export class AiSdkTurn {
2159
2136
  // Flush the in-flight step's partial text/thinking before the terminal
2160
2137
  // abort/error events. Earlier steps already flushed at their
2161
2138
  // `finish-step`; this keeps their and this step's streamed-out output on
2162
- // BOTH exits — user stop and provider error / watchdog timeout — so
2163
- // partialOutputRetained reflects what the user actually saw.
2139
+ // BOTH exits — user stop and provider error / watchdog timeout — so the
2140
+ // transcript keeps what the user actually saw.
2164
2141
  await flushStep().catch(() => { });
2165
2142
  if (this.aborted) {
2166
2143
  queue.push({
@@ -2180,7 +2157,12 @@ export class AiSdkTurn {
2180
2157
  }
2181
2158
  else {
2182
2159
  const terminalError = currentWatchdogTimeout()?.error ?? err;
2183
- 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
+ });
2184
2166
  trace.modelStreamFailed(streamErrorClass, terminalError, priorReplayFailureTrace(priorReplay));
2185
2167
  queue.push({
2186
2168
  type: 'complete',
@@ -2394,7 +2376,11 @@ export class AiSdkTurn {
2394
2376
  diagnostics: [],
2395
2377
  };
2396
2378
  }
2397
- 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);
2398
2384
  // Everything below reads EFFECTIVE model history: raw events folded through
2399
2385
  // the durable projection-transition reducer (#4283). Replay, budgeting and
2400
2386
  // compaction share one input, so no RuntimeEvent replay path can resurrect
@@ -2403,8 +2389,16 @@ export class AiSdkTurn {
2403
2389
  const priorRuntimeContext = preparedContextBudget.events;
2404
2390
  const providerReasoningReplayEventIds = compatibleProviderReasoningReplayEventIds(priorRuntimeContext, input.runtimeContextInvocations, this.deps.backend.providerStateIdentity, this.deps.backend.modelId);
2405
2391
  let contextBudget = preparedContextBudget.policy;
2406
- const budgeted = applyRuntimeEventContextBudget(priorRuntimeContext, contextBudget);
2407
- 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);
2408
2402
  let contextBudgetDiagnostic = budgeted?.diagnostic;
2409
2403
  let projectedHistoryCompactCheckpoint = budgeted?.historyCompactCheckpoint;
2410
2404
  if (preparedContextBudget.diagnosticPatch) {
@@ -119,16 +119,21 @@ export function mergeContextBudgetDiagnosticPatches(left, right) {
119
119
  return left;
120
120
  return mergeContextBudgetDiagnostic(left, right);
121
121
  }
122
- // A history fold reaches the user as one note per send, whichever stage
123
- // performed it: the replay of an existing checkpoint at turn start
124
- // (`priorReplay`) or a fold the request-projection hook made before a request
125
- // of this send (`activeStep`, pre_turn or mid_turn). Since #4486 every new fold
126
- // happens in the hook, so a note keyed on replay alone would arrive one turn
127
- // late — the turn that was compacted would show nothing (#4559).
122
+ // A history fold reaches the user as one note per send. Since #4486 every fresh
123
+ // fold a send performs is an `activeStep` (the request-projection hook), so a
124
+ // `replaced` decision warrants a note only when it is that fresh fold. A
125
+ // `priorReplay` `replaced` is a passive re-application of a checkpoint that some
126
+ // other path already noted on its own turn — explicit compaction writes its own
127
+ // note there (`runtime-kernel`) — and `history-compaction.ts` re-emits it on
128
+ // every later send whose history still matches, so counting it here would
129
+ // duplicate that note again and again (#3587). A `failedOpen` replay is instead
130
+ // a genuine event of this send (the fold was dropped and the full history went
131
+ // out), so it keeps both stages.
128
132
  function hasHistoryCompactDecision(contextBudget, decision) {
129
- return (contextBudget?.compactionDecisions?.some((candidate) => (candidate.stage === 'priorReplay' || candidate.stage === 'activeStep') &&
130
- candidate.boundaryKind === 'historyCompact' &&
131
- candidate.decision === decision) === true);
133
+ return (contextBudget?.compactionDecisions?.some((candidate) => candidate.boundaryKind === 'historyCompact' &&
134
+ candidate.decision === decision &&
135
+ (candidate.stage === 'activeStep' ||
136
+ (decision === 'failedOpen' && candidate.stage === 'priorReplay'))) === true);
132
137
  }
133
138
  export function shouldAppendContextCompactedNote(contextBudget) {
134
139
  return hasHistoryCompactDecision(contextBudget, 'replaced');
@@ -29,6 +29,7 @@ import { isHistoryCompactContentEvent } from './history-compaction.js';
29
29
  import { classifyTerminalRuntimeLedger, commitTerminalRunWithRuntimeFact, } from './terminal-run-commit.js';
30
30
  import { buildToolOperationId } from './runtime-commit-sink.js';
31
31
  import { isContinuationStartRuntimeEvent } from './runtime-event-read-model.js';
32
+ import { runtimeHandoffPause } from '@maka/core/runtime-handoff';
32
33
  import { buildToolResultArchiveResourceRef, parseToolResultArchiveResourceRef, } from './tool-result-archive-resource.js';
33
34
  import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
34
35
  import { rewriteDurableToolResultProjectionArtifactRefs } from './durable-tool-result-projection.js';
@@ -165,6 +166,7 @@ export async function prepareConversationRuntimeLedgerCopy(input) {
165
166
  const selectedRunEvents = await loadConversationCopyRunEvents(sourceRuns, input.sourceEvents, copyTurnIds, input.runtimeEventStore);
166
167
  const runs = await Promise.all(selectedRunEvents.map(async ({ run, events }) => {
167
168
  const operationalEvents = await input.runStore.readEvents(run.sessionId, run.runId);
169
+ assertConversationRuntimeLedgerCopySupported(run, events);
168
170
  const terminal = classifyTerminalRuntimeLedger(run, events);
169
171
  if (run.terminalEvent && terminal.kind !== 'fact') {
170
172
  throw new Error(`Cannot copy terminal AgentRun ${run.runId} without one terminal fact`);
@@ -188,7 +190,6 @@ export async function prepareConversationRuntimeLedgerCopy(input) {
188
190
  inlineRuntimeEvents,
189
191
  runs,
190
192
  };
191
- assertConversationRuntimeLedgerCopySupported(plan);
192
193
  return plan;
193
194
  }
194
195
  /**
@@ -268,9 +269,9 @@ async function rebuildCopiedProjectionTransitions(sessionId, sourceRuns, runs, r
268
269
  owner.operationalEvents.push({ ...event, runId: owner.run.runId, turnId: owner.run.turnId });
269
270
  }
270
271
  }
271
- function assertConversationRuntimeLedgerCopySupported(plan) {
272
- const unsupported = plan.runs.some(({ run, runtimeEvents }) => run.opening.source.kind === 'continuation' ||
273
- runtimeEvents.some(isContinuationStartRuntimeEvent));
272
+ function assertConversationRuntimeLedgerCopySupported(run, runtimeEvents) {
273
+ const unsupported = run.opening.source.kind !== 'fresh' ||
274
+ runtimeEvents.some((event) => isContinuationStartRuntimeEvent(event) || runtimeHandoffPause(event));
274
275
  if (!unsupported)
275
276
  return;
276
277
  const error = new Error('Conversation copy contains durable runtime authority facts that require typed identity rewriting');
@@ -48,6 +48,7 @@ export class GoalContinuationCoordinator {
48
48
  taskGatePolicy;
49
49
  scheduler;
50
50
  disposed = false;
51
+ handoffHeld = false;
51
52
  closeTask;
52
53
  constructor(deps) {
53
54
  this.deps = deps;
@@ -310,6 +311,29 @@ export class GoalContinuationCoordinator {
310
311
  });
311
312
  return resumed;
312
313
  }
314
+ /** Stop new continuation admission, but finish accounting for settled turns. */
315
+ holdForHandoff() {
316
+ if (this.disposed || this.handoffHeld)
317
+ return undefined;
318
+ this.handoffHeld = true;
319
+ for (const lane of this.lanes.values())
320
+ this.clearWaitingTimer(lane);
321
+ let released = false;
322
+ return {
323
+ settled: async () => {
324
+ while (this.activeDrains.size > 0)
325
+ await Promise.all([...this.activeDrains]);
326
+ },
327
+ release: () => {
328
+ if (released)
329
+ return;
330
+ released = true;
331
+ this.handoffHeld = false;
332
+ for (const lane of this.lanes.values())
333
+ this.scheduleDrain(lane);
334
+ },
335
+ };
336
+ }
313
337
  dispose() {
314
338
  if (this.disposed)
315
339
  return;
@@ -392,6 +416,8 @@ export class GoalContinuationCoordinator {
392
416
  scheduleDrain(lane) {
393
417
  if (!this.isCurrent(lane) || lane.draining)
394
418
  return;
419
+ if (this.handoffHeld && lane.queue.length === 0)
420
+ return;
395
421
  const task = this.drainLane(lane).catch((error) => {
396
422
  if (!this.isCurrent(lane))
397
423
  return;
@@ -426,7 +452,7 @@ export class GoalContinuationCoordinator {
426
452
  }
427
453
  item.resolve();
428
454
  }
429
- if (!this.isCurrent(lane) || lane.queue.length > 0)
455
+ if (!this.isCurrent(lane) || lane.queue.length > 0 || this.handoffHeld)
430
456
  return;
431
457
  const goal = this.deps.goalManager.get(lane.sessionId);
432
458
  if (goal?.status === 'waiting' && lane.intent) {
@@ -569,7 +595,10 @@ export class GoalContinuationCoordinator {
569
595
  this.resetWaitingBackoff(lane);
570
596
  }
571
597
  async tryAdmitIntent(lane, intent) {
572
- if (!this.isCurrent(lane) || lane.queue.length > 0 || lane.intent !== intent) {
598
+ if (this.handoffHeld ||
599
+ !this.isCurrent(lane) ||
600
+ lane.queue.length > 0 ||
601
+ lane.intent !== intent) {
573
602
  return;
574
603
  }
575
604
  if (!this.ownedGoal(lane, intent)) {
@@ -577,7 +606,10 @@ export class GoalContinuationCoordinator {
577
606
  return;
578
607
  }
579
608
  const taskPlan = await this.taskGatePolicy.planAdmission(lane.sessionId, intent.checkpoint.goalId);
580
- if (!this.isCurrent(lane) || lane.queue.length > 0 || lane.intent !== intent) {
609
+ if (this.handoffHeld ||
610
+ !this.isCurrent(lane) ||
611
+ lane.queue.length > 0 ||
612
+ lane.intent !== intent) {
581
613
  return;
582
614
  }
583
615
  const goal = this.ownedGoal(lane, intent);
@@ -662,7 +694,7 @@ export class GoalContinuationCoordinator {
662
694
  return this.deps.goalManager.get(lane.sessionId);
663
695
  }
664
696
  scheduleWaitingRetry(lane, goal) {
665
- if (!this.isCurrent(lane) || lane.waitingTimer || !lane.intent)
697
+ if (this.handoffHeld || !this.isCurrent(lane) || lane.waitingTimer || !lane.intent)
666
698
  return;
667
699
  if (!this.deps.goalManager.matches(lane.sessionId, lane.intent.checkpoint)) {
668
700
  lane.intent = undefined;