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
@@ -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;
@@ -20,12 +20,15 @@ import { createHash } from 'node:crypto';
20
20
  import { Buffer } from 'node:buffer';
21
21
  import { stableStringify } from './request-shape.js';
22
22
  import { findCheckpointSummaryDefect, SECTIONED_SUMMARY_FORMAT, } from './history-compact-summary-validation.js';
23
- // v2: coverage and source digest are taken over EFFECTIVE model history (the
24
- // durable Tool Result projection), not raw RuntimeEvent evidence. A v1
25
- // checkpoint's digest was computed over a different source, so it fails the
26
- // shape check and its session re-summarizes rather than replaying a
27
- // coverage claim this policy never made.
28
- export const HISTORY_COMPACT_SOURCE_POLICY_VERSION = 'maka.compactable_runtime_event_projection.v2';
23
+ // v3: coverage identity and the source digest stay pinned on the RAW ledger
24
+ // prefix — the immutable view every creation path (standalone and mid-turn)
25
+ // and both match sites (pre-turn replay and the mid-turn durable projection)
26
+ // share — while the model-visible summary is produced from the EFFECTIVE,
27
+ // transition-folded prefix. A v2 checkpoint's summary could quote a Tool
28
+ // Result body a durable projection transition had already removed, so it is
29
+ // superseded on load and the session re-summarizes rather than replaying a
30
+ // coverage claim whose summary this policy never audited (#4845).
31
+ export const HISTORY_COMPACT_SOURCE_POLICY_VERSION = 'maka.compactable_runtime_event_projection.v3';
29
32
  export function buildHistoryCompactCheckpoint(input) {
30
33
  if (input.coveredRuntimeEvents.length === 0) {
31
34
  throw new Error('History compact checkpoint requires covered RuntimeEvents');
@@ -81,7 +84,7 @@ export function buildHistoryCompactCheckpoint(input) {
81
84
  if (anchored.turnId !== input.headAnchor.turnId ||
82
85
  anchored.turnId !== lastCovered.turnId ||
83
86
  anchored.role !== 'user' ||
84
- anchored.author !== 'user') {
87
+ (anchored.author !== 'user' && anchored.author !== 'host')) {
85
88
  throw new Error("Mid-turn history compact checkpoint head anchor must be the compacted turn's user event");
86
89
  }
87
90
  headAnchor = {
@@ -101,6 +104,7 @@ export function buildHistoryCompactCheckpoint(input) {
101
104
  runtimeEventId: lastEvent.id,
102
105
  },
103
106
  sourceDigest: historyCompactSourceDigest(input.coveredRuntimeEvents),
107
+ effectiveSourceDigest: historyCompactSourceDigest(input.effectiveCoveredRuntimeEvents ?? input.coveredRuntimeEvents),
104
108
  };
105
109
  const highWaterName = input.highWaterName ?? 'history-compact-high-water';
106
110
  const highWaterSeq = input.highWaterSeq ?? createdAt;
@@ -248,6 +252,11 @@ export function validateHistoryCompactCheckpointShape(value, sessionId) {
248
252
  nonEmpty(through?.turnId) &&
249
253
  nonEmpty(through?.runtimeEventId) &&
250
254
  nonEmpty(coverage?.sourceDigest) &&
255
+ // A checkpoint minted under the current source policy pins the effective
256
+ // (transition-folded) view its summary or provider state describes;
257
+ // without the digest there is no content-currency binding at replay, so
258
+ // the record must not validate (#4845 review).
259
+ (checkpoint.source === undefined || nonEmpty(coverage?.effectiveSourceDigest)) &&
251
260
  (checkpoint.source === undefined ||
252
261
  validHistoryCompactCheckpointSource(checkpoint.source, checkpoint.sessionId, coverage)) &&
253
262
  (checkpoint.phase === undefined ||
@@ -366,7 +375,7 @@ export function matchHistoryCompactCheckpointPrefix(checkpoint, events) {
366
375
  anchor.turnId !== checkpoint.headAnchor.turnId ||
367
376
  anchor.turnId !== checkpoint.coverage.through.turnId ||
368
377
  anchor.role !== 'user' ||
369
- anchor.author !== 'user') {
378
+ (anchor.author !== 'user' && anchor.author !== 'host')) {
370
379
  return {
371
380
  coveredEventCount: 0,
372
381
  coveredRuntimeEvents: [],
@@ -473,7 +482,7 @@ function sameHistoryCompactSourceCoverage(current, candidate) {
473
482
  * response's effective projection does change the digest, so a checkpoint can
474
483
  * never be replayed over content it never covered.
475
484
  */
476
- function historyCompactSourceDigest(events) {
485
+ export function historyCompactSourceDigest(events) {
477
486
  const hash = createHash('sha256');
478
487
  for (const event of events) {
479
488
  const serialized = stableStringify(effectiveDigestEvent(event));
@@ -33,7 +33,12 @@ export { HistoryCompactSummarizerError } from './history-compact-error.js';
33
33
  // folded events are projected with the same policy the model would see them.
34
34
  // The format block is the validation module's template, so the mandated
35
35
  // format and the validation can never drift apart.
36
- const SUMMARIZATION_SYSTEM_PROMPT = [
36
+ // It rides as the trailing user message, never as provider instructions
37
+ // (system role): agentic coding models such as kimi k3-256k ignore a system
38
+ // prompt in this shape and keep answering the conversation instead, so the
39
+ // fold fails open forever (#4634), and a distinct system prompt also forfeits
40
+ // the prefix cache the main-loop requests built.
41
+ const SUMMARIZATION_PROMPT = [
37
42
  'You are a context summarization assistant.',
38
43
  'Read the conversation between a user and an AI assistant, then produce a structured summary another LLM will use to continue the same task.',
39
44
  'Do NOT continue the conversation. Do NOT answer questions in it. ONLY output the structured summary.',
@@ -45,16 +50,16 @@ const SUMMARIZATION_SYSTEM_PROMPT = [
45
50
  'Keep each section concise. Preserve exact file paths, function names, commands, and error messages.',
46
51
  ].join('\n');
47
52
  const SUMMARY_REQUEST_INSTRUCTION = 'Now write the structured summary of the conversation above. Output only the summary.';
48
- function shortenSummarizationSystemPrompt() {
53
+ function shortenSummarizationPrompt() {
49
54
  return [
50
- SUMMARIZATION_SYSTEM_PROMPT,
55
+ SUMMARIZATION_PROMPT,
51
56
  '',
52
57
  'Your previous attempt was cut off at the output limit. Produce the same summary in well under half the length: keep every section, drop detail rather than sections.',
53
58
  ].join('\n');
54
59
  }
55
- function repairSummarizationSystemPrompt(reason) {
60
+ function repairSummarizationPrompt(reason) {
56
61
  return [
57
- SUMMARIZATION_SYSTEM_PROMPT,
62
+ SUMMARIZATION_PROMPT,
58
63
  '',
59
64
  `A prior attempt was rejected as ${reason}.`,
60
65
  'Produce one complete replacement summary from the source conversation.',
@@ -85,16 +90,6 @@ export function buildLlmHistorySummarizer(options) {
85
90
  ],
86
91
  });
87
92
  }
88
- // The folded span usually ends on an assistant message. A chat-template
89
- // model handed a conversation that already ends with its own turn emits
90
- // an end-of-sequence token and nothing else (Ollama qwen2.5: finish
91
- // `stop`, one output token, empty text), so the request must end with
92
- // an instruction the model can answer. Hosted providers do not need the
93
- // nudge and are not disturbed by it (#4559).
94
- projectedMessages.push({
95
- role: 'user',
96
- content: [{ type: 'text', text: SUMMARY_REQUEST_INSTRUCTION }],
97
- });
98
93
  // Nothing is trimmed on a local estimate: whether this input fits the
99
94
  // summarizer's window is its provider's answer (`input_too_large`, which
100
95
  // the planner retreats on), and the output is capped outright (#4559).
@@ -119,8 +114,21 @@ export function buildLlmHistorySummarizer(options) {
119
114
  step += 1;
120
115
  const result = await generateText({
121
116
  model,
122
- instructions,
123
- messages,
117
+ // The instruction rides as the trailing user message rather than the
118
+ // AI SDK's `instructions` (system role): the request must still end
119
+ // with an imperative the model can answer (#4559), and no
120
+ // system-role prompt may precede the conversation, which agentic
121
+ // models ignore and which forfeits the main loop's prefix cache
122
+ // (#4634).
123
+ messages: [
124
+ ...messages,
125
+ {
126
+ role: 'user',
127
+ content: [
128
+ { type: 'text', text: `${instructions}\n\n${SUMMARY_REQUEST_INSTRUCTION}` },
129
+ ],
130
+ },
131
+ ],
124
132
  maxOutputTokens,
125
133
  ...(options.providerOptions !== undefined
126
134
  ? { providerOptions: options.providerOptions }
@@ -142,12 +150,12 @@ export function buildLlmHistorySummarizer(options) {
142
150
  : findCheckpointSummaryDefect(result.text, spanUsage ? { summarizerUsage: spanUsage } : undefined);
143
151
  return { text: result.text, defect, truncated };
144
152
  };
145
- let initial = await generateSummary(SUMMARIZATION_SYSTEM_PROMPT, projectedMessages);
153
+ let initial = await generateSummary(SUMMARIZATION_PROMPT, projectedMessages);
146
154
  if (initial.truncated) {
147
155
  // The provider cut the summary at the output cap. One shorter attempt;
148
156
  // a second cut is the provider saying this span will not summarize
149
157
  // inside the cap, and the fold fails open.
150
- initial = await generateSummary(shortenSummarizationSystemPrompt(), projectedMessages);
158
+ initial = await generateSummary(shortenSummarizationPrompt(), projectedMessages);
151
159
  if (initial.truncated)
152
160
  throw new HistoryCompactSummarizerError('output_length');
153
161
  }
@@ -159,7 +167,7 @@ export function buildLlmHistorySummarizer(options) {
159
167
  // A malformed provider completion is often repairable, but retries must
160
168
  // be bounded: one stricter attempt, then the caller's failure circuit
161
169
  // records the stable defect for this compaction input.
162
- const repairInstructions = repairSummarizationSystemPrompt(initial.defect);
170
+ const repairInstructions = repairSummarizationPrompt(initial.defect);
163
171
  let repaired;
164
172
  try {
165
173
  repaired = await generateSummary(repairInstructions, projectedMessages);
@@ -173,7 +181,7 @@ export function buildLlmHistorySummarizer(options) {
173
181
  // the fold past the summarizer provider's window, the rejection is the
174
182
  // planner's retreat signal, not a repair failure to file under the
175
183
  // initial defect (#4559).
176
- if (classifyError(error) === 'ContextLength') {
184
+ if (classifyError(error) === 'context_overflow') {
177
185
  throw new HistoryCompactSummarizerError('input_too_large', { cause: error });
178
186
  }
179
187
  throw new HistoryCompactSummarizerError(initial.defect, {
@@ -202,7 +210,7 @@ export function buildLlmHistorySummarizer(options) {
202
210
  // The summarizer's provider is the one judge of whether this fold fits
203
211
  // its own window: a context-length rejection is the signal the planner
204
212
  // retreats on, so it must keep its name here (#4559).
205
- if (classifyError(error) === 'ContextLength') {
213
+ if (classifyError(error) === 'context_overflow') {
206
214
  throw new HistoryCompactSummarizerError('input_too_large', { cause: error });
207
215
  }
208
216
  throw new HistoryCompactSummarizerError('provider_error', { cause: error });
@@ -20,7 +20,7 @@ import { estimateRuntimeEventChars, estimateRuntimeEventsTokens } from './model-
20
20
  import { compactionDecisionDiagnosticPatch } from './compaction-boundary.js';
21
21
  import { HistoryCompactSummarizerError, } from './history-compact-error.js';
22
22
  import { findCheckpointSummaryDefect } from './history-compact-summary-validation.js';
23
- import { buildHistoryCompactCheckpoint, historyCompactCheckpointToRuntimeEvent, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
23
+ import { buildHistoryCompactCheckpoint, historyCompactCheckpointToRuntimeEvent, historyCompactSourceDigest, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
24
24
  /**
25
25
  * Select the largest contiguous covered prefix that is safe to fold:
26
26
  *
@@ -177,15 +177,39 @@ export async function planHistoryCompaction(input) {
177
177
  const checkpointMatch = input.previousCheckpoint
178
178
  ? matchHistoryCompactCheckpointPrefix(input.previousCheckpoint, coveredRuntimeEvents)
179
179
  : undefined;
180
- const previousCheckpoint = checkpointMatch && !checkpointMatch.reason ? input.previousCheckpoint : undefined;
180
+ let previousCheckpoint = checkpointMatch && !checkpointMatch.reason ? input.previousCheckpoint : undefined;
181
+ // Content-currency gate for roll-forward: the inherited summary or
182
+ // provider state describes the EFFECTIVE view of the previous coverage at
183
+ // its own creation. A projection transition committed since rewrites that
184
+ // view without touching the raw prefix, and reusing the stale content here
185
+ // would launder it into the new checkpoint under the current effective
186
+ // digest — later replay guards would then pass it (#4845 review). On
187
+ // drift, discard the checkpoint and re-summarize the whole effective span.
188
+ if (previousCheckpoint && checkpointMatch && input.projectEffectiveCoverage) {
189
+ const pinned = previousCheckpoint.coverage.effectiveSourceDigest;
190
+ const previousEffectiveCovered = await input.projectEffectiveCoverage(checkpointMatch.coveredRuntimeEvents);
191
+ if (pinned === undefined || historyCompactSourceDigest(previousEffectiveCovered) !== pinned) {
192
+ previousCheckpoint = undefined;
193
+ }
194
+ }
181
195
  const newlyFoldedRuntimeEvents = previousCheckpoint
182
196
  ? checkpointMatch.successorRuntimeEvents
183
197
  : coveredRuntimeEvents;
198
+ // The model-visible summary reads the effective (transition-folded) view
199
+ // of the covered span; the raw events keep the coverage identity.
200
+ const effectiveCoveredRuntimeEvents = input.projectEffectiveCoverage
201
+ ? [...(await input.projectEffectiveCoverage(coveredRuntimeEvents))]
202
+ : undefined;
203
+ const effectiveNewlyFoldedRuntimeEvents = effectiveCoveredRuntimeEvents
204
+ ? newlyFoldedRuntimeEvents.length === coveredRuntimeEvents.length
205
+ ? effectiveCoveredRuntimeEvents
206
+ : effectiveCoveredRuntimeEvents.slice(effectiveCoveredRuntimeEvents.length - newlyFoldedRuntimeEvents.length)
207
+ : undefined;
184
208
  let compacted;
185
209
  try {
186
210
  compacted = await Promise.resolve(input.summarize({
187
- coveredRuntimeEvents,
188
- newlyFoldedRuntimeEvents,
211
+ coveredRuntimeEvents: effectiveCoveredRuntimeEvents ?? coveredRuntimeEvents,
212
+ newlyFoldedRuntimeEvents: effectiveNewlyFoldedRuntimeEvents ?? newlyFoldedRuntimeEvents,
189
213
  ...(previousCheckpoint ? { previousCheckpoint } : {}),
190
214
  }));
191
215
  if (typeof compacted === 'string')
@@ -240,6 +264,7 @@ export async function planHistoryCompaction(input) {
240
264
  const checkpoint = buildHistoryCompactCheckpoint({
241
265
  sessionId: input.sessionId,
242
266
  coveredRuntimeEvents,
267
+ ...(effectiveCoveredRuntimeEvents ? { effectiveCoveredRuntimeEvents } : {}),
243
268
  ...(typeof compacted === 'string' ? { summary: compacted } : { providerState: compacted }),
244
269
  ...(phase === 'mid_turn'
245
270
  ? { phase: 'mid_turn', headAnchor: input.headAnchor }
@@ -0,0 +1,106 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ import { decodeDurableToolResultProjection } from '@maka/core/durable-tool-result-projection';
21
+ import { decodeLedgerTransition, reduceEffectiveModelProjections, } from './model-projection-transition-ledger.js';
22
+ import { isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
23
+ import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
24
+ /**
25
+ * Read-only v1 reconstruction. It never calls a live tool projector, reads an
26
+ * Artifact, changes history, or authorizes access from a hash alone.
27
+ * The evidence port is trusted to return the complete bounded target history.
28
+ */
29
+ export function createLedgerToolResultArchiveReader(evidence) {
30
+ return async (input) => {
31
+ const request = { ...input };
32
+ if (!isArchivedToolResultPlaceholder(request) ||
33
+ !/^[a-f0-9]{64}$/.test(request.bodySha256) ||
34
+ !Number.isSafeInteger(request.originalBytes) ||
35
+ request.originalBytes < 1) {
36
+ return { ok: false, reason: 'corrupt' };
37
+ }
38
+ const maxBytes = request.maxBytes ?? request.originalBytes;
39
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < request.originalBytes)
40
+ return { ok: false, reason: 'too_large' };
41
+ try {
42
+ const loaded = await evidence.read({
43
+ sessionId: request.sessionId,
44
+ runtimeEventId: request.runtimeEventId,
45
+ });
46
+ if (!loaded.ok)
47
+ return {
48
+ ok: false,
49
+ reason: loaded.reason === 'unavailable' ? 'read_failed' : loaded.reason,
50
+ };
51
+ const { event } = loaded;
52
+ const content = event.content;
53
+ if (event.sessionId !== request.sessionId)
54
+ return { ok: false, reason: 'session_mismatch' };
55
+ if (event.id !== request.runtimeEventId ||
56
+ content?.kind !== 'function_response' ||
57
+ content.id !== request.toolCallId ||
58
+ content.name !== request.toolName ||
59
+ content.providerExecuted ||
60
+ !content.modelProjection)
61
+ return { ok: false, reason: 'source_mismatch' };
62
+ let source = decodeDurableToolResultProjection(content.modelProjection);
63
+ const byId = new Map();
64
+ for (const record of loaded.transitions) {
65
+ const transition = decodeLedgerTransition(record, request.sessionId);
66
+ if (!transition ||
67
+ record.sessionId !== request.sessionId ||
68
+ transition.target.runtimeEventId !== event.id)
69
+ return { ok: false, reason: 'corrupt' };
70
+ const previous = byId.get(transition.transitionId);
71
+ if (previous &&
72
+ JSON.stringify({ ...previous, createdAt: 0 }) !==
73
+ JSON.stringify({ ...transition, createdAt: 0 })) {
74
+ return { ok: false, reason: 'corrupt' };
75
+ }
76
+ byId.set(transition.transitionId, transition);
77
+ }
78
+ const reduction = reduceEffectiveModelProjections([event], [...byId.values()]);
79
+ for (const transition of reduction.applied) {
80
+ const replacement = transition.replacement;
81
+ const placeholder = replacement.kind === 'json' ? replacement.value : undefined;
82
+ if (isArchivedToolResultPlaceholder(placeholder) &&
83
+ placeholder.artifactId === request.artifactId) {
84
+ if (placeholder.runtimeEventId !== request.runtimeEventId ||
85
+ placeholder.toolCallId !== request.toolCallId ||
86
+ placeholder.toolName !== request.toolName ||
87
+ placeholder.bodySha256 !== request.bodySha256 ||
88
+ placeholder.originalBytes !== request.originalBytes ||
89
+ placeholder.rewriteVersion !== request.rewriteVersion)
90
+ return { ok: false, reason: 'source_mismatch' };
91
+ const serializedResult = serializeToolResultProjectionV1(source);
92
+ if (Buffer.byteLength(serializedResult, 'utf8') !== request.originalBytes)
93
+ return { ok: false, reason: 'size_mismatch' };
94
+ if (createHash('sha256').update(serializedResult).digest('hex') !== request.bodySha256)
95
+ return { ok: false, reason: 'corrupt' };
96
+ return { ok: true, serializedResult };
97
+ }
98
+ source = transition.replacement;
99
+ }
100
+ return { ok: false, reason: 'not_found' };
101
+ }
102
+ catch {
103
+ return { ok: false, reason: 'corrupt' };
104
+ }
105
+ };
106
+ }
@@ -28,6 +28,15 @@ export function isRuntimeHostedRootAuthority(authority) {
28
28
  export class RuntimeMessageAuthorityInvariantError extends Error {
29
29
  name = 'RuntimeMessageAuthorityInvariantError';
30
30
  }
31
+ /**
32
+ * The id a Root Turn's admitted prompt is durable under. A Root folded from
33
+ * several queued Messages carries no single Message identity, so the id comes
34
+ * from the Run instead — one rule, so the run that writes the prompt and the
35
+ * recovery that rewrites it derive the same id and the store dedupes.
36
+ */
37
+ export function admittedPromptEventId(runId, userMessageId) {
38
+ return userMessageId ?? `${runId}-admitted-prompt`;
39
+ }
31
40
  export class RuntimeHostedRootConflictError extends Error {
32
41
  name = 'RuntimeHostedRootConflictError';
33
42
  code = 'session_busy';