stitchkit 0.68.9 → 0.68.11

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 (59) hide show
  1. package/dist/agent-runtime/deferred-tool-search.d.ts +8 -0
  2. package/dist/agent-runtime/deferred-tool-search.d.ts.map +1 -0
  3. package/dist/agent-runtime/deferred-tool-selection.d.ts +15 -0
  4. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -0
  5. package/dist/agent-runtime/deferred-tool-types.d.ts +131 -0
  6. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -0
  7. package/dist/agent-runtime/deferred-tools-internal.d.ts +10 -0
  8. package/dist/agent-runtime/deferred-tools-internal.d.ts.map +1 -0
  9. package/dist/agent-runtime/deferred-tools.d.ts +4 -0
  10. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -0
  11. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  12. package/dist/agent-runtime-openrouter.js +1 -1
  13. package/dist/agent-runtime.d.ts +1 -0
  14. package/dist/agent-runtime.d.ts.map +1 -1
  15. package/dist/agent-runtime.js +471 -73
  16. package/dist/browser/socket-io.d.ts +8 -2
  17. package/dist/browser/socket-io.d.ts.map +1 -1
  18. package/dist/cli.js +7 -8
  19. package/dist/contract/index.js +2 -2
  20. package/dist/{index-vkk06pv1.js → index-22by16v6.js} +57 -9
  21. package/dist/{index-hmfpjnh7.js → index-22tjt2rk.js} +2 -2
  22. package/dist/{index-1bmpkhj2.js → index-2t6zt5cg.js} +9 -134
  23. package/dist/{index-557by2db.js → index-7b188kmz.js} +15 -0
  24. package/dist/index-bt5179zb.js +99 -0
  25. package/dist/index-eqqyd9v8.js +130 -0
  26. package/dist/{index-51a19y3v.js → index-f24xg2cw.js} +2 -2
  27. package/dist/{index-j2nq04z6.js → index-f6n5n7nz.js} +1 -1
  28. package/dist/{index-9t2tdk1x.js → index-grgvpbch.js} +3 -5
  29. package/dist/{index-n34x0q5e.js → index-hb0mncmj.js} +3 -3
  30. package/dist/{index-6tqys26z.js → index-hcx9yypn.js} +4 -4
  31. package/dist/{index-z575awm9.js → index-hxh98zbm.js} +2 -2
  32. package/dist/{index-bmmtz6r9.js → index-pgsyp3xh.js} +1 -1
  33. package/dist/index-qyrqwr4c.js +41 -0
  34. package/dist/{index-r5s4wqb5.js → index-t23p2b68.js} +1 -1
  35. package/dist/{index-3ydx9j01.js → index-xyvxez9r.js} +3 -3
  36. package/dist/{index-04agqrs8.js → index-y2ctppmg.js} +72 -6
  37. package/dist/index.js +171 -13
  38. package/dist/internal/typed.d.ts +8 -0
  39. package/dist/internal/typed.d.ts.map +1 -1
  40. package/dist/node.js +6 -6
  41. package/dist/observability/index.js +4 -4
  42. package/dist/react.js +1 -1
  43. package/dist/realtime/index.d.ts +1 -1
  44. package/dist/realtime/index.d.ts.map +1 -1
  45. package/dist/realtime/request.d.ts +25 -0
  46. package/dist/realtime/request.d.ts.map +1 -1
  47. package/dist/remote.js +4 -4
  48. package/dist/server/index.js +8 -8
  49. package/dist/testing.js +6 -7
  50. package/dist/tool-invoker.js +6 -8
  51. package/dist/tools/internal/surface-projector.d.ts +7 -0
  52. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  53. package/dist/tools.js +34 -115
  54. package/llms-full.txt +127 -2
  55. package/package.json +1 -1
  56. package/dist/index-6djpbnda.js +0 -56
  57. package/dist/index-88yyydag.js +0 -75
  58. package/dist/index-smpbdg6k.js +0 -27
  59. /package/dist/{index-tss6bk5c.js → index-ksp6e2ye.js} +0 -0
@@ -27,11 +27,18 @@ import {
27
27
  import {
28
28
  createBoundedSinkManager
29
29
  } from "./index-a59da114.js";
30
+ import {
31
+ buildToolManifest,
32
+ mountAgent
33
+ } from "./index-bt5179zb.js";
34
+ import {
35
+ defineRuntimeTool
36
+ } from "./index-eqqyd9v8.js";
30
37
  import {
31
38
  ToolExecutionControlError,
32
39
  isToolExecutionControlError
33
- } from "./index-04agqrs8.js";
34
- import"./index-51a19y3v.js";
40
+ } from "./index-y2ctppmg.js";
41
+ import"./index-f24xg2cw.js";
35
42
  import {
36
43
  AgentAssistantPlaceholderSchema,
37
44
  AgentControlPartSchema,
@@ -63,13 +70,15 @@ import {
63
70
  AgentUsageValueSchema,
64
71
  runStateForTerminalReason
65
72
  } from "./index-ysphyxax.js";
66
- import"./index-6djpbnda.js";
73
+ import"./index-22by16v6.js";
67
74
  import"./index-cby4ar3v.js";
68
75
  import {
69
76
  childSpan,
70
77
  createTraceContext
71
- } from "./index-bmmtz6r9.js";
72
- import"./index-smpbdg6k.js";
78
+ } from "./index-pgsyp3xh.js";
79
+ import {
80
+ executableAgentRuntimeTools
81
+ } from "./index-qyrqwr4c.js";
73
82
  import"./index-0w9abg87.js";
