stitchkit 0.118.1 → 0.119.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 (144) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/browser/http.d.ts.map +1 -1
  3. package/dist/contract/client-types.d.ts +6 -3
  4. package/dist/contract/client-types.d.ts.map +1 -1
  5. package/dist/contract/define-validation.d.ts.map +1 -1
  6. package/dist/contract/define.d.ts +18 -12
  7. package/dist/contract/define.d.ts.map +1 -1
  8. package/dist/contract/endpoint-capabilities.d.ts +28 -0
  9. package/dist/contract/endpoint-capabilities.d.ts.map +1 -0
  10. package/dist/contract/factory.d.ts +49 -19
  11. package/dist/contract/factory.d.ts.map +1 -1
  12. package/dist/contract/tool-view.d.ts +1 -1
  13. package/dist/contract/tool-view.d.ts.map +1 -1
  14. package/dist/contract/transports.d.ts +5 -0
  15. package/dist/contract/transports.d.ts.map +1 -0
  16. package/dist/entrypoints/agent-runtime/coding-tools.js +6 -5
  17. package/dist/entrypoints/agent-runtime/harness.js +6 -5
  18. package/dist/entrypoints/agent-runtime/sandbox.js +6 -5
  19. package/dist/entrypoints/agent-runtime/sqlite/bun.js +9 -8
  20. package/dist/entrypoints/agent-runtime/sqlite/node.js +9 -8
  21. package/dist/entrypoints/agent-runtime/testing.js +9 -8
  22. package/dist/entrypoints/agent-runtime.js +14 -13
  23. package/dist/entrypoints/application/diagnostic-journal.js +3 -3
  24. package/dist/entrypoints/application/directory-inbox.js +4 -4
  25. package/dist/entrypoints/application/opentelemetry.js +1 -1
  26. package/dist/entrypoints/application.js +5 -5
  27. package/dist/entrypoints/cli/publish.js +4 -4
  28. package/dist/entrypoints/cli.js +8 -7
  29. package/dist/entrypoints/contract.d.ts +1 -1
  30. package/dist/entrypoints/contract.d.ts.map +1 -1
  31. package/dist/entrypoints/contract.js +6 -4
  32. package/dist/entrypoints/files.js +3 -3
  33. package/dist/entrypoints/geo/contract.d.ts +7 -0
  34. package/dist/entrypoints/geo/contract.d.ts.map +1 -0
  35. package/dist/entrypoints/geo/contract.js +6 -0
  36. package/dist/entrypoints/geo.js +60 -23
  37. package/dist/entrypoints/http.js +2 -2
  38. package/dist/entrypoints/index.js +8 -6
  39. package/dist/entrypoints/live.js +1 -1
  40. package/dist/entrypoints/node.js +7 -6
  41. package/dist/entrypoints/primitives.js +1 -1
  42. package/dist/entrypoints/process/owner-loss.js +1 -1
  43. package/dist/entrypoints/process.js +3 -3
  44. package/dist/entrypoints/react.js +1 -1
  45. package/dist/entrypoints/remote.js +4 -3
  46. package/dist/entrypoints/server.js +11 -10
  47. package/dist/entrypoints/telegram.js +2 -2
  48. package/dist/entrypoints/testing.js +7 -6
  49. package/dist/entrypoints/tools/connections.js +3 -2
  50. package/dist/entrypoints/tools/contract.js +1 -1
  51. package/dist/entrypoints/tools/invoker.js +5 -4
  52. package/dist/entrypoints/tools/mcp.js +7 -6
  53. package/dist/entrypoints/tools.js +17 -15
  54. package/dist/entrypoints/tracking/contract.js +5 -3
  55. package/dist/entrypoints/tracking/performance.js +3 -3
  56. package/dist/entrypoints/tracking.d.ts +1 -1
  57. package/dist/entrypoints/tracking.d.ts.map +1 -1
  58. package/dist/entrypoints/tracking.js +63 -83
  59. package/dist/entrypoints/xlsx.js +1 -1
  60. package/dist/geo/index.d.ts +2 -1
  61. package/dist/geo/index.d.ts.map +1 -1
  62. package/dist/geo/record.d.ts +8 -0
  63. package/dist/geo/record.d.ts.map +1 -0
  64. package/dist/geo/resolver.d.ts +1 -3
  65. package/dist/geo/resolver.d.ts.map +1 -1
  66. package/dist/geo/schema.d.ts +44 -0
  67. package/dist/geo/schema.d.ts.map +1 -0
  68. package/dist/geo/types.d.ts +2 -13
  69. package/dist/geo/types.d.ts.map +1 -1
  70. package/dist/{index-n5sv4z0w.js → index-1k18qzqa.js} +13 -15
  71. package/dist/{index-tsngj2b5.js → index-2dfvv1jg.js} +206 -206
  72. package/dist/{index-d9hq291n.js → index-4jpykzvw.js} +70 -81
  73. package/dist/{index-ghtpfz4z.js → index-57gqaq8b.js} +2 -2
  74. package/dist/index-69t14s4a.js +39 -0
  75. package/dist/{index-6p3frkv5.js → index-6a69xzrx.js} +4 -4
  76. package/dist/{index-dky0dcmf.js → index-72r9k0av.js} +6 -2
  77. package/dist/{index-vv1sch8a.js → index-8vzh5wpv.js} +13 -8
  78. package/dist/{index-xx1j310k.js → index-8yxgcyt6.js} +171 -169
  79. package/dist/{index-p6apg0jg.js → index-9frf01t9.js} +16 -9
  80. package/dist/{index-q0th8q0z.js → index-9mjrnqxs.js} +1 -3
  81. package/dist/{index-ega3yz4c.js → index-aqwg2dm5.js} +1 -1
  82. package/dist/{index-073nw9qr.js → index-ba7are04.js} +524 -522
  83. package/dist/{index-095ya5hm.js → index-bbvc59gw.js} +13 -11
  84. package/dist/{index-txg1npmg.js → index-cyxp8rbf.js} +1 -1
  85. package/dist/index-d3xdyjt6.js +38 -0
  86. package/dist/{index-n8z3rvzw.js → index-f4njz9j0.js} +3 -5
  87. package/dist/{index-90p34rts.js → index-fcqj44mb.js} +3 -1
  88. package/dist/{index-86nbfysb.js → index-ff39f9dr.js} +3 -3
  89. package/dist/{index-75ns2ybj.js → index-fqd4yqwd.js} +1 -1
  90. package/dist/{index-nqxrm176.js → index-g444vfz2.js} +1 -1
  91. package/dist/{index-vwhrnp67.js → index-kz9734jc.js} +3 -3
  92. package/dist/{index-dr3t5n1v.js → index-nn9qvkww.js} +46 -46
  93. package/dist/{index-qezhmp51.js → index-nz06qw5a.js} +3 -1
  94. package/dist/{index-1bx1xv1k.js → index-pfvde2fz.js} +5 -2
  95. package/dist/{index-s80awwsw.js → index-qch1vcaa.js} +3 -1
  96. package/dist/{index-cycp3r3e.js → index-rxcgp4b9.js} +2 -2
  97. package/dist/{index-w7jq3fz9.js → index-s0qjs6ee.js} +1198 -1196
  98. package/dist/{index-p0rf7sq9.js → index-s20s2mad.js} +209 -209
  99. package/dist/{index-v6vb5qx8.js → index-s3yxw6kt.js} +1 -1
  100. package/dist/{index-cqmqyjax.js → index-sa99p98w.js} +1 -1
  101. package/dist/{index-0gxvns6s.js → index-sba3e6m4.js} +1 -0
  102. package/dist/{index-f24bdt13.js → index-v1swr26p.js} +3 -1
  103. package/dist/{index-rhzkndr5.js → index-x4p3kw1p.js} +533 -530
  104. package/dist/{index-hdjmdwsj.js → index-x8d9fdeg.js} +513 -507
  105. package/dist/{index-htxh46ej.js → index-ycqhyars.js} +2 -2
  106. package/dist/{index-9bwcthxw.js → index-yj6saztf.js} +31 -13
  107. package/dist/{index-tdpmfks8.js → index-ynrf908v.js} +1 -1
  108. package/dist/{index-f6m4c545.js → index-zrdcmg6j.js} +4 -6
  109. package/dist/process/bun-child.d.ts +3 -2
  110. package/dist/process/bun-child.d.ts.map +1 -1
  111. package/dist/server/contract-method.d.ts.map +1 -1
  112. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  113. package/dist/tools/operations/async-operation-canonical-types.d.ts +1 -1
  114. package/dist/tracking/attribution.d.ts +21 -25
  115. package/dist/tracking/attribution.d.ts.map +1 -1
  116. package/dist/tracking/client-visit.d.ts +5 -7
  117. package/dist/tracking/client-visit.d.ts.map +1 -1
  118. package/dist/tracking/client.d.ts +2 -2
  119. package/dist/tracking/client.d.ts.map +1 -1
  120. package/dist/tracking/contract.d.ts +1 -1
  121. package/dist/tracking/host.d.ts +0 -1
  122. package/dist/tracking/host.d.ts.map +1 -1
  123. package/dist/tracking/privacy.d.ts +6 -0
  124. package/dist/tracking/privacy.d.ts.map +1 -1
  125. package/dist/tracking/schemas.d.ts +2 -2
  126. package/dist/tracking/schemas.d.ts.map +1 -1
  127. package/llms/contract.txt +46 -24
  128. package/llms/geo-contract.txt +23 -0
  129. package/llms/geo.txt +40 -4
  130. package/llms/stitchkit.txt +4 -3
  131. package/llms/tools.2.txt +2 -2
  132. package/llms/tools.3.txt +1 -1
  133. package/llms/tracking-contract.txt +1 -1
  134. package/llms/tracking.txt +27 -5
  135. package/llms/{upgrading-0.105.0-0.118.0.txt → upgrading-0.106.0-0.119.0.txt} +121 -410
  136. package/llms/upgrading-0.37.0-0.53.0.txt +969 -0
  137. package/llms/{upgrading-0.44.0-0.62.0.txt → upgrading-0.55.0-0.68.0.txt} +509 -528
  138. package/llms/{upgrading-0.63.0-0.83.0.txt → upgrading-0.69.0-0.95.0.txt} +506 -509
  139. package/llms/{upgrading-0.84.0-0.104.0.txt → upgrading-0.96.0-0.105.0.txt} +410 -506
  140. package/llms/upgrading.txt +5 -5
  141. package/llms-full.txt +247 -38
  142. package/llms.txt +10 -9
  143. package/package.json +23 -19
  144. package/llms/upgrading-0.37.0-0.44.0.txt +0 -444
