maka-agent 0.2.0-dev.10.20260831 → 0.2.0-dev.12.20260901

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 (237) hide show
  1. package/LICENSE +49 -2
  2. package/RUNTIME_HOST_PEER_DEPENDENCIES.rust.tsv +70 -0
  3. package/RUNTIME_HOST_PEER_THIRD_PARTY_NOTICES.txt +1839 -140
  4. package/dist/cli-core.js +25 -1
  5. package/dist/mcp-capability-provider.js +1 -1
  6. package/dist/onboarding-catalog.js +3 -5
  7. package/dist/pi-transcript.js +21 -17
  8. package/dist/pi-tui-layout.js +4 -2
  9. package/dist/pi-tui-mcp-status.js +115 -122
  10. package/dist/pi-tui-pickers.js +11 -5
  11. package/dist/pi-tui-runner.js +133 -102
  12. package/dist/runtime-host-cli-context.js +4 -0
  13. package/dist/runtime-host-cli.js +150 -4
  14. package/dist/runtime-host-lifecycle-transaction.js +5 -2
  15. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  16. package/dist/runtime-host-onboarding.js +12 -16
  17. package/dist/runtime-host-peer-management-command.js +16 -4
  18. package/dist/runtime-host-plugin-command.js +101 -0
  19. package/dist/runtime-host-run-command.js +5 -1
  20. package/dist/runtime-host-service-management-command.js +2 -1
  21. package/dist/runtime-host-setup-command.js +1 -0
  22. package/dist/runtime-host-task-readiness.js +2 -3
  23. package/dist/runtime-host-tui-command.js +1 -1
  24. package/dist/runtime-host-tui-context.js +34 -6
  25. package/dist/runtime-host-update-command.js +13 -5
  26. package/dist/runtime-host-update-discovery.js +1 -0
  27. package/dist/tui-clipboard.js +86 -0
  28. package/dist/tui-copy-catalog.js +256 -0
  29. package/dist/tui-copy-command.js +103 -0
  30. package/dist/tui-mcp-control.js +46 -4
  31. package/dist/tui-mcp-remote-publication.js +395 -0
  32. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  33. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  34. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  35. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  36. package/node_modules/@maka/core/dist/agent-run.js +5 -0
  37. package/node_modules/@maka/core/dist/attachments.js +80 -1
  38. package/node_modules/@maka/core/dist/bounded-response.js +71 -0
  39. package/node_modules/@maka/core/dist/chat-model-choice.js +8 -31
  40. package/node_modules/@maka/core/dist/client-capability-grant.js +149 -0
  41. package/node_modules/@maka/core/dist/connection-readiness.js +3 -31
  42. package/node_modules/@maka/core/dist/deep-research.js +1 -20
  43. package/node_modules/@maka/core/dist/events.js +22 -1
  44. package/node_modules/@maka/core/dist/execution-inspect.js +3 -1
  45. package/node_modules/@maka/core/dist/foreign-session.js +2 -2
  46. package/node_modules/@maka/core/dist/interaction.js +49 -2
  47. package/node_modules/@maka/core/dist/llm-connections.js +74 -82
  48. package/node_modules/@maka/core/dist/model-call-attempt.js +66 -0
  49. package/node_modules/@maka/core/dist/model-catalog.js +238 -313
  50. package/node_modules/@maka/core/dist/model-facts.js +280 -0
  51. package/node_modules/@maka/core/dist/model-metadata.generated.js +1907 -1872
  52. package/node_modules/@maka/core/dist/model-metadata.js +184 -199
  53. package/node_modules/@maka/core/dist/model-projection-transition.js +145 -0
  54. package/node_modules/@maka/core/dist/model-thinking.js +1 -1
  55. package/node_modules/@maka/core/dist/models-dev-projection.js +302 -0
  56. package/node_modules/@maka/core/dist/models-dev-refresh.js +55 -0
  57. package/node_modules/@maka/core/dist/onboarding.js +2 -1
  58. package/node_modules/@maka/core/dist/provider-auth.js +47 -291
  59. package/node_modules/@maka/core/dist/provider-registry.js +68 -357
  60. package/node_modules/@maka/core/dist/runtime-boundary.js +2 -2
  61. package/node_modules/@maka/core/dist/runtime-event.js +5 -1
  62. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +82 -5
  63. package/node_modules/@maka/core/dist/runtime-policy/model-catalog-entry-codec.js +75 -0
  64. package/node_modules/@maka/core/dist/runtime-policy.js +2 -1
  65. package/node_modules/@maka/core/dist/session-send-projection.js +2 -1
  66. package/node_modules/@maka/core/dist/session-start-mode.js +42 -0
  67. package/node_modules/@maka/core/dist/session-todo.js +101 -0
  68. package/node_modules/@maka/core/dist/session.js +119 -5
  69. package/node_modules/@maka/core/dist/slash-command-catalog.js +1 -0
  70. package/node_modules/@maka/core/dist/task-submission-readiness.js +2 -1
  71. package/node_modules/@maka/core/dist/tool-activity-args.js +4 -0
  72. package/node_modules/@maka/core/dist/tool-quiet-preview.js +5 -5
  73. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  74. package/node_modules/@maka/core/dist/workhub-creation-intent.js +896 -0
  75. package/node_modules/@maka/core/package.json +9 -1
  76. package/node_modules/@maka/runtime/dist/active-tool-result-prune.js +45 -131
  77. package/node_modules/@maka/runtime/dist/agent-run.js +58 -44
  78. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +146 -201
  79. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +235 -69
  80. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +4 -41
  81. package/node_modules/@maka/runtime/dist/context-budget-policy.js +8 -1
  82. package/node_modules/@maka/runtime/dist/context-budget.js +9 -81
  83. package/node_modules/@maka/runtime/dist/context-diagnostics.js +63 -27
  84. package/node_modules/@maka/runtime/dist/continuation-replay.js +19 -11
  85. package/node_modules/@maka/runtime/dist/conversation-copy.js +179 -16
  86. package/node_modules/@maka/runtime/dist/deep-research-tools.js +2 -3
  87. package/node_modules/@maka/runtime/dist/durable-tool-result-projection.js +21 -0
  88. package/node_modules/@maka/runtime/dist/execution-inspect.js +13 -3
  89. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +58 -7
  90. package/node_modules/@maka/runtime/dist/history-compact-ledger.js +9 -1
  91. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +2 -2
  92. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +2 -1
  93. package/node_modules/@maka/runtime/dist/history-compaction.js +2 -1
  94. package/node_modules/@maka/runtime/dist/image-file.js +5 -20
  95. package/node_modules/@maka/runtime/dist/latest-context-snapshot.js +114 -20
  96. package/node_modules/@maka/runtime/dist/local-web-fetch.js +2 -43
  97. package/node_modules/@maka/runtime/dist/mcp-tools.js +28 -0
  98. package/node_modules/@maka/runtime/dist/model-adapter.js +47 -15
  99. package/node_modules/@maka/runtime/dist/model-factory.js +7 -1
  100. package/node_modules/@maka/runtime/dist/model-fetcher.js +15 -8
  101. package/node_modules/@maka/runtime/dist/model-history.js +125 -3
  102. package/node_modules/@maka/runtime/dist/model-projection-transition-ledger.js +207 -0
  103. package/node_modules/@maka/runtime/dist/model-runtime.js +7 -4
  104. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +12 -14
  105. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +173 -20
  106. package/node_modules/@maka/runtime/dist/plugin-runtime.js +219 -0
  107. package/node_modules/@maka/runtime/dist/prompt-composition.js +33 -21
  108. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +35 -74
  109. package/node_modules/@maka/runtime/dist/quiescent-session-snapshot.js +78 -0
  110. package/node_modules/@maka/runtime/dist/request-shape.js +256 -343
  111. package/node_modules/@maka/runtime/dist/run-trace.js +2 -24
  112. package/node_modules/@maka/runtime/dist/runtime-continuation-admission.js +1 -1
  113. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +3 -0
  114. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +1 -0
  115. package/node_modules/@maka/runtime/dist/runtime-kernel.js +77 -23
  116. package/node_modules/@maka/runtime/dist/runtime-resume.js +20 -11
  117. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +8 -4
  118. package/node_modules/@maka/runtime/dist/session-manager.js +45 -9
  119. package/node_modules/@maka/runtime/dist/session-recap.js +2 -1
  120. package/node_modules/@maka/runtime/dist/session-todo-tools.js +67 -0
  121. package/node_modules/@maka/runtime/dist/subagent-tools.js +2 -77
  122. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +1 -1
  123. package/node_modules/@maka/runtime/dist/telemetry/model-pricing.generated.js +93 -83
  124. package/node_modules/@maka/runtime/dist/test-connection.js +6 -6
  125. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +227 -0
  126. package/node_modules/@maka/runtime/dist/tool-result-archive.js +40 -168
  127. package/node_modules/@maka/runtime/dist/tool-runtime.js +50 -6
  128. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +39 -16
  129. package/node_modules/@maka/runtime/package.json +2 -1
  130. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +10 -0
  131. package/node_modules/@maka/runtime-host/dist/client/catalog-reader.js +19 -5
  132. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +3 -2
  133. package/node_modules/@maka/runtime-host/dist/client/connection.js +22 -0
  134. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +222 -19
  135. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -1
  136. package/node_modules/@maka/runtime-host/dist/client/oauth-presentation.js +1 -1
  137. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +4 -0
  138. package/node_modules/@maka/runtime-host/dist/client/reconnecting-connection.js +8 -0
  139. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  140. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +2 -0
  141. package/node_modules/@maka/runtime-host/dist/operator/peer-management-frame.js +2 -0
  142. package/node_modules/@maka/runtime-host/dist/operator/service-management-frame.js +2 -0
  143. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +1 -0
  144. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +22 -1
  145. package/node_modules/@maka/{storage/dist/task-ledger-store-internal.js → runtime-host/dist/protocol/connection-catalog-change.js} +7 -13
  146. package/node_modules/@maka/runtime-host/dist/protocol/index.js +43 -2
  147. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +7 -3
  148. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +512 -0
  149. package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +24 -12
  150. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +1 -1
  151. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +1 -1
  152. package/node_modules/@maka/runtime-host/dist/protocol/session-retirement.js +30 -3
  153. package/node_modules/@maka/runtime-host/dist/protocol/session-todo.js +53 -0
  154. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +4 -1
  155. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +92 -4
  156. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +15 -13
  157. package/node_modules/@maka/runtime-host/dist/server/access-credential-metadata.js +4 -2
  158. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +119 -47
  159. package/node_modules/@maka/runtime-host/dist/server/bootstrap-runtime-policy.js +10 -4
  160. package/node_modules/@maka/runtime-host/dist/server/child-agent-composition.js +1 -1
  161. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +192 -18
  162. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +122 -48
  163. package/node_modules/@maka/runtime-host/dist/server/client-capability-provider-id.js +31 -0
  164. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +6 -5
  165. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +1 -0
  166. package/node_modules/@maka/runtime-host/dist/server/deep-research-coordinator.js +1 -1
  167. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +163 -66
  168. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +27 -9
  169. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +38 -43
  170. package/node_modules/@maka/runtime-host/dist/server/extension-bundle.js +249 -0
  171. package/node_modules/@maka/runtime-host/dist/server/extension-package-manifest.js +262 -0
  172. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +0 -23
  173. package/node_modules/@maka/runtime-host/dist/server/host-change-feed.js +11 -0
  174. package/node_modules/@maka/runtime-host/dist/server/index.js +5 -0
  175. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +181 -13
  176. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +6 -0
  177. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +7 -9
  178. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +88 -22
  179. package/node_modules/@maka/runtime-host/dist/server/model-metadata-refresh.js +96 -0
  180. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +43 -118
  181. package/node_modules/@maka/runtime-host/dist/server/plugin-composition-patch.js +58 -0
  182. package/node_modules/@maka/runtime-host/dist/server/plugin-composition-store.js +141 -0
  183. package/node_modules/@maka/runtime-host/dist/server/plugin-package-loader.js +130 -0
  184. package/node_modules/@maka/runtime-host/dist/server/plugin-package-store.js +528 -0
  185. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +249 -0
  186. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +1130 -0
  187. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +4 -0
  188. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +24 -5
  189. package/node_modules/@maka/runtime-host/dist/server/runtime-policy-coordinator.js +31 -2
  190. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +2 -1
  191. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +58 -9
  192. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +30 -13
  193. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -1
  194. package/node_modules/@maka/runtime-host/dist/server/session-todo-coordinator.js +77 -0
  195. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +10 -2
  196. package/node_modules/@maka/runtime-host/dist/server/web-fetch-tool.js +1 -1
  197. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +276 -3
  198. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +101 -1
  199. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +1 -0
  200. package/node_modules/@maka/runtime-host/dist/webrtc-stun-policy.js +114 -0
  201. package/node_modules/@maka/runtime-host/package.json +2 -0
  202. package/node_modules/@maka/storage/dist/agent-run-store.js +80 -15
  203. package/node_modules/@maka/storage/dist/artifact-attachments.js +29 -6
  204. package/node_modules/@maka/storage/dist/artifact-store.js +7 -23
  205. package/node_modules/@maka/storage/dist/artifact-stores.js +13 -2
  206. package/node_modules/@maka/storage/dist/conversation-operational-state.js +3 -0
  207. package/node_modules/@maka/storage/dist/credential-store.js +3 -0
  208. package/node_modules/@maka/storage/dist/execution-stores.js +4 -0
  209. package/node_modules/@maka/storage/dist/file-lifetime-owner.js +30 -2
  210. package/node_modules/@maka/storage/dist/interaction-store-public.js +1 -1
  211. package/node_modules/@maka/storage/dist/interaction-store.js +173 -0
  212. package/node_modules/@maka/storage/dist/model-facts-store.js +79 -0
  213. package/node_modules/@maka/storage/dist/production-session-snapshot.js +761 -0
  214. package/node_modules/@maka/storage/dist/quiescent-session-snapshot.js +1 -1
  215. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +26 -26
  216. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +114 -56
  217. package/node_modules/@maka/storage/dist/runtime-policy/document-io.js +22 -16
  218. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +2 -2
  219. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +1 -1
  220. package/node_modules/@maka/storage/dist/session-message-projection.js +1 -1
  221. package/node_modules/@maka/storage/dist/session-store.js +32 -6
  222. package/node_modules/@maka/storage/dist/{task-ledger-authority.js → session-todo-authority.js} +13 -28
  223. package/node_modules/@maka/storage/dist/session-todo-store.js +169 -0
  224. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +19 -0
  225. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +42 -1
  226. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +10 -1
  227. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +73 -3
  228. package/node_modules/@maka/storage/dist/sqlite-workflow-schema.js +5 -8
  229. package/node_modules/@maka/storage/dist/storage-writer-composition.js +3 -3
  230. package/node_modules/@maka/storage/package.json +3 -1
  231. package/package.json +1 -1
  232. package/node_modules/@maka/core/dist/task-ledger.js +0 -669
  233. package/node_modules/@maka/runtime/dist/task-ledger-tools.js +0 -244
  234. package/node_modules/@maka/runtime/dist/test-helpers.js +0 -61
  235. package/node_modules/@maka/runtime-host/dist/protocol/task-ledger.js +0 -321
  236. package/node_modules/@maka/runtime-host/dist/server/task-ledger-coordinator.js +0 -154
  237. package/node_modules/@maka/storage/dist/task-ledger-store.js +0 -663
