stitchkit 0.118.1 → 0.120.0

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 (180) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +10 -7
  3. package/dist/browser/http.d.ts.map +1 -1
  4. package/dist/contract/client-types.d.ts +6 -3
  5. package/dist/contract/client-types.d.ts.map +1 -1
  6. package/dist/contract/define-validation.d.ts.map +1 -1
  7. package/dist/contract/define.d.ts +18 -12
  8. package/dist/contract/define.d.ts.map +1 -1
  9. package/dist/contract/endpoint-capabilities.d.ts +28 -0
  10. package/dist/contract/endpoint-capabilities.d.ts.map +1 -0
  11. package/dist/contract/factory.d.ts +49 -19
  12. package/dist/contract/factory.d.ts.map +1 -1
  13. package/dist/contract/tool-view.d.ts +1 -1
  14. package/dist/contract/tool-view.d.ts.map +1 -1
  15. package/dist/contract/transports.d.ts +5 -0
  16. package/dist/contract/transports.d.ts.map +1 -0
  17. package/dist/entrypoints/agent-runtime/coding-tools.js +9 -8
  18. package/dist/entrypoints/agent-runtime/harness.js +9 -8
  19. package/dist/entrypoints/agent-runtime/realtime.js +3 -3
  20. package/dist/entrypoints/agent-runtime/sandbox.js +10 -9
  21. package/dist/entrypoints/agent-runtime/sqlite/bun.js +12 -11
  22. package/dist/entrypoints/agent-runtime/sqlite/node.js +12 -11
  23. package/dist/entrypoints/agent-runtime/testing.js +12 -11
  24. package/dist/entrypoints/agent-runtime.js +22 -19
  25. package/dist/entrypoints/application/diagnostic-journal.js +3 -3
  26. package/dist/entrypoints/application/directory-inbox.js +4 -4
  27. package/dist/entrypoints/application/opentelemetry.js +1 -1
  28. package/dist/entrypoints/application.js +10 -10
  29. package/dist/entrypoints/cli/publish.js +4 -4
  30. package/dist/entrypoints/cli.js +13 -12
  31. package/dist/entrypoints/contract.d.ts +1 -1
  32. package/dist/entrypoints/contract.d.ts.map +1 -1
  33. package/dist/entrypoints/contract.js +6 -4
  34. package/dist/entrypoints/files.js +3 -3
  35. package/dist/entrypoints/geo/contract.d.ts +7 -0
  36. package/dist/entrypoints/geo/contract.d.ts.map +1 -0
  37. package/dist/entrypoints/geo/contract.js +6 -0
  38. package/dist/entrypoints/geo.js +60 -23
  39. package/dist/entrypoints/http.js +3 -3
  40. package/dist/entrypoints/index.js +9 -7
  41. package/dist/entrypoints/live.js +1 -1
  42. package/dist/entrypoints/node.js +7 -6
  43. package/dist/entrypoints/primitives.js +1 -1
  44. package/dist/entrypoints/process/owner-loss.js +1 -1
  45. package/dist/entrypoints/process.js +3 -3
  46. package/dist/entrypoints/react.js +1 -1
  47. package/dist/entrypoints/remote.js +4 -3
  48. package/dist/entrypoints/server.js +16 -15
  49. package/dist/entrypoints/telegram/screens.js +5 -5
  50. package/dist/entrypoints/telegram.js +7 -7
  51. package/dist/entrypoints/testing.js +7 -6
  52. package/dist/entrypoints/tools/agent.d.ts +9 -0
  53. package/dist/entrypoints/tools/agent.d.ts.map +1 -0
  54. package/dist/entrypoints/tools/agent.js +16 -0
  55. package/dist/entrypoints/tools/connections.js +7 -6
  56. package/dist/entrypoints/tools/contract.js +1 -1
  57. package/dist/entrypoints/tools/invoker.js +5 -4
  58. package/dist/entrypoints/tools/mcp.js +110 -9
  59. package/dist/entrypoints/tools/toolkit.d.ts +9 -0
  60. package/dist/entrypoints/tools/toolkit.d.ts.map +1 -0
  61. package/dist/entrypoints/tools/toolkit.js +40 -0
  62. package/dist/entrypoints/tools.d.ts +0 -10
  63. package/dist/entrypoints/tools.d.ts.map +1 -1
  64. package/dist/entrypoints/tools.js +38 -80
  65. package/dist/entrypoints/tracking/contract.js +5 -3
  66. package/dist/entrypoints/tracking/performance.js +3 -3
  67. package/dist/entrypoints/tracking.d.ts +1 -1
  68. package/dist/entrypoints/tracking.d.ts.map +1 -1
  69. package/dist/entrypoints/tracking.js +63 -83
  70. package/dist/entrypoints/xlsx.js +1 -1
  71. package/dist/geo/index.d.ts +2 -1
  72. package/dist/geo/index.d.ts.map +1 -1
  73. package/dist/geo/record.d.ts +8 -0
  74. package/dist/geo/record.d.ts.map +1 -0
  75. package/dist/geo/resolver.d.ts +1 -3
  76. package/dist/geo/resolver.d.ts.map +1 -1
  77. package/dist/geo/schema.d.ts +44 -0
  78. package/dist/geo/schema.d.ts.map +1 -0
  79. package/dist/geo/types.d.ts +2 -13
  80. package/dist/geo/types.d.ts.map +1 -1
  81. package/dist/{index-n5sv4z0w.js → index-0qyrcjfs.js} +16 -18
  82. package/dist/index-1psbyyhj.js +21 -0
  83. package/dist/{index-tsngj2b5.js → index-2fc1k9k2.js} +206 -206
  84. package/dist/index-3prvb42w.js +30 -0
  85. package/dist/{index-073nw9qr.js → index-3yb5kft5.js} +524 -522
  86. package/dist/{index-d9hq291n.js → index-4jpykzvw.js} +70 -81
  87. package/dist/index-568w258r.js +76 -0
  88. package/dist/index-69t14s4a.js +39 -0
  89. package/dist/{index-dky0dcmf.js → index-72r9k0av.js} +6 -2
  90. package/dist/{index-6p3frkv5.js → index-7zwtbak8.js} +9 -50
  91. package/dist/{index-90p34rts.js → index-8ryydawp.js} +7 -5
  92. package/dist/{index-vv1sch8a.js → index-8vzh5wpv.js} +13 -8
  93. package/dist/{index-75ns2ybj.js → index-8xyf8h2k.js} +1 -1
  94. package/dist/{index-xx1j310k.js → index-8yxgcyt6.js} +171 -169
  95. package/dist/{index-p6apg0jg.js → index-9frf01t9.js} +16 -9
  96. package/dist/{index-q0th8q0z.js → index-9mjrnqxs.js} +1 -3
  97. package/dist/{index-6f49krb5.js → index-aa50qwv4.js} +1 -1
  98. package/dist/{index-ega3yz4c.js → index-aqwg2dm5.js} +1 -1
  99. package/dist/{index-p0rf7sq9.js → index-bgcwxhxh.js} +225 -223
  100. package/dist/index-bph35vpy.js +77 -0
  101. package/dist/{index-tdpmfks8.js → index-bz479f0x.js} +1 -1
  102. package/dist/index-d3xdyjt6.js +38 -0
  103. package/dist/{index-q968hy6y.js → index-e452syyh.js} +1 -1
  104. package/dist/{index-86nbfysb.js → index-ff39f9dr.js} +3 -3
  105. package/dist/index-h1j71dr1.js +48 -0
  106. package/dist/{index-mgb7r8b8.js → index-jswst0h3.js} +1 -1
  107. package/dist/{index-095ya5hm.js → index-knmnj11j.js} +22 -191
  108. package/dist/{index-vwhrnp67.js → index-kz9734jc.js} +3 -3
  109. package/dist/{index-txg1npmg.js → index-mtwh9hyp.js} +1 -1
  110. package/dist/{index-dr3t5n1v.js → index-nn9qvkww.js} +46 -46
  111. package/dist/{index-ghtpfz4z.js → index-nyyam9ce.js} +2 -2
  112. package/dist/{index-qezhmp51.js → index-nz06qw5a.js} +3 -1
  113. package/dist/{index-1bx1xv1k.js → index-pfvde2fz.js} +5 -2
  114. package/dist/{index-w7jq3fz9.js → index-pq2m7t46.js} +1142 -1212
  115. package/dist/{index-yk4g8805.js → index-pq7rkwkk.js} +1 -30
  116. package/dist/{index-s80awwsw.js → index-qch1vcaa.js} +3 -1
  117. package/dist/{index-hdjmdwsj.js → index-qctbzmg9.js} +521 -511
  118. package/dist/{index-n8z3rvzw.js → index-qevqn3d3.js} +3 -5
  119. package/dist/{index-nqxrm176.js → index-r3db01kh.js} +1 -1
  120. package/dist/{index-v6vb5qx8.js → index-s3yxw6kt.js} +1 -1
  121. package/dist/{index-cqmqyjax.js → index-sa99p98w.js} +1 -1
  122. package/dist/index-sb9dr3tq.js +14 -0
  123. package/dist/{index-0gxvns6s.js → index-sba3e6m4.js} +1 -0
  124. package/dist/{index-f24bdt13.js → index-v1swr26p.js} +3 -1
  125. package/dist/{index-rhzkndr5.js → index-x4p3kw1p.js} +533 -530
  126. package/dist/{index-cycp3r3e.js → index-yb9n4pgj.js} +2 -2
  127. package/dist/{index-htxh46ej.js → index-ycqhyars.js} +2 -2
  128. package/dist/{index-9bwcthxw.js → index-yj6saztf.js} +31 -13
  129. package/dist/{index-f6m4c545.js → index-zrdcmg6j.js} +4 -6
  130. package/dist/{index-tvtacc9a.js → index-zyc64nbh.js} +1 -34
  131. package/dist/process/bun-child.d.ts +3 -2
  132. package/dist/process/bun-child.d.ts.map +1 -1
  133. package/dist/server/contract-method.d.ts.map +1 -1
  134. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  135. package/dist/tools/operations/async-operation-canonical-types.d.ts +1 -1
  136. package/dist/tracking/attribution.d.ts +21 -25
  137. package/dist/tracking/attribution.d.ts.map +1 -1
  138. package/dist/tracking/client-visit.d.ts +5 -7
  139. package/dist/tracking/client-visit.d.ts.map +1 -1
  140. package/dist/tracking/client.d.ts +2 -2
  141. package/dist/tracking/client.d.ts.map +1 -1
  142. package/dist/tracking/contract.d.ts +1 -1
  143. package/dist/tracking/host.d.ts +0 -1
  144. package/dist/tracking/host.d.ts.map +1 -1
  145. package/dist/tracking/privacy.d.ts +6 -0
  146. package/dist/tracking/privacy.d.ts.map +1 -1
  147. package/dist/tracking/schemas.d.ts +2 -2
  148. package/dist/tracking/schemas.d.ts.map +1 -1
  149. package/llms/agent-runtime-harness.txt +4 -3
  150. package/llms/agent-runtime-sandbox.txt +1 -1
  151. package/llms/agent-runtime.2.txt +3 -2
  152. package/llms/agent-runtime.3.txt +4 -46
  153. package/llms/agent-runtime.4.txt +113 -0
  154. package/llms/agent-runtime.txt +11 -13
  155. package/llms/cli.txt +1 -1
  156. package/llms/contract.txt +46 -24
  157. package/llms/geo-contract.txt +23 -0
  158. package/llms/geo.txt +40 -4
  159. package/llms/stitchkit.txt +16 -9
  160. package/llms/testing.txt +4 -6
  161. package/llms/tools-agent.txt +24 -0
  162. package/llms/tools-mcp.txt +71 -6
  163. package/llms/tools-toolkit.txt +23 -0
  164. package/llms/tools.2.txt +8 -5
  165. package/llms/tools.3.txt +9 -78
  166. package/llms/tools.txt +8 -8
  167. package/llms/tracking-contract.txt +1 -1
  168. package/llms/tracking.txt +27 -5
  169. package/llms/{upgrading-0.105.0-0.118.0.txt → upgrading-0.106.0-0.120.0.txt} +152 -410
  170. package/llms/upgrading-0.37.0-0.53.0.txt +969 -0
  171. package/llms/{upgrading-0.44.0-0.62.0.txt → upgrading-0.55.0-0.68.0.txt} +509 -528
  172. package/llms/{upgrading-0.63.0-0.83.0.txt → upgrading-0.69.0-0.95.0.txt} +506 -509
  173. package/llms/{upgrading-0.84.0-0.104.0.txt → upgrading-0.96.0-0.105.0.txt} +410 -506
  174. package/llms/upgrading.txt +5 -5
  175. package/llms-full.txt +475 -154
  176. package/llms.txt +17 -14
  177. package/package.json +32 -20
  178. package/llms/upgrading-0.37.0-0.44.0.txt +0 -444
  179. package/dist/{index-arjmb6de.js → index-1jwsfkfz.js} +0 -0
  180. package/dist/{index-qndsr7f0.js → index-5efrpfmj.js} +3 -3
