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
@@ -17,8 +17,9 @@
17
17
  * under the License.
18
18
  */
19
19
  import { RetryError } from 'ai';
20
+ import { MODEL_FAILURE_MESSAGE_MAX_BYTES } from '@maka/core/model-failure';
20
21
  import { truncateUtf8 } from '@maka/core/diagnostic-log';
21
- import { isAuthenticationErrorText, redactSecrets } from '@maka/core/redaction';
22
+ import { isAuthenticationErrorText } from '@maka/core/redaction';
22
23
  /**
23
24
  * Structured provider error identifiers that mean the INPUT exceeded the
24
25
  * model's context window. These come from the provider's error JSON and are
@@ -80,7 +81,6 @@ const USAGE_LIMIT_TEXT_PATTERNS = [
80
81
  /(?:credit|balance|allowance)[^.]{0,40}(?:exhaust|reached)|exhaust[^.]{0,20}(?:credit|balance)/i,
81
82
  /subscription/i,
82
83
  ];
83
- const PROVIDER_FAILURE_SUMMARY_MAX_BYTES = 2 * 1024;
84
84
  const PROVIDER_FAILURE_FIELD_MAX_BYTES = 256;
85
85
  const MAX_SAFE_TIMER_DELAY_MS = 2_147_483_647;
86
86
  const OPENAI_RESPONSES_WEBSOCKET_TRANSPORT_ERROR = 'OPENAI_RESPONSES_WEBSOCKET_TRANSPORT_ERROR';
@@ -153,13 +153,8 @@ function parseRetryAfterMs(headers) {
153
153
  return null;
154
154
  return Math.ceil(delayMs);
155
155
  }
156
- /**
157
- * Normalizes provider retry facts without leaking SDK error objects or raw
158
- * response headers across the ModelAdapter boundary.
159
- */
160
- export function providerRetryMetadata(error) {
161
- const facts = normalizeProviderError(error);
162
- if (!facts)
156
+ function retryMetadataFromFacts(facts, errorClass = classifyProviderFacts(facts)) {
157
+ if (facts.aborted)
163
158
  return { retryable: false };
164
159
  const { evidence } = facts;
165
160
  if (RUNTIME_RETRYABLE_ERROR_CODES.has(evidence.code))
@@ -169,9 +164,8 @@ export function providerRetryMetadata(error) {
169
164
  if (isTrustedCodexEdgeRejection(facts))
170
165
  return { retryable: false };
171
166
  const status = Number(evidence.statusCode || evidence.code);
172
- const errorClass = classifyProviderFacts(facts);
173
167
  const retryAfterMs = parseRetryAfterMs(facts.responseHeaders ?? {});
174
- if (errorClass === 'ProviderCapacity') {
168
+ if (errorClass === 'provider_capacity') {
175
169
  // Capacity is transient even when the provider sends a malformed delay;
176
170
  // fall back to the adapter's bounded local backoff in that case.
177
171
  return {
@@ -179,13 +173,13 @@ export function providerRetryMetadata(error) {
179
173
  ...(retryAfterMs !== undefined && retryAfterMs !== null ? { retryAfterMs } : {}),
180
174
  };
181
175
  }
182
- if (errorClass === 'RateLimit' || status === 429) {
176
+ if (errorClass === 'rate_limit' || status === 429) {
183
177
  if (retryAfterMs === undefined || retryAfterMs === null)
184
178
  return { retryable: false };
185
179
  return { retryable: true, retryAfterMs };
186
180
  }
187
- const retryable = errorClass === 'Network' ||
188
- errorClass === 'ProviderUnavailable' ||
181
+ const retryable = errorClass === 'network' ||
182
+ errorClass === 'provider_unavailable' ||
189
183
  status === 408 ||
190
184
  status === 409 ||
191
185
  (status >= 500 && status <= 599);
@@ -312,15 +306,7 @@ function normalizeProviderError(error) {
312
306
  }
313
307
  return undefined;
314
308
  }
315
- /**
316
- * Retains only allowlisted provider failure fields. The provider value may also
317
- * contain request bodies, headers, or credentials, so it must never be copied
318
- * or serialized as diagnostic output wholesale.
319
- */
320
- export function providerFailureSummary(error) {
321
- const facts = normalizeProviderError(error);
322
- if (!facts)
323
- return undefined;
309
+ function failureSummaryFromFacts(facts) {
324
310
  const sources = facts.summarySources;
325
311
  const message = firstProviderMessage(facts);
326
312
  const code = firstProviderField(sources, ['code']) ?? firstProviderField(sources, ['type']);
@@ -335,41 +321,25 @@ export function providerFailureSummary(error) {
335
321
  if (!message && metadata.length === 0)
336
322
  return undefined;
337
323
  const suffix = metadata.length > 0 ? ` (${metadata.join(', ')})` : '';
338
- const messageBudget = Math.max(1, PROVIDER_FAILURE_SUMMARY_MAX_BYTES - Buffer.byteLength(suffix, 'utf8'));
339
- const summary = `${truncateUtf8(redactSecrets(message ?? 'Provider request failed'), messageBudget, '…')}${suffix}`;
324
+ const messageBudget = Math.max(1, MODEL_FAILURE_MESSAGE_MAX_BYTES - Buffer.byteLength(suffix, 'utf8'));
325
+ const summary = `${truncateUtf8(message ?? 'Provider request failed', messageBudget, '…')}${suffix}`;
340
326
  return {
341
- message: truncateUtf8(summary, PROVIDER_FAILURE_SUMMARY_MAX_BYTES, '…'),
327
+ message: truncateUtf8(summary, MODEL_FAILURE_MESSAGE_MAX_BYTES, '…'),
342
328
  ...(code || statusCode ? { code: code ?? statusCode } : {}),
343
329
  };
344
330
  }
345
- const DURABLE_PROVIDER_ERROR_CLASSES = new Set([
346
- 'Abort',
347
- 'Auth',
348
- 'ContextLength',
349
- 'Network',
350
- 'ProviderCapacity',
351
- 'ProviderBilling',
352
- 'ProviderUnavailable',
353
- 'RateLimit',
354
- 'Timeout',
355
- ]);
356
331
  /**
357
332
  * Projects provider errors into a small durable fingerprint. Unlike the
358
333
  * presentation summary, this intentionally excludes provider messages and
359
- * response bodies: even redacted free text can echo prompts or credentials.
334
+ * response bodies: free text can echo prompts or credentials.
360
335
  */
361
336
  export function providerFailureDiagnostic(error) {
362
- const facts = providerFailureDiagnosticFacts(error);
337
+ const facts = extractProviderErrorFacts(error);
363
338
  if (!facts)
364
- return { errorClass: 'Other', retryable: false };
339
+ return { errorClass: 'unknown', retryable: false };
365
340
  const sources = facts.summarySources;
366
- const rawStatus = facts.evidence.statusCode || firstProviderField(sources, ['statusCode', 'status']);
367
- const numericStatus = Number(rawStatus);
368
- const httpStatus = Number.isInteger(numericStatus) && numericStatus >= 100 && numericStatus <= 599
369
- ? numericStatus
370
- : undefined;
371
- const classified = classifyProviderFacts(facts);
372
- const errorClass = durableProviderErrorClass(facts, classified, httpStatus);
341
+ const httpStatus = providerHttpStatus(facts);
342
+ const errorClass = classifyProviderFacts(facts);
373
343
  const providerCode = firstProviderField(sources, ['code']) ?? firstProviderField(sources, ['type']);
374
344
  const providerRequestId = firstProviderField(sources, ['requestId', 'request_id']) ??
375
345
  boundedProviderField(facts.responseHeaders?.['x-request-id']);
@@ -378,36 +348,14 @@ export function providerFailureDiagnostic(error) {
378
348
  ...(httpStatus !== undefined ? { httpStatus } : {}),
379
349
  ...(providerCode !== undefined ? { providerCode } : {}),
380
350
  ...(providerRequestId !== undefined ? { providerRequestId } : {}),
381
- retryable: providerRetryMetadata(facts.target).retryable,
351
+ retryable: retryMetadataFromFacts(facts, errorClass).retryable,
382
352
  };
383
353
  }
384
- function durableProviderErrorClass(facts, classified, httpStatus) {
385
- // Structured context-overflow and capacity evidence can legitimately arrive
386
- // behind a generic 4xx/5xx proxy response and remains stronger than the wrapper code.
387
- if (classified === 'ContextLength' ||
388
- classified === 'ProviderCapacity' ||
389
- (classified === 'ProviderUnavailable' && isTrustedCodexEdgeRejection(facts))) {
390
- return classified;
391
- }
392
- if (httpStatus === 401 || httpStatus === 403)
393
- return 'Auth';
394
- if (httpStatus === 402)
395
- return 'ProviderBilling';
396
- if (httpStatus === 408)
397
- return 'Timeout';
398
- if (httpStatus === 413)
399
- return 'ContextLength';
400
- if (httpStatus === 429)
401
- return 'RateLimit';
402
- if (httpStatus !== undefined && httpStatus >= 400 && httpStatus <= 499) {
403
- return 'RequestRejected';
404
- }
405
- if (httpStatus !== undefined && httpStatus >= 500 && httpStatus <= 599) {
406
- return 'ProviderUnavailable';
354
+ function extractProviderErrorFacts(error) {
355
+ if (RetryError.isInstance(error) && error.reason === 'abort') {
356
+ const facts = normalizeProviderError(error);
357
+ return facts ? { ...facts, aborted: true } : undefined;
407
358
  }
408
- return DURABLE_PROVIDER_ERROR_CLASSES.has(classified) ? classified : 'Other';
409
- }
410
- function providerFailureDiagnosticFacts(error) {
411
359
  let current = providerErrorTarget(error);
412
360
  let fallback;
413
361
  let codedFallback;
@@ -503,7 +451,7 @@ function boundedProviderField(value) {
503
451
  const normalized = String(value).trim();
504
452
  if (!normalized)
505
453
  return undefined;
506
- return truncateUtf8(redactSecrets(normalized), PROVIDER_FAILURE_FIELD_MAX_BYTES, '…');
454
+ return truncateUtf8(normalized, PROVIDER_FAILURE_FIELD_MAX_BYTES, '…');
507
455
  }
508
456
  function boundedProviderMessage(value, parseJson = true) {
509
457
  if (typeof value !== 'string')
@@ -531,7 +479,7 @@ function boundedProviderMessage(value, parseJson = true) {
531
479
  }
532
480
  if (!normalized)
533
481
  return undefined;
534
- return truncateUtf8(redactSecrets(normalized), PROVIDER_FAILURE_SUMMARY_MAX_BYTES, '…');
482
+ return truncateUtf8(normalized, MODEL_FAILURE_MESSAGE_MAX_BYTES, '…');
535
483
  }
536
484
  /**
537
485
  * Provider context-length overflow signatures. A request-level 400/413 whose
@@ -633,76 +581,111 @@ export function isContextOverflowErrorText(text) {
633
581
  * wrap a provider failure in a misleading status or message; the weak
634
582
  * heuristics rank last so "generate" can never become a rate limit.
635
583
  */
584
+ export function providerModelFailure(error) {
585
+ const facts = extractProviderErrorFacts(error);
586
+ const kind = facts ? classifyProviderFacts(facts) : 'unknown';
587
+ const summary = facts ? failureSummaryFromFacts(facts) : undefined;
588
+ const retry = facts ? retryMetadataFromFacts(facts, kind) : { retryable: false };
589
+ return {
590
+ type: 'model_failure',
591
+ kind,
592
+ ...retry,
593
+ ...(summary?.code !== undefined ? { code: summary.code } : {}),
594
+ message: summary?.message ?? 'Model request failed',
595
+ };
596
+ }
636
597
  export function classifyError(error) {
637
- if (RetryError.isInstance(error) && error.reason === 'abort')
638
- return 'Abort';
639
- const facts = normalizeProviderError(error);
640
- return facts ? classifyProviderFacts(facts) : 'Other';
598
+ const facts = extractProviderErrorFacts(error);
599
+ return facts ? classifyProviderFacts(facts) : 'unknown';
641
600
  }
642
601
  function classifyProviderFacts(facts) {
643
- const { target: classificationTarget, evidence } = facts;
602
+ if (facts.aborted)
603
+ return 'abort';
604
+ const { evidence } = facts;
644
605
  const { text, statusCode, code, structuredCodes } = evidence;
645
606
  const normalizedCode = code.toLowerCase();
646
607
  if (code === OPENAI_RESPONSES_WEBSOCKET_TRANSPORT_ERROR)
647
- return 'Network';
608
+ return 'network';
648
609
  if (PROVIDER_CAPACITY_CODES.has(normalizedCode) ||
649
610
  structuredCodes.some((c) => PROVIDER_CAPACITY_CODES.has(c))) {
650
- return 'ProviderCapacity';
611
+ return 'provider_capacity';
651
612
  }
652
613
  // Structured provider evidence: the parsed error JSON's code/type is the
653
614
  // only unconditional signal for a context overflow.
654
615
  if (structuredCodes.some((c) => CONTEXT_OVERFLOW_PROVIDER_CODES.has(c)))
655
- return 'ContextLength';
616
+ return 'context_overflow';
656
617
  if (PROVIDER_BILLING_PROVIDER_CODES.has(normalizedCode) ||
657
618
  structuredCodes.some((c) => PROVIDER_BILLING_PROVIDER_CODES.has(c))) {
658
- return 'ProviderBilling';
619
+ return 'provider_billing';
659
620
  }
660
621
  if (text.includes('abort'))
661
- return 'Abort';
622
+ return 'abort';
662
623
  if (statusCode === '402' || code === '402')
663
- return 'ProviderBilling';
624
+ return 'provider_billing';
664
625
  if (statusCode === '429' || code === '429')
665
- return 'RateLimit';
626
+ return 'rate_limit';
666
627
  if (structuredCodes.includes(OPENAI_CODEX_EDGE_REJECTION_CODE) &&
667
628
  isTrustedCodexEdgeRejection(facts)) {
668
- return 'ProviderUnavailable';
629
+ return 'provider_unavailable';
669
630
  }
670
631
  if (statusCode === '401' || statusCode === '403' || code === '401' || code === '403') {
671
632
  // Credential-shaped statuses can still carry account-level usage
672
633
  // evidence: an exhausted plan/credit window for a validly signed-in
673
634
  // user must not tell them to re-authenticate (#2516).
674
635
  if (USAGE_LIMIT_TEXT_PATTERNS.some((pattern) => pattern.test(text))) {
675
- return 'ProviderBilling';
636
+ return 'provider_billing';
676
637
  }
677
- return 'Auth';
638
+ return 'auth';
678
639
  }
679
640
  if (statusCode === '413' || code === '413')
680
- return 'ContextLength';
641
+ return 'context_overflow';
681
642
  // Free-text overflow relations on the composite text, veto-first inside.
682
643
  if (isContextOverflowErrorText(text))
683
- return 'ContextLength';
644
+ return 'context_overflow';
684
645
  if (/^5\d\d$/.test(statusCode) || /^5\d\d$/.test(code))
685
- return 'ProviderUnavailable';
646
+ return 'provider_unavailable';
686
647
  if (structuredCodes.some((c) => PROVIDER_UNAVAILABLE_PROVIDER_CODES.has(c))) {
687
- return 'ProviderUnavailable';
648
+ return 'provider_unavailable';
688
649
  }
689
650
  if (evidence.transportFailure)
690
- return 'Network';
651
+ return 'network';
652
+ if (isTruncatedStreamText(text))
653
+ return 'stream_truncated';
654
+ const httpStatus = providerHttpStatus(facts);
655
+ if (httpStatus === 408)
656
+ return 'timeout';
657
+ if (httpStatus !== undefined && httpStatus >= 500 && httpStatus <= 599) {
658
+ return 'provider_unavailable';
659
+ }
660
+ if (httpStatus !== undefined && httpStatus >= 400 && httpStatus <= 499) {
661
+ return 'request_rejected';
662
+ }
691
663
  // Weak word heuristics, last: they only catch errors that carried no
692
664
  // stronger evidence for any other class. `rate` must be word-shaped
693
665
  // ("generate"/"separate" are not rate limits) while still matching the
694
666
  // rate_limit/RateLimitError identifier spellings.
695
667
  if (/\brate\b|rate[_-]?limit/.test(text))
696
- return 'RateLimit';
668
+ return 'rate_limit';
697
669
  if (isAuthenticationErrorText(text))
698
- return 'Auth';
670
+ return 'auth';
699
671
  if (text.includes('timeout'))
700
- return 'Timeout';
672
+ return 'timeout';
701
673
  if (text.includes('network') ||
702
674
  text.includes('fetch') ||
703
675
  /\btypeerror\b.*\bterminated\b/.test(text))
704
- return 'Network';
705
- return classificationTarget instanceof Error ? classificationTarget.name || 'Other' : 'Other';
676
+ return 'network';
677
+ return 'unknown';
678
+ }
679
+ function isTruncatedStreamText(text) {
680
+ return (text.includes('response stream ended without a finish reason') ||
681
+ text.includes('model stream ended without a finish chunk') ||
682
+ (text.includes('stream disconnected before completion') &&
683
+ text.includes('stream closed before response.completed')));
684
+ }
685
+ function providerHttpStatus(facts) {
686
+ const raw = facts.evidence.statusCode || firstProviderField(facts.summarySources, ['statusCode', 'status']);
687
+ const numeric = Number(raw);
688
+ return Number.isInteger(numeric) && numeric >= 100 && numeric <= 599 ? numeric : undefined;
706
689
  }
707
690
  function isTrustedCodexEdgeRejection(facts) {
708
691
  let current = facts.target;
@@ -718,25 +701,3 @@ function isTrustedCodexEdgeRejection(facts) {
718
701
  }
719
702
  return false;
720
703
  }
721
- export function errorPresentationFromClass(errorClass) {
722
- switch (errorClass) {
723
- case 'ContextLength':
724
- return { reason: 'context_overflow', message: 'Context window exceeded' };
725
- case 'Timeout':
726
- return { reason: 'timeout', message: 'Request timed out' };
727
- case 'Auth':
728
- return { reason: 'auth', message: 'Authentication failed' };
729
- case 'ProviderBilling':
730
- return { reason: 'provider_billing', message: 'Provider billing required' };
731
- case 'ProviderCapacity':
732
- return { reason: 'provider_capacity', message: 'Model service is temporarily at capacity' };
733
- case 'ProviderUnavailable':
734
- return { reason: 'provider_unavailable', message: 'Provider returned an error' };
735
- case 'RateLimit':
736
- return { reason: 'rate_limit', message: 'Rate limit exceeded' };
737
- case 'Network':
738
- return { reason: 'network', message: 'Network error' };
739
- default:
740
- return {};
741
- }
742
- }
@@ -19,7 +19,7 @@
19
19
  import { MODEL_CALL_ATTEMPT_SCHEMA_VERSION, } from '@maka/core/model-call-attempt';
20
20
  import { preparedPromptComposition } from './request-shape.js';
21
21
  import { rawFinishReasonString } from './model-protocol.js';
22
- import { providerFailureDiagnostic, } from './provider-error-classification.js';
22
+ import { providerFailureDiagnostic } from './provider-error-classification.js';
23
23
  import { latestContextProjectionInput } from './latest-context-snapshot.js';
24
24
  import { computeCost } from './telemetry/cost.js';
25
25
  /** Session-scoped construction and pricing for physical provider requests. */
@@ -149,6 +149,9 @@ export function withProviderStreamTracking(input) {
149
149
  params,
150
150
  ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),
151
151
  ...(input.historyCompactRoute ? { historyCompactRoute: input.historyCompactRoute } : {}),
152
+ ...(input.historyCompactBoundary
153
+ ? { historyCompactBoundary: input.historyCompactBoundary }
154
+ : {}),
152
155
  doStream,
153
156
  }),
154
157
  },
@@ -196,14 +199,18 @@ export class ProviderRequestTracker {
196
199
  * that call, not new calls, so they share this id.
197
200
  */
198
201
  logicalCallIdByStep = new Map();
202
+ requestCompositionIdByStep = new Map();
199
203
  constructor(input) {
200
204
  this.input = input;
201
205
  }
202
206
  get traceId() {
203
207
  return this.input.traceId;
204
208
  }
205
- setStep(step) {
209
+ setStep(step, requestCompositionId) {
206
210
  this.step = step;
211
+ if (requestCompositionId !== undefined) {
212
+ this.requestCompositionIdByStep.set(step, requestCompositionId);
213
+ }
207
214
  }
208
215
  async trackStream(input) {
209
216
  throwIfAbortedBeforeDispatch(input.abortSignal);
@@ -329,36 +336,75 @@ export class ProviderRequestTracker {
329
336
  const usage = strictProviderRequestUsage(finish?.usage);
330
337
  const contextWindow = positiveInteger(this.input.contextWindow);
331
338
  const failure = finish?.error !== undefined ? providerFailureDiagnostic(finish.error) : undefined;
332
- const record = {
333
- traceId: this.input.traceId,
334
- attemptId,
335
- turnId: this.input.turnId,
336
- step,
337
- attempt,
338
- providerId: input.providerId,
339
- modelId: input.modelId,
340
- ...(contextWindow !== undefined ? { contextWindow } : {}),
341
- startedAt,
342
- completedAt,
343
- status,
344
- ...(finish?.reason !== undefined ? { finishReason: finish.reason } : {}),
345
- ...(failure !== undefined ? { failure } : {}),
346
- latencyMs: Math.max(0, completedAt - startedAt),
347
- ...(timeToFirstTokenMs !== undefined ? { timeToFirstTokenMs } : {}),
348
- ...(usage ?? {}),
349
- };
339
+ const finishReason = finish?.reason;
340
+ const firstTokenMs = timeToFirstTokenMs;
350
341
  accountingSettlement = accountingSettlement.then(async () => {
351
- await this.emitModelCallAttempt(record, {
342
+ const accounting = this.input.accounting;
343
+ if (!accounting)
344
+ return;
345
+ const runId = accounting.resolveRunId();
346
+ if (runId === undefined)
347
+ return;
348
+ const usageBasis = resolveUsageBasis(usage);
349
+ const cost = usage ? accounting.resolveCost?.(usage) : undefined;
350
+ const priced = cost?.costUsd !== undefined;
351
+ const record = {
352
+ schemaVersion: MODEL_CALL_ATTEMPT_SCHEMA_VERSION,
352
353
  logicalCallId,
353
- usage,
354
- contextWindow,
355
- promptComposition: composition,
356
- // Frozen when THIS request was prepared, so a checkpoint published
357
- // mid-flight by another turn cannot be sealed into a prompt built
358
- // before it existed.
359
- historyCompactBoundary: input.historyCompactBoundary,
360
- historyCompactRoute: input.historyCompactRoute ?? this.input.accounting?.historyCompactRoute,
361
- });
354
+ attemptId,
355
+ traceId: this.input.traceId,
356
+ sessionId: accounting.sessionId,
357
+ runId,
358
+ turnId: this.input.turnId,
359
+ ...(accounting.connectionSlug !== undefined
360
+ ? { connectionSlug: accounting.connectionSlug }
361
+ : {}),
362
+ step: Math.max(0, step),
363
+ ...(this.requestCompositionIdByStep.get(step)
364
+ ? { requestCompositionId: this.requestCompositionIdByStep.get(step) }
365
+ : {}),
366
+ attempt: Math.max(0, attempt - 1),
367
+ callKind: accounting.callKind,
368
+ ...((input.historyCompactRoute ?? accounting.historyCompactRoute) !== undefined
369
+ ? { historyCompactRoute: input.historyCompactRoute ?? accounting.historyCompactRoute }
370
+ : {}),
371
+ providerId: accounting.providerId ?? input.providerId,
372
+ modelId: input.modelId,
373
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
374
+ ...(composition ? { promptComposition: composition } : {}),
375
+ startedAt,
376
+ completedAt,
377
+ latencyMs: Math.max(0, completedAt - startedAt),
378
+ ...(firstTokenMs !== undefined ? { timeToFirstTokenMs: firstTokenMs } : {}),
379
+ status,
380
+ ...(finishReason !== undefined ? { finishReason } : {}),
381
+ ...(failure ?? {}),
382
+ usageBasis,
383
+ ...(usageBasis === 'missing' ? {} : modelCallUsageFields(usage)),
384
+ costBasis: priced ? 'priced' : 'unpriced',
385
+ ...(priced
386
+ ? {
387
+ costUsd: cost?.costUsd,
388
+ ...(cost?.pricingRevision !== undefined
389
+ ? { pricingRevision: cost.pricingRevision }
390
+ : {}),
391
+ ...(cost?.pricingRates !== undefined ? { pricingRates: cost.pricingRates } : {}),
392
+ }
393
+ : {}),
394
+ };
395
+ // Only a completed MAIN call describes the conversation's own context, so
396
+ // only that one carries the derived row. A failed, aborted or compaction
397
+ // call commits its metering alone and leaves the last answer standing.
398
+ const latestContext = record.callKind === 'main' && record.status === 'completed'
399
+ ? latestContextProjectionInput(record, record.promptComposition, input.historyCompactBoundary)
400
+ : undefined;
401
+ try {
402
+ await accounting.record({ attempt: record, ...(latestContext ? { latestContext } : {}) });
403
+ }
404
+ catch {
405
+ // Reported through the run's accounting-incomplete signal by the sink
406
+ // itself. Settlement must not fail the turn the call already completed.
407
+ }
362
408
  });
363
409
  await accountingSettlement;
364
410
  };
@@ -380,85 +426,6 @@ export class ProviderRequestTracker {
380
426
  }
381
427
  return { observeOutput, finalize };
382
428
  }
383
- /**
384
- * Projects a settled attempt into the canonical accounting record.
385
- *
386
- * Never throws. This runs from the stream's `pull` handler, where a rejection
387
- * would reach `controller.error` and fail an otherwise-complete model
388
- * response. The dispatch-time gate is `assertAccountingReady`; a failure here
389
- * means the call happened and was billed but went unrecorded, which is
390
- * reported, not raised.
391
- */
392
- async emitModelCallAttempt(record, context) {
393
- const accounting = this.input.accounting;
394
- if (!accounting)
395
- return;
396
- const runId = accounting.resolveRunId();
397
- if (runId === undefined)
398
- return;
399
- const usage = context.usage;
400
- const usageBasis = resolveUsageBasis(usage);
401
- const cost = usage ? accounting.resolveCost?.(usage) : undefined;
402
- const priced = cost?.costUsd !== undefined;
403
- const attempt = {
404
- schemaVersion: MODEL_CALL_ATTEMPT_SCHEMA_VERSION,
405
- logicalCallId: context.logicalCallId,
406
- attemptId: record.attemptId,
407
- traceId: record.traceId,
408
- sessionId: accounting.sessionId,
409
- runId,
410
- turnId: record.turnId,
411
- ...(accounting.connectionSlug !== undefined
412
- ? { connectionSlug: accounting.connectionSlug }
413
- : {}),
414
- // The physical ordinals are one-based on the diagnostic record; the
415
- // canonical record counts retries from zero.
416
- step: Math.max(0, record.step),
417
- attempt: Math.max(0, record.attempt - 1),
418
- callKind: accounting.callKind,
419
- ...(context.historyCompactRoute !== undefined
420
- ? { historyCompactRoute: context.historyCompactRoute }
421
- : {}),
422
- providerId: accounting.providerId ?? record.providerId,
423
- modelId: record.modelId,
424
- ...(context.contextWindow !== undefined ? { contextWindow: context.contextWindow } : {}),
425
- ...(context.promptComposition ? { promptComposition: context.promptComposition } : {}),
426
- startedAt: record.startedAt,
427
- completedAt: record.completedAt,
428
- latencyMs: record.latencyMs,
429
- ...(record.timeToFirstTokenMs !== undefined
430
- ? { timeToFirstTokenMs: record.timeToFirstTokenMs }
431
- : {}),
432
- status: record.status,
433
- ...(record.finishReason !== undefined ? { finishReason: record.finishReason } : {}),
434
- ...(record.failure ?? {}),
435
- usageBasis,
436
- ...(usageBasis === 'missing' ? {} : modelCallUsageFields(usage)),
437
- costBasis: priced ? 'priced' : 'unpriced',
438
- ...(priced
439
- ? {
440
- costUsd: cost?.costUsd,
441
- ...(cost?.pricingRevision !== undefined
442
- ? { pricingRevision: cost.pricingRevision }
443
- : {}),
444
- ...(cost?.pricingRates !== undefined ? { pricingRates: cost.pricingRates } : {}),
445
- }
446
- : {}),
447
- };
448
- // Only a completed MAIN call describes the conversation's own context, so
449
- // only that one carries the derived row. A failed, aborted or compaction
450
- // call commits its metering alone and leaves the last answer standing.
451
- const latestContext = attempt.callKind === 'main' && attempt.status === 'completed'
452
- ? latestContextProjectionInput(attempt, attempt.promptComposition, context.historyCompactBoundary)
453
- : undefined;
454
- try {
455
- await accounting.record({ attempt, ...(latestContext ? { latestContext } : {}) });
456
- }
457
- catch {
458
- // Reported through the run's accounting-incomplete signal by the sink
459
- // itself. Settlement must not fail the turn the call already completed.
460
- }
461
- }
462
429
  }
463
430
  function throwIfAbortedBeforeDispatch(signal) {
464
431
  if (signal?.aborted) {
@@ -152,6 +152,29 @@ export function toolCatalogHash(tools) {
152
152
  .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
153
153
  .map(toolShapeForDiagnostics));
154
154
  }
155
+ /** Canonical, JSON-safe schemas for the exact provider-visible tool subset. */
156
+ export function requestCompositionToolSchemas(tools, activeToolNames) {
157
+ const active = new Set(activeToolNames);
158
+ return tools
159
+ .filter((tool) => active.has(tool.name))
160
+ .map((tool) => {
161
+ const inputSchema = JSON.parse(stableStringify(schemaShapeForHash(tool.parameters)));
162
+ if (!isPlainObject(inputSchema)) {
163
+ throw new Error(`Tool ${JSON.stringify(tool.name)} produced a non-object input schema`);
164
+ }
165
+ return {
166
+ name: tool.name,
167
+ description: tool.description,
168
+ inputSchema,
169
+ ...(tool.providerTool
170
+ ? {
171
+ providerTool: JSON.parse(stableStringify(tool.providerTool)),
172
+ }
173
+ : {}),
174
+ };
175
+ })
176
+ .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
177
+ }
155
178
  export function stableStringify(value) {
156
179
  return JSON.stringify(canonicalize(value));
157
180
  }