@@ -16,7 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { PROVIDER_DEFAULTS, classifyConnectionModelInventory, connectionEnabledModelIds, } from '@maka/core/llm-connections';
19
+ import { PROVIDER_REGISTRY, providerDefaultsOf, providerFallbackModelIds, connectionModelsEnumerateAccount, connectionEnabledModelIds, } from '@maka/core/llm-connections';
20
20
  import { anthropicV1Url, googleApiUrl, openResponsesUrl } from './provider-urls.js';
21
21
  import { resolveModelRuntime } from './model-runtime.js';
22
22
  import { fetchGitHubCopilotModels } from './model-fetcher.js';
@@ -41,7 +41,7 @@ function resolveConnectionTestModel(connection, model, fallbackModels) {
41
41
  return explicitModel;
42
42
  const discoveredIds = connection.models?.map(({ id }) => id.trim()).filter((id) => id.length > 0) ?? [];
43
43
  const enabled = connectionEnabledModelIds(connection);
44
- const listed = classifyConnectionModelInventory(connection) === 'live' ? new Set(discoveredIds) : undefined;
44
+ const listed = connectionModelsEnumerateAccount(connection) ? new Set(discoveredIds) : undefined;
45
45
  const preferred = listed
46
46
  ? [...enabled.filter((id) => listed.has(id)), ...enabled.filter((id) => !listed.has(id))]
47
47
  : enabled;
@@ -97,7 +97,7 @@ export async function runConnectionTestEffect(connection, apiKey, options, model
97
97
  }
98
98
  }