@@ -14,15 +14,13 @@ import {
14
14
  import {
15
15
  ToolExecutionControlError2,
16
16
  isToolExecutionControlError2
17
- } from "./index-v6vb5qx8.js";
17
+ } from "./index-s3yxw6kt.js";
18
18
  import {
19
19
  agentDurableEventId2
20
20
  } from "./index-mnkk1ffz.js";
21
21
  import {
22
- createLocalStepDurability2,
23
- isAgentToolError2,
24
- createToolDurabilityContext
25
- } from "./index-tvtacc9a.js";
22
+ createLocalStepDurability2
23
+ } from "./index-zyc64nbh.js";
26
24
  import {
27
25
  canonicalAgentJson2,
28
26
  createToolChronology,
@@ -35,13 +33,19 @@ import {
35
33
  ProviderJournalRequestSchema,
36
34
  ProviderJournalResponseSchema,
37
35
  isActiveRunState
38
- } from "./index-xx1j310k.js";
36
+ } from "./index-8yxgcyt6.js";
39
37
  import {
40
38
  messageOf
41
39
  } from "./index-g149e9pk.js";
40
+ import {
41
+ createToolDurabilityContext
42
+ } from "./index-sb9dr3tq.js";
42
43
  import {
43
44
  createMutationQueue
44
45
  } from "./index-sykb5ag7.js";
46
+ import {
47
+ isAgentToolError2
48
+ } from "./index-1psbyyhj.js";
45
49
  import {
46
50
  assertPositiveSafeInteger
47
51
  } from "./index-0s4xebbg.js";
