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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +38 -19
  2. package/README.zh-CN.md +34 -19
  3. package/dist/acp/maka-acp-agent.js +2 -1
  4. package/dist/acp/session-configuration.js +143 -0
  5. package/dist/acp/session-registry.js +90 -4
  6. package/dist/cli-core.js +2 -0
  7. package/dist/pi-transcript-tools.js +6 -0
  8. package/dist/pi-transcript.js +5 -12
  9. package/dist/pi-tui-layout.js +56 -10
  10. package/dist/pi-tui-pickers.js +102 -1
  11. package/dist/pi-tui-runner.js +230 -46
  12. package/dist/pi-tui-todo.js +221 -0
  13. package/dist/pi-tui-transcript-viewer.js +134 -7
  14. package/dist/runtime-host-cli-context.js +224 -78
  15. package/dist/runtime-host-cli-installation.js +8 -2
  16. package/dist/runtime-host-cli.js +31 -1
  17. package/dist/runtime-host-handoff-surface.js +106 -0
  18. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  19. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  20. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  21. package/dist/runtime-host-local-handoff.js +48 -5
  22. package/dist/runtime-host-local-managed-activation.js +84 -0
  23. package/dist/runtime-host-local-source-retirement.js +18 -2
  24. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  25. package/dist/runtime-host-operator-retirement.js +50 -0
  26. package/dist/runtime-host-service-manager.js +3 -3
  27. package/dist/runtime-host-session-channel.js +13 -0
  28. package/dist/runtime-host-session-driver.js +46 -26
  29. package/dist/runtime-host-session-update.js +62 -0
  30. package/dist/runtime-host-tui-command.js +38 -73
  31. package/dist/runtime-host-tui-context.js +1 -0
  32. package/dist/runtime-host-tui-owner.js +226 -0
  33. package/dist/tui-copy-catalog.js +219 -6
  34. package/dist/tui-host-owner-copy.js +24 -0
  35. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  36. package/node_modules/@maka/core/dist/agent-run.js +1 -0
  37. package/node_modules/@maka/core/dist/attachments.js +3 -0
  38. package/node_modules/@maka/core/dist/canonical-json.js +27 -0
  39. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  40. package/node_modules/@maka/core/dist/capabilities.js +35 -0
  41. package/node_modules/@maka/core/dist/computer-use.js +0 -1
  42. package/node_modules/@maka/core/dist/display-redaction.js +18 -0
  43. package/node_modules/@maka/core/dist/llm-connections.js +13 -0
  44. package/node_modules/@maka/core/dist/model-call-attempt.js +2 -0
  45. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  46. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  47. package/node_modules/@maka/core/dist/model-metadata.js +7 -3
  48. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  49. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  50. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  51. package/node_modules/@maka/core/dist/redaction.js +35 -0
  52. package/node_modules/@maka/core/dist/run-composition.js +77 -2
  53. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  54. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  55. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  56. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  57. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  58. package/node_modules/@maka/core/dist/session.js +84 -56
  59. package/node_modules/@maka/core/dist/slash-command-catalog.js +3 -0
  60. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  61. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  62. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  63. package/node_modules/@maka/core/package.json +5 -0
  64. package/node_modules/@maka/eval/dist/experiment-directory.js +4 -13
  65. package/node_modules/@maka/mcp/dist/index.js +131 -1
  66. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +0 -13
  67. package/node_modules/@maka/runtime/dist/agent-run.js +351 -105
  68. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +29 -13
  69. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  70. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +184 -183
  71. package/node_modules/@maka/runtime/dist/archive-read-tool.js +2 -2
  72. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +0 -16
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +158 -15
  75. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +3 -3
  76. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  77. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  78. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  79. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  80. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +174 -0
  81. package/node_modules/@maka/runtime/dist/mcp-tools.js +7 -2
  82. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  83. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  84. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  85. package/node_modules/@maka/runtime/dist/model-fetcher.js +49 -2
  86. package/node_modules/@maka/runtime/dist/model-history.js +0 -112
  87. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  88. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  89. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  90. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  91. package/node_modules/@maka/runtime/dist/plugin-runtime.js +20 -10
  92. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +205 -0
  93. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  94. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +76 -109
  95. package/node_modules/@maka/runtime/dist/request-shape.js +23 -0
  96. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  97. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +83 -55
  98. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +121 -159
  99. package/node_modules/@maka/runtime/dist/runtime-kernel.js +157 -112
  100. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  101. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  102. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  103. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  104. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  105. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  106. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +21 -0
  107. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +0 -5
  108. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  109. package/node_modules/@maka/runtime/dist/test-connection.js +16 -17
  110. package/node_modules/@maka/runtime/dist/tool-activation-identity.js +41 -0
  111. package/node_modules/@maka/runtime/dist/tool-availability.js +11 -1
  112. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  113. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +63 -1
  114. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +42 -12
  115. package/node_modules/@maka/runtime/dist/tool-result-archive.js +27 -4
  116. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  117. package/node_modules/@maka/runtime/package.json +2 -0
  118. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  119. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  120. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  121. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +179 -0
  122. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +275 -0
  123. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  124. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  125. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  126. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  127. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +46 -5
  128. package/node_modules/@maka/runtime-host/dist/control/endpoint.js +1 -3
  129. package/node_modules/@maka/runtime-host/dist/node-error.js +22 -0
  130. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  131. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +1 -3
  132. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  133. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +0 -1
  134. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +1 -1
  135. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +1 -3
  136. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  137. package/node_modules/@maka/runtime-host/dist/protocol/index.js +29 -1
  138. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  139. package/node_modules/@maka/runtime-host/dist/protocol/plan.js +1 -0
  140. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +27 -5
  141. package/node_modules/@maka/runtime-host/dist/protocol/project-catalog.js +2 -2
  142. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  143. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  144. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  145. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  146. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +31 -2
  147. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  148. package/node_modules/@maka/runtime-host/dist/server/agent-graph-coordinator.js +0 -3
  149. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  150. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  151. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +32 -32
  152. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +144 -33
  153. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  154. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +45 -16
  155. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  156. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  157. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  158. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  159. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  160. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +47 -22
  161. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  162. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  163. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  164. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  165. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  166. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  167. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  168. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  169. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +5 -2
  170. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +12 -55
  171. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  172. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  173. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  174. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  175. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  176. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +20 -2
  177. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +13 -4
  178. package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +46 -0
  179. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  180. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  181. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -5
  182. package/node_modules/@maka/storage/dist/codex-session-adapter.js +284 -198
  183. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  184. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  185. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  186. package/node_modules/@maka/storage/dist/git-exec.js +61 -0
  187. package/node_modules/@maka/storage/dist/git-worktree-child-executor.js +8 -35
  188. package/node_modules/@maka/storage/dist/goal-authority.js +2 -2
  189. package/node_modules/@maka/storage/dist/interaction-store.js +2 -2
  190. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  191. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  192. package/node_modules/@maka/storage/dist/project-catalog.js +2 -23
  193. package/node_modules/@maka/storage/dist/runtime-event-invariants.js +2 -2
  194. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  195. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +8 -3
  196. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  197. package/node_modules/@maka/storage/dist/scheduled-task-store.js +249 -283
  198. package/node_modules/@maka/storage/dist/session-bundle-manifest.js +5 -17
  199. package/node_modules/@maka/storage/dist/session-bundle-policy.js +26 -5
  200. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +2 -1
  201. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  202. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  203. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  204. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  205. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  206. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  207. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  208. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +130 -27
  209. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  210. package/node_modules/@maka/storage/dist/storage-id.js +28 -0
  211. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +138 -0
  212. package/node_modules/@maka/storage/dist/workspace-identity.js +2 -15
  213. package/node_modules/@maka/storage/dist/workspace-version-authority-internal.js +1 -8
  214. package/node_modules/@maka/storage/package.json +2 -0
  215. package/package.json +1 -1
