stitchkit 0.98.2 → 0.100.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 (143) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/dist/agent-runtime/contained-darwin.d.ts +0 -17
  3. package/dist/agent-runtime/contained-darwin.d.ts.map +1 -1
  4. package/dist/agent-runtime/contained-write.d.ts.map +1 -1
  5. package/dist/agent-runtime/invocation-attempt.d.ts +22 -0
  6. package/dist/agent-runtime/invocation-attempt.d.ts.map +1 -0
  7. package/dist/agent-runtime/invocation-failure.d.ts +6 -0
  8. package/dist/agent-runtime/invocation-failure.d.ts.map +1 -0
  9. package/dist/agent-runtime/invocation-payload.d.ts +18 -0
  10. package/dist/agent-runtime/invocation-payload.d.ts.map +1 -0
  11. package/dist/agent-runtime/invocation-read.d.ts +131 -0
  12. package/dist/agent-runtime/invocation-read.d.ts.map +1 -0
  13. package/dist/agent-runtime/invocation-schema.d.ts +378 -0
  14. package/dist/agent-runtime/invocation-schema.d.ts.map +1 -0
  15. package/dist/agent-runtime/invocations.d.ts +46 -0
  16. package/dist/agent-runtime/invocations.d.ts.map +1 -0
  17. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -1
  18. package/dist/agent-runtime/run-execution-state.d.ts +4 -2
  19. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -1
  20. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  21. package/dist/agent-runtime/run-failure.d.ts.map +1 -1
  22. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -1
  23. package/dist/agent-runtime/run-operation-lifecycle.d.ts +2 -2
  24. package/dist/agent-runtime/run-operation-lifecycle.d.ts.map +1 -1
  25. package/dist/agent-runtime/run-provider-ledger.d.ts +1 -0
  26. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -1
  27. package/dist/agent-runtime/runtime.d.ts +11 -0
  28. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  29. package/dist/agent-runtime/store-create.d.ts.map +1 -1
  30. package/dist/agent-runtime/store-event-once.d.ts +29 -0
  31. package/dist/agent-runtime/store-event-once.d.ts.map +1 -0
  32. package/dist/agent-runtime/store.d.ts +5 -0
  33. package/dist/agent-runtime/store.d.ts.map +1 -1
  34. package/dist/application/change-subscription.d.ts +36 -0
  35. package/dist/application/change-subscription.d.ts.map +1 -0
  36. package/dist/application/diagnostic-journal-contract.d.ts +3 -6
  37. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  38. package/dist/application/notification-delivery.d.ts +32 -0
  39. package/dist/application/notification-delivery.d.ts.map +1 -0
  40. package/dist/application/notification-outbox-state.d.ts +37 -0
  41. package/dist/application/notification-outbox-state.d.ts.map +1 -0
  42. package/dist/application/notification-outbox.d.ts +7 -1
  43. package/dist/application/notification-outbox.d.ts.map +1 -1
  44. package/dist/application/watch-hub-core.d.ts +10 -15
  45. package/dist/application/watch-hub-core.d.ts.map +1 -1
  46. package/dist/application/watch-hub.d.ts +10 -2
  47. package/dist/application/watch-hub.d.ts.map +1 -1
  48. package/dist/browser/session-credentials.d.ts +20 -0
  49. package/dist/browser/session-credentials.d.ts.map +1 -0
  50. package/dist/browser/session.d.ts +31 -0
  51. package/dist/browser/session.d.ts.map +1 -0
  52. package/dist/durability/events.d.ts +6 -0
  53. package/dist/durability/events.d.ts.map +1 -1
  54. package/dist/entrypoints/agent-runtime/coding-tools.js +5 -4
  55. package/dist/entrypoints/agent-runtime/harness.js +8 -6
  56. package/dist/entrypoints/agent-runtime/sandbox.js +5 -4
  57. package/dist/entrypoints/agent-runtime/sqlite/bun.js +3 -3
  58. package/dist/entrypoints/agent-runtime/sqlite/node.js +3 -3
  59. package/dist/entrypoints/agent-runtime/testing.js +3 -3
  60. package/dist/entrypoints/agent-runtime.d.ts +3 -0
  61. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  62. package/dist/entrypoints/agent-runtime.js +21 -10
  63. package/dist/entrypoints/application/diagnostic-journal.js +2 -1
  64. package/dist/entrypoints/application.d.ts +3 -1
  65. package/dist/entrypoints/application.d.ts.map +1 -1
  66. package/dist/entrypoints/application.js +629 -189
  67. package/dist/entrypoints/cli.js +6 -6
  68. package/dist/entrypoints/files.js +2 -1
  69. package/dist/entrypoints/index.d.ts +2 -0
  70. package/dist/entrypoints/index.d.ts.map +1 -1
  71. package/dist/entrypoints/index.js +172 -0
  72. package/dist/entrypoints/live.js +68 -13
  73. package/dist/entrypoints/react.d.ts +1 -1
  74. package/dist/entrypoints/react.d.ts.map +1 -1
  75. package/dist/entrypoints/react.js +59 -16
  76. package/dist/entrypoints/testing.js +1 -1
  77. package/dist/entrypoints/tools/connections.js +2 -2
  78. package/dist/entrypoints/tools/invoker.js +4 -4
  79. package/dist/entrypoints/tools.js +8 -8
  80. package/dist/{index-wsm5w4ee.js → index-0b1cnze2.js} +35 -3
  81. package/dist/{index-np4m8hd3.js → index-0r0fbk7z.js} +9 -7
  82. package/dist/{index-p9sh0xx4.js → index-5p2m7we1.js} +3 -3
  83. package/dist/{index-55hkhm67.js → index-8qt2m66q.js} +1 -1
  84. package/dist/{index-hmp4800j.js → index-9t3dffv2.js} +3 -3
  85. package/dist/{index-khtgb21r.js → index-bm5rx7n6.js} +2 -2
  86. package/dist/{index-gxrt5h6v.js → index-cyktc4bp.js} +3 -0
  87. package/dist/{index-xw3s75nj.js → index-d8m8zpd8.js} +1 -1
  88. package/dist/{index-px2gm2jp.js → index-fhwqwxe0.js} +17 -55
  89. package/dist/{index-het2he5g.js → index-gw8bmyaj.js} +5 -3
  90. package/dist/{index-8p52kd5p.js → index-js7gqrb1.js} +96 -14
  91. package/dist/{index-wt743f7f.js → index-k6gpggb9.js} +2 -1
  92. package/dist/index-q3pyb9n0.js +22 -0
  93. package/dist/{index-f1nb70ae.js → index-r066jx76.js} +4 -4
  94. package/dist/{index-sp1tzwnb.js → index-s84he4v7.js} +2 -2
  95. package/dist/{index-863ea9jb.js → index-sh3s86na.js} +3 -3
  96. package/dist/{index-nts4a2br.js → index-xwhjjw2x.js} +879 -280
  97. package/dist/{index-1m2thnq0.js → index-y9qn426m.js} +2 -2
  98. package/dist/index-zjjyynm3.js +42 -0
  99. package/dist/internal/coalesced-task.d.ts +15 -0
  100. package/dist/internal/coalesced-task.d.ts.map +1 -0
  101. package/dist/internal/darwin-binding.d.ts +19 -0
  102. package/dist/internal/darwin-binding.d.ts.map +1 -0
  103. package/dist/internal/exclusive-lock.d.ts +20 -7
  104. package/dist/internal/exclusive-lock.d.ts.map +1 -1
  105. package/dist/internal/mutation-queue.d.ts +4 -0
  106. package/dist/internal/mutation-queue.d.ts.map +1 -0
  107. package/dist/internal/process-identity.d.ts +1 -1
  108. package/dist/internal/process-identity.d.ts.map +1 -1
  109. package/dist/internal/process-instance.d.ts +26 -0
  110. package/dist/internal/process-instance.d.ts.map +1 -0
  111. package/dist/live/watch-client-state.d.ts +71 -0
  112. package/dist/live/watch-client-state.d.ts.map +1 -0
  113. package/dist/live/watch-client.d.ts +5 -1
  114. package/dist/live/watch-client.d.ts.map +1 -1
  115. package/dist/live/watch-contract.d.ts +12 -0
  116. package/dist/live/watch-contract.d.ts.map +1 -1
  117. package/dist/react/cache-bridge.d.ts +10 -0
  118. package/dist/react/cache-bridge.d.ts.map +1 -1
  119. package/dist/tools/schema/flatten-join.d.ts.map +1 -1
  120. package/llms/agent-runtime.2.txt +94 -0
  121. package/llms/agent-runtime.3.txt +24 -0
  122. package/llms/application.2.txt +68 -2
  123. package/llms/application.txt +32 -2
  124. package/llms/files.txt +1 -1
  125. package/llms/live.txt +7 -0
  126. package/llms/react.txt +8 -0
  127. package/llms/server.3.txt +35 -0
  128. package/llms/stitchkit.2.txt +41 -0
  129. package/llms/stitchkit.3.txt +22 -0
  130. package/llms/stitchkit.txt +3 -3
  131. package/llms/tools.txt +9 -8
  132. package/llms/upgrading-0.37.0.txt +176 -0
  133. package/llms/{upgrading-0.37.0-0.58.0.txt → upgrading-0.44.0-0.60.0.txt} +229 -169
  134. package/llms/{upgrading-0.59.0-0.71.0.txt → upgrading-0.61.0-0.73.0.txt} +122 -229
  135. package/llms/{upgrading-0.72.0-0.98.0.txt → upgrading-0.74.0-0.100.0.txt} +96 -122
  136. package/llms/upgrading.txt +4 -3
  137. package/llms-full.txt +431 -14
  138. package/llms.txt +11 -10
  139. package/native/darwin-arm64.node +0 -0
  140. package/native/darwin-x64.node +0 -0
  141. package/package.json +1 -1
  142. package/dist/agent-runtime/run-mutation-queue.d.ts +0 -21
  143. package/dist/agent-runtime/run-mutation-queue.d.ts.map +0 -1