@@ -53,6 +57,9 @@ import {
53
57
  transportResult
54
58
  } from "./index-9jfdm5tg.js";
55
59
 
60
+ // src/agent-runtime/runtime-internals.ts
61
+ import { z } from "zod";
62
+
56
63
  // src/agent-runtime/run-store-retry.ts
57
64
  var STORE_RETRY_DELAYS_MS = [25, 100, 400];
58
65
  function storeRetryDelay(failures) {
@@ -249,6 +256,187 @@ async function commitAgentRunTerminal(input) {
249
256
  throw new AgentRuntimeConflictError2("terminal commit");
250
257
  }
251
258
 
259
+ // src/agent-runtime/runtime-internals.ts
260
+ function findRun(runs, runId) {
261
+ const run = runs.find((candidate) => candidate.id === runId);
262
+ if (!run)
263
+ throw new AgentRuntimeConflictError2("run lookup");
264
+ return run;
265
+ }
266
+ function jsonValue(value) {
267
+ const parsed = z.json().safeParse(value);
268
+ return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
269
+ }
270
+ function providerEnvelope(value) {
271
+ const parsed = AgentJsonObjectSchema2.safeParse(value);
272
+ if (!parsed.success)
273
+ return;
274
+ return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
275
+ }
276
+ function providerResponseIdentity(id, provider) {
277
+ return AgentProviderResponseSchema2.parse({
278
+ id,
279
+ ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
280
+ });
281
+ }
282
+ function appendText(parts, text) {
283
+ const previous = parts.at(-1);
284
+ if (previous?.type === "text") {
285
+ const next = AgentMessagePartSchema2.parse({ ...previous, text: previous.text + text });
286
+ parts.splice(parts.length - 1, 1, next);
287
+ return;
288
+ }
289
+ parts.push(AgentMessagePartSchema2.parse({ type: "text", text }));
290
+ }
291
+ function abortTerminalReason(signal) {
292
+ if (signal.reason === "shutdown")
293
+ return "shutdown";
294
+ if (signal.reason === "timeout")
295
+ return "timeout";
296
+ if (signal.reason === "supersede")
297
+ return "superseded";
298
+ return "interrupted";
299
+ }
300
+ function addUsage(total, step) {
301
+ const sum = (left, right) => {
302
+ if (left?.value === undefined && right?.value === undefined) {
303
+ return { provenance: "unavailable" };
304
+ }
305
+ if (left?.value === undefined)
306
+ return { ...right, provenance: "computed" };
307
+ if (right?.value === undefined)
308
+ return { ...left, provenance: "computed" };
309
+ return { value: left.value + right.value, provenance: "computed" };
310
+ };
311
+ const sumCost = (left, right) => {
312
+ if (left?.value === undefined || right?.value === undefined) {
313
+ return { provenance: "unavailable" };
314
+ }
315
+ if (left.currency !== right.currency)
316
+ return { provenance: "unavailable" };
317
+ return {
318
+ value: left.value + right.value,
319
+ ...left.currency && { currency: left.currency },
320
+ provenance: "computed"
321
+ };
322
+ };
323
+ if (!total)
324
+ return step;
325
+ const cost = sumCost(total.cost, step.cost);
326
+ return {
327
+ inputTokens: sum(total.inputTokens, step.inputTokens),
328
+ outputTokens: sum(total.outputTokens, step.outputTokens),
329
+ reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
330
+ cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
331
+ cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
332
+ ...cost && { cost }
333
+ };
334
+ }
335
+ function mergeModelTotals(sdkTotal, accumulated) {
336
+ const pick = (total, ours) => {
337
+ if (ours?.provenance === "unavailable")
338
+ return ours;
339
+ return total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
340
+ };
341
+ return {
342
+ inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
343
+ outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
344
+ reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
345
+ cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
346
+ cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
347
+ cost: accumulated?.cost ?? { provenance: "unavailable" }
348
+ };
349
+ }
350
+ function statedUsage(usage) {
351
+ const stated = (value) => value ?? { provenance: "unavailable" };
352
+ if (!usage)
353
+ return unknownUsage();
354
+ return {
355
+ inputTokens: stated(usage.inputTokens),
356
+ outputTokens: stated(usage.outputTokens),
357
+ reasoningTokens: stated(usage.reasoningTokens),
358
+ cacheReadTokens: stated(usage.cacheReadTokens),
359
+ cacheWriteTokens: stated(usage.cacheWriteTokens),
360
+ cost: stated(usage.cost)
361
+ };
362
+ }
363
+ function unknownUsage() {
364
+ const nothing = { provenance: "unavailable" };
365
+ return {
366
+ inputTokens: nothing,
367
+ outputTokens: nothing,
368
+ reasoningTokens: nothing,
369
+ cacheReadTokens: nothing,
370
+ cacheWriteTokens: nothing,
371
+ cost: nothing
372
+ };
373
+ }
374
+ function normalizeSdkUsage(value) {
375
+ const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
376
+ return {
377
+ inputTokens: reported(value.inputTokens),
378
+ outputTokens: reported(value.outputTokens),
379
+ reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
380
+ cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
381
+ cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
382
+ };
383
+ }
384
+ function createIdleDeadline(parent, timeoutMs) {
385
+ if (timeoutMs === undefined) {
386
+ const noop = () => {
387
+ return;
388
+ };
389
+ return {
390
+ signal: parent,
391
+ touch: noop,
392
+ start: noop,
393
+ stop: noop,
394
+ suspend: noop,
395
+ resume: noop,
396
+ dispose: noop
397
+ };
398
+ }
399
+ const controller = new AbortController;
400
+ let timer;
401
+ let active = false;
402
+ let suspended = 0;
403
+ const clear = () => {
404
+ if (timer !== undefined)
405
+ clearTimeout(timer);
406
+ timer = undefined;
407
+ };
408
+ const touch = () => {
409
+ clear();
410
+ if (!active || suspended > 0 || controller.signal.aborted)
411
+ return;
412
+ timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
413
+ };
414
+ return {
415
+ signal: AbortSignal.any([parent, controller.signal]),
416
+ touch,
417
+ start() {
418
+ active = true;
419
+ touch();
420
+ },
421
+ stop() {
422
+ active = false;
423
+ clear();
424
+ },
425
+ suspend() {
426
+ suspended += 1;
427
+ clear();
428
+ },
429
+ resume() {
430
+ suspended = Math.max(0, suspended - 1);
431
+ touch();
432
+ },
433
+ dispose() {
434
+ active = false;
435
+ clear();
436
+ }
437
+ };
438
+ }
439
+
252
440
  // src/agent-runtime/context-refusal.ts
253
441
  class AgentContextOverflowError2 extends Error {
254
442
  name = "AgentContextOverflowError";
@@ -400,6 +588,32 @@ function createAgentSessionCoordinator2() {
400
588
  };
401
589
  }
402
590
 
591
+ // src/agent-runtime/deferred-tools-internal.ts
592
+ var repairs = new WeakMap;
593
+ var catalogs = new WeakMap;
594
+ function registerDeferredToolRepair(prepareStep, repair) {
595
+ repairs.set(prepareStep, repair);
596
+ }
597
+ function deferredToolRepair(prepareStep) {
598
+ return prepareStep ? repairs.get(prepareStep) : undefined;
599
+ }
600
+ function registerDeferredToolCatalog(tools, searchName, names) {
601
+ const search = tools[searchName];
602
+ if (search && typeof search === "object")
603
+ catalogs.set(search, names);
604
+ }
605
+ function deferredToolCatalog(tools, searchName) {
606
+ const search = tools[searchName];
607
+ return search && typeof search === "object" ? catalogs.get(search) : undefined;
608
+ }
609
+ function repairedSearchCall(toolCall, searchName) {
610
+ return {
611
+ ...toolCall,
612
+ toolName: searchName,
613
+ input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
614
+ };
615
+ }
616
+
403
617
  // src/agent-runtime/history.ts
404
618
  import { modelMessageSchema as modelMessageSchema2 } from "ai";
405
619
 
@@ -669,90 +883,120 @@ async function projectAgentHistory2(messages, options = {}) {
669
883
  return [...(await projectAgentHistoryDetailed2(messages, options)).messages];
670
884
  }
671
885
 
886
+ // src/agent-runtime/invocation-attempt.ts
887
+ import { AsyncLocalStorage } from "node:async_hooks";
888
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
889
+ import { wrapLanguageModel } from "ai";
890
+
891
+ // src/agent-runtime/invocation-failure.ts
892
+ class InvocationReceiptError extends Error {
893
+ constructor(cause) {
894
+ super("Model invocation receipt could not be recorded", { cause });
895
+ this.name = "InvocationReceiptError";
896
+ }
897
+ }
898
+ async function invocationAudit(work) {
899
+ try {
900
+ return await work();
901
+ } catch (error) {
902
+ throw error instanceof InvocationReceiptError ? error : new InvocationReceiptError(error);
903
+ }
904
+ }
905
+
906
+ // src/agent-runtime/invocation-payload.ts
907
+ import {
908
+ createCipheriv,
909
+ createDecipheriv,
910
+ createHash,
911
+ randomBytes,
912
+ randomUUID
913
+ } from "node:crypto";
914
+ import { z as z3 } from "zod";
915
+
672
916
  // src/agent-runtime/invocation-schema.ts
673
- import { z } from "zod";
674
- var Id = z.string().min(1).max(512);
675
- var Hash = z.string().regex(/^[a-f0-9]{64}$/);
676
- var ModelInvocationTraceSchema2 = z.object({
917
+ import { z as z2 } from "zod";
918
+ var Id = z2.string().min(1).max(512);
919
+ var Hash = z2.string().regex(/^[a-f0-9]{64}$/);
920
+ var ModelInvocationTraceSchema2 = z2.object({
677
921
  operationId: Id,
678
922
  purpose: Id,
679
923
  project: Id,
680
- parent: z.object({ traceId: Id, invocationId: Id.optional() }).strict().optional(),
924
+ parent: z2.object({ traceId: Id, invocationId: Id.optional() }).strict().optional(),
681
925
  experiment: Id.optional(),
682
926
  case: Id.optional(),
683
927
  profile: Id.optional()
684
928
  }).strict();
685
- var CompletionInvocationInputSchema2 = z.object({
929
+ var CompletionInvocationInputSchema2 = z2.object({
686
930
  conversationId: Id,
687
931
  idempotencyKey: Id,
688
932
  trace: ModelInvocationTraceSchema2,
689
- prompt: z.string().min(1),
690
- models: z.array(Id).min(1).max(8),
691
- settings: z.object({
692
- maxOutputTokens: z.int().positive().optional(),
693
- temperature: z.number().finite().optional(),
694
- topP: z.number().min(0).max(1).optional(),
695
- seed: z.int().optional()
933
+ prompt: z2.string().min(1),
934
+ models: z2.array(Id).min(1).max(8),
935
+ settings: z2.object({
936
+ maxOutputTokens: z2.int().positive().optional(),
937
+ temperature: z2.number().finite().optional(),
938
+ topP: z2.number().min(0).max(1).optional(),
939
+ seed: z2.int().optional()
696
940
  }).strict().optional(),
697
- timeoutMs: z.int().positive().max(3600000)
941
+ timeoutMs: z2.int().positive().max(3600000)
698
942
  }).strict();
699
- var Identity = z.object({
943
+ var Identity = z2.object({
700
944
  provider: Id.nullable(),
701
945
  modelId: Id.nullable(),
702
946
  responseId: Id.nullable()
703
947
  }).strict();
704
- var InvocationCallerSchema = z.object({ subject: Id }).strict();
705
- var InvocationProcessSchema = z.object({
948
+ var InvocationCallerSchema = z2.object({ subject: Id }).strict();
949
+ var InvocationProcessSchema = z2.object({
706
950
  instanceId: Id,
707
- pid: z.int().positive(),
951
+ pid: z2.int().positive(),
708
952
  hostname: Id
709
953
  }).strict();
710
- var Base = z.object({
954
+ var Base = z2.object({
711
955
  conversationId: Id,
712
956
  invocationId: Id,
713
957
  operationId: Id,
714
958
  runId: Id.optional()
715
959
  });
716
960
  var InvocationStartedSchema = Base.extend({
717
- type: z.literal("invocation/started"),
718
- mode: z.enum(["completion", "agent"]),
961
+ type: z2.literal("invocation/started"),
962
+ mode: z2.enum(["completion", "agent"]),
719
963
  trace: ModelInvocationTraceSchema2,
720
964
  caller: InvocationCallerSchema,
721
965
  executingProcess: InvocationProcessSchema,
722
966
  fingerprint: Hash,
723
- requested: z.object({ models: z.array(Id), payloadSha256: Hash }).strict()
967
+ requested: z2.object({ models: z2.array(Id), payloadSha256: Hash }).strict()
724
968
  }).strict();
725
969
  var InvocationAttemptContextSchema = Base.extend({
726
970
  attemptId: Id,
727
- step: z.int().nonnegative()
971
+ step: z2.int().nonnegative()
728
972
  }).strict();
729
- var Attempt = Base.extend({ attemptId: Id, step: z.int().nonnegative() });
973
+ var Attempt = Base.extend({ attemptId: Id, step: z2.int().nonnegative() });
730
974
  var InvocationRequestSchema = Attempt.extend({
731
- type: z.literal("provider/request"),
732
- requested: z.object({ modelId: Id, provider: Id }).strict(),
975
+ type: z2.literal("provider/request"),
976
+ requested: z2.object({ modelId: Id, provider: Id }).strict(),
733
977
  executingProcess: InvocationProcessSchema,
734
- sent: z.object({
978
+ sent: z2.object({
735
979
  modelId: Id,
736
980
  provider: Id,
737
981
  payloadSha256: Hash,
738
982
  artifactId: Id,
739
- tools: z.int().nonnegative()
983
+ tools: z2.int().nonnegative()
740
984
  }).strict()
741
985
  }).strict();
742
986
  var InvocationResponseSchema = Attempt.extend({
743
- type: z.literal("provider/response"),
744
- status: z.enum(["succeeded", "failed", "cancelled"]),
987
+ type: z2.literal("provider/response"),
988
+ status: z2.enum(["succeeded", "failed", "cancelled"]),
745
989
  effective: Identity,
746
990
  usage: AgentUsageSchema2,
747
991
  artifactId: Id,
748
992
  payloadSha256: Hash
749
993
  }).strict();
750
994
  var InvocationFinishedSchema = Base.extend({
751
- type: z.literal("invocation/finished"),
752
- failure: z.object({ artifactId: Id, payloadSha256: Hash }).strict().optional(),
753
- status: z.enum(["succeeded", "failed", "cancelled"])
995
+ type: z2.literal("invocation/finished"),
996
+ failure: z2.object({ artifactId: Id, payloadSha256: Hash }).strict().optional(),
997
+ status: z2.enum(["succeeded", "failed", "cancelled"])
754
998
  }).strict();
755
- var ModelInvocationRecordSchema2 = z.discriminatedUnion("type", [
999
+ var ModelInvocationRecordSchema2 = z2.discriminatedUnion("type", [
756
1000
  InvocationStartedSchema,
757
1001
  InvocationRequestSchema,
758
1002
  InvocationResponseSchema,
@@ -761,44 +1005,16 @@ var ModelInvocationRecordSchema2 = z.discriminatedUnion("type", [
761
1005
  var InvocationPayloadSchema = Base.extend({
762
1006
  artifactId: Id,
763
1007
  sha256: Hash,
764
- bytes: z.int().nonnegative(),
765
- iv: z.string(),
766
- tag: z.string(),
767
- ciphertext: z.string()
1008
+ bytes: z2.int().nonnegative(),
1009
+ iv: z2.string(),
1010
+ tag: z2.string(),
1011
+ ciphertext: z2.string()
768
1012
  }).strict();
769
1013
 
770
- // src/agent-runtime/invocation-attempt.ts
771
- import { AsyncLocalStorage } from "node:async_hooks";
772
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
773
- import { wrapLanguageModel } from "ai";
774
-
775
- // src/agent-runtime/invocation-failure.ts
776
- class InvocationReceiptError extends Error {
777
- constructor(cause) {
778
- super("Model invocation receipt could not be recorded", { cause });
779
- this.name = "InvocationReceiptError";
780
- }
781
- }
782
- async function invocationAudit(work) {
783
- try {
784
- return await work();
785
- } catch (error) {
786
- throw error instanceof InvocationReceiptError ? error : new InvocationReceiptError(error);
787
- }
788
- }
789
-
790
1014
  // src/agent-runtime/invocation-payload.ts
791
- import {
792
- createCipheriv,
793
- createDecipheriv,
794
- createHash,
795
- randomBytes,
796
- randomUUID
797
- } from "node:crypto";
798
- import { z as z2 } from "zod";
799
1015
  function invocationJson(value) {
800
1016
  const errors = new WeakSet;
801
- return z2.json().parse(JSON.parse(JSON.stringify(value, (_key, item) => {
1017
+ return z3.json().parse(JSON.parse(JSON.stringify(value, (_key, item) => {
802
1018
  if (item instanceof Uint8Array)
803
1019
  return { base64: Buffer.from(item).toString("base64") };
804
1020
  if (item instanceof ArrayBuffer)
@@ -842,253 +1058,71 @@ function createInvocationPayloads(store, key, maxBytes) {
842
1058
  artifactId,
843
1059
  sha256,
844
1060
  bytes: data.byteLength,
845
- iv: iv.toString("base64"),
846
- tag: cipher.getAuthTag().toString("base64"),
847
- ciphertext: ciphertext.toString("base64")
848
- }
849
- }, artifactId);
850
- return { artifactId, sha256 };
851
- },
852
- decrypt(conversationId, value) {
853
- const payload = InvocationPayloadSchema.parse(value);
854
- if (payload.bytes > maxBytes || payload.ciphertext.length > Math.ceil(maxBytes / 3) * 4) {
855
- throw new RangeError("Invocation payload exceeds maxPayloadBytes");
856
- }
857
- const decipher = createDecipheriv("aes-256-gcm", encryptionKey, Buffer.from(payload.iv, "base64"));
858
- decipher.setAAD(Buffer.from(JSON.stringify([conversationId, payload.invocationId, payload.artifactId])));
859
- decipher.setAuthTag(Buffer.from(payload.tag, "base64"));
860
- const data = Buffer.concat([
861
- decipher.update(Buffer.from(payload.ciphertext, "base64")),
862
- decipher.final()
863
- ]);
864
- if (data.length !== payload.bytes || createHash("sha256").update(data).digest("hex") !== payload.sha256) {
865
- throw new Error("Invocation payload integrity mismatch");
866
- }
867
- return z2.json().parse(JSON.parse(data.toString("utf8")));
868
- }
869
- };
870
- }
871
-
872
- // src/agent-runtime/provider-origin.ts
873
- import {
874
- InvalidToolApprovalError,
875
- InvalidToolApprovalSignatureError,
876
- ToolCallNotFoundForApprovalError
877
- } from "ai";
878
- var providerOrigin = new WeakSet;
879
- function isOwnInputRefusal(error) {
880
- return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
881
- }
882
- function markProviderOrigin(error) {
883
- if (typeof error === "object" && error !== null)
884
- providerOrigin.add(error);
885
- return error;
886
- }
887
- function hasProviderOrigin(error) {
888
- return typeof error === "object" && error !== null && providerOrigin.has(error);
889
- }
890
- function markProviderStream(stream) {
891
- const reader = stream.getReader();
892
- return new ReadableStream({
893
- async pull(controller) {
894
- let read;
895
- try {
896
- read = await reader.read();
897
- } catch (error) {
898
- controller.error(isOwnInputRefusal(error) ? error : markProviderOrigin(error));
899
- return;
900
- }
901
- if (read.done)
902
- controller.close();
903
- else
904
- controller.enqueue(read.value);
905
- },
906
- cancel(reason) {
907
- return reader.cancel(reason);
908
- }
909
- });
910
- }
911
-
912
- // src/agent-runtime/runtime-internals.ts
913
- import { z as z3 } from "zod";
914
- function findRun(runs, runId) {
915
- const run = runs.find((candidate) => candidate.id === runId);
916
- if (!run)
917
- throw new AgentRuntimeConflictError2("run lookup");
918
- return run;
919
- }
920
- function jsonValue(value) {
921
- const parsed = z3.json().safeParse(value);
922
- return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
923
- }
924
- function providerEnvelope(value) {
925
- const parsed = AgentJsonObjectSchema2.safeParse(value);
926
- if (!parsed.success)
927
- return;
928
- return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
929
- }
930
- function providerResponseIdentity(id, provider) {
931
- return AgentProviderResponseSchema2.parse({
932
- id,
933
- ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
934
- });
935
- }
936
- function appendText(parts, text) {
937
- const previous = parts.at(-1);
938
- if (previous?.type === "text") {
939
- const next = AgentMessagePartSchema2.parse({ ...previous, text: previous.text + text });
940
- parts.splice(parts.length - 1, 1, next);
941
- return;
942
- }
943
- parts.push(AgentMessagePartSchema2.parse({ type: "text", text }));
944
- }
945
- function abortTerminalReason(signal) {
946
- if (signal.reason === "shutdown")
947
- return "shutdown";
948
- if (signal.reason === "timeout")
949
- return "timeout";
950
- if (signal.reason === "supersede")
951
- return "superseded";
952
- return "interrupted";
953
- }
954
- function addUsage(total, step) {
955
- const sum = (left, right) => {
956
- if (left?.value === undefined && right?.value === undefined) {
957
- return { provenance: "unavailable" };
958
- }
959
- if (left?.value === undefined)
960
- return { ...right, provenance: "computed" };
961
- if (right?.value === undefined)
962
- return { ...left, provenance: "computed" };
963
- return { value: left.value + right.value, provenance: "computed" };
964
- };
965
- const sumCost = (left, right) => {
966
- if (left?.value === undefined || right?.value === undefined) {
967
- return { provenance: "unavailable" };
968
- }
969
- if (left.currency !== right.currency)
970
- return { provenance: "unavailable" };
971
- return {
972
- value: left.value + right.value,
973
- ...left.currency && { currency: left.currency },
974
- provenance: "computed"
975
- };
976
- };
977
- if (!total)
978
- return step;
979
- const cost = sumCost(total.cost, step.cost);
980
- return {
981
- inputTokens: sum(total.inputTokens, step.inputTokens),
982
- outputTokens: sum(total.outputTokens, step.outputTokens),
983
- reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
984
- cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
985
- cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
986
- ...cost && { cost }
987
- };
988
- }
989
- function mergeModelTotals(sdkTotal, accumulated) {
990
- const pick = (total, ours) => {
991
- if (ours?.provenance === "unavailable")
992
- return ours;
993
- return total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
994
- };
995
- return {
996
- inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
997
- outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
998
- reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
999
- cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
1000
- cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
1001
- cost: accumulated?.cost ?? { provenance: "unavailable" }
1061
+ iv: iv.toString("base64"),
1062
+ tag: cipher.getAuthTag().toString("base64"),
1063
+ ciphertext: ciphertext.toString("base64")
1064
+ }
1065
+ }, artifactId);
1066
+ return { artifactId, sha256 };
1067
+ },
1068
+ decrypt(conversationId, value) {
1069
+ const payload = InvocationPayloadSchema.parse(value);
1070
+ if (payload.bytes > maxBytes || payload.ciphertext.length > Math.ceil(maxBytes / 3) * 4) {
1071
+ throw new RangeError("Invocation payload exceeds maxPayloadBytes");
1072
+ }
1073
+ const decipher = createDecipheriv("aes-256-gcm", encryptionKey, Buffer.from(payload.iv, "base64"));
1074
+ decipher.setAAD(Buffer.from(JSON.stringify([conversationId, payload.invocationId, payload.artifactId])));
1075
+ decipher.setAuthTag(Buffer.from(payload.tag, "base64"));
1076
+ const data = Buffer.concat([
1077
+ decipher.update(Buffer.from(payload.ciphertext, "base64")),
1078
+ decipher.final()
1079
+ ]);
1080
+ if (data.length !== payload.bytes || createHash("sha256").update(data).digest("hex") !== payload.sha256) {
1081
+ throw new Error("Invocation payload integrity mismatch");
1082
+ }
1083
+ return z3.json().parse(JSON.parse(data.toString("utf8")));
1084
+ }
1002
1085
  };
1003
1086
  }
1004
- function statedUsage(usage) {
1005
- const stated = (value) => value ?? { provenance: "unavailable" };
1006
- if (!usage)
1007
- return unknownUsage();
1008
- return {
1009
- inputTokens: stated(usage.inputTokens),
1010
- outputTokens: stated(usage.outputTokens),
1011
- reasoningTokens: stated(usage.reasoningTokens),
1012
- cacheReadTokens: stated(usage.cacheReadTokens),
1013
- cacheWriteTokens: stated(usage.cacheWriteTokens),
1014
- cost: stated(usage.cost)
1015
- };
1087
+
1088
+ // src/agent-runtime/provider-origin.ts
1089
+ import {
1090
+ InvalidToolApprovalError,
1091
+ InvalidToolApprovalSignatureError,
1092
+ ToolCallNotFoundForApprovalError
1093
+ } from "ai";
1094
+ var providerOrigin = new WeakSet;
1095
+ function isOwnInputRefusal(error) {
1096
+ return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
1016
1097
  }
1017
- function unknownUsage() {
1018
- const nothing = { provenance: "unavailable" };
1019
- return {
1020
- inputTokens: nothing,
1021
- outputTokens: nothing,
1022
- reasoningTokens: nothing,
1023
- cacheReadTokens: nothing,
1024
- cacheWriteTokens: nothing,
1025
- cost: nothing
1026
- };
1098
+ function markProviderOrigin(error) {
1099
+ if (typeof error === "object" && error !== null)
1100
+ providerOrigin.add(error);
1101
+ return error;
1027
1102
  }
1028
- function normalizeSdkUsage(value) {
1029
- const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
1030
- return {
1031
- inputTokens: reported(value.inputTokens),
1032
- outputTokens: reported(value.outputTokens),
1033
- reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
1034
- cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
1035
- cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
1036
- };
1103
+ function hasProviderOrigin(error) {
1104
+ return typeof error === "object" && error !== null && providerOrigin.has(error);
1037
1105
  }
1038
- function createIdleDeadline(parent, timeoutMs) {
1039
- if (timeoutMs === undefined) {
1040
- const noop = () => {
1041
- return;
1042
- };
1043
- return {
1044
- signal: parent,
1045
- touch: noop,
1046
- start: noop,
1047
- stop: noop,
1048
- suspend: noop,
1049
- resume: noop,
1050
- dispose: noop
1051
- };
1052
- }
1053
- const controller = new AbortController;
1054
- let timer;
1055
- let active = false;
1056
- let suspended = 0;
1057
- const clear = () => {
1058
- if (timer !== undefined)
1059
- clearTimeout(timer);
1060
- timer = undefined;
1061
- };
1062
- const touch = () => {
1063
- clear();
1064
- if (!active || suspended > 0 || controller.signal.aborted)
1065
- return;
1066
- timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
1067
- };
1068
- return {
1069
- signal: AbortSignal.any([parent, controller.signal]),
1070
- touch,
1071
- start() {
1072
- active = true;
1073
- touch();
1074
- },
1075
- stop() {
1076
- active = false;
1077
- clear();
1078
- },
1079
- suspend() {
1080
- suspended += 1;
1081
- clear();
1082
- },
1083
- resume() {
1084
- suspended = Math.max(0, suspended - 1);
1085
- touch();
1106
+ function markProviderStream(stream) {
1107
+ const reader = stream.getReader();
1108
+ return new ReadableStream({
1109
+ async pull(controller) {
1110
+ let read;
1111
+ try {
1112
+ read = await reader.read();
1113
+ } catch (error) {
1114
+ controller.error(isOwnInputRefusal(error) ? error : markProviderOrigin(error));
1115
+ return;
1116
+ }
1117
+ if (read.done)
1118
+ controller.close();
1119
+ else
1120
+ controller.enqueue(read.value);
1086
1121
  },
1087
- dispose() {
1088
- active = false;
1089
- clear();
1122
+ cancel(reason) {
1123
+ return reader.cancel(reason);
1090
1124
  }
1091
- };
1125
+ });
1092
1126
  }
1093
1127
 
1094
1128
  // src/agent-runtime/invocation-attempt.ts
@@ -1833,184 +1867,66 @@ function classifyProviderFailure2(error) {
1833
1867
  if (error instanceof AgentProviderStreamCutError2) {
1834
1868
  return { reason: "stream-cut", retryable: true, evidence: "none" };
1835
1869
  }
1836
- const status = statusOf(error);
1837
- const byStatus = status === undefined ? undefined : BY_STATUS[status];
1838
- if (byStatus) {
1839
- return {
1840
- reason: byStatus,
1841
- status,
1842
- retryable: RETRYABLE.has(byStatus),
1843
- evidence: "status"
1844
- };
1845
- }
1846
- const message = messageOf(error);
1847
- for (const [pattern, reason] of BY_MESSAGE) {
1848
- if (pattern.test(message)) {
1849
- return {
1850
- reason,
1851
- ...status !== undefined && { status },
1852
- retryable: RETRYABLE.has(reason),
1853
- evidence: "message"
1854
- };
1855
- }
1856
- }
1857
- return {
1858
- reason: "unknown",
1859
- ...status !== undefined && { status },
1860
- retryable: false,
1861
- evidence: "none"
1862
- };
1863
- }
1864
- function isToolResultFailure2(output) {
1865
- const parsed = typeof output === "string" ? parseJson(output) : output;
1866
- if (!isRecord(parsed))
1867
- return false;
1868
- if ("error" in parsed)
1869
- return true;
1870
- return isRecord(parsed.value) && "error" in parsed.value;
1871
- }
1872
- function parseJson(value) {
1873
- try {
1874
- return JSON.parse(value);
1875
- } catch {
1876
- return;
1877
- }
1878
- }
1879
-
1880
- // src/agent-runtime/retry-policy.ts
1881
- async function recordAgentRetryDecision2(input) {
1882
- const retry = input.failure.retryable && input.attempt < input.policy.maxAttempts;
1883
- const delayMs = retry ? input.policy.delayMs({ attempt: input.attempt, failure: input.failure }) : 0;
1884
- if (!Number.isInteger(delayMs) || delayMs < 0) {
1885
- throw new TypeError("Retry delay must be a non-negative integer");
1886
- }
1887
- if (retry) {
1888
- await input.store.appendEvent({
1889
- conversationId: input.conversationId,
1890
- kind: "retry/scheduled",
1891
- payload: { attempt: input.attempt + 1, delayMs, reason: input.failure.reason }
1892
- });
1893
- }
1894
- return { retry, delayMs };
1895
- }
1896
-
1897
- // src/agent-runtime/state-slots.ts
1898
- import { z as z7 } from "zod";
1899
- function defineStateSlot2(input) {
1900
- if (input.name.length === 0)
1901
- throw new TypeError("State slot name must not be empty");
1902
- const version = input.version ?? 1;
1903
- if (!Number.isInteger(version) || version < 1) {
1904
- throw new TypeError("State slot version must be a positive integer");
1905
- }
1906
- return {
1907
- name: input.name,
1908
- version,
1909
- schema: input.schema,
1910
- ...input.description && { description: input.description }
1911
- };
1912
- }
1913
- var StateSetPayloadSchema = z7.object({
1914
- name: z7.string().min(1),
1915
- version: z7.int().positive(),
1916
- value: z7.json(),
1917
- actor: z7.enum(["agent", "human", "system"])
1918
- }).strict();
1919
- function slotRegistry(definitions) {
1920
- const result = new Map;
1921
- for (const definition of definitions) {
1922
- if (result.has(definition.name))
1923
- throw new TypeError(`Duplicate state slot: ${definition.name}`);
1924
- result.set(definition.name, definition);
1925
- }
1926
- return result;
1927
- }
1928
- function createAgentStateSlotStore2(input) {
1929
- const definitions = slotRegistry(input.definitions);
1930
- const set = async (request) => {
1931
- const definition = definitions.get(request.name);
1932
- if (!definition)
1933
- throw new TypeError(`Unknown state slot: ${request.name}`);
1934
- const value = definition.schema.parse(request.value);
1935
- const payload = StateSetPayloadSchema.parse({
1936
- name: definition.name,
1937
- version: definition.version,
1938
- value,
1939
- actor: request.actor
1940
- });
1941
- const event = await input.store.appendEvent({
1942
- conversationId: request.conversationId,
1943
- kind: "state/set",
1944
- payload
1945
- });
1946
- return {
1947
- name: definition.name,
1948
- version: definition.version,
1949
- value,
1950
- updatedAt: event.occurredAt,
1951
- seq: event.seq
1870
+ const status = statusOf(error);
1871
+ const byStatus = status === undefined ? undefined : BY_STATUS[status];
1872
+ if (byStatus) {
1873
+ return {
1874
+ reason: byStatus,
1875
+ status,
1876
+ retryable: RETRYABLE.has(byStatus),
1877
+ evidence: "status"
1952
1878
  };
1953
- };
1954
- const list = async (conversationId) => {
1955
- const values = new Map;
1956
- let cursor = 1;
1957
- for (;; ) {
1958
- const page = await input.store.readEvents({
1959
- conversationId,
1960
- fromSeq: cursor,
1961
- limit: 1000
1962
- });
1963
- for (const event of page.items) {
1964
- if (event.kind !== "state/set")
1965
- continue;
1966
- const payload = StateSetPayloadSchema.parse(event.payload);
1967
- const definition = definitions.get(payload.name);
1968
- if (!definition || definition.version !== payload.version)
1969
- continue;
1970
- values.set(payload.name, {
1971
- name: payload.name,
1972
- version: payload.version,
1973
- value: definition.schema.parse(payload.value),
1974
- updatedAt: event.occurredAt,
1975
- seq: event.seq
1976
- });
1977
- }
1978
- if (page.nextSeq === undefined)
1979
- break;
1980
- cursor = page.nextSeq;
1879
+ }
1880
+ const message = messageOf(error);
1881
+ for (const [pattern, reason] of BY_MESSAGE) {
1882
+ if (pattern.test(message)) {
1883
+ return {
1884
+ reason,
1885
+ ...status !== undefined && { status },
1886
+ retryable: RETRYABLE.has(reason),
1887
+ evidence: "message"
1888
+ };
1981
1889
  }
1982
- return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
1890
+ }
1891
+ return {
1892
+ reason: "unknown",
1893
+ ...status !== undefined && { status },
1894
+ retryable: false,
1895
+ evidence: "none"
1983
1896
  };
1984
- const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
1985
- return { set, get, list };
1986
1897
  }
1987
- function renderAgentStateSlots2(values) {
1988
- if (values.length === 0)
1898
+ function isToolResultFailure2(output) {
1899
+ const parsed = typeof output === "string" ? parseJson(output) : output;
1900
+ if (!isRecord(parsed))
1901
+ return false;
1902
+ if ("error" in parsed)
1903
+ return true;
1904
+ return isRecord(parsed.value) && "error" in parsed.value;
1905
+ }
1906
+ function parseJson(value) {
1907
+ try {
1908
+ return JSON.parse(value);
1909
+ } catch {
1989
1910
  return;
1990
- return [
1991
- "Durable conversation state (authoritative; newer than compacted history):",
1992
- ...values.map((slot) => `${slot.name}: ${JSON.stringify(slot.value)}`)
1993
- ].join(`
1994
- `);
1911
+ }
1912
+ }
1913
+
1914
+ // src/agent-runtime/retry-policy.ts
1915
+ async function recordAgentRetryDecision2(input) {
1916
+ const retry = input.failure.retryable && input.attempt < input.policy.maxAttempts;
1917
+ const delayMs = retry ? input.policy.delayMs({ attempt: input.attempt, failure: input.failure }) : 0;
1918
+ if (!Number.isInteger(delayMs) || delayMs < 0) {
1919
+ throw new TypeError("Retry delay must be a non-negative integer");
1920
+ }
1921
+ if (retry) {
1922
+ await input.store.appendEvent({
1923
+ conversationId: input.conversationId,
1924
+ kind: "retry/scheduled",
1925
+ payload: { attempt: input.attempt + 1, delayMs, reason: input.failure.reason }
1926
+ });
1927
+ }
1928
+ return { retry, delayMs };
1995
1929
  }
1996
- var agentGoalStateSlot2 = defineStateSlot2({
1997
- name: "goal",
1998
- description: "The durable objective and lifecycle of this conversation.",
1999
- schema: z7.object({
2000
- objective: z7.string().min(1),
2001
- status: z7.enum(["active", "complete", "blocked"])
2002
- }).strict()
2003
- });
2004
- var agentTodoStateSlot2 = defineStateSlot2({
2005
- name: "todo",
2006
- description: "The durable ordered work plan for this conversation.",
2007
- schema: z7.object({
2008
- items: z7.array(z7.object({
2009
- step: z7.string().min(1),
2010
- status: z7.enum(["pending", "in_progress", "completed"])
2011
- }).strict())
2012
- }).strict()
2013
- });
2014
1930
 
2015
1931
  // src/agent-runtime/runtime-control.ts
2016
1932
  async function interruptAgentRun(state, input) {
@@ -2823,32 +2739,6 @@ import {
2823
2739
  stepCountIs
2824
2740
  } from "ai";
2825
2741
 
2826
- // src/agent-runtime/deferred-tools-internal.ts
2827
- var repairs = new WeakMap;
2828
- var catalogs = new WeakMap;
2829
- function registerDeferredToolRepair(prepareStep, repair) {
2830
- repairs.set(prepareStep, repair);
2831
- }
2832
- function deferredToolRepair(prepareStep) {
2833
- return prepareStep ? repairs.get(prepareStep) : undefined;
2834
- }
2835
- function registerDeferredToolCatalog(tools, searchName, names) {
2836
- const search = tools[searchName];
2837
- if (search && typeof search === "object")
2838
- catalogs.set(search, names);
2839
- }
2840
- function deferredToolCatalog(tools, searchName) {
2841
- const search = tools[searchName];
2842
- return search && typeof search === "object" ? catalogs.get(search) : undefined;
2843
- }
2844
- function repairedSearchCall(toolCall, searchName) {
2845
- return {
2846
- ...toolCall,
2847
- toolName: searchName,
2848
- input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
2849
- };
2850
- }
2851
-
2852
2742
  // src/agent-runtime/owned-provider-stream.ts
2853
2743
  var DEFAULT_CLEANUP_TIMEOUT_MS = 1000;
2854
2744
  async function settleCleanup(operation, timeoutMs) {
@@ -3739,6 +3629,126 @@ async function commitRunTerminal(execution) {
3739
3629
 
3740
3630
  // src/agent-runtime/run-prompt-history.ts
3741
3631
  import { createHash as createHash4 } from "node:crypto";
3632
+
3633
+ // src/agent-runtime/state-slots.ts
3634
+ import { z as z7 } from "zod";
3635
+ function defineStateSlot2(input) {
3636
+ if (input.name.length === 0)
3637
+ throw new TypeError("State slot name must not be empty");
3638
+ const version = input.version ?? 1;
3639
+ if (!Number.isInteger(version) || version < 1) {
3640
+ throw new TypeError("State slot version must be a positive integer");
3641
+ }
3642
+ return {
3643
+ name: input.name,
3644
+ version,
3645
+ schema: input.schema,
3646
+ ...input.description && { description: input.description }
3647
+ };
3648
+ }
3649
+ var StateSetPayloadSchema = z7.object({
3650
+ name: z7.string().min(1),
3651
+ version: z7.int().positive(),
3652
+ value: z7.json(),
3653
+ actor: z7.enum(["agent", "human", "system"])
3654
+ }).strict();
3655
+ function slotRegistry(definitions) {
3656
+ const result = new Map;
3657
+ for (const definition of definitions) {
3658
+ if (result.has(definition.name))
3659
+ throw new TypeError(`Duplicate state slot: ${definition.name}`);
3660
+ result.set(definition.name, definition);
3661
+ }
3662
+ return result;
3663
+ }
3664
+ function createAgentStateSlotStore2(input) {
3665
+ const definitions = slotRegistry(input.definitions);
3666
+ const set = async (request) => {
3667
+ const definition = definitions.get(request.name);
3668
+ if (!definition)
3669
+ throw new TypeError(`Unknown state slot: ${request.name}`);
3670
+ const value = definition.schema.parse(request.value);
3671
+ const payload = StateSetPayloadSchema.parse({
3672
+ name: definition.name,
3673
+ version: definition.version,
3674
+ value,
3675
+ actor: request.actor
3676
+ });
3677
+ const event = await input.store.appendEvent({
3678
+ conversationId: request.conversationId,
3679
+ kind: "state/set",
3680
+ payload
3681
+ });
3682
+ return {
3683
+ name: definition.name,
3684
+ version: definition.version,
3685
+ value,
3686
+ updatedAt: event.occurredAt,
3687
+ seq: event.seq
3688
+ };
3689
+ };
3690
+ const list = async (conversationId) => {
3691
+ const values = new Map;
3692
+ let cursor = 1;
3693
+ for (;; ) {
3694
+ const page = await input.store.readEvents({
3695
+ conversationId,
3696
+ fromSeq: cursor,
3697
+ limit: 1000
3698
+ });
3699
+ for (const event of page.items) {
3700
+ if (event.kind !== "state/set")
3701
+ continue;
3702
+ const payload = StateSetPayloadSchema.parse(event.payload);
3703
+ const definition = definitions.get(payload.name);
3704
+ if (!definition || definition.version !== payload.version)
3705
+ continue;
3706
+ values.set(payload.name, {
3707
+ name: payload.name,
3708
+ version: payload.version,
3709
+ value: definition.schema.parse(payload.value),
3710
+ updatedAt: event.occurredAt,
3711
+ seq: event.seq
3712
+ });
3713
+ }
3714
+ if (page.nextSeq === undefined)
3715
+ break;
3716
+ cursor = page.nextSeq;
3717
+ }
3718
+ return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
3719
+ };
3720
+ const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
3721
+ return { set, get, list };
3722
+ }
3723
+ function renderAgentStateSlots2(values) {
3724
+ if (values.length === 0)
3725
+ return;
3726
+ return [
3727
+ "Durable conversation state (authoritative; newer than compacted history):",
3728
+ ...values.map((slot) => `${slot.name}: ${JSON.stringify(slot.value)}`)
3729
+ ].join(`
3730
+ `);
3731
+ }
3732
+ var agentGoalStateSlot2 = defineStateSlot2({
3733
+ name: "goal",
3734
+ description: "The durable objective and lifecycle of this conversation.",
3735
+ schema: z7.object({
3736
+ objective: z7.string().min(1),
3737
+ status: z7.enum(["active", "complete", "blocked"])
3738
+ }).strict()
3739
+ });
3740
+ var agentTodoStateSlot2 = defineStateSlot2({
3741
+ name: "todo",
3742
+ description: "The durable ordered work plan for this conversation.",
3743
+ schema: z7.object({
3744
+ items: z7.array(z7.object({
3745
+ step: z7.string().min(1),
3746
+ status: z7.enum(["pending", "in_progress", "completed"])
3747
+ }).strict())
3748
+ }).strict()
3749
+ });
3750
+
3751
+ // src/agent-runtime/run-prompt-history.ts
3742
3752
  function snapshotForRunPrompt(snapshot, runId) {
3743
3753
  const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
3744
3754
  if (runIndex < 0)