@@ -14,7 +14,7 @@ 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";
@@ -35,7 +35,7 @@ import {
35
35
  ProviderJournalRequestSchema,
36
36
  ProviderJournalResponseSchema,
37
37
  isActiveRunState
38
- } from "./index-xx1j310k.js";
38
+ } from "./index-8yxgcyt6.js";
39
39
  import {
40
40
  messageOf
41
41
  } from "./index-g149e9pk.js";
@@ -53,6 +53,9 @@ import {
53
53
  transportResult
54
54
  } from "./index-9jfdm5tg.js";
55
55
 
56
+ // src/agent-runtime/runtime-internals.ts
57
+ import { z } from "zod";
58
+
56
59
  // src/agent-runtime/run-store-retry.ts
57
60
  var STORE_RETRY_DELAYS_MS = [25, 100, 400];
58
61
  function storeRetryDelay(failures) {
@@ -249,6 +252,187 @@ async function commitAgentRunTerminal(input) {
249
252
  throw new AgentRuntimeConflictError2("terminal commit");
250
253
  }
251
254
 
255
+ // src/agent-runtime/runtime-internals.ts
256
+ function findRun(runs, runId) {
257
+ const run = runs.find((candidate) => candidate.id === runId);
258
+ if (!run)
259
+ throw new AgentRuntimeConflictError2("run lookup");
260
+ return run;
261
+ }
262
+ function jsonValue(value) {
263
+ const parsed = z.json().safeParse(value);
264
+ return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
265
+ }
266
+ function providerEnvelope(value) {
267
+ const parsed = AgentJsonObjectSchema2.safeParse(value);
268
+ if (!parsed.success)
269
+ return;
270
+ return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
271
+ }
272
+ function providerResponseIdentity(id, provider) {
273
+ return AgentProviderResponseSchema2.parse({
274
+ id,
275
+ ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
276
+ });
277
+ }
278
+ function appendText(parts, text) {
279
+ const previous = parts.at(-1);
280
+ if (previous?.type === "text") {
281
+ const next = AgentMessagePartSchema2.parse({ ...previous, text: previous.text + text });
282
+ parts.splice(parts.length - 1, 1, next);
283
+ return;
284
+ }
285
+ parts.push(AgentMessagePartSchema2.parse({ type: "text", text }));
286
+ }
287
+ function abortTerminalReason(signal) {
288
+ if (signal.reason === "shutdown")
289
+ return "shutdown";
290
+ if (signal.reason === "timeout")
291
+ return "timeout";
292
+ if (signal.reason === "supersede")
293
+ return "superseded";
294
+ return "interrupted";
295
+ }
296
+ function addUsage(total, step) {
297
+ const sum = (left, right) => {
298
+ if (left?.value === undefined && right?.value === undefined) {
299
+ return { provenance: "unavailable" };
300
+ }
301
+ if (left?.value === undefined)
302
+ return { ...right, provenance: "computed" };
303
+ if (right?.value === undefined)
304
+ return { ...left, provenance: "computed" };
305
+ return { value: left.value + right.value, provenance: "computed" };
306
+ };
307
+ const sumCost = (left, right) => {
308
+ if (left?.value === undefined || right?.value === undefined) {
309
+ return { provenance: "unavailable" };
310
+ }
311
+ if (left.currency !== right.currency)
312
+ return { provenance: "unavailable" };
313
+ return {
314
+ value: left.value + right.value,
315
+ ...left.currency && { currency: left.currency },
316
+ provenance: "computed"
317
+ };
318
+ };
319
+ if (!total)
320
+ return step;
321
+ const cost = sumCost(total.cost, step.cost);
322
+ return {
323
+ inputTokens: sum(total.inputTokens, step.inputTokens),
324
+ outputTokens: sum(total.outputTokens, step.outputTokens),
325
+ reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
326
+ cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
327
+ cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
328
+ ...cost && { cost }
329
+ };
330
+ }
331
+ function mergeModelTotals(sdkTotal, accumulated) {
332
+ const pick = (total, ours) => {
333
+ if (ours?.provenance === "unavailable")
334
+ return ours;
335
+ return total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
336
+ };
337
+ return {
338
+ inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
339
+ outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
340
+ reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
341
+ cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
342
+ cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
343
+ cost: accumulated?.cost ?? { provenance: "unavailable" }
344
+ };
345
+ }
346
+ function statedUsage(usage) {
347
+ const stated = (value) => value ?? { provenance: "unavailable" };
348
+ if (!usage)
349
+ return unknownUsage();
350
+ return {
351
+ inputTokens: stated(usage.inputTokens),
352
+ outputTokens: stated(usage.outputTokens),
353
+ reasoningTokens: stated(usage.reasoningTokens),
354
+ cacheReadTokens: stated(usage.cacheReadTokens),
355
+ cacheWriteTokens: stated(usage.cacheWriteTokens),
356
+ cost: stated(usage.cost)
357
+ };
358
+ }
359
+ function unknownUsage() {
360
+ const nothing = { provenance: "unavailable" };
361
+ return {
362
+ inputTokens: nothing,
363
+ outputTokens: nothing,
364
+ reasoningTokens: nothing,
365
+ cacheReadTokens: nothing,
366
+ cacheWriteTokens: nothing,
367
+ cost: nothing
368
+ };
369
+ }
370
+ function normalizeSdkUsage(value) {
371
+ const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
372
+ return {
373
+ inputTokens: reported(value.inputTokens),
374
+ outputTokens: reported(value.outputTokens),
375
+ reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
376
+ cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
377
+ cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
378
+ };
379
+ }
380
+ function createIdleDeadline(parent, timeoutMs) {
381
+ if (timeoutMs === undefined) {
382
+ const noop = () => {
383
+ return;
384
+ };
385
+ return {
386
+ signal: parent,
387
+ touch: noop,
388
+ start: noop,
389
+ stop: noop,
390
+ suspend: noop,
391
+ resume: noop,
392
+ dispose: noop
393
+ };
394
+ }
395
+ const controller = new AbortController;
396
+ let timer;
397
+ let active = false;
398
+ let suspended = 0;
399
+ const clear = () => {
400
+ if (timer !== undefined)
401
+ clearTimeout(timer);
402
+ timer = undefined;
403
+ };
404
+ const touch = () => {
405
+ clear();
406
+ if (!active || suspended > 0 || controller.signal.aborted)
407
+ return;
408
+ timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
409
+ };
410
+ return {
411
+ signal: AbortSignal.any([parent, controller.signal]),
412
+ touch,
413
+ start() {
414
+ active = true;
415
+ touch();
416
+ },
417
+ stop() {
418
+ active = false;
419
+ clear();
420
+ },
421
+ suspend() {
422
+ suspended += 1;
423
+ clear();
424
+ },
425
+ resume() {
426
+ suspended = Math.max(0, suspended - 1);
427
+ touch();
428
+ },
429
+ dispose() {
430
+ active = false;
431
+ clear();
432
+ }
433
+ };
434
+ }
435
+
252
436
  // src/agent-runtime/context-refusal.ts
253
437
  class AgentContextOverflowError2 extends Error {
254
438
  name = "AgentContextOverflowError";
@@ -400,6 +584,32 @@ function createAgentSessionCoordinator2() {
400
584
  };
401
585
  }
402
586
 
587
+ // src/agent-runtime/deferred-tools-internal.ts
588
+ var repairs = new WeakMap;
589
+ var catalogs = new WeakMap;
590
+ function registerDeferredToolRepair(prepareStep, repair) {
591
+ repairs.set(prepareStep, repair);
592
+ }
593
+ function deferredToolRepair(prepareStep) {
594
+ return prepareStep ? repairs.get(prepareStep) : undefined;
595
+ }
596
+ function registerDeferredToolCatalog(tools, searchName, names) {
597
+ const search = tools[searchName];
598
+ if (search && typeof search === "object")
599
+ catalogs.set(search, names);
600
+ }
601
+ function deferredToolCatalog(tools, searchName) {
602
+ const search = tools[searchName];
603
+ return search && typeof search === "object" ? catalogs.get(search) : undefined;
604
+ }
605
+ function repairedSearchCall(toolCall, searchName) {
606
+ return {
607
+ ...toolCall,
608
+ toolName: searchName,
609
+ input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
610
+ };
611
+ }
612
+
403
613
  // src/agent-runtime/history.ts
404
614
  import { modelMessageSchema as modelMessageSchema2 } from "ai";
405
615
 
@@ -669,90 +879,120 @@ async function projectAgentHistory2(messages, options = {}) {
669
879
  return [...(await projectAgentHistoryDetailed2(messages, options)).messages];
670
880
  }
671
881
 
882
+ // src/agent-runtime/invocation-attempt.ts
883
+ import { AsyncLocalStorage } from "node:async_hooks";
884
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
885
+ import { wrapLanguageModel } from "ai";
886
+
887
+ // src/agent-runtime/invocation-failure.ts
888
+ class InvocationReceiptError extends Error {
889
+ constructor(cause) {
890
+ super("Model invocation receipt could not be recorded", { cause });
891
+ this.name = "InvocationReceiptError";
892
+ }
893
+ }
894
+ async function invocationAudit(work) {
895
+ try {
896
+ return await work();
897
+ } catch (error) {
898
+ throw error instanceof InvocationReceiptError ? error : new InvocationReceiptError(error);
899
+ }
900
+ }
901
+
902
+ // src/agent-runtime/invocation-payload.ts
903
+ import {
904
+ createCipheriv,
905
+ createDecipheriv,
906
+ createHash,
907
+ randomBytes,
908
+ randomUUID
909
+ } from "node:crypto";
910
+ import { z as z3 } from "zod";
911
+
672
912
  // 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({
913
+ import { z as z2 } from "zod";
914
+ var Id = z2.string().min(1).max(512);
915
+ var Hash = z2.string().regex(/^[a-f0-9]{64}$/);
916
+ var ModelInvocationTraceSchema2 = z2.object({
677
917
  operationId: Id,
678
918
  purpose: Id,
679
919
  project: Id,
680
- parent: z.object({ traceId: Id, invocationId: Id.optional() }).strict().optional(),
920
+ parent: z2.object({ traceId: Id, invocationId: Id.optional() }).strict().optional(),
681
921
  experiment: Id.optional(),
682
922
  case: Id.optional(),
683
923
  profile: Id.optional()
684
924
  }).strict();
685
- var CompletionInvocationInputSchema2 = z.object({
925
+ var CompletionInvocationInputSchema2 = z2.object({
686
926
  conversationId: Id,
687
927
  idempotencyKey: Id,
688
928
  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()
929
+ prompt: z2.string().min(1),
930
+ models: z2.array(Id).min(1).max(8),
931
+ settings: z2.object({
932
+ maxOutputTokens: z2.int().positive().optional(),
933
+ temperature: z2.number().finite().optional(),
934
+ topP: z2.number().min(0).max(1).optional(),
935
+ seed: z2.int().optional()
696
936
  }).strict().optional(),
697
- timeoutMs: z.int().positive().max(3600000)
937
+ timeoutMs: z2.int().positive().max(3600000)
698
938
  }).strict();
699
- var Identity = z.object({
939
+ var Identity = z2.object({
700
940
  provider: Id.nullable(),
701
941
  modelId: Id.nullable(),
702
942
  responseId: Id.nullable()
703
943
  }).strict();
704
- var InvocationCallerSchema = z.object({ subject: Id }).strict();
705
- var InvocationProcessSchema = z.object({
944
+ var InvocationCallerSchema = z2.object({ subject: Id }).strict();
945
+ var InvocationProcessSchema = z2.object({
706
946
  instanceId: Id,
707
- pid: z.int().positive(),
947
+ pid: z2.int().positive(),
708
948
  hostname: Id
709
949
  }).strict();
710
- var Base = z.object({
950
+ var Base = z2.object({
711
951
  conversationId: Id,
712
952
  invocationId: Id,
713
953
  operationId: Id,
714
954
  runId: Id.optional()
715
955
  });
716
956
  var InvocationStartedSchema = Base.extend({
717
- type: z.literal("invocation/started"),
718
- mode: z.enum(["completion", "agent"]),
957
+ type: z2.literal("invocation/started"),
958
+ mode: z2.enum(["completion", "agent"]),
719
959
  trace: ModelInvocationTraceSchema2,
720
960
  caller: InvocationCallerSchema,
721
961
  executingProcess: InvocationProcessSchema,
722
962
  fingerprint: Hash,
723
- requested: z.object({ models: z.array(Id), payloadSha256: Hash }).strict()
963
+ requested: z2.object({ models: z2.array(Id), payloadSha256: Hash }).strict()
724
964
  }).strict();
725
965
  var InvocationAttemptContextSchema = Base.extend({
726
966
  attemptId: Id,
727
- step: z.int().nonnegative()
967
+ step: z2.int().nonnegative()
728
968
  }).strict();
729
- var Attempt = Base.extend({ attemptId: Id, step: z.int().nonnegative() });
969
+ var Attempt = Base.extend({ attemptId: Id, step: z2.int().nonnegative() });
730
970
  var InvocationRequestSchema = Attempt.extend({
731
- type: z.literal("provider/request"),
732
- requested: z.object({ modelId: Id, provider: Id }).strict(),
971
+ type: z2.literal("provider/request"),
972
+ requested: z2.object({ modelId: Id, provider: Id }).strict(),
733
973
  executingProcess: InvocationProcessSchema,
734
- sent: z.object({
974
+ sent: z2.object({
735
975
  modelId: Id,
736
976
  provider: Id,
737
977
  payloadSha256: Hash,
738
978
  artifactId: Id,
739
- tools: z.int().nonnegative()
979
+ tools: z2.int().nonnegative()
740
980
  }).strict()
741
981
  }).strict();
742
982
  var InvocationResponseSchema = Attempt.extend({
743
- type: z.literal("provider/response"),
744
- status: z.enum(["succeeded", "failed", "cancelled"]),
983
+ type: z2.literal("provider/response"),
984
+ status: z2.enum(["succeeded", "failed", "cancelled"]),
745
985
  effective: Identity,
746
986
  usage: AgentUsageSchema2,
747
987
  artifactId: Id,
748
988
  payloadSha256: Hash
749
989
  }).strict();
750
990
  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"])
991
+ type: z2.literal("invocation/finished"),
992
+ failure: z2.object({ artifactId: Id, payloadSha256: Hash }).strict().optional(),
993
+ status: z2.enum(["succeeded", "failed", "cancelled"])
754
994
  }).strict();
755
- var ModelInvocationRecordSchema2 = z.discriminatedUnion("type", [
995
+ var ModelInvocationRecordSchema2 = z2.discriminatedUnion("type", [
756
996
  InvocationStartedSchema,
757
997
  InvocationRequestSchema,
758
998
  InvocationResponseSchema,
@@ -761,44 +1001,16 @@ var ModelInvocationRecordSchema2 = z.discriminatedUnion("type", [
761
1001
  var InvocationPayloadSchema = Base.extend({
762
1002
  artifactId: Id,
763
1003
  sha256: Hash,
764
- bytes: z.int().nonnegative(),
765
- iv: z.string(),
766
- tag: z.string(),
767
- ciphertext: z.string()
1004
+ bytes: z2.int().nonnegative(),
1005
+ iv: z2.string(),
1006
+ tag: z2.string(),
1007
+ ciphertext: z2.string()
768
1008
  }).strict();
769
1009
 
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
1010
  // 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
1011
  function invocationJson(value) {
800
1012
  const errors = new WeakSet;
801
- return z2.json().parse(JSON.parse(JSON.stringify(value, (_key, item) => {
1013
+ return z3.json().parse(JSON.parse(JSON.stringify(value, (_key, item) => {
802
1014
  if (item instanceof Uint8Array)
803
1015
  return { base64: Buffer.from(item).toString("base64") };
804
1016
  if (item instanceof ArrayBuffer)
@@ -842,253 +1054,71 @@ function createInvocationPayloads(store, key, maxBytes) {
842
1054
  artifactId,
843
1055
  sha256,
844
1056
  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" }
1057
+ iv: iv.toString("base64"),
1058
+ tag: cipher.getAuthTag().toString("base64"),
1059
+ ciphertext: ciphertext.toString("base64")
1060
+ }
1061
+ }, artifactId);
1062
+ return { artifactId, sha256 };
1063
+ },
1064
+ decrypt(conversationId, value) {
1065
+ const payload = InvocationPayloadSchema.parse(value);
1066
+ if (payload.bytes > maxBytes || payload.ciphertext.length > Math.ceil(maxBytes / 3) * 4) {
1067
+ throw new RangeError("Invocation payload exceeds maxPayloadBytes");
1068
+ }
1069
+ const decipher = createDecipheriv("aes-256-gcm", encryptionKey, Buffer.from(payload.iv, "base64"));
1070
+ decipher.setAAD(Buffer.from(JSON.stringify([conversationId, payload.invocationId, payload.artifactId])));
1071
+ decipher.setAuthTag(Buffer.from(payload.tag, "base64"));
1072
+ const data = Buffer.concat([
1073
+ decipher.update(Buffer.from(payload.ciphertext, "base64")),
1074
+ decipher.final()
1075
+ ]);
1076
+ if (data.length !== payload.bytes || createHash("sha256").update(data).digest("hex") !== payload.sha256) {
1077
+ throw new Error("Invocation payload integrity mismatch");
1078
+ }
1079
+ return z3.json().parse(JSON.parse(data.toString("utf8")));
1080
+ }
1002
1081
  };
1003
1082
  }
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
- };
1083
+
1084
+ // src/agent-runtime/provider-origin.ts
1085
+ import {
1086
+ InvalidToolApprovalError,
1087
+ InvalidToolApprovalSignatureError,
1088
+ ToolCallNotFoundForApprovalError
1089
+ } from "ai";
1090
+ var providerOrigin = new WeakSet;
1091
+ function isOwnInputRefusal(error) {
1092
+ return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
1016
1093
  }
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
- };
1094
+ function markProviderOrigin(error) {
1095
+ if (typeof error === "object" && error !== null)
1096
+ providerOrigin.add(error);
1097
+ return error;
1027
1098
  }
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
- };
1099
+ function hasProviderOrigin(error) {
1100
+ return typeof error === "object" && error !== null && providerOrigin.has(error);
1037
1101
  }
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();
1102
+ function markProviderStream(stream) {
1103
+ const reader = stream.getReader();
1104
+ return new ReadableStream({
1105
+ async pull(controller) {
1106
+ let read;
1107
+ try {
1108
+ read = await reader.read();
1109
+ } catch (error) {
1110
+ controller.error(isOwnInputRefusal(error) ? error : markProviderOrigin(error));
1111
+ return;
1112
+ }
1113
+ if (read.done)
1114
+ controller.close();
1115
+ else
1116
+ controller.enqueue(read.value);
1086
1117
  },
1087
- dispose() {
1088
- active = false;
1089
- clear();
1118
+ cancel(reason) {
1119
+ return reader.cancel(reason);
1090
1120
  }
1091
- };
1121
+ });
1092
1122
  }
1093
1123
 
1094
1124
  // src/agent-runtime/invocation-attempt.ts
@@ -1833,184 +1863,66 @@ function classifyProviderFailure2(error) {
1833
1863
  if (error instanceof AgentProviderStreamCutError2) {
1834
1864
  return { reason: "stream-cut", retryable: true, evidence: "none" };
1835
1865
  }
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
1866
+ const status = statusOf(error);
1867
+ const byStatus = status === undefined ? undefined : BY_STATUS[status];
1868
+ if (byStatus) {
1869
+ return {
1870
+ reason: byStatus,
1871
+ status,
1872
+ retryable: RETRYABLE.has(byStatus),
1873
+ evidence: "status"
1952
1874
  };
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;
1875
+ }
1876
+ const message = messageOf(error);
1877
+ for (const [pattern, reason] of BY_MESSAGE) {
1878
+ if (pattern.test(message)) {
1879
+ return {
1880
+ reason,
1881
+ ...status !== undefined && { status },
1882
+ retryable: RETRYABLE.has(reason),
1883
+ evidence: "message"
1884
+ };
1981
1885
  }
1982
- return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
1886
+ }
1887
+ return {
1888
+ reason: "unknown",
1889
+ ...status !== undefined && { status },
1890
+ retryable: false,
1891
+ evidence: "none"
1983
1892
  };
1984
- const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
1985
- return { set, get, list };
1986
1893
  }
1987
- function renderAgentStateSlots2(values) {
1988
- if (values.length === 0)
1894
+ function isToolResultFailure2(output) {
1895
+ const parsed = typeof output === "string" ? parseJson(output) : output;
1896
+ if (!isRecord(parsed))
1897
+ return false;
1898
+ if ("error" in parsed)
1899
+ return true;
1900
+ return isRecord(parsed.value) && "error" in parsed.value;
1901
+ }
1902
+ function parseJson(value) {
1903
+ try {
1904
+ return JSON.parse(value);
1905
+ } catch {
1989
1906
  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
- `);
1907
+ }
1908
+ }
1909
+
1910
+ // src/agent-runtime/retry-policy.ts
1911
+ async function recordAgentRetryDecision2(input) {
1912
+ const retry = input.failure.retryable && input.attempt < input.policy.maxAttempts;
1913
+ const delayMs = retry ? input.policy.delayMs({ attempt: input.attempt, failure: input.failure }) : 0;
1914
+ if (!Number.isInteger(delayMs) || delayMs < 0) {
1915
+ throw new TypeError("Retry delay must be a non-negative integer");
1916
+ }
1917
+ if (retry) {
1918
+ await input.store.appendEvent({
1919
+ conversationId: input.conversationId,
1920
+ kind: "retry/scheduled",
1921
+ payload: { attempt: input.attempt + 1, delayMs, reason: input.failure.reason }
1922
+ });
1923
+ }
1924
+ return { retry, delayMs };
1995
1925
  }
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
1926
 
2015
1927
  // src/agent-runtime/runtime-control.ts
2016
1928
  async function interruptAgentRun(state, input) {
@@ -2823,32 +2735,6 @@ import {
2823
2735
  stepCountIs
2824
2736
  } from "ai";
2825
2737
 
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
2738
  // src/agent-runtime/owned-provider-stream.ts
2853
2739
  var DEFAULT_CLEANUP_TIMEOUT_MS = 1000;
2854
2740
  async function settleCleanup(operation, timeoutMs) {
@@ -3739,6 +3625,126 @@ async function commitRunTerminal(execution) {
3739
3625
 
3740
3626
  // src/agent-runtime/run-prompt-history.ts
3741
3627
  import { createHash as createHash4 } from "node:crypto";
3628
+
3629
+ // src/agent-runtime/state-slots.ts
3630
+ import { z as z7 } from "zod";
3631
+ function defineStateSlot2(input) {
3632
+ if (input.name.length === 0)
3633
+ throw new TypeError("State slot name must not be empty");
3634
+ const version = input.version ?? 1;
3635
+ if (!Number.isInteger(version) || version < 1) {
3636
+ throw new TypeError("State slot version must be a positive integer");
3637
+ }
3638
+ return {
3639
+ name: input.name,
3640
+ version,
3641
+ schema: input.schema,
3642
+ ...input.description && { description: input.description }
3643
+ };
3644
+ }
3645
+ var StateSetPayloadSchema = z7.object({
3646
+ name: z7.string().min(1),
3647
+ version: z7.int().positive(),
3648
+ value: z7.json(),
3649
+ actor: z7.enum(["agent", "human", "system"])
3650
+ }).strict();
3651
+ function slotRegistry(definitions) {
3652
+ const result = new Map;
3653
+ for (const definition of definitions) {
3654
+ if (result.has(definition.name))
3655
+ throw new TypeError(`Duplicate state slot: ${definition.name}`);
3656
+ result.set(definition.name, definition);
3657
+ }
3658
+ return result;
3659
+ }
3660
+ function createAgentStateSlotStore2(input) {
3661
+ const definitions = slotRegistry(input.definitions);
3662
+ const set = async (request) => {
3663
+ const definition = definitions.get(request.name);
3664
+ if (!definition)
3665
+ throw new TypeError(`Unknown state slot: ${request.name}`);
3666
+ const value = definition.schema.parse(request.value);
3667
+ const payload = StateSetPayloadSchema.parse({
3668
+ name: definition.name,
3669
+ version: definition.version,
3670
+ value,
3671
+ actor: request.actor
3672
+ });
3673
+ const event = await input.store.appendEvent({
3674
+ conversationId: request.conversationId,
3675
+ kind: "state/set",
3676
+ payload
3677
+ });
3678
+ return {
3679
+ name: definition.name,
3680
+ version: definition.version,
3681
+ value,
3682
+ updatedAt: event.occurredAt,
3683
+ seq: event.seq
3684
+ };
3685
+ };
3686
+ const list = async (conversationId) => {
3687
+ const values = new Map;
3688
+ let cursor = 1;
3689
+ for (;; ) {
3690
+ const page = await input.store.readEvents({
3691
+ conversationId,
3692
+ fromSeq: cursor,
3693
+ limit: 1000
3694
+ });
3695
+ for (const event of page.items) {
3696
+ if (event.kind !== "state/set")
3697
+ continue;
3698
+ const payload = StateSetPayloadSchema.parse(event.payload);
3699
+ const definition = definitions.get(payload.name);
3700
+ if (!definition || definition.version !== payload.version)
3701
+ continue;
3702
+ values.set(payload.name, {
3703
+ name: payload.name,
3704
+ version: payload.version,
3705
+ value: definition.schema.parse(payload.value),
3706
+ updatedAt: event.occurredAt,
3707
+ seq: event.seq
3708
+ });
3709
+ }
3710
+ if (page.nextSeq === undefined)
3711
+ break;
3712
+ cursor = page.nextSeq;
3713
+ }
3714
+ return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
3715
+ };
3716
+ const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
3717
+ return { set, get, list };
3718
+ }
3719
+ function renderAgentStateSlots2(values) {
3720
+ if (values.length === 0)
3721
+ return;
3722
+ return [
3723
+ "Durable conversation state (authoritative; newer than compacted history):",
3724
+ ...values.map((slot) => `${slot.name}: ${JSON.stringify(slot.value)}`)
3725
+ ].join(`
3726
+ `);
3727
+ }
3728
+ var agentGoalStateSlot2 = defineStateSlot2({
3729
+ name: "goal",
3730
+ description: "The durable objective and lifecycle of this conversation.",
3731
+ schema: z7.object({
3732
+ objective: z7.string().min(1),
3733
+ status: z7.enum(["active", "complete", "blocked"])
3734
+ }).strict()
3735
+ });
3736
+ var agentTodoStateSlot2 = defineStateSlot2({
3737
+ name: "todo",
3738
+ description: "The durable ordered work plan for this conversation.",
3739
+ schema: z7.object({
3740
+ items: z7.array(z7.object({
3741
+ step: z7.string().min(1),
3742
+ status: z7.enum(["pending", "in_progress", "completed"])
3743
+ }).strict())
3744
+ }).strict()
3745
+ });
3746
+
3747
+ // src/agent-runtime/run-prompt-history.ts
3742
3748
  function snapshotForRunPrompt(snapshot, runId) {
3743
3749
  const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
3744
3750
  if (runIndex < 0)