@@ -16,7 +16,7 @@ import {
16
16
  createToolChronology,
17
17
  isAssistantHistoryEvidence,
18
18
  isCompleteAgentHistoryTurn
19
- } from "./index-gxrt5h6v.js";
19
+ } from "./index-cyktc4bp.js";
20
20
  import {
21
21
  AgentAssistantPlaceholderSchema,
22
22
  AgentJsonObjectSchema,
@@ -27,8 +27,12 @@ import {
27
27
  AgentRunOperationSchema,
28
28
  AgentRunSchema,
29
29
  AgentSnapshotSchema,
30
+ AgentUsageSchema,
30
31
  runStateForTerminalReason
31
32
  } from "./index-gtj3zc53.js";
33
+ import {
34
+ createMutationQueue
35
+ } from "./index-q3pyb9n0.js";
32
36
  import {
33
37
  createLocalStepDurability,
34
38
  createToolDurabilityContext,
@@ -37,7 +41,10 @@ import {
37
41
  import {
38
42
  ToolExecutionControlError,
39
43
  isToolExecutionControlError
40
- } from "./index-55hkhm67.js";
44
+ } from "./index-8qt2m66q.js";
45
+ import {
46
+ serializeCanonicalJson
47
+ } from "./index-k5hsfc3j.js";
41
48
  import {
42
49
  isRecord,
43
50
  transportResult
@@ -596,15 +603,821 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
596
603
  decisions.push(decide(message, "omitted", "incomplete-tool-turn"));
597
604
  continue;
598
605
  }
599
- const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
600
- chronology = nextChronology;
601
- projected.push(...assistant.messages);
602
- decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
603
- }
604
- return { messages: projected, decisions, system };
605
- }
606
- async function projectAgentHistory(messages, options = {}) {
607
- return [...(await projectAgentHistoryDetailed(messages, options)).messages];
606
+ const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
607
+ chronology = nextChronology;
608
+ projected.push(...assistant.messages);
609
+ decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
610
+ }
611
+ return { messages: projected, decisions, system };
612
+ }
613
+ async function projectAgentHistory(messages, options = {}) {
614
+ return [...(await projectAgentHistoryDetailed(messages, options)).messages];
615
+ }
616
+
617
+ // src/agent-runtime/invocation-schema.ts
618
+ import { z } from "zod";
619
+ var Id = z.string().min(1).max(512);
620
+ var Hash = z.string().regex(/^[a-f0-9]{64}$/);
621
+ var ModelInvocationTraceSchema = z.object({
622
+ operationId: Id,
623
+ purpose: Id,
624
+ project: Id,
625
+ parent: z.object({ traceId: Id, invocationId: Id.optional() }).strict().optional(),
626
+ experiment: Id.optional(),
627
+ case: Id.optional(),
628
+ profile: Id.optional()
629
+ }).strict();
630
+ var CompletionInvocationInputSchema = z.object({
631
+ conversationId: Id,
632
+ idempotencyKey: Id,
633
+ trace: ModelInvocationTraceSchema,
634
+ prompt: z.string().min(1),
635
+ models: z.array(Id).min(1).max(8),
636
+ settings: z.object({
637
+ maxOutputTokens: z.int().positive().optional(),
638
+ temperature: z.number().finite().optional(),
639
+ topP: z.number().min(0).max(1).optional(),
640
+ seed: z.int().optional()
641
+ }).strict().optional(),
642
+ timeoutMs: z.int().positive().max(3600000)
643
+ }).strict();
644
+ var Identity = z.object({
645
+ provider: Id.nullable(),
646
+ modelId: Id.nullable(),
647
+ responseId: Id.nullable()
648
+ }).strict();
649
+ var InvocationCallerSchema = z.object({ subject: Id }).strict();
650
+ var InvocationProcessSchema = z.object({
651
+ instanceId: Id,
652
+ pid: z.int().positive(),
653
+ hostname: Id
654
+ }).strict();
655
+ var Base = z.object({
656
+ conversationId: Id,
657
+ invocationId: Id,
658
+ operationId: Id,
659
+ runId: Id.optional()
660
+ });
661
+ var InvocationStartedSchema = Base.extend({
662
+ type: z.literal("invocation/started"),
663
+ mode: z.enum(["completion", "agent"]),
664
+ trace: ModelInvocationTraceSchema,
665
+ caller: InvocationCallerSchema,
666
+ executingProcess: InvocationProcessSchema,
667
+ fingerprint: Hash,
668
+ requested: z.object({ models: z.array(Id), payloadSha256: Hash }).strict()
669
+ }).strict();
670
+ var InvocationAttemptContextSchema = Base.extend({
671
+ attemptId: Id,
672
+ step: z.int().nonnegative()
673
+ }).strict();
674
+ var Attempt = Base.extend({ attemptId: Id, step: z.int().nonnegative() });
675
+ var InvocationRequestSchema = Attempt.extend({
676
+ type: z.literal("provider/request"),
677
+ requested: z.object({ modelId: Id, provider: Id }).strict(),
678
+ executingProcess: InvocationProcessSchema,
679
+ sent: z.object({
680
+ modelId: Id,
681
+ provider: Id,
682
+ payloadSha256: Hash,
683
+ artifactId: Id,
684
+ tools: z.int().nonnegative()
685
+ }).strict()
686
+ }).strict();
687
+ var InvocationResponseSchema = Attempt.extend({
688
+ type: z.literal("provider/response"),
689
+ status: z.enum(["succeeded", "failed", "cancelled"]),
690
+ effective: Identity,
691
+ usage: AgentUsageSchema,
692
+ artifactId: Id,
693
+ payloadSha256: Hash
694
+ }).strict();
695
+ var InvocationFinishedSchema = Base.extend({
696
+ type: z.literal("invocation/finished"),
697
+ failure: z.object({ artifactId: Id, payloadSha256: Hash }).strict().optional(),
698
+ status: z.enum(["succeeded", "failed", "cancelled"])
699
+ }).strict();
700
+ var ModelInvocationRecordSchema = z.discriminatedUnion("type", [
701
+ InvocationStartedSchema,
702
+ InvocationRequestSchema,
703
+ InvocationResponseSchema,
704
+ InvocationFinishedSchema
705
+ ]);
706
+ var InvocationPayloadSchema = Base.extend({
707
+ artifactId: Id,
708
+ sha256: Hash,
709
+ bytes: z.int().nonnegative(),
710
+ iv: z.string(),
711
+ tag: z.string(),
712
+ ciphertext: z.string()
713
+ }).strict();
714
+
715
+ // src/agent-runtime/invocation-attempt.ts
716
+ import { AsyncLocalStorage } from "node:async_hooks";
717
+ import { randomUUID as randomUUID2 } from "node:crypto";
718
+ import { wrapLanguageModel } from "ai";
719
+
720
+ // src/agent-runtime/invocation-failure.ts
721
+ class InvocationReceiptError extends Error {
722
+ constructor(cause) {
723
+ super("Model invocation receipt could not be recorded", { cause });
724
+ this.name = "InvocationReceiptError";
725
+ }
726
+ }
727
+ async function invocationAudit(work) {
728
+ try {
729
+ return await work();
730
+ } catch (error) {
731
+ throw error instanceof InvocationReceiptError ? error : new InvocationReceiptError(error);
732
+ }
733
+ }
734
+
735
+ // src/agent-runtime/invocation-payload.ts
736
+ import {
737
+ createCipheriv,
738
+ createDecipheriv,
739
+ createHash,
740
+ randomBytes,
741
+ randomUUID
742
+ } from "node:crypto";
743
+ import { z as z2 } from "zod";
744
+ function invocationJson(value) {
745
+ return z2.json().parse(JSON.parse(JSON.stringify(value, (_key, item) => {
746
+ if (item instanceof Uint8Array)
747
+ return { base64: Buffer.from(item).toString("base64") };
748
+ if (item instanceof ArrayBuffer)
749
+ return { base64: Buffer.from(item).toString("base64") };
750
+ if (item instanceof Error)
751
+ return { name: item.name, message: item.message, cause: item.cause };
752
+ return item;
753
+ })));
754
+ }
755
+ function invocationHash(value) {
756
+ return createHash("sha256").update(serializeCanonicalJson(invocationJson(value))).digest("hex");
757
+ }
758
+ function createInvocationPayloads(store, key, maxBytes) {
759
+ if (key.byteLength !== 32)
760
+ throw new TypeError("Invocation payload key must contain 32 bytes");
761
+ const encryptionKey = Uint8Array.from(key);
762
+ return {
763
+ async write(identity, value) {
764
+ const data = Buffer.from(serializeCanonicalJson(invocationJson(value)));
765
+ if (data.byteLength > maxBytes)
766
+ throw new RangeError("Invocation payload exceeds maxPayloadBytes");
767
+ const artifactId = randomUUID();
768
+ const sha256 = createHash("sha256").update(data).digest("hex");
769
+ const iv = randomBytes(12);
770
+ const cipher = createCipheriv("aes-256-gcm", encryptionKey, iv);
771
+ cipher.setAAD(Buffer.from(JSON.stringify([identity.conversationId, identity.invocationId, artifactId])));
772
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
773
+ const { conversationId } = identity;
774
+ await store.appendEvent({
775
+ conversationId,
776
+ kind: "provider/payload",
777
+ payload: {
778
+ ...identity,
779
+ artifactId,
780
+ sha256,
781
+ bytes: data.byteLength,
782
+ iv: iv.toString("base64"),
783
+ tag: cipher.getAuthTag().toString("base64"),
784
+ ciphertext: ciphertext.toString("base64")
785
+ }
786
+ });
787
+ return { artifactId, sha256 };
788
+ },
789
+ decrypt(conversationId, value) {
790
+ const payload = InvocationPayloadSchema.parse(value);
791
+ if (payload.bytes > maxBytes || payload.ciphertext.length > Math.ceil(maxBytes / 3) * 4) {
792
+ throw new RangeError("Invocation payload exceeds maxPayloadBytes");
793
+ }
794
+ const decipher = createDecipheriv("aes-256-gcm", encryptionKey, Buffer.from(payload.iv, "base64"));
795
+ decipher.setAAD(Buffer.from(JSON.stringify([conversationId, payload.invocationId, payload.artifactId])));
796
+ decipher.setAuthTag(Buffer.from(payload.tag, "base64"));
797
+ const data = Buffer.concat([
798
+ decipher.update(Buffer.from(payload.ciphertext, "base64")),
799
+ decipher.final()
800
+ ]);
801
+ if (data.length !== payload.bytes || createHash("sha256").update(data).digest("hex") !== payload.sha256) {
802
+ throw new Error("Invocation payload integrity mismatch");
803
+ }
804
+ return z2.json().parse(JSON.parse(data.toString("utf8")));
805
+ }
806
+ };
807
+ }
808
+
809
+ // src/agent-runtime/provider-origin.ts
810
+ import {
811
+ InvalidToolApprovalError,
812
+ InvalidToolApprovalSignatureError,
813
+ ToolCallNotFoundForApprovalError
814
+ } from "ai";
815
+ var providerOrigin = new WeakSet;
816
+ function isOwnInputRefusal(error) {
817
+ return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
818
+ }
819
+ function markProviderOrigin(error) {
820
+ if (typeof error === "object" && error !== null)
821
+ providerOrigin.add(error);
822
+ return error;
823
+ }
824
+ function hasProviderOrigin(error) {
825
+ return typeof error === "object" && error !== null && providerOrigin.has(error);
826
+ }
827
+ function markProviderStream(stream) {
828
+ const reader = stream.getReader();
829
+ return new ReadableStream({
830
+ async pull(controller) {
831
+ let read;
832
+ try {
833
+ read = await reader.read();
834
+ } catch (error) {
835
+ controller.error(isOwnInputRefusal(error) ? error : markProviderOrigin(error));
836
+ return;
837
+ }
838
+ if (read.done)
839
+ controller.close();
840
+ else
841
+ controller.enqueue(read.value);
842
+ },
843
+ cancel(reason) {
844
+ return reader.cancel(reason);
845
+ }
846
+ });
847
+ }
848
+
849
+ // src/agent-runtime/runtime-internals.ts
850
+ import { z as z3 } from "zod";
851
+ function findRun(runs, runId) {
852
+ const run = runs.find((candidate) => candidate.id === runId);
853
+ if (!run)
854
+ throw new AgentRuntimeConflictError("run lookup");
855
+ return run;
856
+ }
857
+ function jsonValue(value) {
858
+ const parsed = z3.json().safeParse(value);
859
+ return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
860
+ }
861
+ function providerEnvelope(value) {
862
+ const parsed = AgentJsonObjectSchema.safeParse(value);
863
+ if (!parsed.success)
864
+ return;
865
+ return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
866
+ }
867
+ function providerResponseIdentity(id, provider) {
868
+ return AgentProviderResponseSchema.parse({
869
+ id,
870
+ ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
871
+ });
872
+ }
873
+ function appendText(parts, text) {
874
+ const previous = parts.at(-1);
875
+ if (previous?.type === "text") {
876
+ const next = AgentMessagePartSchema.parse({ ...previous, text: previous.text + text });
877
+ parts.splice(parts.length - 1, 1, next);
878
+ return;
879
+ }
880
+ parts.push(AgentMessagePartSchema.parse({ type: "text", text }));
881
+ }
882
+ function abortTerminalReason(signal) {
883
+ if (signal.reason === "shutdown")
884
+ return "shutdown";
885
+ if (signal.reason === "timeout")
886
+ return "timeout";
887
+ if (signal.reason === "supersede")
888
+ return "superseded";
889
+ return "interrupted";
890
+ }
891
+ function addUsage(total, step) {
892
+ const sum = (left, right) => {
893
+ if (left?.value === undefined && right?.value === undefined) {
894
+ return { provenance: "unavailable" };
895
+ }
896
+ if (left?.value === undefined)
897
+ return { ...right, provenance: "computed" };
898
+ if (right?.value === undefined)
899
+ return { ...left, provenance: "computed" };
900
+ return { value: left.value + right.value, provenance: "computed" };
901
+ };
902
+ const sumCost = (left, right) => {
903
+ if (left?.value === undefined || right?.value === undefined) {
904
+ return { provenance: "unavailable" };
905
+ }
906
+ if (left.currency !== right.currency)
907
+ return { provenance: "unavailable" };
908
+ return {
909
+ value: left.value + right.value,
910
+ ...left.currency && { currency: left.currency },
911
+ provenance: "computed"
912
+ };
913
+ };
914
+ if (!total)
915
+ return step;
916
+ const cost = sumCost(total.cost, step.cost);
917
+ return {
918
+ inputTokens: sum(total.inputTokens, step.inputTokens),
919
+ outputTokens: sum(total.outputTokens, step.outputTokens),
920
+ reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
921
+ cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
922
+ cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
923
+ ...cost && { cost }
924
+ };
925
+ }
926
+ function mergeModelTotals(sdkTotal, accumulated) {
927
+ const pick = (total, ours) => {
928
+ if (ours?.provenance === "unavailable")
929
+ return ours;
930
+ return total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
931
+ };
932
+ return {
933
+ inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
934
+ outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
935
+ reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
936
+ cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
937
+ cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
938
+ cost: accumulated?.cost ?? { provenance: "unavailable" }
939
+ };
940
+ }
941
+ function statedUsage(usage) {
942
+ const stated = (value) => value ?? { provenance: "unavailable" };
943
+ if (!usage)
944
+ return unknownUsage();
945
+ return {
946
+ inputTokens: stated(usage.inputTokens),
947
+ outputTokens: stated(usage.outputTokens),
948
+ reasoningTokens: stated(usage.reasoningTokens),
949
+ cacheReadTokens: stated(usage.cacheReadTokens),
950
+ cacheWriteTokens: stated(usage.cacheWriteTokens),
951
+ cost: stated(usage.cost)
952
+ };
953
+ }
954
+ function unknownUsage() {
955
+ const nothing = { provenance: "unavailable" };
956
+ return {
957
+ inputTokens: nothing,
958
+ outputTokens: nothing,
959
+ reasoningTokens: nothing,
960
+ cacheReadTokens: nothing,
961
+ cacheWriteTokens: nothing,
962
+ cost: nothing
963
+ };
964
+ }
965
+ function normalizeSdkUsage(value) {
966
+ const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
967
+ return {
968
+ inputTokens: reported(value.inputTokens),
969
+ outputTokens: reported(value.outputTokens),
970
+ reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
971
+ cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
972
+ cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
973
+ };
974
+ }
975
+ function createIdleDeadline(parent, timeoutMs) {
976
+ if (timeoutMs === undefined) {
977
+ const noop = () => {
978
+ return;
979
+ };
980
+ return {
981
+ signal: parent,
982
+ touch: noop,
983
+ start: noop,
984
+ stop: noop,
985
+ suspend: noop,
986
+ resume: noop,
987
+ dispose: noop
988
+ };
989
+ }
990
+ const controller = new AbortController;
991
+ let timer;
992
+ let active = false;
993
+ let suspended = 0;
994
+ const clear = () => {
995
+ if (timer !== undefined)
996
+ clearTimeout(timer);
997
+ timer = undefined;
998
+ };
999
+ const touch = () => {
1000
+ clear();
1001
+ if (!active || suspended > 0 || controller.signal.aborted)
1002
+ return;
1003
+ timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
1004
+ };
1005
+ return {
1006
+ signal: AbortSignal.any([parent, controller.signal]),
1007
+ touch,
1008
+ start() {
1009
+ active = true;
1010
+ touch();
1011
+ },
1012
+ stop() {
1013
+ active = false;
1014
+ clear();
1015
+ },
1016
+ suspend() {
1017
+ suspended += 1;
1018
+ clear();
1019
+ },
1020
+ resume() {
1021
+ suspended = Math.max(0, suspended - 1);
1022
+ touch();
1023
+ },
1024
+ dispose() {
1025
+ active = false;
1026
+ clear();
1027
+ }
1028
+ };
1029
+ }
1030
+
1031
+ // src/agent-runtime/invocation-attempt.ts
1032
+ var currentAttempt = new AsyncLocalStorage;
1033
+ function currentModelInvocationAttempt() {
1034
+ const value = currentAttempt.getStore();
1035
+ return value && { ...value };
1036
+ }
1037
+ function wrapInvocationModel(writer, selected, step, model = selected.model) {
1038
+ if (typeof model === "string")
1039
+ throw new TypeError("Invocation receipts require a resolved model object");
1040
+ const begin = async (params) => invocationAudit(async () => {
1041
+ const context = { ...writer.identity, step, attemptId: randomUUID2() };
1042
+ const { headers: _headers, abortSignal: _signal, ...payload } = params;
1043
+ const artifact = await writer.payloads.write(writer.identity, payload);
1044
+ await writer.append({
1045
+ ...writer.identity,
1046
+ type: "provider/request",
1047
+ attemptId: context.attemptId,
1048
+ step,
1049
+ executingProcess: writer.process,
1050
+ requested: {
1051
+ modelId: selected.descriptor.modelId,
1052
+ provider: selected.descriptor.provider
1053
+ },
1054
+ sent: {
1055
+ modelId: model.modelId,
1056
+ provider: model.provider,
1057
+ payloadSha256: artifact.sha256,
1058
+ artifactId: artifact.artifactId,
1059
+ tools: params.tools?.length ?? 0
1060
+ }
1061
+ });
1062
+ try {
1063
+ await writer.onAttempt?.({ ...context });
1064
+ } catch (error) {
1065
+ await finish(context, "failed", { phase: "transport-audit", error });
1066
+ throw error;
1067
+ }
1068
+ return context;
1069
+ });
1070
+ const finish = async (context, status, payload, usage, response, providerMetadata) => invocationAudit(async () => {
1071
+ const artifact = await writer.payloads.write(writer.identity, payload);
1072
+ await writer.append({
1073
+ ...writer.identity,
1074
+ type: "provider/response",
1075
+ attemptId: context.attemptId,
1076
+ step,
1077
+ status,
1078
+ effective: {
1079
+ provider: selected.resolveResponseProvider?.({ providerMetadata }) ?? null,
1080
+ modelId: response?.modelId ?? null,
1081
+ responseId: response?.id ?? null
1082
+ },
1083
+ usage: reportedUsage(selected, usage, providerMetadata),
1084
+ artifactId: artifact.artifactId,
1085
+ payloadSha256: artifact.sha256
1086
+ });
1087
+ });
1088
+ return wrapLanguageModel({
1089
+ model,
1090
+ middleware: {
1091
+ specificationVersion: "v4",
1092
+ async wrapGenerate({ doGenerate, params }) {
1093
+ const context = await begin(params);
1094
+ let result;
1095
+ try {
1096
+ result = await currentAttempt.run(context, doGenerate);
1097
+ } catch (error) {
1098
+ await finish(context, params.abortSignal?.aborted ? "cancelled" : "failed", {
1099
+ error
1100
+ });
1101
+ throw markProviderOrigin(error);
1102
+ }
1103
+ await finish(context, result.finishReason.unified === "error" ? "failed" : "succeeded", {
1104
+ content: result.content,
1105
+ usage: result.usage,
1106
+ response: result.response,
1107
+ providerMetadata: result.providerMetadata
1108
+ }, result.usage, result.response, result.providerMetadata);
1109
+ if (result.finishReason.unified === "error") {
1110
+ throw markProviderOrigin(new Error("Provider returned an error finish reason"));
1111
+ }
1112
+ return result;
1113
+ },
1114
+ async wrapStream({ doStream, params }) {
1115
+ const context = await begin(params);
1116
+ let result;
1117
+ try {
1118
+ result = await currentAttempt.run(context, doStream);
1119
+ } catch (error) {
1120
+ await finish(context, params.abortSignal?.aborted ? "cancelled" : "failed", {
1121
+ error
1122
+ });
1123
+ throw markProviderOrigin(error);
1124
+ }
1125
+ const reader = result.stream.getReader();
1126
+ let ended = false;
1127
+ let failed = false;
1128
+ let response;
1129
+ const output = [];
1130
+ let outputBytes = 0;
1131
+ const end = async (status, value, usage, metadata) => {
1132
+ if (ended)
1133
+ return;
1134
+ ended = true;
1135
+ await finish(context, status, { output, terminal: value }, usage, response, metadata);
1136
+ };
1137
+ return {
1138
+ ...result,
1139
+ stream: new ReadableStream({
1140
+ async pull(controller) {
1141
+ let next;
1142
+ try {
1143
+ next = await currentAttempt.run(context, () => reader.read());
1144
+ } catch (error) {
1145
+ await end(params.abortSignal?.aborted ? "cancelled" : "failed", { error });
1146
+ controller.error(markProviderOrigin(error));
1147
+ return;
1148
+ }
1149
+ if (next.done) {
1150
+ await end("failed", { reason: "stream-ended-without-finish" });
1151
+ controller.close();
1152
+ return;
1153
+ }
1154
+ const part = next.value;
1155
+ if (part.type === "response-metadata")
1156
+ response = part;
1157
+ if (part.type === "finish") {
1158
+ await end(failed || part.finishReason.unified === "error" ? "failed" : "succeeded", part, part.usage, part.providerMetadata);
1159
+ } else {
1160
+ if (part.type === "error")
1161
+ failed = true;
1162
+ const json = invocationJson(part);
1163
+ outputBytes += Buffer.byteLength(JSON.stringify(json));
1164
+ if (outputBytes > 1048576) {
1165
+ await reader.cancel();
1166
+ await end("failed", { reason: "receipt-output-limit" });
1167
+ throw new RangeError("Invocation stream evidence exceeds 1 MiB");
1168
+ }
1169
+ output.push(json);
1170
+ }
1171
+ controller.enqueue(part);
1172
+ },
1173
+ async cancel(reason) {
1174
+ try {
1175
+ await currentAttempt.run(context, () => reader.cancel(reason));
1176
+ } finally {
1177
+ await end("cancelled", { reason: "consumer-cancelled" });
1178
+ }
1179
+ }
1180
+ })
1181
+ };
1182
+ }
1183
+ }
1184
+ });
1185
+ }
1186
+ function reportedUsage(selected, value, providerMetadata) {
1187
+ const usage = {
1188
+ inputTokens: value?.inputTokens.total,
1189
+ outputTokens: value?.outputTokens.total,
1190
+ totalTokens: undefined,
1191
+ inputTokenDetails: {
1192
+ noCacheTokens: value?.inputTokens.noCache,
1193
+ cacheReadTokens: value?.inputTokens.cacheRead,
1194
+ cacheWriteTokens: value?.inputTokens.cacheWrite
1195
+ },
1196
+ outputTokenDetails: {
1197
+ textTokens: value?.outputTokens.text,
1198
+ reasoningTokens: value?.outputTokens.reasoning
1199
+ },
1200
+ ...value?.raw && { raw: value.raw }
1201
+ };
1202
+ return selected.normalizeUsage?.({ usage, providerMetadata }) ?? normalizeSdkUsage(usage);
1203
+ }
1204
+
1205
+ // src/agent-runtime/invocations.ts
1206
+ import { randomUUID as randomUUID3 } from "node:crypto";
1207
+ import { hostname } from "node:os";
1208
+ import { generateText } from "ai";
1209
+ import { z as z5 } from "zod";
1210
+
1211
+ // src/agent-runtime/invocation-read.ts
1212
+ import { z as z4 } from "zod";
1213
+ var InvocationReadInputSchema = z4.object({
1214
+ conversationId: z4.string().min(1),
1215
+ fromSeq: z4.int().positive().optional(),
1216
+ limit: z4.int().positive().max(1e4)
1217
+ }).strict();
1218
+ async function readInvocationRecords(store, input) {
1219
+ const page = await store.readEvents(InvocationReadInputSchema.parse(input));
1220
+ return {
1221
+ items: page.items.flatMap((event) => {
1222
+ if (![
1223
+ "invocation/started",
1224
+ "invocation/finished",
1225
+ "provider/request",
1226
+ "provider/response"
1227
+ ].includes(event.kind))
1228
+ return [];
1229
+ if (!event.payload || typeof event.payload !== "object" || !("invocationId" in event.payload))
1230
+ return [];
1231
+ return [
1232
+ {
1233
+ seq: event.seq,
1234
+ occurredAt: event.occurredAt,
1235
+ record: ModelInvocationRecordSchema.parse(event.payload)
1236
+ }
1237
+ ];
1238
+ }),
1239
+ ...page.nextSeq !== undefined && { nextSeq: page.nextSeq }
1240
+ };
1241
+ }
1242
+ async function readInvocationPayload(store, payloads, input) {
1243
+ let fromSeq;
1244
+ do {
1245
+ const page = await store.readEvents({
1246
+ conversationId: input.conversationId,
1247
+ fromSeq,
1248
+ limit: 1000
1249
+ });
1250
+ for (const event of page.items) {
1251
+ if (event.kind !== "provider/payload")
1252
+ continue;
1253
+ const payload = InvocationPayloadSchema.parse(event.payload);
1254
+ if (payload.artifactId === input.artifactId)
1255
+ return payloads.decrypt(input.conversationId, payload);
1256
+ }
1257
+ fromSeq = page.nextSeq;
1258
+ } while (fromSeq !== undefined);
1259
+ throw new Error("Invocation artifact not found");
1260
+ }
1261
+
1262
+ // src/agent-runtime/invocations.ts
1263
+ var executingProcess = { instanceId: randomUUID3(), pid: process.pid, hostname: hostname() };
1264
+ var agentBindings = new WeakMap;
1265
+ function beginAgentInvocation(ledger, store, input, context) {
1266
+ const binding = agentBindings.get(ledger);
1267
+ if (!binding || binding.store !== store)
1268
+ throw new TypeError("Agent and invocations must share the same store");
1269
+ return binding.start(input, context);
1270
+ }
1271
+ function createModelInvocationLedger(config) {
1272
+ const { store } = config;
1273
+ const appendOnce = store.appendEventOnce?.bind(store);
1274
+ if (!appendOnce)
1275
+ throw new TypeError("Model invocations require atomic store.appendEventOnce");
1276
+ const maxPayloadBytes = z5.int().min(1024).max(64 * 1024 * 1024).parse(config.maxPayloadBytes ?? 4 * 1024 * 1024);
1277
+ const payloads = createInvocationPayloads(store, config.payloadKey, maxPayloadBytes);
1278
+ const authorize = async (input) => InvocationCallerSchema.parse(await config.authorize(input));
1279
+ const start = async (input) => {
1280
+ const trace = ModelInvocationTraceSchema.parse(input.trace);
1281
+ const caller = await authorize({
1282
+ context: input.context,
1283
+ conversationId: input.conversationId,
1284
+ action: input.mode === "completion" ? "complete" : "agent",
1285
+ trace
1286
+ });
1287
+ const fingerprint = invocationHash({
1288
+ mode: input.mode,
1289
+ caller,
1290
+ trace,
1291
+ requested: input.requested
1292
+ });
1293
+ const identity = {
1294
+ conversationId: input.conversationId,
1295
+ invocationId: randomUUID3(),
1296
+ operationId: trace.operationId,
1297
+ ...input.runId && { runId: input.runId }
1298
+ };
1299
+ const started = InvocationStartedSchema.parse({
1300
+ ...identity,
1301
+ type: "invocation/started",
1302
+ mode: input.mode,
1303
+ trace,
1304
+ caller,
1305
+ executingProcess,
1306
+ fingerprint,
1307
+ requested: { models: input.models, payloadSha256: invocationHash(input.requested) }
1308
+ });
1309
+ const admission = await appendOnce({ conversationId: input.conversationId, kind: "invocation/started", payload: started }, input.key);
1310
+ const previous = InvocationStartedSchema.parse(admission.event.payload);
1311
+ if (previous.fingerprint !== fingerprint)
1312
+ throw new Error("Invocation idempotency key conflicts with an existing request");
1313
+ const writer = {
1314
+ identity: { ...identity, invocationId: previous.invocationId },
1315
+ process: executingProcess,
1316
+ payloads,
1317
+ onAttempt: config.onAttempt,
1318
+ async append(record) {
1319
+ const parsed = ModelInvocationRecordSchema.parse(record);
1320
+ await store.appendEvent({
1321
+ conversationId: input.conversationId,
1322
+ kind: parsed.type,
1323
+ payload: parsed
1324
+ });
1325
+ }
1326
+ };
1327
+ return { writer, duplicate: admission.outcome === "duplicate" };
1328
+ };
1329
+ const finish = (writer, status, failure) => writer.append({
1330
+ ...writer.identity,
1331
+ type: "invocation/finished",
1332
+ status,
1333
+ ...failure && { failure }
1334
+ });
1335
+ const ledger = {
1336
+ async complete(rawInput, context, signal) {
1337
+ const input = CompletionInvocationInputSchema.parse(rawInput);
1338
+ const { writer, duplicate } = await start({
1339
+ conversationId: input.conversationId,
1340
+ key: `completion:${input.idempotencyKey}`,
1341
+ trace: input.trace,
1342
+ mode: "completion",
1343
+ context,
1344
+ requested: input,
1345
+ models: input.models
1346
+ });
1347
+ const invocationId = writer.identity.invocationId;
1348
+ if (duplicate)
1349
+ return { invocationId, outcome: "duplicate" };
1350
+ const deadline = AbortSignal.timeout(input.timeoutMs);
1351
+ const abortSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
1352
+ try {
1353
+ for (const [step, key] of input.models.entries()) {
1354
+ abortSignal.throwIfAborted();
1355
+ const selected = config.models.resolve(key);
1356
+ try {
1357
+ const result = await generateText({
1358
+ model: wrapInvocationModel(writer, selected, step),
1359
+ prompt: input.prompt,
1360
+ ...input.settings,
1361
+ maxRetries: 0,
1362
+ abortSignal
1363
+ });
1364
+ await finish(writer, "succeeded");
1365
+ return { invocationId, outcome: "succeeded", text: result.text };
1366
+ } catch (error) {
1367
+ if (!hasProviderOrigin(error) || abortSignal.aborted || step === input.models.length - 1)
1368
+ throw error;
1369
+ }
1370
+ }
1371
+ throw new Error("No completion model attempt available");
1372
+ } catch (error) {
1373
+ const status = abortSignal.aborted ? "cancelled" : "failed";
1374
+ const artifact = await payloads.write(writer.identity, { error });
1375
+ await finish(writer, status, {
1376
+ artifactId: artifact.artifactId,
1377
+ payloadSha256: artifact.sha256
1378
+ });
1379
+ return { invocationId, outcome: status };
1380
+ }
1381
+ },
1382
+ async read(rawInput, context) {
1383
+ const input = InvocationReadInputSchema.parse(rawInput);
1384
+ await authorize({ context, conversationId: input.conversationId, action: "read" });
1385
+ return readInvocationRecords(store, input);
1386
+ },
1387
+ async readPayload(input, context) {
1388
+ await authorize({
1389
+ context,
1390
+ conversationId: input.conversationId,
1391
+ action: "read-payload"
1392
+ });
1393
+ return readInvocationPayload(store, payloads, input);
1394
+ }
1395
+ };
1396
+ agentBindings.set(ledger, {
1397
+ store,
1398
+ async start(input, context) {
1399
+ const { conversationId, id: runId } = input.run;
1400
+ const view = await store.loadRun({ conversationId, runId });
1401
+ if (view?.run.state !== "running" || view.run.ownerId !== input.run.ownerId || view.run.fencingToken !== input.run.fencingToken) {
1402
+ throw new Error("Invocation requires an owned running agent run");
1403
+ }
1404
+ const { writer } = await start({
1405
+ conversationId,
1406
+ runId,
1407
+ trace: input.trace,
1408
+ key: `agent:${runId}`,
1409
+ context,
1410
+ mode: "agent",
1411
+ models: [],
1412
+ requested: { runId }
1413
+ });
1414
+ return {
1415
+ wrap: (selected, step, override) => wrapInvocationModel(writer, selected, step, override),
1416
+ finish: (status) => finish(writer, status)
1417
+ };
1418
+ }
1419
+ });
1420
+ return ledger;
608
1421
  }
