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
@@ -25,33 +25,6 @@ export function buildStatusPatch(status, ts, blockedReason) {
25
25
  statusUpdatedAt: ts,
26
26
  };
27
27
  }
28
- export function buildTurnStateMessage(input) {
29
- const lineage = input.lineage ?? {};
30
- return {
31
- type: 'turn_state',
32
- id: input.id,
33
- turnId: input.turnId,
34
- ts: input.ts,
35
- status: input.status,
36
- ...(lineage.parentTurnId ? { parentTurnId: lineage.parentTurnId } : {}),
37
- ...(lineage.retriedFromTurnId ? { retriedFromTurnId: lineage.retriedFromTurnId } : {}),
38
- ...(lineage.regeneratedFromTurnId
39
- ? { regeneratedFromTurnId: lineage.regeneratedFromTurnId }
40
- : {}),
41
- ...(lineage.branchOfTurnId ? { branchOfTurnId: lineage.branchOfTurnId } : {}),
42
- ...(lineage.parentSessionId ? { parentSessionId: lineage.parentSessionId } : {}),
43
- ...(input.status === 'aborted' ? { abortedAt: input.ts } : {}),
44
- ...(input.status === 'aborted' && input.abortSource ? { abortSource: input.abortSource } : {}),
45
- ...(input.status === 'failed' ? { errorClass: input.errorClass ?? 'unknown' } : {}),
46
- partialOutputRetained: input.partialOutputRetained,
47
- };
48
- }
49
- export function turnHasRetainedOutput(messages, turnId) {
50
- return messages.some((message) => (message.type === 'assistant' &&
51
- message.turnId === turnId &&
52
- message.text.trim().length > 0) ||
53
- (message.type === 'tool_result' && message.turnId === turnId));
54
- }
55
28
  export function normalizeStopSessionSource(source, workHubActionId) {
56
29
  if (source !== 'workhub_direct_stop' && workHubActionId !== undefined) {
57
30
  throw new Error('WorkHub direct-stop identity requires its dedicated Stop source');
@@ -184,6 +184,27 @@ export class AgentGraphCoordinator {
184
184
  async hasLiveSessionState(rootSessionId) {
185
185
  return (await this.readSessionState(rootSessionId)) === 'live';
186
186
  }
187
+ /**
188
+ * Classify durable graph state for Session retirement without changing the
189
+ * broader live-state semantics used by recovery and graph epoch selection.
190
+ */
191
+ async readRetirementDisposition(rootSessionId) {
192
+ const snapshot = buildAgentGraphClientSnapshot(await this.#readClientModelInputForGraph(rootSessionId, await this.currentGraphId(rootSessionId)));
193
+ if (snapshot.scheduleRevision === 0)
194
+ return { kind: 'clear' };
195
+ switch (snapshot.status) {
196
+ case 'empty':
197
+ case 'completed':
198
+ return { kind: 'clear' };
199
+ case 'stopped':
200
+ case 'failed':
201
+ return { kind: 'quiescent_open' };
202
+ case 'active':
203
+ case 'waiting':
204
+ case 'closing':
205
+ return { kind: 'busy', status: snapshot.status };
206
+ }
207
+ }
187
208
  /**
188
209
  * Reconstruct one stable, reference-only control/data-plane timeline page.
189
210
  *
@@ -22,11 +22,6 @@ import { stableHash } from './request-shape.js';
22
22
  export const VIEW_AGENT_GRAPH_TOOL_NAME = 'view_agent_graph';
23
23
  export const UPDATE_AGENT_GRAPH_TOOL_NAME = 'update_agent_graph';
24
24
  export const YIELD_AGENT_GRAPH_TOOL_NAME = 'yield_agent_graph';
25
- export const AGENT_GRAPH_SUPERVISOR_TOOL_NAMES = [
26
- VIEW_AGENT_GRAPH_TOOL_NAME,
27
- UPDATE_AGENT_GRAPH_TOOL_NAME,
28
- YIELD_AGENT_GRAPH_TOOL_NAME,
29
- ];
30
25
  const TOOL_VIEW_MAX_TERMINAL_WORK = 64;
31
26
  const TOOL_VIEW_MAX_STOPPED_TARGETS = 64;
32
27
  const TOOL_VIEW_MAX_INSTRUCTION_CHARS = 2_000;
@@ -16,7 +16,6 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { redactSecrets } from '@maka/core/redaction';
20
19
  import { GITHUB_COPILOT_API_VERSION, GITHUB_COPILOT_COMPAT_HEADERS, } from './subscription-credentials.js';
21
20
  import { openAiCodexHeaders } from './subscription-auth.js';
22
21
  export function buildSubscriptionModelFetch(input) {
@@ -327,7 +326,7 @@ function codexInstructionsFromBody(body) {
327
326
  return 'You are Maka, a helpful AI assistant.';
328
327
  }
329
328
  function formatOpenAiCodexHttpError(statusCode, detail) {
330
- const compact = redactSecrets(detail).replace(/\s+/g, ' ').trim().slice(0, 240);
329
+ const compact = detail.replace(/\s+/g, ' ').trim().slice(0, 240);
331
330
  return compact
332
331
  ? `Codex OAuth request failed: HTTP ${statusCode} ${compact}`
333
332
  : `Codex OAuth request failed: HTTP ${statusCode}`;
@@ -337,7 +336,7 @@ function openAiCodexHttpError(response, detail, exhaustedEdgeRejection = false)
337
336
  ? 'openai_codex_edge_rejection'
338
337
  : openAiCodexProviderCode(detail);
339
338
  const rawRequestId = response.headers.get('x-request-id')?.trim();
340
- const requestId = rawRequestId ? redactSecrets(rawRequestId).slice(0, 256) : undefined;
339
+ const requestId = rawRequestId ? rawRequestId.slice(0, 256) : undefined;
341
340
  return Object.assign(new Error(formatOpenAiCodexHttpError(response.status, detail)), {
342
341
  name: exhaustedEdgeRejection ? 'OpenAiCodexEdgeRejectionError' : 'OpenAiCodexHttpError',
343
342
  ...(exhaustedEdgeRejection ? { code: 'openai_codex_edge_rejection' } : {}),
@@ -358,7 +357,7 @@ function openAiCodexProviderCode(detail) {
358
357
  const value = error.code ?? error.type;
359
358
  if (typeof value !== 'string' && typeof value !== 'number')
360
359
  return undefined;
361
- const normalized = redactSecrets(String(value).trim()).slice(0, 256);
360
+ const normalized = String(value).trim().slice(0, 256);
362
361
  return normalized || undefined;
363
362
  }
364
363
  catch {
@@ -17,8 +17,8 @@
17
17
  * under the License.
18
18
  */
19
19
  import { randomUUID } from 'node:crypto';
20
- import { PROVIDER_REGISTRY, providerDefaultsOf, providerFallbackModelIds, connectionModelsEnumerateAccount, connectionEnabledModelIds, } from '@maka/core/llm-connections';
21
- import { anthropicV1Url, googleApiUrl, openResponsesUrl } from './provider-urls.js';
20
+ import { PROVIDER_REGISTRY, effectiveBaseUrl, providerDefaultsOf, providerFallbackModelIds, connectionModelsEnumerateAccount, connectionEnabledModelIds, } from '@maka/core/llm-connections';
21
+ import { openResponsesUrl } from './provider-urls.js';
22
22
  import { resolveModelRuntime } from './model-runtime.js';
23
23
  import { fetchGitHubCopilotModels } from './model-fetcher.js';
24
24
  import { CONNECTION_EFFECT_ERROR_BODY_MAX_BYTES, ConnectionEffectFetchError, fetchForConnectionEffect, } from './connection-effect-fetch.js';
@@ -105,7 +105,9 @@ async function testConnectionStrict(connection, apiKey, model, fetchFn, t0, time
105
105
  if (!defaults) {
106
106
  return { ok: false, errorMessage: `Unknown provider type "${connection.providerType}"` };
107
107
  }
108
- const sessionId = connection.providerType === 'opencode-go' ? randomUUID() : undefined;
108
+ const sessionId = connection.providerType === 'opencode-go' || connection.providerType === 'opencode-free'
109
+ ? randomUUID()
110
+ : undefined;
109
111
  const auth = defaults.authKind;
110
112
  const secret = auth === 'none' ? '' : apiKey;
111
113
  const testModel = resolveConnectionTestModel(connection, model, providerFallbackModelIds(defaults));
@@ -147,15 +149,14 @@ async function testConnectionModel(connection, secret, testModel, fetchFn, t0, t
147
149
  if (providerDefaultsOf(connection.providerType)?.runtimeAdapter.kind === 'unavailable') {
148
150
  return retiredProviderTestResult(connection.providerType);
149
151
  }
152
+ if (connection.providerType === 'github-copilot') {
153
+ return probeGitHubCopilot(effectiveBaseUrl(connection), secret, testModel, t0, fetchFn);
154
+ }
150
155
  const { adapter, baseUrl, wire } = resolveModelRuntime(connection, testModel);
151
156
  const requestHeaders = withOpenCodeSessionHeader(connection.providerType, sessionId);
152
157
  switch (adapter.kind) {
153
158
  case 'anthropic':
154
- return await probeAnthropic(connection, baseUrl, secret, testModel, t0, fetchFn, requestHeaders);
155
- case 'unavailable':
156
- // Unreachable: the guard above returns first. The arm keeps the switch
157
- // exhaustive so a newly retired provider cannot slip past it.
158
- return retiredProviderTestResult(connection.providerType);
159
+ return await probeAnthropic(adapter, baseUrl, secret, testModel, t0, fetchFn, requestHeaders);
159
160
  case 'openai':
160
161
  return wire === 'openai-responses'
161
162
  ? await probeOpenAIResponses(baseUrl, secret, testModel, t0, fetchFn, requestHeaders)
@@ -166,8 +167,6 @@ async function testConnectionModel(connection, secret, testModel, fetchFn, t0, t
166
167
  return wire === 'openai-responses'
167
168
  ? await probeOpenAIResponses(baseUrl, secret, testModel, t0, fetchFn, requestHeaders)
168
169
  : await probeOpenAI(connection, baseUrl, secret, testModel, t0, fetchFn, timeoutMs, requestHeaders);
169
- case 'github-copilot':
170
- return await probeGitHubCopilot(baseUrl, secret, testModel, t0, fetchFn);
171
170
  case 'google':
172
171
  return await probeGoogle(baseUrl, secret, testModel, t0, adapter.normalizeBaseUrl !== false, fetchFn);
173
172
  case 'cohere':
@@ -227,14 +226,17 @@ async function probeCohere(baseUrl, apiKey, model, t0, fetchFn) {
227
226
  function retiredProviderTestResult(providerType) {
228
227
  return { ok: false, errorMessage: `"${providerType}" is retired and can no longer be used.` };
229
228
  }
230
- async function probeAnthropic(connection, baseUrl, secret, model, t0, fetchFn, requestHeaders) {
229
+ async function probeAnthropic(adapter, baseUrl, secret, model, t0, fetchFn, requestHeaders) {
231
230
  const headers = {
232
231
  ...requestHeaders,
233
- 'x-api-key': secret,
232
+ ...(adapter.auth === 'bearer'
233
+ ? { authorization: `Bearer ${secret}` }
234
+ : { 'x-api-key': secret }),
234
235
  'anthropic-version': '2023-06-01',
235
236
  'content-type': 'application/json',
236
237
  };
237
- const r = await fetchForConnectionEffect(fetchFn, anthropicV1Url(baseUrl, '/messages'), {
238
+ const url = `${stripTrailing(baseUrl)}/messages`;
239
+ const r = await fetchForConnectionEffect(fetchFn, url, {
238
240
  method: 'POST',
239
241
  headers,
240
242
  body: JSON.stringify({
@@ -311,9 +313,7 @@ function isOpenAIChatCompletion(value) {
311
313
  }));
312
314
  }
313
315
  async function probeGoogle(baseUrl, apiKey, model, t0, normalizeBaseUrl, fetchFn) {
314
- const url = normalizeBaseUrl
315
- ? googleApiUrl(baseUrl, `/models/${encodeURIComponent(model)}:generateContent`, apiKey)
316
- : `${stripTrailing(baseUrl)}/models/${encodeURIComponent(model)}:generateContent`;
316
+ const url = `${stripTrailing(baseUrl)}/models/${encodeURIComponent(model)}:generateContent${normalizeBaseUrl ? `?key=${encodeURIComponent(apiKey)}` : ''}`;
317
317
  const r = await fetchForConnectionEffect(fetchFn, url, {
318
318
  method: 'POST',
319
319
  headers: {
@@ -337,7 +337,6 @@ async function httpFailure(r, t0) {
337
337
  await r.cancel();
338
338
  return {
339
339
  ok: false,
340
- errorMessage: 'OAuth 已登录,但当前账号或 provider 正在 rate limit。请稍后重试,或先切换到其它可用模型。',
341
340
  statusCode,
342
341
  errorClass: 'provider_unavailable',
343
342
  latencyMs: Date.now() - t0,
@@ -0,0 +1,41 @@
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 { stableHash, toolCatalogHash } from './request-shape.js';
20
+ const TOOL_ACTIVATION_IDENTITY = Symbol('maka.toolActivationIdentity');
21
+ /** Bind a Runtime-owned contribution identity to a Tool without exposing it to providers. */
22
+ export function bindToolActivationIdentity(tool, identity) {
23
+ return Object.freeze({
24
+ ...tool,
25
+ [TOOL_ACTIVATION_IDENTITY]: stableHash({
26
+ identity,
27
+ schemaHash: toolCatalogHash([tool]),
28
+ }),
29
+ });
30
+ }
31
+ /**
32
+ * Stable logical identity used by deferred-tool activation.
33
+ *
34
+ * Host wrappers without explicit contribution metadata fall back to their
35
+ * canonical provider-visible shape, so rebuilding an equivalent wrapper does
36
+ * not revoke activation. Dynamic contributors bind generation-aware metadata.
37
+ */
38
+ export function toolActivationKey(tool) {
39
+ const explicit = tool[TOOL_ACTIVATION_IDENTITY];
40
+ return explicit ?? stableHash({ kind: 'host', schemaHash: toolCatalogHash([tool]) });
41
+ }
@@ -20,6 +20,7 @@ import MiniSearch from 'minisearch';
20
20
  import { z } from 'zod';
21
21
  import { estimateTokens } from './context-budget-helpers.js';
22
22
  import { canonicalizeToolSet, stableHash, toolSchemaCharsForDiagnostics } from './request-shape.js';
23
+ import { toolActivationKey } from './tool-activation-identity.js';
23
24
  /** Canonical name of Maka's provider-independent deferred-tool search connector. */
24
25
  export const TOOL_SEARCH_NAME = 'tool_search';
25
26
  /** Provider-safe alias used because OpenAI Responses reserves `tool_search`. */
@@ -101,6 +102,7 @@ export class ToolAvailabilityRuntime {
101
102
  invalidTool;
102
103
  tools;
103
104
  toolsByName;
105
+ activationKeysByName;
104
106
  groups;
105
107
  searchableNames;
106
108
  directNames;
@@ -115,6 +117,7 @@ export class ToolAvailabilityRuntime {
115
117
  }
116
118
  this.tools = [...tools];
117
119
  this.toolsByName = new Map(tools.map((tool) => [tool.name, tool]));
120
+ this.activationKeysByName = new Map(tools.map((tool) => [tool.name, toolActivationKey(tool)]));
118
121
  const known = new Set(this.toolsByName.keys());
119
122
  const searchable = config === undefined
120
123
  ? new Set()
@@ -240,6 +243,13 @@ export class ToolAvailabilityRuntime {
240
243
  const allTools = [...this.tools, connector];
241
244
  const canonical = canonicalizeToolSet(allTools, this.invalidTool);
242
245
  const knownNames = new Set(canonical.providerTools.map((tool) => tool.name));
246
+ // Activation belongs to a stable logical contribution, not a temporary
247
+ // wrapper object or merely its name. Equivalent Host wrappers survive
248
+ // per-step rebuilding; a replaced Plugin generation does not.
249
+ for (const [name, activatedKey] of activeTools) {
250
+ if (this.activationKeysByName.get(name) !== activatedKey)
251
+ activeTools.delete(name);
252
+ }
243
253
  const requiredNames = [...requiredToolNames].filter((name) => knownNames.has(name));
244
254
  const step = { active: new Set() };
245
255
  const computeActive = () => {
@@ -308,7 +318,7 @@ export class ToolAvailabilityRuntime {
308
318
  schemaChars += chars;
309
319
  }
310
320
  for (const name of activated)
311
- activeTools.set(name, this.toolsByName.get(name));
321
+ activeTools.set(name, this.activationKeysByName.get(name));
312
322
  const result = {
313
323
  activated,
314
324
  ...(blocked ? { blocked } : {}),
@@ -0,0 +1,38 @@
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
+ /** Frozen bytes for archive rewriteVersion 1. Do not inherit future UI/provider formatting changes. */
20
+ export function serializeToolResultProjectionV1(projection) {
21
+ switch (projection.kind) {
22
+ case 'text':
23
+ return JSON.stringify(projection.text);
24
+ case 'json':
25
+ return JSON.stringify(projection.value);
26
+ case 'execution_denied':
27
+ return JSON.stringify({ kind: 'text', text: projection.reason ?? '' });
28
+ case 'failure':
29
+ return JSON.stringify(projection.message);
30
+ case 'content':
31
+ return JSON.stringify(projection.parts.map((part) => part.kind === 'text'
32
+ ? { type: 'text', text: part.text }
33
+ : {
34
+ type: 'text',
35
+ text: `[Artifact ${JSON.stringify(part.ref.kind === 'session_context' ? part.ref.refId : part.ref.relativePath)} (${part.mediaType}) is stored in this Session.]`,
36
+ }));
37
+ }
38
+ }
@@ -35,12 +35,72 @@ const MAX_SEARCH_SNIPPET_CHARS = 240;
35
35
  const MAX_SEARCH_PATTERN_CHARS = 256;
36
36
  /** Preview length surfaced by inspect for text/object payloads. */
37
37
  const INSPECT_PREVIEW_CHARS = 600;
38
+ export function isLedgerArchiveIdentity(value) {
39
+ if (!isRecord(value))
40
+ return false;
41
+ return (value.storage === 'ledger' &&
42
+ value.artifactId === undefined &&
43
+ ['runtimeEventId', 'toolCallId', 'toolName'].every((key) => typeof value[key] === 'string' &&
44
+ value[key].length > 0 &&
45
+ value[key].length <= 512) &&
46
+ typeof value.sourceProjectionDigest === 'string' &&
47
+ /^sha256:[a-f0-9]{64}$/.test(value.sourceProjectionDigest) &&
48
+ (value.previousTransitionId === undefined ||
49
+ (typeof value.previousTransitionId === 'string' &&
50
+ /^mptransition-[a-f0-9]{32}$/.test(value.previousTransitionId))) &&
51
+ typeof value.bodySha256 === 'string' &&
52
+ /^[a-f0-9]{64}$/.test(value.bodySha256) &&
53
+ Number.isSafeInteger(value.originalBytes) &&
54
+ Number(value.originalBytes) > 0);
55
+ }
38
56
  export function buildToolResultArchiveResourceRef(input) {
57
+ if (input.storage === 'ledger') {
58
+ if (!isLedgerArchiveIdentity(input))
59
+ throw new Error('Invalid ledger archive identity');
60
+ const value = [
61
+ input.runtimeEventId,
62
+ input.toolCallId,
63
+ input.toolName,
64
+ input.sourceProjectionDigest,
65
+ input.previousTransitionId ?? null,
66
+ input.bodySha256,
67
+ input.originalBytes,
68
+ ];
69
+ return `maka://archive-ledger/v1/${encodeURIComponent(JSON.stringify(value))}`;
70
+ }
39
71
  const artifactId = encodeURIComponent(input.artifactId);
40
72
  const sha256 = encodeURIComponent(input.bodySha256);
41
73
  return `maka://archive/${artifactId}/${sha256}/${input.originalBytes}`;
42
74
  }
43
75
  export function parseToolResultArchiveResourceRef(ref) {
76
+ if (ref.startsWith('maka://archive-ledger/')) {
77
+ try {
78
+ const prefix = 'maka://archive-ledger/v1/';
79
+ if (!ref.startsWith(prefix) || ref.length > 16384)
80
+ return null;
81
+ const values = JSON.parse(decodeURIComponent(ref.slice(prefix.length)));
82
+ if (!Array.isArray(values) || values.length !== 7)
83
+ return null;
84
+ const [runtimeEventId, toolCallId, toolName, sourceProjectionDigest, previous, bodySha256, originalBytes,] = values;
85
+ const identity = {
86
+ storage: 'ledger',
87
+ runtimeEventId,
88
+ toolCallId,
89
+ toolName,
90
+ sourceProjectionDigest,
91
+ ...(previous === null ? {} : { previousTransitionId: previous }),
92
+ bodySha256,
93
+ originalBytes,
94
+ };
95
+ return isLedgerArchiveIdentity(identity) &&
96
+ buildToolResultArchiveResourceRef(identity) === ref
97
+ ? identity
98
+ : null;
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
44
104
  let url;
45
105
  try {
46
106
  url = new URL(ref);
@@ -162,7 +222,9 @@ function inspectArchive(ref, identity, value, serializedResult) {
162
222
  kind: 'tool_result_archive',
163
223
  operation: 'inspect',
164
224
  ref,
165
- artifactId: identity.artifactId,
225
+ ...(identity.storage === 'ledger'
226
+ ? { storage: 'ledger', runtimeEventId: identity.runtimeEventId }
227
+ : { artifactId: identity.artifactId }),
166
228
  originalBytes: identity.originalBytes,
167
229
  };
168
230
  const readHint = 'Call ArchiveRead with operation "read" (unit "char" or "line"), offset, and limit for bounded pages, or operation "search" with a pattern to locate text.';
@@ -40,11 +40,12 @@
40
40
  */
41
41
  import { MATERIALIZED_IMAGE_TOKENS } from '@maka/core/attachments';
42
42
  import { DURABLE_TOOL_RESULT_PROJECTION_VERSION } from '@maka/core/durable-tool-result-projection';
43
- import { buildModelProjectionTransition, } from '@maka/core/model-projection-transition';
43
+ import { buildModelProjectionTransition, durableToolResultProjectionDigest, } from '@maka/core/model-projection-transition';
44
44
  import { estimateTokens, finitePositive, sha256, turnKey, utf8ByteLength, } from './context-budget-helpers.js';
45
- import { durableProjectionToToolResultOutput, projectionArtifactMedia, } from './durable-tool-result-projection.js';
45
+ import { projectionArtifactMedia } from './durable-tool-result-projection.js';
46
46
  import { baseToolResultProjection, nextInChain } from './model-projection-transition-ledger.js';
47
- import { ARCHIVED_TOOL_RESULT_REWRITE_VERSION, buildArchivedToolResultPlaceholder, isArchivedToolResultPlaceholder, serializeToolResultForArchive, } from './tool-result-archive.js';
47
+ import { ARCHIVED_TOOL_RESULT_REWRITE_VERSION, buildArchivedToolResultPlaceholder, buildLedgerArchivedToolResultPlaceholder, isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
48
+ import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
48
49
  const DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS = 2048;
49
50
  /**
50
51
  * What the model actually reads for one Tool Result, as bytes.
@@ -55,8 +56,7 @@ const DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS = 2048;
55
56
  * body that is not the one removed from the model's view.
56
57
  */
57
58
  export function serializedToolResultProjection(projection) {
58
- const output = durableProjectionToToolResultOutput(projection);
59
- return serializeToolResultForArchive(output.type === 'execution-denied' ? { kind: 'text', text: output.reason ?? '' } : output.value);
59
+ return serializeToolResultProjectionV1(projection);
60
60
  }
61
61
  /** The replacement a pruned Tool Result projects to. */
62
62
  export function archivedToolResultProjection(placeholder) {
@@ -90,16 +90,21 @@ export async function archiveToolResultAsTransition(services, request) {
90
90
  originalEstimatedTokens: request.originalEstimatedTokens,
91
91
  rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
92
92
  reason: request.reason,
93
+ sourceProjectionDigest: durableToolResultProjectionDigest(request.sourceProjection),
94
+ ...(request.previousTransitionId
95
+ ? { previousTransitionId: request.previousTransitionId }
96
+ : {}),
93
97
  }));
94
98
  }
95
99
  catch {
96
100
  return undefined;
97
101
  }
98
- const artifactId = archived?.artifactId;
99
- if (typeof artifactId !== 'string' || artifactId.trim().length === 0)
102
+ if (!archived)
103
+ return undefined;
104
+ if (!archived.ledger &&
105
+ (typeof archived.artifactId !== 'string' || archived.artifactId.trim().length === 0))
100
106
  return undefined;
101
- const placeholder = buildArchivedToolResultPlaceholder({
102
- artifactId,
107
+ const common = {
103
108
  runtimeEventId: request.runtimeEventId,
104
109
  toolCallId: request.toolCallId,
105
110
  toolName: request.toolName,
@@ -108,7 +113,23 @@ export async function archiveToolResultAsTransition(services, request) {
108
113
  originalBytes: request.originalBytes,
109
114
  reason: request.reason,
110
115
  ...(request.supersession ? { supersession: request.supersession } : {}),
111
- });
116
+ };
117
+ let placeholder;
118
+ try {
119
+ placeholder = archived.ledger
120
+ ? buildLedgerArchivedToolResultPlaceholder({
121
+ ...common,
122
+ storage: 'ledger',
123
+ sourceProjectionDigest: durableToolResultProjectionDigest(request.sourceProjection),
124
+ ...(request.previousTransitionId
125
+ ? { previousTransitionId: request.previousTransitionId }
126
+ : {}),
127
+ })
128
+ : buildArchivedToolResultPlaceholder({ ...common, artifactId: archived.artifactId });
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
112
133
  let transition;
113
134
  try {
114
135
  transition = buildModelProjectionTransition({
@@ -129,7 +150,16 @@ export async function archiveToolResultAsTransition(services, request) {
129
150
  : {}),
130
151
  now: services.now(),
131
152
  });
132
- await services.recordTransition(transition);
153
+ if (placeholder.rewriteVersion === 2 &&
154
+ Buffer.byteLength(JSON.stringify(transition)) > 32 * 1024)
155
+ return undefined;
156
+ if (archived.ledger && archived.commitTransition) {
157
+ if (!(await archived.commitTransition(transition, services.recordTransition)))
158
+ return undefined;
159
+ }
160
+ else {
161
+ await services.recordTransition(transition);
162
+ }
133
163
  const winner = await winningTransition(services, transition);
134
164
  if (winner && winner.transitionId !== transition.transitionId) {
135
165
  // The rival won. Show what the ledger says, not what this writer wrote;
@@ -236,7 +266,7 @@ export function collectReachableArchiveArtifactIds(events) {
236
266
  const content = event.content;
237
267
  if (content?.kind !== 'function_response')
238
268
  continue;
239
- if (isArchivedToolResultPlaceholder(content.result)) {
269
+ if (isArchivedToolResultPlaceholder(content.result) && content.result.rewriteVersion === 1) {
240
270
  reachable.add(content.result.artifactId);
241
271
  }
242
272
  }
@@ -17,9 +17,28 @@
17
17
  * under the License.
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
- import { buildToolResultArchiveResourceRef, TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS, } from './tool-result-archive-resource.js';
20
+ import { buildToolResultArchiveResourceRef, TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS, isLedgerArchiveIdentity, } from './tool-result-archive-resource.js';
21
21
  export const ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND = 'maka.archived_tool_result';
22
22
  export const ARCHIVED_TOOL_RESULT_REWRITE_VERSION = 1;
23
+ export function buildLedgerArchivedToolResultPlaceholder(input) {
24
+ return {
25
+ storage: 'ledger',
26
+ runtimeEventId: input.runtimeEventId,
27
+ toolCallId: input.toolCallId,
28
+ toolName: input.toolName,
29
+ sourceProjectionDigest: input.sourceProjectionDigest,
30
+ ...(input.previousTransitionId ? { previousTransitionId: input.previousTransitionId } : {}),
31
+ bodySha256: input.bodySha256,
32
+ originalBytes: input.originalBytes,
33
+ originalEstimatedTokens: input.originalEstimatedTokens,
34
+ reason: input.reason,
35
+ ...(input.supersession ? { supersession: input.supersession } : {}),
36
+ kind: ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND,
37
+ rewriteVersion: 2,
38
+ resourceRef: buildToolResultArchiveResourceRef(input),
39
+ readInstructions: TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS,
40
+ };
41
+ }
23
42
  export function stableToolResultArchiveArtifactId(event) {
24
43
  return `tool-result-archive-${createHash('sha256')
25
44
  .update(JSON.stringify({
@@ -57,10 +76,12 @@ export function isArchivedToolResultPlaceholder(value) {
57
76
  if (!value || typeof value !== 'object')
58
77
  return false;
59
78
  const candidate = value;
79
+ const ledgerIdentity = isLedgerArchiveIdentity(value);
60
80
  return (candidate.kind === ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND &&
61
- candidate.rewriteVersion === ARCHIVED_TOOL_RESULT_REWRITE_VERSION &&
62
- typeof candidate.artifactId === 'string' &&
63
- candidate.artifactId.length > 0 &&
81
+ ((candidate.rewriteVersion === 1 &&
82
+ typeof candidate.artifactId === 'string' &&
83
+ candidate.artifactId.length > 0) ||
84
+ (candidate.rewriteVersion === 2 && ledgerIdentity)) &&
64
85
  typeof candidate.runtimeEventId === 'string' &&
65
86
  candidate.runtimeEventId.length > 0 &&
66
87
  typeof candidate.toolCallId === 'string' &&
@@ -100,6 +121,8 @@ function isValidSupersession(value) {
100
121
  export function withToolResultArchiveResourceRef(value) {
101
122
  if (!isArchivedToolResultPlaceholder(value))
102
123
  return value;
124
+ if (value.rewriteVersion === 2)
125
+ return buildLedgerArchivedToolResultPlaceholder(value);
103
126
  return {
104
127
  ...value,
105
128
  resourceRef: buildToolResultArchiveResourceRef({