99
99
  async function testConnectionStrict(connection, apiKey, model, fetchFn, t0, timeoutMs = CONNECTION_TEST_TIMEOUT_MS) {
100
- const defaults = PROVIDER_DEFAULTS[connection.providerType];
100
+ const defaults = PROVIDER_REGISTRY[connection.providerType];
101
101
  // Unknown providerType → can't pick an auth path or fallback model. Return a
102
102
  // clear failure rather than crashing. Mirrors `isRealConnection`.
103
103
  if (!defaults) {
@@ -105,13 +105,13 @@ async function testConnectionStrict(connection, apiKey, model, fetchFn, t0, time
105
105
  }
106
106
  const auth = defaults.authKind;
107
107
  const secret = auth === 'none' ? '' : apiKey;
108
- const testModel = resolveConnectionTestModel(connection, model, defaults.fallbackModels);
108
+ const testModel = resolveConnectionTestModel(connection, model, providerFallbackModelIds(defaults));
109
109
  if (!testModel) {
110
110
  return { ok: false, errorMessage: 'No model to test' };
111
111
  }
112
112
  if (connection.providerType === 'opencode-free' && !model?.trim()) {
113
113
  const candidates = [
114
- ...new Set([...connectionEnabledModelIds(connection), ...defaults.fallbackModels]),
114
+ ...new Set([...connectionEnabledModelIds(connection), ...providerFallbackModelIds(defaults)]),
115
115
  ];
116
116
  let lastFailure;
117
117
  for (let index = 0; index < candidates.length; index += 1) {
@@ -141,7 +141,7 @@ async function testConnectionModel(connection, secret, testModel, fetchFn, t0, t
141
141
  // A stored connection can still be opened long after its provider stopped
142
142
  // being offered, and the caller renders this result — so a retired provider
143
143
  // has to fail the test, not crash it.
144
- if (PROVIDER_DEFAULTS[connection.providerType]?.runtimeAdapter.kind === 'unavailable') {
144
+ if (providerDefaultsOf(connection.providerType)?.runtimeAdapter.kind === 'unavailable') {
145
145
  return retiredProviderTestResult(connection.providerType);
146
146
  }
147
147
  const { adapter, baseUrl, wire } = resolveModelRuntime(connection, testModel);
@@ -0,0 +1,227 @@
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 { DURABLE_TOOL_RESULT_PROJECTION_VERSION } from '@maka/core/durable-tool-result-projection';
20
+ import { buildModelProjectionTransition, } from '@maka/core/model-projection-transition';
21
+ import { estimateTokens, finitePositive, sha256, turnKey, utf8ByteLength, } from './context-budget-helpers.js';
22
+ import { durableProjectionToToolResultOutput } from './durable-tool-result-projection.js';
23
+ import { baseToolResultProjection, nextInChain } from './model-projection-transition-ledger.js';
24
+ import { ARCHIVED_TOOL_RESULT_REWRITE_VERSION, buildArchivedToolResultPlaceholder, isArchivedToolResultPlaceholder, serializeToolResultForArchive, } from './tool-result-archive.js';
25
+ const DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS = 2048;
26
+ /**
27
+ * What the model actually reads for one Tool Result, as bytes.
28
+ *
29
+ * Both the prune thresholds and the archived body are measured over the
30
+ * effective durable projection rather than the raw execution fact: the
31
+ * projection is what costs context, and archiving anything else would store a
32
+ * body that is not the one removed from the model's view.
33
+ */
34
+ export function serializedToolResultProjection(projection) {
35
+ const output = durableProjectionToToolResultOutput(projection);
36
+ return serializeToolResultForArchive(output.type === 'execution-denied' ? { kind: 'text', text: output.reason ?? '' } : output.value);
37
+ }
38
+ /** The replacement a pruned Tool Result projects to. */
39
+ export function archivedToolResultProjection(placeholder) {
40
+ return {
41
+ version: DURABLE_TOOL_RESULT_PROJECTION_VERSION,
42
+ kind: 'json',
43
+ value: placeholder,
44
+ };
45
+ }
46
+ /**
47
+ * Archive one body and commit the transition that replaces its projection.
48
+ *
49
+ * Returns `undefined` when either durable step fails: the caller then leaves
50
+ * the model-visible content exactly as it was, which is the only outcome that
51
+ * keeps "visible history is append-only" true under partial failure.
52
+ */
53
+ export async function archiveToolResultAsTransition(services, request) {
54
+ const bodySha256 = sha256(request.serializedResult);
55
+ let archived;
56
+ try {
57
+ archived = await Promise.resolve(services.archiveToolResult({
58
+ sessionId: services.sessionId,
59
+ runtimeEventId: request.runtimeEventId,
60
+ turnId: request.turnId,
61
+ toolCallId: request.toolCallId,
62
+ toolName: request.toolName,
63
+ result: request.result,
64
+ serializedResult: request.serializedResult,
65
+ bodySha256,
66
+ originalBytes: request.originalBytes,
67
+ originalEstimatedTokens: request.originalEstimatedTokens,
68
+ rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
69
+ reason: request.reason,
70
+ }));
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ const artifactId = archived?.artifactId;
76
+ if (typeof artifactId !== 'string' || artifactId.trim().length === 0)
77
+ return undefined;
78
+ const placeholder = buildArchivedToolResultPlaceholder({
79
+ artifactId,
80
+ runtimeEventId: request.runtimeEventId,
81
+ toolCallId: request.toolCallId,
82
+ toolName: request.toolName,
83
+ bodySha256,
84
+ originalEstimatedTokens: request.originalEstimatedTokens,
85
+ originalBytes: request.originalBytes,
86
+ reason: request.reason,
87
+ ...(request.supersession ? { supersession: request.supersession } : {}),
88
+ });
89
+ let transition;
90
+ try {
91
+ transition = buildModelProjectionTransition({
92
+ sessionId: services.sessionId,
93
+ target: {
94
+ runtimeEventId: request.runtimeEventId,
95
+ part: 'tool_result',
96
+ toolCallId: request.toolCallId,
97
+ toolName: request.toolName,
98
+ },
99
+ sourceProjection: request.sourceProjection,
100
+ // The placeholder inside the replacement is the whole archive record:
101
+ // artifact id, body digest and original size. The transition does not
102
+ // repeat them — one fact, one place.
103
+ replacement: archivedToolResultProjection(placeholder),
104
+ ...(request.previousTransitionId
105
+ ? { previousTransitionId: request.previousTransitionId }
106
+ : {}),
107
+ now: services.now(),
108
+ });
109
+ await services.recordTransition(transition);
110
+ const winner = await winningTransition(services, transition);
111
+ if (winner && winner.transitionId !== transition.transitionId) {
112
+ // The rival won. Show what the ledger says, not what this writer wrote;
113
+ // its own record stays durable and inert, and the body it archived is
114
+ // unreachable exactly as a refused transition's archive should be.
115
+ const replaced = winner.replacement.kind === 'json' ? winner.replacement.value : undefined;
116
+ if (!isArchivedToolResultPlaceholder(replaced))
117
+ return undefined;
118
+ return { placeholder: replaced, transition: winner };
119
+ }
120
+ }
121
+ catch {
122
+ // The archive artifact is now unreferenced: nothing in the effective
123
+ // history names it, which is what reducer-derived reachability reports. It
124
+ // is content-addressed, so a retry of the same decision reuses it rather
125
+ // than publishing a second one. No cleanup pass consumes that reachability
126
+ // yet, so such an artifact is retained until one does — it cannot break
127
+ // replay, but it is not reclaimed either (#4283).
128
+ return undefined;
129
+ }
130
+ return { placeholder, transition };
131
+ }
132
+ /** The transition the durable fold accepts for this target, after an append. */
133
+ async function winningTransition(services, appended) {
134
+ if (!services.loadTransitions)
135
+ return appended;
136
+ const { transitions } = await services.loadTransitions();
137
+ return nextInChain(transitions, appended.previousTransitionId, appended.sourceProjectionDigest, {
138
+ id: appended.target.toolCallId,
139
+ name: appended.target.toolName,
140
+ });
141
+ }
142
+ /**
143
+ * Prior-Turn results large enough to archive before compaction.
144
+ *
145
+ * Collection reads events the transition reducer has already folded, so a
146
+ * result an earlier transition replaced is measured at its replacement size and
147
+ * simply falls below the threshold — there is no second "already pruned?"
148
+ * predicate to keep in step with the fold.
149
+ */
150
+ export function collectStaleToolResultArchiveCandidates(events, prunePolicy, charsPerToken) {
151
+ if (prunePolicy?.enabled !== true)
152
+ return [];
153
+ const maxResultEstimatedTokens = finitePositive(prunePolicy.maxResultEstimatedTokens) ??
154
+ DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS;
155
+ const minRecentTurnsFull = Math.max(0, Math.floor(prunePolicy.minRecentTurnsFull ?? 1));
156
+ const protectedTurnIds = recentTurnIds(events, minRecentTurnsFull);
157
+ const candidates = [];
158
+ for (const event of events) {
159
+ const content = event.content;
160
+ if (event.partial ||
161
+ event.modelVisibility === 'hidden' ||
162
+ content?.kind !== 'function_response' ||
163
+ protectedTurnIds.has(turnKey(event))) {
164
+ continue;
165
+ }
166
+ const sourceProjection = baseToolResultProjection(event);
167
+ if (!sourceProjection)
168
+ continue;
169
+ const serializedResult = serializedToolResultProjection(sourceProjection);
170
+ const originalBytes = utf8ByteLength(serializedResult);
171
+ const originalEstimatedTokens = estimateTokens(serializedResult.length, charsPerToken);
172
+ if (originalEstimatedTokens <= maxResultEstimatedTokens)
173
+ continue;
174
+ candidates.push({
175
+ runtimeEventId: event.id,
176
+ turnId: event.turnId,
177
+ toolCallId: content.id,
178
+ toolName: content.name,
179
+ result: content.result,
180
+ sourceProjection,
181
+ serializedResult,
182
+ originalEstimatedTokens,
183
+ originalBytes,
184
+ rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
185
+ reason: 'stale_tool_result_pruned_before_compact',
186
+ });
187
+ }
188
+ return candidates;
189
+ }
190
+ /**
191
+ * Archive artifacts the effective history still needs.
192
+ *
193
+ * Derived from the folded events, never from a parallel bookkeeping table: an
194
+ * artifact is reachable exactly when a placeholder the model can still see names
195
+ * it. An archive whose transition was refused is therefore unreachable by
196
+ * construction.
197
+ *
198
+ * This is the reachability authority a reclaiming pass must ask; no such pass
199
+ * exists yet, so nothing here is reclaimed today (#4283). Adding one is what
200
+ * makes an unreferenced archive temporary rather than retained.
201
+ */
202
+ export function collectReachableArchiveArtifactIds(events) {
203
+ const reachable = new Set();
204
+ for (const event of events) {
205
+ const content = event.content;
206
+ if (content?.kind !== 'function_response')
207
+ continue;
208
+ if (isArchivedToolResultPlaceholder(content.result)) {
209
+ reachable.add(content.result.artifactId);
210
+ }
211
+ }
212
+ return reachable;
213
+ }
214
+ function recentTurnIds(events, count) {
215
+ if (count <= 0)
216
+ return new Set();
217
+ const order = [];
218
+ const seen = new Set();
219
+ for (const event of events) {
220
+ const key = turnKey(event);
221
+ if (seen.has(key))
222
+ continue;
223
+ seen.add(key);
224
+ order.push(key);
225
+ }
226
+ return new Set(order.slice(Math.max(0, order.length - count)));
227
+ }
@@ -17,11 +17,9 @@
17
17
  * under the License.
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
- import { estimateTokens, finitePositive, sha256, stableJsonLength, turnKey, utf8ByteLength, } from './context-budget-helpers.js';
21
20
  import { buildToolResultArchiveResourceRef, TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS, } from './tool-result-archive-resource.js';
22
21
  export const ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND = 'maka.archived_tool_result';
23
22
  export const ARCHIVED_TOOL_RESULT_REWRITE_VERSION = 1;
24
- const DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS = 2048;
25
23
  export function stableToolResultArchiveArtifactId(event) {
26
24
  return `tool-result-archive-${createHash('sha256')
27
25
  .update(JSON.stringify({
@@ -45,130 +43,6 @@ export function deserializeToolResultArchive(serialized) {
45
43
  return serialized;
46
44
  }
47
45
  }
48
- export function pruneStaleToolResultsBeforeCompact(events, prunePolicy, charsPerToken) {
49
- if (prunePolicy?.enabled !== true) {
50
- return {
51
- events: [...events],
52
- prunedToolResults: 0,
53
- archiveWriteFailures: 0,
54
- estimatedTokensBefore: 0,
55
- estimatedTokensAfter: 0,
56
- };
57
- }
58
- const maxResultEstimatedTokens = finitePositive(prunePolicy.maxResultEstimatedTokens) ??
59
- DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS;
60
- const minRecentTurnsFull = Math.max(0, Math.floor(prunePolicy.minRecentTurnsFull ?? 1));
61
- const protectedTurnIds = recentTurnIds(events, minRecentTurnsFull);
62
- const archiveRefs = normalizeArchiveRefs(prunePolicy.archiveRefs);
63
- let prunedToolResults = 0;
64
- let archiveWriteFailures = 0;
65
- let estimatedTokensBefore = 0;
66
- let estimatedTokensAfter = 0;
67
- const prunedEvents = events.map((event) => {
68
- const content = event.content;
69
- if (event.partial ||
70
- event.modelVisibility === 'hidden' ||
71
- content?.kind !== 'function_response' ||
72
- (content.providerExecuted === true && content.providerOutput !== undefined) ||
73
- protectedTurnIds.has(turnKey(event))) {
74
- return event;
75
- }
76
- if (isArchivedToolResultPlaceholder(content.result))
77
- return event;
78
- const serializedResult = serializeToolResultForArchive(content.result);
79
- const resultBytes = utf8ByteLength(serializedResult);
80
- const resultEstimatedTokens = estimateTokens(serializedResult.length, charsPerToken);
81
- if (resultEstimatedTokens <= maxResultEstimatedTokens)
82
- return event;
83
- const archiveRef = archiveRefs.get(event.id);
84
- if (!archiveRef ||
85
- !archiveRefMatches(archiveRef, {
86
- runtimeEventId: event.id,
87
- toolCallId: content.id,
88
- toolName: content.name,
89
- bodySha256: sha256(serializedResult),
90
- originalBytes: resultBytes,
91
- originalEstimatedTokens: resultEstimatedTokens,
92
- })) {
93
- archiveWriteFailures += 1;
94
- return event;
95
- }
96
- const placeholder = {
97
- kind: ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND,
98
- rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
99
- artifactId: archiveRef.artifactId,
100
- resourceRef: buildToolResultArchiveResourceRef({
101
- artifactId: archiveRef.artifactId,
102
- bodySha256: archiveRef.bodySha256,
103
- originalBytes: resultBytes,
104
- }),
105
- readInstructions: TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS,
106
- runtimeEventId: event.id,
107
- toolCallId: content.id,
108
- toolName: content.name,
109
- bodySha256: archiveRef.bodySha256,
110
- originalEstimatedTokens: resultEstimatedTokens,
111
- originalBytes: resultBytes,
112
- reason: 'stale_tool_result_pruned_before_compact',
113
- };
114
- const placeholderEstimatedTokens = estimateTokens(stableJsonLength(placeholder), charsPerToken);
115
- prunedToolResults += 1;
116
- estimatedTokensBefore += resultEstimatedTokens;
117
- estimatedTokensAfter += placeholderEstimatedTokens;
118
- return {
119
- ...event,
120
- content: {
121
- ...content,
122
- result: placeholder,
123
- },
124
- };
125
- });
126
- return {
127
- events: prunedEvents,
128
- prunedToolResults,
129
- archiveWriteFailures,
130
- estimatedTokensBefore,
131
- estimatedTokensAfter,
132
- };
133
- }
134
- export function collectStaleToolResultArchiveCandidates(events, prunePolicy, charsPerToken) {
135
- if (prunePolicy?.enabled !== true)
136
- return [];
137
- const maxResultEstimatedTokens = finitePositive(prunePolicy.maxResultEstimatedTokens) ??
138
- DEFAULT_MAX_TOOL_RESULT_ESTIMATED_TOKENS;
139
- const minRecentTurnsFull = Math.max(0, Math.floor(prunePolicy.minRecentTurnsFull ?? 1));
140
- const protectedTurnIds = recentTurnIds(events, minRecentTurnsFull);
141
- const candidates = [];
142
- for (const event of events) {
143
- const content = event.content;
144
- if (event.partial ||
145
- event.modelVisibility === 'hidden' ||
146
- content?.kind !== 'function_response' ||
147
- (content.providerExecuted === true && content.providerOutput !== undefined) ||
148
- protectedTurnIds.has(turnKey(event)) ||
149
- isArchivedToolResultPlaceholder(content.result)) {
150
- continue;
151
- }
152
- const serializedResult = serializeToolResultForArchive(content.result);
153
- const originalBytes = utf8ByteLength(serializedResult);
154
- const originalEstimatedTokens = estimateTokens(serializedResult.length, charsPerToken);
155
- if (originalEstimatedTokens <= maxResultEstimatedTokens)
156
- continue;
157
- candidates.push({
158
- runtimeEventId: event.id,
159
- turnId: event.turnId,
160
- toolCallId: content.id,
161
- toolName: content.name,
162
- result: content.result,
163
- serializedResult,
164
- originalEstimatedTokens,
165
- originalBytes,
166
- rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
167
- reason: 'stale_tool_result_pruned_before_compact',
168
- });
169
- }
170
- return candidates;
171
- }
172
46
  export function serializeToolResultForArchive(result) {
173
47
  if (result === undefined)
174
48
  return 'undefined';
@@ -201,7 +75,26 @@ export function isArchivedToolResultPlaceholder(value) {
201
75
  typeof candidate.originalBytes === 'number' &&
202
76
  Number.isFinite(candidate.originalBytes) &&
203
77
  candidate.originalBytes > 0 &&
204
- candidate.reason === 'stale_tool_result_pruned_before_compact');
78
+ (candidate.reason === 'stale_tool_result_pruned_before_compact' ||
79
+ candidate.reason === 'active_current_turn_tool_result_pruned_before_next_step') &&
80
+ isValidSupersession(candidate.supersession));
81
+ }
82
+ function isValidSupersession(value) {
83
+ if (value === undefined)
84
+ return true;
85
+ if (!value || typeof value !== 'object')
86
+ return false;
87
+ const candidate = value;
88
+ return ((candidate.reason === 'exact_duplicate' ||
89
+ candidate.reason === 'newer_read_covers_range' ||
90
+ candidate.reason === 'newer_snapshot' ||
91
+ candidate.reason === 'failure_resolved') &&
92
+ typeof candidate.supersededByToolCallId === 'string' &&
93
+ candidate.supersededByToolCallId.length > 0 &&
94
+ (candidate.reason === 'failure_resolved'
95
+ ? typeof candidate.failureBodySha256 === 'string' &&
96
+ /^[a-f0-9]{64}$/.test(candidate.failureBodySha256)
97
+ : candidate.failureBodySha256 === undefined));
205
98
  }
206
99
  /** Add the canonical ArchiveRead address to persisted v1 placeholders. */
207
100
  export function withToolResultArchiveResourceRef(value) {
@@ -217,45 +110,24 @@ export function withToolResultArchiveResourceRef(value) {
217
110
  readInstructions: TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS,
218
111
  };
219
112
  }
220
- function normalizeArchiveRefs(refs) {
221
- const map = new Map();
222
- if (!refs)
223
- return map;
224
- if (Array.isArray(refs)) {
225
- for (const ref of refs)
226
- map.set(ref.runtimeEventId, ref);
227
- return map;
228
- }
229
- for (const [runtimeEventId, ref] of Object.entries(refs)) {
230
- map.set(runtimeEventId, ref);
231
- }
232
- return map;
233
- }
234
- function archiveRefMatches(ref, candidate) {
235
- return (ref.runtimeEventId === candidate.runtimeEventId &&
236
- ref.toolCallId === candidate.toolCallId &&
237
- ref.toolName === candidate.toolName &&
238
- ref.rewriteVersion === ARCHIVED_TOOL_RESULT_REWRITE_VERSION &&
239
- ref.reason === 'stale_tool_result_pruned_before_compact' &&
240
- typeof ref.artifactId === 'string' &&
241
- ref.artifactId.length > 0 &&
242
- typeof ref.bodySha256 === 'string' &&
243
- ref.bodySha256.length > 0 &&
244
- ref.bodySha256 === candidate.bodySha256 &&
245
- ref.originalEstimatedTokens === candidate.originalEstimatedTokens &&
246
- ref.originalBytes === candidate.originalBytes);
247
- }
248
- function recentTurnIds(events, count) {
249
- if (count <= 0)
250
- return new Set();
251
- const order = [];
252
- const seen = new Set();
253
- for (const event of events) {
254
- const key = turnKey(event);
255
- if (seen.has(key))
256
- continue;
257
- seen.add(key);
258
- order.push(key);
259
- }
260
- return new Set(order.slice(Math.max(0, order.length - count)));
113
+ export function buildArchivedToolResultPlaceholder(input) {
114
+ return {
115
+ kind: ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND,
116
+ rewriteVersion: ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
117
+ artifactId: input.artifactId,
118
+ resourceRef: buildToolResultArchiveResourceRef({
119
+ artifactId: input.artifactId,
120
+ bodySha256: input.bodySha256,
121
+ originalBytes: input.originalBytes,
122
+ }),
123
+ readInstructions: TOOL_RESULT_ARCHIVE_READ_INSTRUCTIONS,
124
+ runtimeEventId: input.runtimeEventId,
125
+ toolCallId: input.toolCallId,
126
+ toolName: input.toolName,
127
+ bodySha256: input.bodySha256,
128
+ originalEstimatedTokens: input.originalEstimatedTokens,
129
+ originalBytes: input.originalBytes,
130
+ reason: input.reason,
131
+ ...(input.supersession ? { supersession: input.supersession } : {}),
132
+ };
261
133
  }
@@ -57,6 +57,7 @@ export const LOOP_GATE_IDENTICAL_THRESHOLD = 3;
57
57
  const SANDBOX_BOUNDARY_FAILURE_ROUND_LIMIT = 3;
58
58
  const SUBAGENT_TOOL_LIMIT_MESSAGE = '子代理并发过多:同一轮最多 5 个子代理。请等待已有任务完成后再继续。';
59
59
  const CLIENT_CAPABILITY_BOUNDARY_MESSAGE = 'Client Capability tools require the Bypass execution boundary because their client-side effects cannot be sandboxed by the Host. Switch this Session to Bypass and retry.';
60
+ const CLIENT_CAPABILITY_PREPARATION_MESSAGE = 'Client Capability tool is missing its Host admission preparation contract.';
60
61
  function composeChildAbortSignal(invocationSignal, childSignal) {
61
62
  if (!childSignal || childSignal === invocationSignal)
62
63
  return invocationSignal;
@@ -796,7 +797,8 @@ export class ToolRuntime {
796
797
  return this.errorReturn(reason);
797
798
  }
798
799
  let clientCapabilityBoundary;
799
- if (tool.categoryHint === 'client_capability') {
800
+ let preparedExecution;
801
+ if (tool.hostAdmission === 'client_capability') {
800
802
  try {
801
803
  clientCapabilityBoundary = await this.readExecutionBoundary();
802
804
  }
@@ -812,8 +814,13 @@ export class ToolRuntime {
812
814
  this.recordLoopGateOutcome(callSignature, true);
813
815
  return this.errorReturn(reason);
814
816
  }
815
- if (clientCapabilityBoundary.kind !== 'bypass') {
816
- await refuseBeforeDispatch(CLIENT_CAPABILITY_BOUNDARY_MESSAGE, {
817
+ const admissionFailure = !tool.prepareExecution
818
+ ? CLIENT_CAPABILITY_PREPARATION_MESSAGE
819
+ : clientCapabilityBoundary.kind !== 'bypass' && this.input.header.permissionMode !== 'ask'
820
+ ? CLIENT_CAPABILITY_BOUNDARY_MESSAGE
821
+ : undefined;
822
+ if (admissionFailure) {
823
+ await refuseBeforeDispatch(admissionFailure, {
817
824
  reason: 'requires_bypass',
818
825
  source: 'client_capability',
819
826
  });
@@ -824,7 +831,39 @@ export class ToolRuntime {
824
831
  errorClass: 'ClientCapabilityBoundary',
825
832
  });
826
833
  this.recordLoopGateOutcome(callSignature, true);
827
- return this.errorReturn(CLIENT_CAPABILITY_BOUNDARY_MESSAGE);
834
+ return this.errorReturn(admissionFailure);
835
+ }
836
+ // Narrowed by admissionFailure above; Bypass still prepares so the
837
+ // provider cannot regain a direct pre-T1 dispatch path.
838
+ const prepareExecution = tool.prepareExecution;
839
+ const pauseTarget = this.input.getPermissionPauseTarget();
840
+ pauseTarget?.pause();
841
+ try {
842
+ preparedExecution = await prepareExecution(structuredClone(executionArgs), {
843
+ sessionId: this.input.sessionId,
844
+ turnId,
845
+ ...(runId ? { runId } : {}),
846
+ cwd: this.input.header.cwd,
847
+ executionBoundary: clientCapabilityBoundary,
848
+ permissionMode: this.input.header.permissionMode,
849
+ toolCallId: toolUseId,
850
+ abortSignal: ctx.abortSignal,
851
+ });
852
+ }
853
+ catch (error) {
854
+ const reason = formatSyntheticToolErrorText(error);
855
+ await refuseBeforeDispatch(reason);
856
+ trace?.emit('tool', 'tool_failed', 'Client Capability preparation failed', {
857
+ toolUseId,
858
+ toolName: tool.name,
859
+ status: 'error',
860
+ errorClass: 'ClientCapabilityPreparation',
861
+ });
862
+ this.recordLoopGateOutcome(callSignature, true);
863
+ return this.errorReturn(reason);
864
+ }
865
+ finally {
866
+ pauseTarget?.resume();
828
867
  }
829
868
  }
830
869
  let managedMutationAdmission;
@@ -857,6 +896,7 @@ export class ToolRuntime {
857
896
  }
858
897
  const reservedSubagentSlot = this.reserveSubagentSlot(tool);
859
898
  if (!reservedSubagentSlot) {
899
+ await preparedExecution?.cancel();
860
900
  await disposeManagedMutationAdmission(managedMutationAdmission);
861
901
  trace?.emit('tool', 'tool_failed', 'Tool execution rejected by runtime limit', {
862
902
  toolUseId,
@@ -884,6 +924,7 @@ export class ToolRuntime {
884
924
  });
885
925
  }
886
926
  catch (error) {
927
+ await preparedExecution?.cancel();
887
928
  if (reservedSubagentSlot)
888
929
  this.releaseSubagentSlot(tool);
889
930
  await disposeManagedMutationAdmission(managedMutationAdmission);
@@ -926,7 +967,7 @@ export class ToolRuntime {
926
967
  try {
927
968
  const runId = this.input.runId;
928
969
  const executionBoundary = clientCapabilityBoundary ?? (await this.readExecutionBoundary());
929
- const invokeTool = () => tool.impl(structuredClone(executionArgs), {
970
+ const toolContext = {
930
971
  sessionId: this.input.sessionId,
931
972
  turnId,
932
973
  ...(runId ? { runId } : {}),
@@ -980,7 +1021,10 @@ export class ToolRuntime {
980
1021
  }),
981
1022
  askUserQuestion: (questions) => this.askUserQuestion(turnId, toolUseId, questions, ctx.abortSignal, queue),
982
1023
  requestSandboxBoundary: (expansion, justification) => this.requestSandboxBoundary(turnId, toolUseId, expansion, justification, ctx.abortSignal, queue),
983
- });
1024
+ };
1025
+ const invokeTool = () => preparedExecution
1026
+ ? preparedExecution.execute(toolContext)
1027
+ : tool.impl(structuredClone(executionArgs), toolContext);
984
1028
  const invokeManagedTransform = () => tool.managedMutationTransform(structuredClone(executionArgs));
985
1029
  const prepareOperationValue = async (immutableSnapshot = false) => {
986
1030
  const rawResult = await (immutableSnapshot ? invokeManagedTransform() : invokeTool());