609
1422
 
610
1423
  // src/agent-runtime/managed-tools.ts
@@ -632,9 +1445,9 @@ function createAgentToolFenceLifecycle(config) {
632
1445
  }
633
1446
 
634
1447
  // src/agent-runtime/prompt.ts
635
- import { z } from "zod";
636
- var AgentTokenCountSchema = z.object({
637
- value: z.int().nonnegative().optional(),
1448
+ import { z as z6 } from "zod";
1449
+ var AgentTokenCountSchema = z6.object({
1450
+ value: z6.int().nonnegative().optional(),
638
1451
  provenance: AgentProvenanceSchema.extract([
639
1452
  "measured",
640
1453
  "computed",
@@ -754,7 +1567,7 @@ function knownValue(value) {
754
1567
  }
755
1568
  function composeAgentPrompt(sections) {
756
1569
  return async (options) => {
757
- const event = z.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
1570
+ const event = z6.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
758
1571
  const rendered = [];
759
1572
  let systemTotal = 0;
760
1573
  let userTotal = 0;
@@ -957,7 +1770,7 @@ async function recordAgentRetryDecision(input) {
957
1770
  }
958
1771
 
959
1772
  // src/agent-runtime/state-slots.ts
960
- import { z as z2 } from "zod";
1773
+ import { z as z7 } from "zod";
961
1774
  function defineStateSlot(input) {
962
1775
  if (input.name.length === 0)
963
1776
  throw new TypeError("State slot name must not be empty");
@@ -972,11 +1785,11 @@ function defineStateSlot(input) {
972
1785
  ...input.description && { description: input.description }
973
1786
  };
974
1787
  }
975
- var StateSetPayloadSchema = z2.object({
976
- name: z2.string().min(1),
977
- version: z2.int().positive(),
978
- value: z2.json(),
979
- actor: z2.enum(["agent", "human", "system"])
1788
+ var StateSetPayloadSchema = z7.object({
1789
+ name: z7.string().min(1),
1790
+ version: z7.int().positive(),
1791
+ value: z7.json(),
1792
+ actor: z7.enum(["agent", "human", "system"])
980
1793
  }).strict();
981
1794
  function slotRegistry(definitions) {
982
1795
  const result = new Map;
@@ -1058,204 +1871,22 @@ function renderAgentStateSlots(values) {
1058
1871
  var agentGoalStateSlot = defineStateSlot({
1059
1872
  name: "goal",
1060
1873
  description: "The durable objective and lifecycle of this conversation.",
1061
- schema: z2.object({
1062
- objective: z2.string().min(1),
1063
- status: z2.enum(["active", "complete", "blocked"])
1874
+ schema: z7.object({
1875
+ objective: z7.string().min(1),
1876
+ status: z7.enum(["active", "complete", "blocked"])
1064
1877
  }).strict()
1065
1878
  });
1066
1879
  var agentTodoStateSlot = defineStateSlot({
1067
1880
  name: "todo",
1068
1881
  description: "The durable ordered work plan for this conversation.",
1069
- schema: z2.object({
1070
- items: z2.array(z2.object({
1071
- step: z2.string().min(1),
1072
- status: z2.enum(["pending", "in_progress", "completed"])
1882
+ schema: z7.object({
1883
+ items: z7.array(z7.object({
1884
+ step: z7.string().min(1),
1885
+ status: z7.enum(["pending", "in_progress", "completed"])
1073
1886
  }).strict())
1074
1887
  }).strict()
1075
1888
  });
1076
1889
 
1077
- // src/agent-runtime/runtime-internals.ts
1078
- import { z as z3 } from "zod";
1079
- function findRun(runs, runId) {
1080
- const run = runs.find((candidate) => candidate.id === runId);
1081
- if (!run)
1082
- throw new AgentRuntimeConflictError("run lookup");
1083
- return run;
1084
- }
1085
- function jsonValue(value) {
1086
- const parsed = z3.json().safeParse(value);
1087
- return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
1088
- }
1089
- function providerEnvelope(value) {
1090
- const parsed = AgentJsonObjectSchema.safeParse(value);
1091
- if (!parsed.success)
1092
- return;
1093
- return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
1094
- }
1095
- function providerResponseIdentity(id, provider) {
1096
- return AgentProviderResponseSchema.parse({
1097
- id,
1098
- ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
1099
- });
1100
- }
1101
- function appendText(parts, text) {
1102
- const previous = parts.at(-1);
1103
- if (previous?.type === "text") {
1104
- const next = AgentMessagePartSchema.parse({ ...previous, text: previous.text + text });
1105
- parts.splice(parts.length - 1, 1, next);
1106
- return;
1107
- }
1108
- parts.push(AgentMessagePartSchema.parse({ type: "text", text }));
1109
- }
1110
- function abortTerminalReason(signal) {
1111
- if (signal.reason === "shutdown")
1112
- return "shutdown";
1113
- if (signal.reason === "timeout")
1114
- return "timeout";
1115
- if (signal.reason === "supersede")
1116
- return "superseded";
1117
- return "interrupted";
1118
- }
1119
- function addUsage(total, step) {
1120
- const sum = (left, right) => {
1121
- if (left?.value === undefined && right?.value === undefined) {
1122
- return { provenance: "unavailable" };
1123
- }
1124
- if (left?.value === undefined)
1125
- return { ...right, provenance: "computed" };
1126
- if (right?.value === undefined)
1127
- return { ...left, provenance: "computed" };
1128
- return { value: left.value + right.value, provenance: "computed" };
1129
- };
1130
- const sumCost = (left, right) => {
1131
- if (left?.value === undefined || right?.value === undefined) {
1132
- return { provenance: "unavailable" };
1133
- }
1134
- if (left.currency !== right.currency)
1135
- return { provenance: "unavailable" };
1136
- return {
1137
- value: left.value + right.value,
1138
- ...left.currency && { currency: left.currency },
1139
- provenance: "computed"
1140
- };
1141
- };
1142
- if (!total)
1143
- return step;
1144
- const cost = sumCost(total.cost, step.cost);
1145
- return {
1146
- inputTokens: sum(total.inputTokens, step.inputTokens),
1147
- outputTokens: sum(total.outputTokens, step.outputTokens),
1148
- reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
1149
- cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
1150
- cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
1151
- ...cost && { cost }
1152
- };
1153
- }
1154
- function mergeModelTotals(sdkTotal, accumulated) {
1155
- const pick = (total, ours) => {
1156
- if (ours?.provenance === "unavailable")
1157
- return ours;
1158
- return total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
1159
- };
1160
- return {
1161
- inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
1162
- outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
1163
- reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
1164
- cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
1165
- cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
1166
- cost: accumulated?.cost ?? { provenance: "unavailable" }
1167
- };
1168
- }
1169
- function statedUsage(usage) {
1170
- const stated = (value) => value ?? { provenance: "unavailable" };
1171
- if (!usage)
1172
- return unknownUsage();
1173
- return {
1174
- inputTokens: stated(usage.inputTokens),
1175
- outputTokens: stated(usage.outputTokens),
1176
- reasoningTokens: stated(usage.reasoningTokens),
1177
- cacheReadTokens: stated(usage.cacheReadTokens),
1178
- cacheWriteTokens: stated(usage.cacheWriteTokens),
1179
- cost: stated(usage.cost)
1180
- };
1181
- }
1182
- function unknownUsage() {
1183
- const nothing = { provenance: "unavailable" };
1184
- return {
1185
- inputTokens: nothing,
1186
- outputTokens: nothing,
1187
- reasoningTokens: nothing,
1188
- cacheReadTokens: nothing,
1189
- cacheWriteTokens: nothing,
1190
- cost: nothing
1191
- };
1192
- }
1193
- function normalizeSdkUsage(value) {
1194
- const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
1195
- return {
1196
- inputTokens: reported(value.inputTokens),
1197
- outputTokens: reported(value.outputTokens),
1198
- reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
1199
- cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
1200
- cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
1201
- };
1202
- }
1203
- function createIdleDeadline(parent, timeoutMs) {
1204
- if (timeoutMs === undefined) {
1205
- const noop = () => {
1206
- return;
1207
- };
1208
- return {
1209
- signal: parent,
1210
- touch: noop,
1211
- start: noop,
1212
- stop: noop,
1213
- suspend: noop,
1214
- resume: noop,
1215
- dispose: noop
1216
- };
1217
- }
1218
- const controller = new AbortController;
1219
- let timer;
1220
- let active = false;
1221
- let suspended = 0;
1222
- const clear = () => {
1223
- if (timer !== undefined)
1224
- clearTimeout(timer);
1225
- timer = undefined;
1226
- };
1227
- const touch = () => {
1228
- clear();
1229
- if (!active || suspended > 0 || controller.signal.aborted)
1230
- return;
1231
- timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
1232
- };
1233
- return {
1234
- signal: AbortSignal.any([parent, controller.signal]),
1235
- touch,
1236
- start() {
1237
- active = true;
1238
- touch();
1239
- },
1240
- stop() {
1241
- active = false;
1242
- clear();
1243
- },
1244
- suspend() {
1245
- suspended += 1;
1246
- clear();
1247
- },
1248
- resume() {
1249
- suspended = Math.max(0, suspended - 1);
1250
- touch();
1251
- },
1252
- dispose() {
1253
- active = false;
1254
- clear();
1255
- }
1256
- };
1257
- }
1258
-
1259
1890
  // src/agent-runtime/runtime-control.ts
1260
1891
  async function interruptAgentRun(state, input) {
1261
1892
  const { store } = state.config;
@@ -1744,64 +2375,8 @@ function checkpoint(execution) {
1744
2375
  });
1745
2376
  }
1746
2377
 
1747
- // src/agent-runtime/run-mutation-queue.ts
1748
- function createRunMutationQueue() {
1749
- let tail = Promise.resolve();
1750
- return (mutation) => {
1751
- const result = tail.then(mutation, mutation);
1752
- tail = result.then(() => {
1753
- return;
1754
- }, () => {
1755
- return;
1756
- });
1757
- return result;
1758
- };
1759
- }
1760
-
1761
- // src/agent-runtime/run-operation-lifecycle.ts
1762
- import { wrapLanguageModel } from "ai";
1763
-
1764
- // src/agent-runtime/provider-origin.ts
1765
- import {
1766
- InvalidToolApprovalError,
1767
- InvalidToolApprovalSignatureError,
1768
- ToolCallNotFoundForApprovalError
1769
- } from "ai";
1770
- var providerOrigin = new WeakSet;
1771
- function isOwnInputRefusal(error) {
1772
- return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
1773
- }
1774
- function markProviderOrigin(error) {
1775
- if (typeof error === "object" && error !== null)
1776
- providerOrigin.add(error);
1777
- return error;
1778
- }
1779
- function hasProviderOrigin(error) {
1780
- return typeof error === "object" && error !== null && providerOrigin.has(error);
1781
- }
1782
- function markProviderStream(stream) {
1783
- const reader = stream.getReader();
1784
- return new ReadableStream({
1785
- async pull(controller) {
1786
- let read;
1787
- try {
1788
- read = await reader.read();
1789
- } catch (error) {
1790
- controller.error(isOwnInputRefusal(error) ? error : markProviderOrigin(error));
1791
- return;
1792
- }
1793
- if (read.done)
1794
- controller.close();
1795
- else
1796
- controller.enqueue(read.value);
1797
- },
1798
- cancel(reason) {
1799
- return reader.cancel(reason);
1800
- }
1801
- });
1802
- }
1803
-
1804
2378
  // src/agent-runtime/run-operation-lifecycle.ts
2379
+ import { wrapLanguageModel as wrapLanguageModel2 } from "ai";
1805
2380
  function createAgentRunOperationLifecycle(config) {
1806
2381
  let active;
1807
2382
  let providerCallId;
@@ -1853,7 +2428,7 @@ function createAgentRunOperationLifecycle(config) {
1853
2428
  await startModelRequest(fallbackCallId, step);
1854
2429
  return model;
1855
2430
  }
1856
- return wrapLanguageModel({
2431
+ return wrapLanguageModel2({
1857
2432
  model,
1858
2433
  middleware: {
1859
2434
  specificationVersion: "v4",
@@ -2029,7 +2604,7 @@ async function acquireRun(dependencies, input) {
2029
2604
  lastPromptTokens: { provenance: "unavailable" }
2030
2605
  };
2031
2606
  const idleDeadline = createIdleDeadline(input.signal, idleTimeoutMs);
2032
- const serialize = createRunMutationQueue();
2607
+ const serialize = createMutationQueue();
2033
2608
  const operationLifecycle = createAgentRunOperationLifecycle({
2034
2609
  store: config.store,
2035
2610
  runtimeEpoch,
@@ -2057,6 +2632,8 @@ async function acquireRun(dependencies, input) {
2057
2632
 
2058
2633
  // src/agent-runtime/run-failure.ts
2059
2634
  function failureThisRuntimeOwns(error) {
2635
+ if (error instanceof InvocationReceiptError)
2636
+ return "runtime_failure";
2060
2637
  if (error instanceof AgentContextOverflowError)
2061
2638
  return "context_overflow";
2062
2639
  if (error instanceof AgentRuntimeConflictError)
@@ -2174,14 +2751,14 @@ async function* ownedProviderStream(input) {
2174
2751
  }
2175
2752
 
2176
2753
  // src/agent-runtime/run-provider-ledger.ts
2177
- import { createHash } from "node:crypto";
2754
+ import { createHash as createHash2 } from "node:crypto";
2178
2755
  function withoutBinaryParts(message) {
2179
2756
  const reference = (value) => {
2180
2757
  if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
2181
2758
  const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
2182
2759
  return {
2183
2760
  binary: true,
2184
- sha256: createHash("sha256").update(bytes).digest("hex"),
2761
+ sha256: createHash2("sha256").update(bytes).digest("hex"),
2185
2762
  bytes: bytes.byteLength
2186
2763
  };
2187
2764
  }
@@ -2201,6 +2778,16 @@ function withoutBinaryParts(message) {
2201
2778
  }
2202
2779
  async function createRunProviderLedger(input) {
2203
2780
  const { store, state } = input;
2781
+ if (input.audited) {
2782
+ return {
2783
+ async recordRequest() {},
2784
+ async recordResponse(response) {
2785
+ return providerResponseIdentity(response.id, state.selectedModel?.resolveResponseProvider?.({
2786
+ providerMetadata: response.providerMetadata
2787
+ }));
2788
+ }
2789
+ };
2790
+ }
2204
2791
  const requestModelId = input.selectedModel.descriptor.modelId;
2205
2792
  const knownMessageShas = new Set;
2206
2793
  {
@@ -2226,7 +2813,7 @@ async function createRunProviderLedger(input) {
2226
2813
  const messageShas = [];
2227
2814
  for (const message of request.messages) {
2228
2815
  const body = canonicalAgentJson(JSON.parse(JSON.stringify(withoutBinaryParts(message))));
2229
- const sha256 = createHash("sha256").update(body).digest("hex");
2816
+ const sha256 = createHash2("sha256").update(body).digest("hex");
2230
2817
  messageShas.push(sha256);
2231
2818
  if (knownMessageShas.has(sha256))
2232
2819
  continue;
@@ -2237,8 +2824,8 @@ async function createRunProviderLedger(input) {
2237
2824
  });
2238
2825
  knownMessageShas.add(sha256);
2239
2826
  }
2240
- const instructionsSha256 = createHash("sha256").update(typeof request.instructions === "string" ? request.instructions : canonicalAgentJson(JSON.parse(JSON.stringify(withoutBinaryParts(request.instructions))))).digest("hex");
2241
- const bodySha256 = createHash("sha256").update(instructionsSha256).update(messageShas.join(",")).digest("hex");
2827
+ const instructionsSha256 = createHash2("sha256").update(typeof request.instructions === "string" ? request.instructions : canonicalAgentJson(JSON.parse(JSON.stringify(withoutBinaryParts(request.instructions))))).digest("hex");
2828
+ const bodySha256 = createHash2("sha256").update(instructionsSha256).update(messageShas.join(",")).digest("hex");
2242
2829
  await store.appendEvent({
2243
2830
  conversationId: state.run.conversationId,
2244
2831
  kind: "provider/request",
@@ -2637,7 +3224,7 @@ async function prepareAttemptStep(context, attempt, options) {
2637
3224
  messages: [...prepared?.messages ?? options.messages, ...injected]
2638
3225
  };
2639
3226
  const providerMessages = preparedStep?.messages ?? options.messages;
2640
- const model = await execution.operationLifecycle.prepareModel(preparedStep?.model ?? turn.selectedModel.model, options.stepNumber, generateId());
3227
+ const model = await execution.operationLifecycle.prepareModel(execution.invocation ? execution.invocation.wrap(turn.selectedModel, options.stepNumber, preparedStep?.model) : preparedStep?.model ?? turn.selectedModel.model, options.stepNumber, generateId());
2641
3228
  const override = preparedStep;
2642
3229
  if (override?.instructions !== undefined)
2643
3230
  loop.instructionsOverride = override.instructions;
@@ -2825,7 +3412,8 @@ async function runModelAttempts(execution, turn) {
2825
3412
  const ledger = await createRunProviderLedger({
2826
3413
  store: config.store,
2827
3414
  state,
2828
- selectedModel: turn.selectedModel
3415
+ selectedModel: turn.selectedModel,
3416
+ audited: execution.invocation !== undefined
2829
3417
  });
2830
3418
  const context = { execution, turn, loop, ledger };
2831
3419
  for (;; ) {
@@ -3008,7 +3596,7 @@ async function commitRunTerminal(execution) {
3008
3596
  }
3009
3597
 
3010
3598
  // src/agent-runtime/run-prompt-history.ts
3011
- import { createHash as createHash2 } from "node:crypto";
3599
+ import { createHash as createHash3 } from "node:crypto";
3012
3600
  function snapshotForRunPrompt(snapshot, runId) {
3013
3601
  const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
3014
3602
  if (runIndex < 0)
@@ -3027,7 +3615,7 @@ var USER_INSTRUCTION_SEED_KEY = "prompt.user-instructions";
3027
3615
  function seededInstructionMessage(input) {
3028
3616
  return AgentMessageSchema.parse({
3029
3617
  schemaVersion: 1,
3030
- id: createHash2("sha256").update(`${input.conversationId}\x00${input.seedKey}\x00${input.index}`).digest("hex"),
3618
+ id: createHash3("sha256").update(`${input.conversationId}\x00${input.seedKey}\x00${input.index}`).digest("hex"),
3031
3619
  conversationId: input.conversationId,
3032
3620
  role: "user",
3033
3621
  status: "committed",
@@ -3250,6 +3838,15 @@ function createRunExecutor(dependencies) {
3250
3838
  return acquisition.result;
3251
3839
  const { execution } = acquisition;
3252
3840
  try {
3841
+ const invocations = dependencies.config.invocations;
3842
+ if (invocations) {
3843
+ const trace = await invocations.trace({
3844
+ context: input.context,
3845
+ conversationId: execution.state.run.conversationId,
3846
+ run: execution.state.run
3847
+ });
3848
+ execution.invocation = await beginAgentInvocation(invocations.ledger, dependencies.config.store, { run: execution.state.run, trace }, input.context);
3849
+ }
3253
3850
  const turn = await prepareTurn(execution);
3254
3851
  await runModelAttempts(execution, turn);
3255
3852
  await settleStreamOutcome(execution);
@@ -3258,7 +3855,9 @@ function createRunExecutor(dependencies) {
3258
3855
  } finally {
3259
3856
  execution.idleDeadline.dispose();
3260
3857
  }
3261
- return commitRunTerminal(execution);
3858
+ const result = await commitRunTerminal(execution);
3859
+ await execution.invocation?.finish(result.reason === "success" ? "succeeded" : ["interrupted", "cancelled", "timeout", "shutdown"].includes(result.reason) ? "cancelled" : "failed");
3860
+ return result;
3262
3861
  };
3263
3862
  }
3264
3863
 
@@ -3641,4 +4240,4 @@ function createAgentRuntime(config) {
3641
4240
  };
3642
4241
  }
3643
4242
 
3644
- export { AgentRuntimeConflictError, normalizeSdkUsage, AgentContextOverflowError, createAgentSessionCoordinator, registerDeferredToolRepair, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, createAgentRuntimeEventSink, projectAgentHistoryDetailed, projectAgentHistory, createAgentToolFenceLifecycle, AgentTokenCountSchema, selectAgentHistory, composeAgentPrompt, AgentProviderStreamCutError, classifyProviderFailure, isToolResultFailure, recordAgentRetryDecision, defineStateSlot, createAgentStateSlotStore, renderAgentStateSlots, agentGoalStateSlot, agentTodoStateSlot, createAgentRuntime };
4243
+ export { AgentRuntimeConflictError, normalizeSdkUsage, AgentContextOverflowError, createAgentSessionCoordinator, registerDeferredToolRepair, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, createAgentRuntimeEventSink, projectAgentHistoryDetailed, projectAgentHistory, ModelInvocationTraceSchema, CompletionInvocationInputSchema, ModelInvocationRecordSchema, currentModelInvocationAttempt, createModelInvocationLedger, createAgentToolFenceLifecycle, AgentTokenCountSchema, selectAgentHistory, composeAgentPrompt, AgentProviderStreamCutError, classifyProviderFailure, isToolResultFailure, recordAgentRetryDecision, defineStateSlot, createAgentStateSlotStore, renderAgentStateSlots, agentGoalStateSlot, agentTodoStateSlot, createAgentRuntime };