@@ -46,22 +46,9 @@ export function stableJsonLength(value) {
46
46
  export function turnKey(event) {
47
47
  return event.turnId || '<unknown-turn>';
48
48
  }
49
- export function uniqueSorted(values) {
50
- return [...new Set(values.filter((value) => value.length > 0))].sort();
51
- }
52
49
  export function sha256(text) {
53
50
  return createHash('sha256').update(text).digest('hex');
54
51
  }
55
- export function stableStringify(value) {
56
- if (value === undefined)
57
- return '';
58
- try {
59
- return JSON.stringify(value) ?? '';
60
- }
61
- catch {
62
- return String(value);
63
- }
64
- }
65
52
  export function finitePositive(value) {
66
53
  return typeof value === 'number' && Number.isFinite(value) && value > 0
67
54
  ? Math.floor(value)
@@ -70,6 +57,3 @@ export function finitePositive(value) {
70
57
  export function utf8ByteLength(text) {
71
58
  return Buffer.byteLength(text, 'utf8');
72
59
  }
73
- export function optionalNonNegativeFiniteNumber(value) {
74
- return value === undefined || (typeof value === 'number' && Number.isFinite(value) && value >= 0);
75
- }
@@ -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,12 +29,15 @@ 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
- import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
34
+ import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, buildLedgerArchivedToolResultPlaceholder, } from './tool-result-archive.js';
34
35
  import { rewriteDurableToolResultProjectionArtifactRefs } from './durable-tool-result-projection.js';
35
- import { buildModelProjectionTransition, decodeModelProjectionTransition, MODEL_PROJECTION_TRANSITION_EVENT_TYPE, } from '@maka/core/model-projection-transition';
36
+ import { buildModelProjectionTransition, durableToolResultProjectionDigest, decodeModelProjectionTransition, MODEL_PROJECTION_TRANSITION_EVENT_TYPE, } from '@maka/core/model-projection-transition';
36
37
  import { baseToolResultProjection, decodeLedgerTransition, reduceEffectiveModelProjections, } from './model-projection-transition-ledger.js';
37
38
  import { archivedToolResultProjection } from './tool-result-archive-transition.js';
39
+ import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
40
+ import { createHash } from 'node:crypto';
38
41
  /** Walks every typed StorageRef site reached by conversation-copy rewriting. */
39
42
  function collectConversationCopyStorageRefs(input) {
40
43
  const refs = [];
@@ -165,6 +168,7 @@ export async function prepareConversationRuntimeLedgerCopy(input) {
165
168
  const selectedRunEvents = await loadConversationCopyRunEvents(sourceRuns, input.sourceEvents, copyTurnIds, input.runtimeEventStore);
166
169
  const runs = await Promise.all(selectedRunEvents.map(async ({ run, events }) => {
167
170
  const operationalEvents = await input.runStore.readEvents(run.sessionId, run.runId);
171
+ assertConversationRuntimeLedgerCopySupported(run, events);
168
172
  const terminal = classifyTerminalRuntimeLedger(run, events);
169
173
  if (run.terminalEvent && terminal.kind !== 'fact') {
170
174
  throw new Error(`Cannot copy terminal AgentRun ${run.runId} without one terminal fact`);
@@ -188,7 +192,6 @@ export async function prepareConversationRuntimeLedgerCopy(input) {
188
192
  inlineRuntimeEvents,
189
193
  runs,
190
194
  };
191
- assertConversationRuntimeLedgerCopySupported(plan);
192
195
  return plan;
193
196
  }
194
197
  /**
@@ -268,9 +271,9 @@ async function rebuildCopiedProjectionTransitions(sessionId, sourceRuns, runs, r
268
271
  owner.operationalEvents.push({ ...event, runId: owner.run.runId, turnId: owner.run.turnId });
269
272
  }
270
273
  }
271
- function assertConversationRuntimeLedgerCopySupported(plan) {
272
- const unsupported = plan.runs.some(({ run, runtimeEvents }) => run.opening.source.kind === 'continuation' ||
273
- runtimeEvents.some(isContinuationStartRuntimeEvent));
274
+ function assertConversationRuntimeLedgerCopySupported(run, runtimeEvents) {
275
+ const unsupported = run.opening.source.kind !== 'fresh' ||
276
+ runtimeEvents.some((event) => isContinuationStartRuntimeEvent(event) || runtimeHandoffPause(event));
274
277
  if (!unsupported)
275
278
  return;
276
279
  const error = new Error('Conversation copy contains durable runtime authority facts that require typed identity rewriting');
@@ -307,6 +310,7 @@ export async function cloneConversationRuntimeLedger(input) {
307
310
  runtimeEventIds,
308
311
  providerTraceIds,
309
312
  agentRunEventIds: operationalEventIds,
313
+ ledgerArchives: new Map(),
310
314
  };
311
315
  const clonedEventBySourceId = new Map();
312
316
  for (const plan of flattenedPlans) {
@@ -327,6 +331,64 @@ export async function cloneConversationRuntimeLedger(input) {
327
331
  // successor is rebuilt against the projection it actually replaces.
328
332
  const transitionIds = new Map();
329
333
  const transitionState = new Map();
334
+ const clonedTransitions = new Map();
335
+ const visiting = new Set();
336
+ const finished = new Set();
337
+ const transitionsByTarget = new Map();
338
+ for (const plan of flattenedPlans) {
339
+ for (const record of plan.operationalEvents) {
340
+ if (record.type !== MODEL_PROJECTION_TRANSITION_EVENT_TYPE)
341
+ continue;
342
+ const transition = decodeModelProjectionTransition(record.data?.transition, record.sessionId);
343
+ const group = transitionsByTarget.get(transition.target.runtimeEventId) ?? [];
344
+ group.push(record);
345
+ transitionsByTarget.set(transition.target.runtimeEventId, group);
346
+ }
347
+ }
348
+ // ArchiveRead can itself be archived. Resolve its referenced target first,
349
+ // then rebuild this result's transitions against its final copied projection.
350
+ const finishTarget = (sourceId) => {
351
+ if (finished.has(sourceId))
352
+ return;
353
+ if (visiting.has(sourceId))
354
+ throw new Error('Cyclic copied archive reference');
355
+ visiting.add(sourceId);
356
+ const target = clonedEventBySourceId.get(sourceId);
357
+ if (target?.content?.kind === 'function_response' && target.content.name === 'ArchiveRead') {
358
+ const resolveResult = (value) => rewriteArchiveReadResult(value, references, (ref) => {
359
+ const identity = parseToolResultArchiveResourceRef(ref);
360
+ if (identity?.storage === 'ledger' && clonedEventBySourceId.has(identity.runtimeEventId))
361
+ finishTarget(identity.runtimeEventId);
362
+ });
363
+ target.content.result = resolveResult(target.content.result);
364
+ const projection = target.content.modelProjection;
365
+ if (projection?.kind === 'json')
366
+ target.content.modelProjection = {
367
+ ...projection,
368
+ value: resolveResult(projection.value),
369
+ };
370
+ }
371
+ for (const record of transitionsByTarget.get(sourceId) ?? []) {
372
+ clonedTransitions.set(record, cloneModelProjectionTransition(record, references, clonedEventBySourceId, transitionIds, transitionState));
373
+ }
374
+ visiting.delete(sourceId);
375
+ finished.add(sourceId);
376
+ };
377
+ for (const sourceId of clonedEventBySourceId.keys())
378
+ finishTarget(sourceId);
379
+ for (const event of clonedEventBySourceId.values()) {
380
+ if (event.content?.kind === 'text')
381
+ event.content.text = rewriteLedgerArchiveText(event.content.text, references);
382
+ if (event.content?.kind === 'function_call' && event.content.name === 'ArchiveRead') {
383
+ const args = event.content.args;
384
+ if (args && typeof args === 'object' && 'ref' in args && typeof args.ref === 'string') {
385
+ event.content = {
386
+ ...event.content,
387
+ args: { ...args, ref: rewriteLedgerArchiveText(args.ref, references) },
388
+ };
389
+ }
390
+ }
391
+ }
330
392
  const preparedPlans = flattenedPlans.map((plan) => {
331
393
  const runId = runIds.get(plan.run.runId);
332
394
  const clonedOperationalEvents = plan.operationalEvents.flatMap((event) => {
@@ -334,7 +396,7 @@ export async function cloneConversationRuntimeLedger(input) {
334
396
  sessionId: input.referenceMap.targetSessionId,
335
397
  runId,
336
398
  eventId: operationalEventIds.get(event.id),
337
- }, references, sourceCompactableEvents.get(plan.run.runId) ?? [], clonedEventBySourceId, checkpointIds, transitionIds, transitionState, providerTraceIds, logicalCallIds);
399
+ }, references, sourceCompactableEvents.get(plan.run.runId) ?? [], clonedEventBySourceId, checkpointIds, providerTraceIds, logicalCallIds, clonedTransitions);
338
400
  return clonedEvent ? [clonedEvent] : [];
339
401
  });
340
402
  const terminalEvent = plan.terminal.kind === 'fact'
@@ -350,7 +412,22 @@ export async function cloneConversationRuntimeLedger(input) {
350
412
  terminalEvent,
351
413
  };
352
414
  });
353
- const copiedMessages = input.copiedMessages.map((message) => rewriteConversationCopyMessage(message, references));
415
+ const archiveReadCalls = new Set(flattenedPlans.flatMap((plan) => plan.events.flatMap((event) => event.content?.kind === 'function_response' && event.content.name === 'ArchiveRead'
416
+ ? [`${event.turnId}:${event.content.id}`]
417
+ : [])));
418
+ const copiedMessages = input.copiedMessages.map((message) => {
419
+ const copied = rewriteConversationCopyMessage(message, references);
420
+ if (copied.type === 'user' || copied.type === 'assistant')
421
+ return { ...copied, text: rewriteLedgerArchiveText(copied.text, references) };
422
+ if (copied.type === 'tool_result' &&
423
+ archiveReadCalls.has(`${copied.turnId}:${copied.toolUseId}`)) {
424
+ return {
425
+ ...copied,
426
+ content: rewriteArchiveReadResult(copied.content, references),
427
+ };
428
+ }
429
+ return copied;
430
+ });
354
431
  const importedSourceEventIds = new Set();
355
432
  const orderedBatches = input.plan.inlineRuntimeEvents.flatMap((event) => {
356
433
  const cloned = clonedEventBySourceId.get(event.id);
@@ -399,6 +476,33 @@ export async function cloneConversationRuntimeLedger(input) {
399
476
  })),
400
477
  };
401
478
  }
479
+ function rewriteLedgerArchiveText(text, references) {
480
+ for (const [source, target] of references.ledgerArchives ?? [])
481
+ text = text.split(source).join(target.resourceRef);
482
+ return text;
483
+ }
484
+ /** Only ArchiveRead's defined envelope is rewritten, never its opaque content/items. */
485
+ function rewriteArchiveReadResult(value, references, before) {
486
+ if (!value || typeof value !== 'object' || Array.isArray(value))
487
+ return value;
488
+ const record = value;
489
+ if (record.kind === 'json')
490
+ return { ...record, value: rewriteArchiveReadResult(record.value, references, before) };
491
+ if (record.kind !== 'tool_result_archive' || typeof record.ref !== 'string')
492
+ return value;
493
+ before?.(record.ref);
494
+ const mapped = references.ledgerArchives?.get(record.ref);
495
+ if (!mapped)
496
+ return value;
497
+ return {
498
+ ...record,
499
+ ref: mapped.resourceRef,
500
+ ...(record.storage === 'ledger' && typeof record.runtimeEventId === 'string'
501
+ ? { runtimeEventId: mapped.runtimeEventId }
502
+ : {}),
503
+ ...(typeof record.originalBytes === 'number' ? { originalBytes: mapped.originalBytes } : {}),
504
+ };
505
+ }
402
506
  async function loadConversationCopyRunEvents(sourceRuns, sourceEvents, copyTurnIds, runtimeEventStore) {
403
507
  const copiedTurnIds = new Set(copyTurnIds);
404
508
  return Promise.all(sourceRuns.flatMap((run) => {
@@ -545,7 +649,7 @@ export function collectConversationCopySessionFileRefs(input) {
545
649
  }
546
650
  return refs;
547
651
  }
548
- function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clonedRuntimeEvents, checkpointIds, transitionIds, transitionState, providerTraceIds, logicalCallIds) {
652
+ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clonedRuntimeEvents, checkpointIds, providerTraceIds, logicalCallIds, clonedTransitions) {
549
653
  if (event.type === 'event_corrupt') {
550
654
  throw new Error(`Cannot copy corrupt AgentRun event ${event.id}`);
551
655
  }
@@ -600,7 +704,7 @@ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clo
600
704
  const checkpoint = buildHistoryCompactCheckpoint({
601
705
  sessionId: references.targetSessionId,
602
706
  coveredRuntimeEvents,
603
- summary: sourceCheckpoint.summary,
707
+ summary: rewriteLedgerArchiveText(sourceCheckpoint.summary, references),
604
708
  highWaterName: sourceCheckpoint.highWaterName,
605
709
  highWaterSeq: sourceCheckpoint.highWaterSeq,
606
710
  now: sourceCheckpoint.createdAt,
@@ -621,7 +725,7 @@ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clo
621
725
  };
622
726
  }
623
727
  else if (event.type === MODEL_PROJECTION_TRANSITION_EVENT_TYPE) {
624
- const cloned = cloneModelProjectionTransition(event, references, clonedRuntimeEvents, transitionIds, transitionState);
728
+ const cloned = clonedTransitions.get(event);
625
729
  // Every transition whose target is in the copied slice was gathered into
626
730
  // this run's ledger, wherever it was recorded. So a transition that finds no
627
731
  // cloned target has genuinely lost its target as well, and dropping it
@@ -659,16 +763,37 @@ function cloneModelProjectionTransition(event, references, clonedRuntimeEvents,
659
763
  const clonedTarget = clonedRuntimeEvents.get(source.target.runtimeEventId);
660
764
  if (!clonedTarget)
661
765
  return null;
662
- const placeholder = source.replacement.kind === 'json' ? source.replacement.value : undefined;
663
- if (!isArchivedToolResultPlaceholder(placeholder)) {
766
+ const rawPlaceholder = source.replacement.kind === 'json' ? source.replacement.value : undefined;
767
+ if (!isArchivedToolResultPlaceholder(rawPlaceholder)) {
664
768
  throw new Error(`Cannot copy unsupported model projection transition ${event.id}`);
665
769
  }
770
+ const placeholder = rawPlaceholder;
666
771
  const existing = transitionState.get(clonedTarget.id);
667
772
  const sourceProjection = existing?.projection ?? baseToolResultProjection(clonedTarget);
668
773
  if (!sourceProjection) {
669
774
  throw new Error(`Cannot copy model projection transition ${event.id} onto its target`);
670
775
  }
671
- const rewritten = rewriteArchivedToolResult(placeholder, references);
776
+ let rewritten;
777
+ if (placeholder.rewriteVersion === 2) {
778
+ const { previousTransitionId: _previous, ...rest } = placeholder;
779
+ const serialized = serializeToolResultProjectionV1(sourceProjection);
780
+ rewritten = buildLedgerArchivedToolResultPlaceholder({
781
+ ...rest,
782
+ runtimeEventId: clonedTarget.id,
783
+ sourceProjectionDigest: durableToolResultProjectionDigest(sourceProjection),
784
+ bodySha256: createHash('sha256').update(serialized).digest('hex'),
785
+ originalBytes: Buffer.byteLength(serialized),
786
+ ...(source.previousTransitionId
787
+ ? {
788
+ previousTransitionId: requiredMappedId(transitionIds, source.previousTransitionId, 'model projection transition'),
789
+ }
790
+ : {}),
791
+ });
792
+ references.ledgerArchives?.set(buildToolResultArchiveResourceRef(placeholder), rewritten);
793
+ }
794
+ else {
795
+ rewritten = rewriteArchivedToolResult(placeholder, references);
796
+ }
672
797
  const transition = buildModelProjectionTransition({
673
798
  sessionId: references.targetSessionId,
674
799
  target: {
@@ -1029,6 +1154,18 @@ function rewriteToolResultContent(content, references) {
1029
1154
  return { ...content, ref: rewriteStorageRef(content.ref, references) };
1030
1155
  }
1031
1156
  if (content.kind === 'archived_tool_result') {
1157
+ if (content.rewriteVersion === 2 && content.resourceRef) {
1158
+ const rewritten = references.ledgerArchives?.get(content.resourceRef);
1159
+ if (!rewritten)
1160
+ throw new Error('Cannot copy ledger archive without its committed transition');
1161
+ return {
1162
+ ...content,
1163
+ runtimeEventId: rewritten.runtimeEventId,
1164
+ resourceRef: rewritten.resourceRef,
1165
+ bodySha256: rewritten.bodySha256,
1166
+ originalBytes: rewritten.originalBytes,
1167
+ };
1168
+ }
1032
1169
  const snapshot = rewriteArchivedSnapshot(content, references);
1033
1170
  if (snapshot)
1034
1171
  return snapshot;
@@ -1256,6 +1393,12 @@ function rewriteProjectionArtifactRef(ref, references) {
1256
1393
  return rewritten;
1257
1394
  }
1258
1395
  function rewriteArchivedToolResult(value, references) {
1396
+ if (value.rewriteVersion === 2) {
1397
+ const rewritten = references.ledgerArchives?.get(buildToolResultArchiveResourceRef(value));
1398
+ if (!rewritten)
1399
+ throw new Error('Cannot copy ledger archive without its committed transition');
1400
+ return rewritten;
1401
+ }
1259
1402
  const artifactId = rewriteOwnedArtifactId(value.artifactId, references);
1260
1403
  const resource = value.resourceRef
1261
1404
  ? parseToolResultArchiveResourceRef(value.resourceRef)
@@ -1264,7 +1407,7 @@ function rewriteArchivedToolResult(value, references) {
1264
1407
  ...value,
1265
1408
  runtimeEventId: rewriteOwnedId(value.runtimeEventId, references.runtimeEventIds, 'RuntimeEvent'),
1266
1409
  artifactId,
1267
- ...(resource && artifactId !== value.artifactId
1410
+ ...(resource && resource.storage !== 'ledger' && artifactId !== value.artifactId
1268
1411
  ? {
1269
1412
  resourceRef: buildToolResultArchiveResourceRef({
1270
1413
  ...resource,
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { createGitHubCopilotAccountTokens, GITHUB_COPILOT_DEFAULT_API_ENDPOINT, isSupportedGitHubCopilotAccountToken, } from './subscription-credentials.js';
20
- import { fetchGitHubCopilotModels } from './model-fetcher.js';
20
+ import { fetchGitHubCopilotModels, GitHubCopilotModelPolicyError } from './model-fetcher.js';
21
21
  import { ConnectionEffectHttpError } from './connection-effect-outcome.js';
22
22
  import { OAUTH_LOGIN_MAX_TOKEN_CHARS, OAuthTokenEndpointError, requestOAuthEndpointJson, } from './oauth-login.js';
23
23
  import { OAUTH_PROVIDER_CONTRACTS, OAuthDeviceAuthorizationExpiredError, oauthExpiresAt, requireOAuthBoundedString, requireOAuthDataRecord, requireOAuthPositiveInteger, } from './oauth-provider-contracts.js';
@@ -185,8 +185,8 @@ export async function verifyGitHubCopilotModelEntitlement(input) {
185
185
  // body tell us nothing about the subscription, and reporting them as
186
186
  // ineligibility would send a paying user back through a device login that
187
187
  // was never the problem.
188
- if (error instanceof ConnectionEffectHttpError &&
189
- (error.status === 401 || error.status === 403)) {
188
+ if (error instanceof GitHubCopilotModelPolicyError ||
189
+ (error instanceof ConnectionEffectHttpError && (error.status === 401 || error.status === 403))) {
190
190
  throw new GitHubCopilotEntitlementError({ cause: error });
191
191
  }
192
192
  throw new GitHubCopilotEntitlementUnavailableError(error instanceof ConnectionEffectHttpError ? error.status : undefined, { cause: error });
@@ -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 });