74
83
  import"./index-6k1937bx.js";
75
84
 
@@ -324,78 +333,462 @@ function createAgentSessionCoordinator() {
324
333
  }
325
334
  };
326
335
  }
327
- // src/agent-runtime/event-schema.ts
336
+ // src/agent-runtime/deferred-tool-types.ts
328
337
  import { z } from "zod";
329
- var AgentAdmissionEventSchema = z.object({
330
- type: z.literal("admission"),
338
+ var DeferredAgentToolSearchInputSchema = z.object({
339
+ query: z.string().min(1),
340
+ reason: z.enum(["inactive_call"]).optional()
341
+ });
342
+ var DeferredAgentToolMatchSchema = z.object({
343
+ name: z.string(),
344
+ description: z.string()
345
+ });
346
+ var DeferredAgentToolReceiptSchema = z.object({
347
+ schemaVersion: z.literal(1),
348
+ kind: z.literal("stitchkit.deferred-tool-selection"),
349
+ status: z.enum(["SELECTED", "SEARCH_REQUIRED", "NO_MATCH", "SELECTION_REFUSED"]),
350
+ runId: z.string(),
351
+ surfaceKey: z.string(),
352
+ selected: z.array(z.string()),
353
+ matches: z.array(DeferredAgentToolMatchSchema),
354
+ truncated: z.boolean()
355
+ }).superRefine((receipt, context) => {
356
+ const selected = receipt.status === "SELECTED" || receipt.status === "SEARCH_REQUIRED";
357
+ if (selected !== receipt.selected.length > 0) {
358
+ context.addIssue({
359
+ code: "custom",
360
+ path: ["selected"],
361
+ message: `${receipt.status} receipt has inconsistent selected tools`
362
+ });
363
+ }
364
+ });
365
+
366
+ // src/agent-runtime/deferred-tool-selection.ts
367
+ var encoder = new TextEncoder;
368
+ function utf8Bytes(value) {
369
+ return encoder.encode(typeof value === "string" ? value : JSON.stringify(value)).byteLength;
370
+ }
371
+ function positive(name, value) {
372
+ if (!Number.isInteger(value) || value <= 0)
373
+ throw new Error(`${name} must be a positive integer`);
374
+ }
375
+ function uniqueKnown(names, surface) {
376
+ const seen = new Set;
377
+ let rejected = 0;
378
+ for (const name of names) {
379
+ if (seen.has(name) || !surface.byName.has(name)) {
380
+ rejected += 1;
381
+ continue;
382
+ }
383
+ seen.add(name);
384
+ }
385
+ return { names: [...seen], rejected };
386
+ }
387
+ function schemaBytes(names, surface) {
388
+ let bytes = 0;
389
+ for (const name of names) {
390
+ const entry = name === surface.searchEntry.name ? surface.searchEntry : surface.byName.get(name);
391
+ if (entry)
392
+ bytes += utf8Bytes(entry);
393
+ }
394
+ return bytes;
395
+ }
396
+ function ranked(query, manifest) {
397
+ const needle = query.trim().toLocaleLowerCase();
398
+ return manifest.map((entry, order) => {
399
+ const name = entry.name.toLocaleLowerCase();
400
+ const description = entry.description.toLocaleLowerCase();
401
+ const score = name === needle ? 0 : name.startsWith(needle) ? 1 : name.split(/[_-]/u).some((token) => token.startsWith(needle)) ? 2 : name.includes(needle) ? 3 : description.includes(needle) ? 4 : 5;
402
+ return { name: entry.name, order, score };
403
+ }).filter((entry) => entry.score < 5).sort((left, right) => left.score - right.score || left.order - right.order).map((entry) => entry.name);
404
+ }
405
+ function latestSelection(messages, searchName, runId, surface, maxSelectedTools) {
406
+ let selected = [];
407
+ let found = false;
408
+ for (const message of messages) {
409
+ if (message.role !== "tool" || typeof message.content === "string")
410
+ continue;
411
+ const replacement = [];
412
+ let validReceipts = 0;
413
+ for (const part of message.content) {
414
+ if (part.type !== "tool-result" || part.toolName !== searchName)
415
+ continue;
416
+ if (part.output.type !== "json")
417
+ continue;
418
+ const parsed = DeferredAgentToolReceiptSchema.safeParse(part.output.value);
419
+ if (!parsed.success || parsed.data.runId !== runId || parsed.data.surfaceKey !== surface.key)
420
+ continue;
421
+ const known = uniqueKnown(parsed.data.selected, surface);
422
+ if (known.rejected > 0 || known.names.length !== parsed.data.selected.length)
423
+ continue;
424
+ replacement.push(...known.names);
425
+ validReceipts += 1;
426
+ }
427
+ if (validReceipts > 0) {
428
+ const merged = uniqueKnown(replacement, surface).names;
429
+ if (merged.length > maxSelectedTools)
430
+ continue;
431
+ selected = merged;
432
+ found = true;
433
+ }
434
+ }
435
+ return { selected, source: found ? "durable" : "catalog" };
436
+ }
437
+
438
+ // src/agent-runtime/deferred-tool-search.ts
439
+ var description = "Search the available tool catalog and select exact tools for the next step.";
440
+ function placeholderDeferredSearch(name) {
441
+ return defineRuntimeTool({
442
+ name,
443
+ description,
444
+ identity: { serviceName: "agent-runtime", action: "deferred-tool-search", method: "POST" },
445
+ input: DeferredAgentToolSearchInputSchema,
446
+ output: DeferredAgentToolReceiptSchema,
447
+ transports: ["AGENT"],
448
+ handler: () => ({
449
+ schemaVersion: 1,
450
+ kind: "stitchkit.deferred-tool-selection",
451
+ status: "NO_MATCH",
452
+ runId: "construction",
453
+ surfaceKey: "construction",
454
+ selected: [],
455
+ matches: [],
456
+ truncated: false
457
+ })
458
+ });
459
+ }
460
+ function createDeferredSearchTool(config, runContext, surface) {
461
+ return defineRuntimeTool({
462
+ name: config.search.name,
463
+ description,
464
+ identity: { serviceName: "agent-runtime", action: "deferred-tool-search", method: "POST" },
465
+ input: DeferredAgentToolSearchInputSchema,
466
+ output: DeferredAgentToolReceiptSchema,
467
+ transports: ["AGENT"],
468
+ handler: async ({ input }) => {
469
+ const queryOversized = utf8Bytes(input.query) > config.search.maxQueryBytes;
470
+ const proposed = queryOversized ? [] : input.reason === "inactive_call" ? [input.query] : config.search.select ? await config.search.select({
471
+ query: input.query,
472
+ manifest: surface.manifest,
473
+ context: runContext.context,
474
+ runId: runContext.run.id,
475
+ surfaceKey: surface.key
476
+ }) : ranked(input.query, surface.manifest);
477
+ const known = uniqueKnown(proposed, surface);
478
+ const selected = known.names.slice(0, config.search.maxResults);
479
+ const candidateActive = [config.search.name, ...surface.alwaysOn, ...selected];
480
+ const refused = queryOversized || selected.length > config.activation.maxSelectedTools || candidateActive.length > config.activation.maxActiveTools || schemaBytes(candidateActive, surface) > config.activation.maxSchemaBytes;
481
+ const admitted = refused ? [] : selected;
482
+ const matches = [];
483
+ let truncated = known.names.length > selected.length;
484
+ for (const name of selected) {
485
+ const entry = surface.byName.get(name);
486
+ if (!entry)
487
+ continue;
488
+ const next = [...matches, { name, description: entry.description }];
489
+ if (utf8Bytes({
490
+ schemaVersion: 1,
491
+ kind: "stitchkit.deferred-tool-selection",
492
+ status: "SELECTED",
493
+ runId: runContext.run.id,
494
+ surfaceKey: surface.key,
495
+ selected: admitted,
496
+ matches: next,
497
+ truncated
498
+ }) > config.search.maxResultBytes) {
499
+ truncated = true;
500
+ break;
501
+ }
502
+ matches.push({ name, description: entry.description });
503
+ }
504
+ const status = refused ? "SELECTION_REFUSED" : input.reason === "inactive_call" && admitted.length > 0 ? "SEARCH_REQUIRED" : admitted.length > 0 ? "SELECTED" : "NO_MATCH";
505
+ let receipt = {
506
+ schemaVersion: 1,
507
+ kind: "stitchkit.deferred-tool-selection",
508
+ status,
509
+ runId: runContext.run.id,
510
+ surfaceKey: surface.key,
511
+ selected: admitted,
512
+ matches,
513
+ truncated
514
+ };
515
+ if (utf8Bytes(receipt) > config.search.maxResultBytes) {
516
+ receipt = {
517
+ schemaVersion: 1,
518
+ kind: "stitchkit.deferred-tool-selection",
519
+ status: "SELECTION_REFUSED",
520
+ runId: runContext.run.id,
521
+ surfaceKey: surface.key,
522
+ selected: [],
523
+ matches: [],
524
+ truncated: true
525
+ };
526
+ }
527
+ if (utf8Bytes(receipt) > config.search.maxResultBytes) {
528
+ throw new AgentContextOverflowError("Deferred Agent search receipt exceeds its byte ceiling");
529
+ }
530
+ config.observe?.({
531
+ schemaVersion: 1,
532
+ type: "search",
533
+ runId: runContext.run.id,
534
+ surfaceKey: surface.key,
535
+ catalogTools: surface.manifest.length,
536
+ baseTools: surface.alwaysOn.length + 1,
537
+ pinnedTools: 0,
538
+ selectedTools: receipt.selected.length,
539
+ activeTools: surface.alwaysOn.length + receipt.selected.length + 1,
540
+ activeSchemaBytes: schemaBytes([config.search.name, ...surface.alwaysOn, ...receipt.selected], surface),
541
+ rejectedNames: known.rejected,
542
+ replacementTools: receipt.selected.length,
543
+ source: "current"
544
+ });
545
+ return receipt;
546
+ }
547
+ });
548
+ }
549
+
550
+ // src/agent-runtime/deferred-tools-internal.ts
551
+ var repairs = new WeakMap;
552
+ var catalogs = new WeakMap;
553
+ function registerDeferredToolRepair(prepareStep, repair) {
554
+ repairs.set(prepareStep, repair);
555
+ }
556
+ function deferredToolRepair(prepareStep) {
557
+ return prepareStep ? repairs.get(prepareStep) : undefined;
558
+ }
559
+ function registerDeferredToolCatalog(tools, searchName, names) {
560
+ const search = tools[searchName];
561
+ if (search && typeof search === "object")
562
+ catalogs.set(search, names);
563
+ }
564
+ function deferredToolCatalog(tools, searchName) {
565
+ const search = tools[searchName];
566
+ return search && typeof search === "object" ? catalogs.get(search) : undefined;
567
+ }
568
+ function repairedSearchCall(toolCall, searchName) {
569
+ return {
570
+ ...toolCall,
571
+ toolName: searchName,
572
+ input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
573
+ };
574
+ }
575
+
576
+ // src/agent-runtime/deferred-tools.ts
577
+ function configuredSurfaces(config) {
578
+ return "surfaces" in config ? config.surfaces : { default: config };
579
+ }
580
+ function resolveSurface(config, surfaces, runContext) {
581
+ const key = "surfaces" in config ? config.selectSurface(runContext) : "default";
582
+ const surface = surfaces.get(key);
583
+ if (!surface)
584
+ throw new Error(`Unknown deferred Agent tool surface "${key}"`);
585
+ return surface;
586
+ }
587
+ function resolveAllSurfaces(config) {
588
+ const placeholderSearch = placeholderDeferredSearch(config.search.name);
589
+ const surfaces = new Map;
590
+ for (const [key, definition] of Object.entries(configuredSurfaces(config))) {
591
+ const runtimeTools = executableAgentRuntimeTools(definition.runtimeTools ?? []);
592
+ const fullManifest = buildToolManifest({
593
+ ...definition,
594
+ runtimeTools: [...runtimeTools, placeholderSearch],
595
+ transport: "AGENT"
596
+ });
597
+ const searchEntry = fullManifest.find((entry) => entry.name === config.search.name);
598
+ if (!searchEntry)
599
+ throw new Error(`Search tool "${config.search.name}" is not Agent-exposed`);
600
+ const manifest = fullManifest.filter((entry) => entry.name !== config.search.name);
601
+ const byName = new Map(manifest.map((entry) => [entry.name, entry]));
602
+ const provisional = {
603
+ key,
604
+ definition,
605
+ manifest,
606
+ byName,
607
+ searchEntry,
608
+ alwaysOn: []
609
+ };
610
+ const alwaysOn = uniqueKnown(definition.alwaysOn ?? [], provisional);
611
+ if (alwaysOn.rejected > 0)
612
+ throw new Error(`Surface "${key}" has an unknown or duplicate alwaysOn tool`);
613
+ surfaces.set(key, { ...provisional, alwaysOn: alwaysOn.names });
614
+ }
615
+ if (surfaces.size === 0)
616
+ throw new Error("Deferred Agent tool surface registry must not be empty");
617
+ return surfaces;
618
+ }
619
+ function assertConstructionBudgets(config, surfaces) {
620
+ for (const surface of surfaces.values()) {
621
+ const base = [...surface.alwaysOn, config.search.name];
622
+ if (base.length > config.activation.maxActiveTools) {
623
+ throw new Error(`Surface "${surface.key}" base tools exceed maxActiveTools`);
624
+ }
625
+ if (schemaBytes(base, surface) > config.activation.maxSchemaBytes) {
626
+ throw new Error(`Surface "${surface.key}" base tools exceed maxSchemaBytes`);
627
+ }
628
+ }
629
+ const minimumReceipt = {
630
+ schemaVersion: 1,
631
+ kind: "stitchkit.deferred-tool-selection",
632
+ status: "NO_MATCH",
633
+ runId: "run",
634
+ surfaceKey: "surface",
635
+ selected: [],
636
+ matches: [],
637
+ truncated: false
638
+ };
639
+ if (config.search.maxResultBytes < utf8Bytes(minimumReceipt)) {
640
+ throw new Error("search.maxResultBytes cannot contain the minimum search receipt");
641
+ }
642
+ }
643
+ function assertActiveBudget(config, names, surface) {
644
+ if (names.length > config.activation.maxActiveTools) {
645
+ throw new AgentContextOverflowError("Deferred Agent active-tool ceiling exceeded");
646
+ }
647
+ const bytes = schemaBytes(names, surface);
648
+ if (bytes > config.activation.maxSchemaBytes) {
649
+ throw new AgentContextOverflowError("Deferred Agent schema-byte ceiling exceeded");
650
+ }
651
+ return bytes;
652
+ }
653
+ function createDeferredAgentToolSurface(config) {
654
+ positive("search.maxQueryBytes", config.search.maxQueryBytes);
655
+ positive("search.maxResults", config.search.maxResults);
656
+ positive("search.maxResultBytes", config.search.maxResultBytes);
657
+ positive("activation.maxSelectedTools", config.activation.maxSelectedTools);
658
+ positive("activation.maxActiveTools", config.activation.maxActiveTools);
659
+ positive("activation.maxSchemaBytes", config.activation.maxSchemaBytes);
660
+ const surfaces = resolveAllSurfaces(config);
661
+ assertConstructionBudgets(config, surfaces);
662
+ return {
663
+ mount(runContext, mountConfig = {}) {
664
+ const surface = resolveSurface(config, surfaces, runContext);
665
+ const runtimeTools = [
666
+ ...executableAgentRuntimeTools(surface.definition.runtimeTools ?? []),
667
+ createDeferredSearchTool(config, runContext, surface)
668
+ ];
669
+ const tools = mountAgent([...surface.definition.services ?? []], {
670
+ ...mountConfig,
671
+ runtimeTools
672
+ });
673
+ registerDeferredToolCatalog(tools, config.search.name, new Set(surface.byName.keys()));
674
+ return tools;
675
+ },
676
+ prepareStep(applicationPrepareStep) {
677
+ const prepared = async (input) => {
678
+ const application = await applicationPrepareStep?.(input);
679
+ const surface = resolveSurface(config, surfaces, input);
680
+ const selection = latestSelection(input.messages, config.search.name, input.run.id, surface, config.activation.maxSelectedTools);
681
+ const currentSelection = latestSelection(input.responseMessages, config.search.name, input.run.id, surface, config.activation.maxSelectedTools);
682
+ const pins = uniqueKnown(config.pins?.(input) ?? [], surface);
683
+ if (pins.rejected > 0) {
684
+ throw new AgentContextOverflowError("Deferred Agent pins contain unknown or duplicate tools");
685
+ }
686
+ const selected = uniqueKnown(selection.selected, surface);
687
+ const names = uniqueKnown([config.search.name, ...surface.alwaysOn, ...pins.names, ...selected.names], surface).names;
688
+ if (!names.includes(config.search.name))
689
+ names.unshift(config.search.name);
690
+ const bytes = assertActiveBudget(config, names, surface);
691
+ config.observe?.({
692
+ schemaVersion: 1,
693
+ type: "step",
694
+ runId: input.run.id,
695
+ surfaceKey: surface.key,
696
+ catalogTools: surface.manifest.length,
697
+ baseTools: surface.alwaysOn.length + 1,
698
+ pinnedTools: pins.names.length,
699
+ selectedTools: selected.names.length,
700
+ activeTools: names.length,
701
+ activeSchemaBytes: bytes,
702
+ rejectedNames: selected.rejected,
703
+ replacementTools: selected.names.length,
704
+ source: currentSelection.source === "durable" ? "current" : selection.source
705
+ });
706
+ return { ...application, activeTools: names };
707
+ };
708
+ const repair = async ({ toolCall, tools, error }) => {
709
+ const catalog = deferredToolCatalog(tools, config.search.name);
710
+ if (!("toolName" in error) || !catalog?.has(toolCall.toolName) || toolCall.toolName in tools) {
711
+ return null;
712
+ }
713
+ return repairedSearchCall(toolCall, config.search.name);
714
+ };
715
+ registerDeferredToolRepair(prepared, repair);
716
+ return prepared;
717
+ }
718
+ };
719
+ }
720
+ // src/agent-runtime/event-schema.ts
721
+ import { z as z2 } from "zod";
722
+ var AgentAdmissionEventSchema = z2.object({
723
+ type: z2.literal("admission"),
331
724
  eventId: AgentRecordIdSchema,
332
725
  conversationId: AgentRecordIdSchema,
333
726
  runId: AgentRecordIdSchema,
334
727
  snapshotVersion: AgentRecordVersionSchema,
335
728
  input: AgentMessageSchema,
336
729
  run: AgentRunSchema,
337
- assistant: z.union([AgentAssistantPlaceholderSchema, AgentMessageSchema]),
730
+ assistant: z2.union([AgentAssistantPlaceholderSchema, AgentMessageSchema]),
338
731
  emittedAt: AgentTimestampSchema
339
732
  });
340
- var EventIdentitySchema = z.object({
733
+ var EventIdentitySchema = z2.object({
341
734
  conversationId: AgentRecordIdSchema,
342
735
  runId: AgentRecordIdSchema,
343
736
  emittedAt: AgentTimestampSchema
344
737
  });
345
738
  var AgentTransientDeltaEventSchema = EventIdentitySchema.extend({
346
- type: z.literal("assistant-delta"),
347
- runtimeEpoch: z.string().min(1),
348
- sequence: z.int().nonnegative(),
349
- textDelta: z.string()
739
+ type: z2.literal("assistant-delta"),
740
+ runtimeEpoch: z2.string().min(1),
741
+ sequence: z2.int().nonnegative(),
742
+ textDelta: z2.string()
350
743
  });
351
744
  var AgentTransientReasoningIdentitySchema = EventIdentitySchema.extend({
352
- runtimeEpoch: z.string().min(1),
353
- sequence: z.int().nonnegative(),
745
+ runtimeEpoch: z2.string().min(1),
746
+ sequence: z2.int().nonnegative(),
354
747
  provider: AgentProviderEnvelopeSchema.optional()
355
748
  });
356
749
  var AgentReasoningStartEventSchema = AgentTransientReasoningIdentitySchema.extend({
357
- type: z.literal("reasoning-start")
750
+ type: z2.literal("reasoning-start")
358
751
  });
359
752
  var AgentReasoningDeltaEventSchema = AgentTransientReasoningIdentitySchema.extend({
360
- type: z.literal("reasoning-delta"),
361
- textDelta: z.string()
753
+ type: z2.literal("reasoning-delta"),
754
+ textDelta: z2.string()
362
755
  });
363
756
  var AgentReasoningEndEventSchema = AgentTransientReasoningIdentitySchema.extend({
364
- type: z.literal("reasoning-end")
757
+ type: z2.literal("reasoning-end")
365
758
  });
366
759
  var AgentCheckpointEventSchema = EventIdentitySchema.extend({
367
- type: z.literal("assistant-checkpoint"),
760
+ type: z2.literal("assistant-checkpoint"),
368
761
  eventId: AgentRecordIdSchema,
369
762
  snapshotVersion: AgentRecordVersionSchema,
370
763
  message: AgentMessageSchema,
371
764
  metrics: AgentRunMetricsSchema.optional()
372
765
  });
373
766
  var AgentRunStateEventSchema = EventIdentitySchema.extend({
374
- type: z.literal("run-state"),
767
+ type: z2.literal("run-state"),
375
768
  eventId: AgentRecordIdSchema,
376
769
  snapshotVersion: AgentRecordVersionSchema,
377
770
  state: AgentRunStateSchema
378
771
  });
379
772
  var AgentToolStatusEventSchema = EventIdentitySchema.extend({
380
- type: z.literal("tool-status"),
381
- runtimeEpoch: z.string().min(1),
382
- sequence: z.int().nonnegative(),
773
+ type: z2.literal("tool-status"),
774
+ runtimeEpoch: z2.string().min(1),
775
+ sequence: z2.int().nonnegative(),
383
776
  callId: AgentRecordIdSchema,
384
- toolName: z.string().min(1),
385
- status: z.enum(["started", "completed", "failed", "interrupted"]),
386
- input: z.json().optional(),
387
- output: z.json().optional()
777
+ toolName: z2.string().min(1),
778
+ status: z2.enum(["started", "completed", "failed", "interrupted"]),
779
+ input: z2.json().optional(),
780
+ output: z2.json().optional()
388
781
  });
389
782
  var AgentTerminalEventSchema = EventIdentitySchema.extend({
390
- type: z.literal("terminal"),
783
+ type: z2.literal("terminal"),
391
784
  eventId: AgentRecordIdSchema,
392
785
  snapshotVersion: AgentRecordVersionSchema,
393
786
  reason: AgentTerminalReasonSchema,
394
- policyName: z.string().min(1).optional(),
787
+ policyName: z2.string().min(1).optional(),
395
788
  message: AgentMessageSchema,
396
789
  metrics: AgentRunMetricsSchema.optional()
397
790
  });
398
- var AgentRuntimeEventSchema = z.discriminatedUnion("type", [
791
+ var AgentRuntimeEventSchema = z2.discriminatedUnion("type", [
399
792
  AgentAdmissionEventSchema,
400
793
  AgentTransientDeltaEventSchema,
401
794
  AgentReasoningStartEventSchema,
@@ -406,11 +799,11 @@ var AgentRuntimeEventSchema = z.discriminatedUnion("type", [
406
799
  AgentToolStatusEventSchema,
407
800
  AgentTerminalEventSchema
408
801
  ]);
409
- var AgentRuntimeEventCursorSchema = z.object({
802
+ var AgentRuntimeEventCursorSchema = z2.object({
410
803
  snapshotVersion: AgentRecordVersionSchema.optional(),
411
- durableEventIds: z.array(AgentRecordIdSchema).optional(),
412
- runtimeEpoch: z.string().min(1).optional(),
413
- sequence: z.int().nonnegative().optional()
804
+ durableEventIds: z2.array(AgentRecordIdSchema).optional(),
805
+ runtimeEpoch: z2.string().min(1).optional(),
806
+ sequence: z2.int().nonnegative().optional()
414
807
  });
415
808
  function isDurableEvent(event) {
416
809
  return event.type === "admission" || event.type === "assistant-checkpoint" || event.type === "run-state" || event.type === "terminal";
@@ -723,22 +1116,22 @@ function createAgentToolFenceLifecycle(config) {
723
1116
  };
724
1117
  }
725
1118
  // src/agent-runtime/models.ts
726
- import { z as z2 } from "zod";
727
- var AgentModelCapabilitySchema = z2.enum(["tools", "vision", "reasoning", "files"]);
728
- var AgentModelDescriptorSchema = z2.object({
729
- provider: z2.string().min(1),
730
- modelId: z2.string().min(1),
731
- contextWindow: z2.int().positive(),
732
- capabilities: z2.array(AgentModelCapabilitySchema),
733
- observedAt: z2.iso.datetime({ offset: true }).optional(),
734
- source: z2.string().min(1).optional(),
735
- availability: z2.enum(["available", "unavailable"]).optional()
1119
+ import { z as z3 } from "zod";
1120
+ var AgentModelCapabilitySchema = z3.enum(["tools", "vision", "reasoning", "files"]);
1121
+ var AgentModelDescriptorSchema = z3.object({
1122
+ provider: z3.string().min(1),
1123
+ modelId: z3.string().min(1),
1124
+ contextWindow: z3.int().positive(),
1125
+ capabilities: z3.array(AgentModelCapabilitySchema),
1126
+ observedAt: z3.iso.datetime({ offset: true }).optional(),
1127
+ source: z3.string().min(1).optional(),
1128
+ availability: z3.enum(["available", "unavailable"]).optional()
736
1129
  });
737
- var AgentModelRegistrySnapshotSchema = z2.object({
738
- schemaVersion: z2.literal(1),
739
- source: z2.string().min(1),
740
- observedAt: z2.iso.datetime({ offset: true }),
741
- models: z2.record(z2.string().min(1), AgentModelDescriptorSchema)
1130
+ var AgentModelRegistrySnapshotSchema = z3.object({
1131
+ schemaVersion: z3.literal(1),
1132
+ source: z3.string().min(1),
1133
+ observedAt: z3.iso.datetime({ offset: true }),
1134
+ models: z3.record(z3.string().min(1), AgentModelDescriptorSchema)
742
1135
  });
743
1136
  function defineModelRegistry(config) {
744
1137
  const descriptors = new Map;
@@ -809,38 +1202,38 @@ function validateAgentModelSnapshot(input, policy) {
809
1202
  return snapshot;
810
1203
  }
811
1204
  // src/agent-runtime/observability.ts
812
- import { z as z3 } from "zod";
813
- var AgentRunEventBaseSchema = z3.object({
814
- schemaVersion: z3.literal(1),
1205
+ import { z as z4 } from "zod";
1206
+ var AgentRunEventBaseSchema = z4.object({
1207
+ schemaVersion: z4.literal(1),
815
1208
  eventId: AgentRecordIdSchema,
816
1209
  conversationId: AgentRecordIdSchema,
817
1210
  runId: AgentRecordIdSchema,
818
- traceId: z3.string().min(1),
819
- spanId: z3.string().min(1),
820
- parentSpanId: z3.string().min(1).optional(),
1211
+ traceId: z4.string().min(1),
1212
+ spanId: z4.string().min(1),
1213
+ parentSpanId: z4.string().min(1).optional(),
821
1214
  state: AgentRunStateSchema,
822
- modelId: z3.string().min(1).optional(),
823
- durationMs: z3.number().nonnegative().optional(),
1215
+ modelId: z4.string().min(1).optional(),
1216
+ durationMs: z4.number().nonnegative().optional(),
824
1217
  emittedAt: AgentTimestampSchema
825
1218
  });
826
1219
  var AgentRunStartedEventSchema = AgentRunEventBaseSchema.extend({
827
- type: z3.literal("run-started"),
828
- queueWaitMs: z3.number().nonnegative().optional()
1220
+ type: z4.literal("run-started"),
1221
+ queueWaitMs: z4.number().nonnegative().optional()
829
1222
  });
830
1223
  var AgentStepFinishedEventSchema = AgentRunEventBaseSchema.extend({
831
- type: z3.literal("step-finished"),
832
- step: z3.int().nonnegative(),
833
- ttftMs: z3.number().nonnegative().optional(),
1224
+ type: z4.literal("step-finished"),
1225
+ step: z4.int().nonnegative(),
1226
+ ttftMs: z4.number().nonnegative().optional(),
834
1227
  usage: AgentUsageSchema
835
1228
  });
836
1229
  var AgentRunTerminalEventSchema = AgentRunEventBaseSchema.extend({
837
- type: z3.literal("run-terminal"),
1230
+ type: z4.literal("run-terminal"),
838
1231
  terminalReason: AgentTerminalReasonSchema,
839
- ttftMs: z3.number().nonnegative().optional(),
840
- internalCause: z3.unknown().optional(),
1232
+ ttftMs: z4.number().nonnegative().optional(),
1233
+ internalCause: z4.unknown().optional(),
841
1234
  usage: AgentUsageSchema
842
1235
  });
843
- var AgentRunEventSchema = z3.discriminatedUnion("type", [
1236
+ var AgentRunEventSchema = z4.discriminatedUnion("type", [
844
1237
  AgentRunStartedEventSchema,
845
1238
  AgentStepFinishedEventSchema,
846
1239
  AgentRunTerminalEventSchema
@@ -889,9 +1282,9 @@ function createAgentObservability(config) {
889
1282
  };
890
1283
  }
891
1284
  // src/agent-runtime/prompt.ts
892
- import { z as z4 } from "zod";
893
- var AgentTokenCountSchema = z4.object({
894
- value: z4.int().nonnegative().optional(),
1285
+ import { z as z5 } from "zod";
1286
+ var AgentTokenCountSchema = z5.object({
1287
+ value: z5.int().nonnegative().optional(),
895
1288
  provenance: AgentProvenanceSchema.extract([
896
1289
  "measured",
897
1290
  "computed",
@@ -1206,7 +1599,7 @@ import {
1206
1599
  } from "ai";
1207
1600
 
1208
1601
  // src/agent-runtime/runtime-internals.ts
1209
- import { z as z5 } from "zod";
1602
+ import { z as z6 } from "zod";
1210
1603
 
1211
1604
  // src/agent-runtime/terminal-commit.ts
1212
1605
  class AgentRuntimeConflictError extends Error {
@@ -1339,7 +1732,7 @@ function findRun(runs, runId) {
1339
1732
  return run;
1340
1733
  }
1341
1734
  function jsonValue(value) {
1342
- const parsed = z5.json().safeParse(value);
1735
+ const parsed = z6.json().safeParse(value);
1343
1736
  return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
1344
1737
  }
1345
1738
  function providerEnvelope(value) {
@@ -1795,6 +2188,7 @@ function createRunExecutor(dependencies) {
1795
2188
  abortSignal: executionSignal,
1796
2189
  maxRetries: 0,
1797
2190
  stopWhen: stopConditions,
2191
+ repairToolCall: deferredToolRepair(config.loop?.prepareStep),
1798
2192
  ...(config.loop?.prepareStep || injection) && {
1799
2193
  prepareStep: async (options) => {
1800
2194
  const prepared = await config.loop?.prepareStep?.({
@@ -2855,6 +3249,9 @@ export {
2855
3249
  AgentUsageValueSchema,
2856
3250
  CheckpointRunAssistantSchema,
2857
3251
  CommitRunTerminalSchema,
3252
+ DeferredAgentToolMatchSchema,
3253
+ DeferredAgentToolReceiptSchema,
3254
+ DeferredAgentToolSearchInputSchema,
2858
3255
  RecoverAgentRunSchema,
2859
3256
  ReplaceCompactedRangeSchema,
2860
3257
  RequestRunInterruptSchema,
@@ -2867,6 +3264,7 @@ export {
2867
3264
  createAgentRuntimeStore,
2868
3265
  createAgentSessionCoordinator,
2869
3266
  createAgentToolFenceLifecycle,
3267
+ createDeferredAgentToolSurface,
2870
3268
  createMemoryAgentRuntimeStore,
2871
3269
  defineAgentProtocol,
2872
3270
  defineModelRegistry,