@anvia/core 1.0.0-rc.1 → 1.0.0-rc.10

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 (162) hide show
  1. package/README.md +381 -85
  2. package/dist/agent/index.d.ts +57 -19
  3. package/dist/agent/index.js +32 -17
  4. package/dist/agent/interactions/index.d.ts +122 -0
  5. package/dist/agent/interactions/index.js +20 -0
  6. package/dist/agent-DWzW9SoH.d.ts +150 -0
  7. package/dist/chunk-3RM57ZT2.js +31 -0
  8. package/dist/chunk-3RM57ZT2.js.map +1 -0
  9. package/dist/chunk-3RWESPUG.js +331 -0
  10. package/dist/chunk-3RWESPUG.js.map +1 -0
  11. package/dist/{chunk-DMPUP4R3.js → chunk-3SKZ2BKP.js} +7 -5
  12. package/dist/chunk-3SKZ2BKP.js.map +1 -0
  13. package/dist/chunk-3XQGVDU5.js +69 -0
  14. package/dist/chunk-3XQGVDU5.js.map +1 -0
  15. package/dist/{chunk-5XKDW36Z.js → chunk-5C6B6ZRH.js} +70 -75
  16. package/dist/chunk-5C6B6ZRH.js.map +1 -0
  17. package/dist/chunk-6BBOCFHV.js +323 -0
  18. package/dist/chunk-6BBOCFHV.js.map +1 -0
  19. package/dist/chunk-7JLAIN6E.js +15 -0
  20. package/dist/chunk-7JLAIN6E.js.map +1 -0
  21. package/dist/chunk-7PHMK7W4.js +1516 -0
  22. package/dist/chunk-7PHMK7W4.js.map +1 -0
  23. package/dist/{chunk-FNQB2JEH.js → chunk-AZB6N7P4.js} +94 -65
  24. package/dist/chunk-AZB6N7P4.js.map +1 -0
  25. package/dist/{chunk-I6G7BC42.js → chunk-D4PACGPA.js} +2 -6
  26. package/dist/chunk-D4PACGPA.js.map +1 -0
  27. package/dist/chunk-EFLT7XZD.js +51 -0
  28. package/dist/chunk-EFLT7XZD.js.map +1 -0
  29. package/dist/{chunk-R2LJSQUW.js → chunk-EMZKPRE6.js} +267 -107
  30. package/dist/chunk-EMZKPRE6.js.map +1 -0
  31. package/dist/chunk-I3Q7XSBB.js +59 -0
  32. package/dist/chunk-I3Q7XSBB.js.map +1 -0
  33. package/dist/chunk-J6LVLV6P.js +13 -0
  34. package/dist/chunk-J6LVLV6P.js.map +1 -0
  35. package/dist/chunk-LTXABCOO.js +127 -0
  36. package/dist/chunk-LTXABCOO.js.map +1 -0
  37. package/dist/chunk-OJBFDBLG.js +164 -0
  38. package/dist/chunk-OJBFDBLG.js.map +1 -0
  39. package/dist/chunk-QGX73TSQ.js +177 -0
  40. package/dist/chunk-QGX73TSQ.js.map +1 -0
  41. package/dist/chunk-QOUPWOGW.js +29 -0
  42. package/dist/chunk-QOUPWOGW.js.map +1 -0
  43. package/dist/chunk-SJMSS5SI.js +171 -0
  44. package/dist/chunk-SJMSS5SI.js.map +1 -0
  45. package/dist/chunk-T2C3CGDQ.js +56 -0
  46. package/dist/chunk-T2C3CGDQ.js.map +1 -0
  47. package/dist/chunk-VX3HS6PE.js +4569 -0
  48. package/dist/chunk-VX3HS6PE.js.map +1 -0
  49. package/dist/chunk-X4LK4ODN.js +86 -0
  50. package/dist/chunk-X4LK4ODN.js.map +1 -0
  51. package/dist/chunk-ZA564323.js +331 -0
  52. package/dist/chunk-ZA564323.js.map +1 -0
  53. package/dist/completion/index.d.ts +5 -4
  54. package/dist/completion/index.js +34 -28
  55. package/dist/documents/index.d.ts +34 -0
  56. package/dist/documents/index.js +340 -0
  57. package/dist/documents/index.js.map +1 -0
  58. package/dist/{dynamic-tools-i9woysFa.d.ts → dynamic-tools-aIZlg5x1.d.ts} +21 -9
  59. package/dist/embeddings/index.d.ts +11 -9
  60. package/dist/embeddings/index.js +3 -3
  61. package/dist/evals/index.d.ts +54 -25
  62. package/dist/evals/index.js +197 -114
  63. package/dist/evals/index.js.map +1 -1
  64. package/dist/extractor/index.d.ts +23 -26
  65. package/dist/extractor/index.js +9 -8
  66. package/dist/guardrails/index.d.ts +7 -129
  67. package/dist/guardrails/index.js +1 -1
  68. package/dist/image-generation/index.d.ts +18 -16
  69. package/dist/image-generation/index.js +4 -2
  70. package/dist/index.d.ts +24 -25
  71. package/dist/index.js +78 -56
  72. package/dist/internal/agent.d.ts +33 -30
  73. package/dist/internal/agent.js +50 -15
  74. package/dist/internal/agent.js.map +1 -1
  75. package/dist/mcp/index.d.ts +7 -15
  76. package/dist/mcp/index.js +3 -348
  77. package/dist/mcp/index.js.map +1 -1
  78. package/dist/memory/index.d.ts +20 -6
  79. package/dist/memory/index.js +12 -10
  80. package/dist/{middleware-KynLg_RW.d.ts → middleware-kcF8AusP.d.ts} +10 -7
  81. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  82. package/dist/model-listing/index.d.ts +3 -1
  83. package/dist/observability/index.d.ts +22 -6
  84. package/dist/observability/index.js +10 -5
  85. package/dist/observability/index.js.map +1 -1
  86. package/dist/pipeline/index.d.ts +103 -58
  87. package/dist/pipeline/index.js +421 -236
  88. package/dist/pipeline/index.js.map +1 -1
  89. package/dist/provider-output-error-BEwDgVv3.d.ts +99 -0
  90. package/dist/{retry-D3Ruy-ba.d.ts → retry-CjvSlKGW.d.ts} +2 -1
  91. package/dist/skills/index.d.ts +5 -4
  92. package/dist/skills/index.js +8 -7
  93. package/dist/speech-generation/index.d.ts +37 -0
  94. package/dist/speech-generation/index.js +10 -0
  95. package/dist/text-ZLECpQE7.d.ts +32 -0
  96. package/dist/{think-tool-DZqZj2LV.d.ts → think-tool-BwCsJ365.d.ts} +16 -2
  97. package/dist/tool/index.d.ts +10 -7
  98. package/dist/tool/index.js +13 -10
  99. package/dist/{tool-C_8GudXn.d.ts → tool-BpqpoRSE.d.ts} +17 -8
  100. package/dist/transcription/index.d.ts +23 -14
  101. package/dist/transcription/index.js +4 -2
  102. package/dist/types-CXNE592e.d.ts +130 -0
  103. package/dist/types-Cr4uiYo5.d.ts +99 -0
  104. package/dist/{types-DhQfwiZn.d.ts → types-DC1U1XwW.d.ts} +1 -1
  105. package/dist/types-DKOXVTcq.d.ts +155 -0
  106. package/dist/types-DgvozfPc.d.ts +349 -0
  107. package/dist/types-DhkodEft.d.ts +105 -0
  108. package/dist/types-DjqRHeAi.d.ts +31 -0
  109. package/dist/{index-DxB74ybJ.d.ts → types-Sue2hb_L.d.ts} +142 -88
  110. package/dist/vector-store/index.d.ts +34 -34
  111. package/dist/vector-store/index.js +10 -6
  112. package/package.json +22 -16
  113. package/dist/agent-DGYY_onS.d.ts +0 -145
  114. package/dist/audio-generation/index.d.ts +0 -31
  115. package/dist/audio-generation/index.js +0 -8
  116. package/dist/chunk-5XKDW36Z.js.map +0 -1
  117. package/dist/chunk-6WGGTJE6.js +0 -139
  118. package/dist/chunk-6WGGTJE6.js.map +0 -1
  119. package/dist/chunk-A3UBYTJT.js +0 -157
  120. package/dist/chunk-A3UBYTJT.js.map +0 -1
  121. package/dist/chunk-ADH7NNCS.js +0 -512
  122. package/dist/chunk-ADH7NNCS.js.map +0 -1
  123. package/dist/chunk-CQNNSZPG.js +0 -9
  124. package/dist/chunk-CQNNSZPG.js.map +0 -1
  125. package/dist/chunk-DMPUP4R3.js.map +0 -1
  126. package/dist/chunk-DZ3CKYTH.js +0 -267
  127. package/dist/chunk-DZ3CKYTH.js.map +0 -1
  128. package/dist/chunk-FNQB2JEH.js.map +0 -1
  129. package/dist/chunk-I6G7BC42.js.map +0 -1
  130. package/dist/chunk-IL3ZSNJI.js +0 -3748
  131. package/dist/chunk-IL3ZSNJI.js.map +0 -1
  132. package/dist/chunk-J6GNQART.js +0 -122
  133. package/dist/chunk-J6GNQART.js.map +0 -1
  134. package/dist/chunk-M3IOWB4Y.js +0 -280
  135. package/dist/chunk-M3IOWB4Y.js.map +0 -1
  136. package/dist/chunk-QY5GZ7HR.js +0 -39
  137. package/dist/chunk-QY5GZ7HR.js.map +0 -1
  138. package/dist/chunk-R2LJSQUW.js.map +0 -1
  139. package/dist/chunk-RFDVKCIE.js +0 -12
  140. package/dist/chunk-RFDVKCIE.js.map +0 -1
  141. package/dist/chunk-RMUBRRSK.js +0 -34
  142. package/dist/chunk-RMUBRRSK.js.map +0 -1
  143. package/dist/chunk-RXKHOYEH.js +0 -466
  144. package/dist/chunk-RXKHOYEH.js.map +0 -1
  145. package/dist/chunk-XDRSPSR7.js +0 -38
  146. package/dist/chunk-XDRSPSR7.js.map +0 -1
  147. package/dist/chunk-XWUC7CIT.js +0 -1
  148. package/dist/chunk-XWUC7CIT.js.map +0 -1
  149. package/dist/errors-CYKUcU89.d.ts +0 -17
  150. package/dist/json-Zo7K3xmt.d.ts +0 -40
  151. package/dist/loaders/index.d.ts +0 -86
  152. package/dist/loaders/index.js +0 -299
  153. package/dist/loaders/index.js.map +0 -1
  154. package/dist/types-B3A4YxaA.d.ts +0 -354
  155. package/dist/types-BBEGKB9m.d.ts +0 -119
  156. package/dist/types-DT3nEemY.d.ts +0 -79
  157. package/dist/types-DulRCYdB.d.ts +0 -70
  158. package/dist/types-p55Jc-sr.d.ts +0 -47
  159. package/dist/ui/index.d.ts +0 -107
  160. package/dist/ui/index.js +0 -10
  161. /package/dist/{audio-generation → agent/interactions}/index.js.map +0 -0
  162. /package/dist/{ui → speech-generation}/index.js.map +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/image-generation/generate-image.ts"],"sourcesContent":["import type { JsonObject } from \"../completion/types\";\nimport { throwIfAborted } from \"../internal/abort\";\nimport { assertJsonObject } from \"../internal/json-object\";\nimport type { ModelCallOptions } from \"../model-call-options\";\nimport {\n type ResolvedRetryOptions,\n type RetrySetting,\n resolveRetryOptions,\n runWithRetries,\n} from \"../retry\";\nimport type { ImageGenerationModel, ImageGenerationRequest, ImageGenerationResult } from \"./types\";\n\nexport type GenerateImageOptions<Model extends ImageGenerationModel = ImageGenerationModel> = {\n model: Model;\n prompt: string;\n width?: number | undefined;\n height?: number | undefined;\n providerOptions?: JsonObject | undefined;\n retries?: RetrySetting | undefined;\n abortSignal?: AbortSignal | undefined;\n};\n\ntype RawResponseOf<Model> =\n Model extends ImageGenerationModel<infer RawResponse> ? RawResponse : unknown;\n\nexport async function generateImage<Model extends ImageGenerationModel>(\n options: GenerateImageOptions<Model>,\n): Promise<ImageGenerationResult<RawResponseOf<Model>>> {\n assertNonEmptyString(options.prompt, \"Image prompt\");\n throwIfAborted(options.abortSignal);\n const width = options.width ?? 1024;\n const height = options.height ?? 1024;\n assertPositiveInteger(width, \"Image width\");\n assertPositiveInteger(height, \"Image height\");\n\n const request: ImageGenerationRequest = { prompt: options.prompt, width, height };\n if (options.providerOptions !== undefined) {\n assertJsonObject(options.providerOptions, \"providerOptions\");\n request.providerOptions = options.providerOptions;\n }\n const result = await runWithRetries(\n () => {\n throwIfAborted(options.abortSignal);\n return options.model.imageGeneration(\n request,\n modelCallOptions(options.abortSignal),\n ) as Promise<ImageGenerationResult<RawResponseOf<Model>>>;\n },\n resolveRetries(options.retries),\n { streaming: false, abortSignal: options.abortSignal },\n );\n if (!Array.isArray(result.images) || result.images.length === 0) {\n throw new Error(\"The image generation model returned no images.\");\n }\n return result;\n}\n\nfunction resolveRetries(setting: RetrySetting | undefined): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(setting);\n}\n\nfunction modelCallOptions(abortSignal: AbortSignal | undefined): ModelCallOptions | undefined {\n return abortSignal === undefined ? undefined : { abortSignal };\n}\n\nfunction assertNonEmptyString(value: string, name: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${name} must be a non-empty string.`);\n }\n}\n\nfunction assertPositiveInteger(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`${name} must be a positive integer.`);\n }\n}\n"],"mappings":";;;;;;;;;;AAyBA,eAAsB,cACpB,SACsD;AACtD,uBAAqB,QAAQ,QAAQ,cAAc;AACnD,iBAAe,QAAQ,WAAW;AAClC,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,SAAS,QAAQ,UAAU;AACjC,wBAAsB,OAAO,aAAa;AAC1C,wBAAsB,QAAQ,cAAc;AAE5C,QAAM,UAAkC,EAAE,QAAQ,QAAQ,QAAQ,OAAO,OAAO;AAChF,MAAI,QAAQ,oBAAoB,QAAW;AACzC,qBAAiB,QAAQ,iBAAiB,iBAAiB;AAC3D,YAAQ,kBAAkB,QAAQ;AAAA,EACpC;AACA,QAAM,SAAS,MAAM;AAAA,IACnB,MAAM;AACJ,qBAAe,QAAQ,WAAW;AAClC,aAAO,QAAQ,MAAM;AAAA,QACnB;AAAA,QACA,iBAAiB,QAAQ,WAAW;AAAA,MACtC;AAAA,IACF;AAAA,IACA,eAAe,QAAQ,OAAO;AAAA,IAC9B,EAAE,WAAW,OAAO,aAAa,QAAQ,YAAY;AAAA,EACvD;AACA,MAAI,CAAC,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,OAAO,WAAW,GAAG;AAC/D,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,SAAO;AACT;AAEA,SAAS,eAAe,SAAqE;AAC3F,SAAO,YAAY,UAAa,YAAY,QAAQ,SAAY,oBAAoB,OAAO;AAC7F;AAEA,SAAS,iBAAiB,aAAoE;AAC5F,SAAO,gBAAgB,SAAY,SAAY,EAAE,YAAY;AAC/D;AAEA,SAAS,qBAAqB,OAAe,MAAoB;AAC/D,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,GAAG;AAC1D,UAAM,IAAI,UAAU,GAAG,IAAI,8BAA8B;AAAA,EAC3D;AACF;AAEA,SAAS,sBAAsB,OAAe,MAAoB;AAChE,MAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAAG;AAC7C,UAAM,IAAI,WAAW,GAAG,IAAI,8BAA8B;AAAA,EAC5D;AACF;","names":[]}
@@ -0,0 +1,13 @@
1
+ // src/mcp/tool.ts
2
+ function isMcpTool(tool) {
3
+ if (typeof tool !== "object" || tool === null || !("mcp" in tool)) {
4
+ return false;
5
+ }
6
+ const mcp = tool.mcp;
7
+ return typeof mcp === "object" && mcp !== null && "serverName" in mcp && typeof mcp.serverName === "string" && mcp.serverName.length > 0 && "remoteName" in mcp && typeof mcp.remoteName === "string" && mcp.remoteName.length > 0;
8
+ }
9
+
10
+ export {
11
+ isMcpTool
12
+ };
13
+ //# sourceMappingURL=chunk-J6LVLV6P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/tool.ts"],"sourcesContent":["import type { McpTool } from \"./types\";\n\nexport function isMcpTool(tool: unknown): tool is McpTool {\n if (typeof tool !== \"object\" || tool === null || !(\"mcp\" in tool)) {\n return false;\n }\n const mcp = tool.mcp;\n return (\n typeof mcp === \"object\" &&\n mcp !== null &&\n \"serverName\" in mcp &&\n typeof mcp.serverName === \"string\" &&\n mcp.serverName.length > 0 &&\n \"remoteName\" in mcp &&\n typeof mcp.remoteName === \"string\" &&\n mcp.remoteName.length > 0\n );\n}\n"],"mappings":";AAEO,SAAS,UAAU,MAAgC;AACxD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,EAAE,SAAS,OAAO;AACjE,WAAO;AAAA,EACT;AACA,QAAM,MAAM,KAAK;AACjB,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,gBAAgB,OAChB,OAAO,IAAI,eAAe,YAC1B,IAAI,WAAW,SAAS,KACxB,gBAAgB,OAChB,OAAO,IAAI,eAAe,YAC1B,IAAI,WAAW,SAAS;AAE5B;","names":[]}
@@ -0,0 +1,127 @@
1
+ import {
2
+ CompletionCapabilityError,
3
+ Usage,
4
+ generateCompletion
5
+ } from "./chunk-7PHMK7W4.js";
6
+ import {
7
+ toProviderJsonSchema
8
+ } from "./chunk-QGX73TSQ.js";
9
+ import {
10
+ isAbortError,
11
+ resolveRetryOptions,
12
+ retryDelayMs,
13
+ retryOptionsForFailure,
14
+ waitForRetry
15
+ } from "./chunk-3RWESPUG.js";
16
+
17
+ // src/extractor/extractor.ts
18
+ import { z } from "zod";
19
+ var SUBMIT_TOOL_NAME = "submit";
20
+ var DEFAULT_EXTRACTOR_INSTRUCTIONS = "You are an AI assistant whose purpose is to extract structured data from the provided text.\nYou have access to a `submit` function that defines the structure of the data to extract.\nAlways call the `submit` function with the structured data. Use default or null values when information is missing.";
21
+ var ExtractionError = class extends Error {
22
+ attempts;
23
+ usage;
24
+ constructor(message, options) {
25
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
26
+ this.name = "ExtractionError";
27
+ this.attempts = options.attempts;
28
+ this.usage = options.usage;
29
+ }
30
+ };
31
+ async function extract(options) {
32
+ if (!(options.outputSchema instanceof z.ZodType)) {
33
+ throw new TypeError("extract outputSchema must be a Zod schema.");
34
+ }
35
+ if (typeof options.text !== "string") {
36
+ throw new TypeError("extract text must be a string.");
37
+ }
38
+ const retries = resolveExtractionRetries(options.retries);
39
+ const maxAttempts = retries?.maxAttempts ?? 1;
40
+ const submitTool = createSubmitTool(options.outputSchema);
41
+ const instructions = extractionInstructions(options.instructions);
42
+ let usage = Usage.empty();
43
+ let lastError;
44
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
45
+ try {
46
+ const result = await generateCompletion({
47
+ model: options.model,
48
+ prompt: options.text,
49
+ instructions,
50
+ tools: [globalThis.structuredClone(submitTool)],
51
+ temperature: options.temperature,
52
+ maxTokens: options.maxTokens,
53
+ providerOptions: options.providerOptions,
54
+ toolChoice: "required",
55
+ retries: false,
56
+ abortSignal: options.abortSignal
57
+ });
58
+ usage = Usage.add(usage, result.usage);
59
+ return {
60
+ ...result,
61
+ output: extractSubmittedData(result.content, options.outputSchema),
62
+ usage
63
+ };
64
+ } catch (error) {
65
+ if (error instanceof CompletionCapabilityError || isAbortError(error)) {
66
+ throw error;
67
+ }
68
+ lastError = error;
69
+ const retryOptions = retryOptionsForFailure(retries, {
70
+ error,
71
+ attempt,
72
+ streaming: false
73
+ });
74
+ if (retryOptions === void 0) {
75
+ throw new ExtractionError("No data extracted", {
76
+ cause: lastError,
77
+ attempts: attempt,
78
+ usage
79
+ });
80
+ }
81
+ await waitForRetry(retryDelayMs(retryOptions, attempt), options.abortSignal);
82
+ }
83
+ }
84
+ throw new ExtractionError("No data extracted", {
85
+ cause: lastError,
86
+ attempts: maxAttempts,
87
+ usage
88
+ });
89
+ }
90
+ function extractionInstructions(instructions) {
91
+ return instructions === void 0 || instructions.length === 0 ? DEFAULT_EXTRACTOR_INSTRUCTIONS : `${DEFAULT_EXTRACTOR_INSTRUCTIONS}
92
+
93
+ ${instructions}`;
94
+ }
95
+ function createSubmitTool(outputSchema) {
96
+ return {
97
+ name: SUBMIT_TOOL_NAME,
98
+ description: "Submit the structured data extracted from the provided text.",
99
+ parameters: toProviderJsonSchema(outputSchema, { io: "input" })
100
+ };
101
+ }
102
+ function resolveExtractionRetries(options) {
103
+ if (options === void 0 || options === false) {
104
+ return void 0;
105
+ }
106
+ return resolveRetryOptions({
107
+ ...options,
108
+ shouldRetry: options.shouldRetry ?? (() => true)
109
+ });
110
+ }
111
+ function extractSubmittedData(content, schema) {
112
+ const submitted = content.filter((item) => item.type === "tool-call").filter((toolCall) => toolCall.toolName === SUBMIT_TOOL_NAME).at(-1);
113
+ if (submitted === void 0) {
114
+ throw new Error("The model did not call the submit tool");
115
+ }
116
+ try {
117
+ return schema.parse(submitted.input);
118
+ } catch (error) {
119
+ throw new Error("Submitted data failed output schema validation", { cause: error });
120
+ }
121
+ }
122
+
123
+ export {
124
+ ExtractionError,
125
+ extract
126
+ };
127
+ //# sourceMappingURL=chunk-LTXABCOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extractor/extractor.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n type AssistantContentPart,\n CompletionCapabilityError,\n type CompletionModel,\n type CompletionResult,\n generateCompletion,\n type JsonObject,\n type ToolDefinition,\n Usage,\n} from \"../completion/index\";\nimport { isAbortError } from \"../internal/abort\";\nimport {\n type ResolvedRetryOptions,\n type RetrySetting,\n resolveRetryOptions,\n retryDelayMs,\n retryOptionsForFailure,\n waitForRetry,\n} from \"../retry\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\n\nconst SUBMIT_TOOL_NAME = \"submit\";\n\nconst DEFAULT_EXTRACTOR_INSTRUCTIONS =\n \"You are an AI assistant whose purpose is to extract structured data from the provided text.\\n\" +\n \"You have access to a `submit` function that defines the structure of the data to extract.\\n\" +\n \"Always call the `submit` function with the structured data. Use default or null values when information is missing.\";\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport type ExtractOptions<Output, Model extends CompletionModel = CompletionModel> = {\n model: Model;\n text: string;\n outputSchema: ZodSchema<Output>;\n instructions?: string | undefined;\n retries?: RetrySetting | undefined;\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n providerOptions?: JsonObject | undefined;\n abortSignal?: AbortSignal | undefined;\n};\n\nexport type ExtractionResult<Output, RawResponse = unknown> = Omit<\n CompletionResult<string, RawResponse>,\n \"output\"\n> & {\n output: Output;\n};\n\nexport class ExtractionError extends Error {\n readonly attempts: number;\n readonly usage: Usage;\n\n constructor(\n message: string,\n options: {\n cause?: unknown;\n attempts: number;\n usage: Usage;\n },\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"ExtractionError\";\n this.attempts = options.attempts;\n this.usage = options.usage;\n }\n}\n\n/** Extract structured data from text using a required, schema-backed submit tool. */\nexport async function extract<Output, Model extends CompletionModel>(\n options: ExtractOptions<Output, Model>,\n): Promise<ExtractionResult<Output, RawResponseOf<Model>>> {\n if (!(options.outputSchema instanceof z.ZodType)) {\n throw new TypeError(\"extract outputSchema must be a Zod schema.\");\n }\n if (typeof options.text !== \"string\") {\n throw new TypeError(\"extract text must be a string.\");\n }\n\n const retries = resolveExtractionRetries(options.retries);\n const maxAttempts = retries?.maxAttempts ?? 1;\n const submitTool = createSubmitTool(options.outputSchema);\n const instructions = extractionInstructions(options.instructions);\n let usage = Usage.empty();\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n const result = await generateCompletion({\n model: options.model,\n prompt: options.text,\n instructions,\n tools: [globalThis.structuredClone(submitTool)],\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n providerOptions: options.providerOptions,\n toolChoice: \"required\",\n retries: false,\n abortSignal: options.abortSignal,\n });\n usage = Usage.add(usage, result.usage);\n return {\n ...result,\n output: extractSubmittedData(result.content, options.outputSchema),\n usage,\n };\n } catch (error) {\n if (error instanceof CompletionCapabilityError || isAbortError(error)) {\n throw error;\n }\n lastError = error;\n const retryOptions = retryOptionsForFailure(retries, {\n error,\n attempt,\n streaming: false,\n });\n if (retryOptions === undefined) {\n throw new ExtractionError(\"No data extracted\", {\n cause: lastError,\n attempts: attempt,\n usage,\n });\n }\n await waitForRetry(retryDelayMs(retryOptions, attempt), options.abortSignal);\n }\n }\n\n throw new ExtractionError(\"No data extracted\", {\n cause: lastError,\n attempts: maxAttempts,\n usage,\n });\n}\n\nfunction extractionInstructions(instructions: string | undefined): string {\n return instructions === undefined || instructions.length === 0\n ? DEFAULT_EXTRACTOR_INSTRUCTIONS\n : `${DEFAULT_EXTRACTOR_INSTRUCTIONS}\\n\\n${instructions}`;\n}\n\nfunction createSubmitTool<Output>(outputSchema: ZodSchema<Output>): ToolDefinition {\n return {\n name: SUBMIT_TOOL_NAME,\n description: \"Submit the structured data extracted from the provided text.\",\n parameters: toProviderJsonSchema(outputSchema, { io: \"input\" }),\n };\n}\n\nfunction resolveExtractionRetries(\n options: RetrySetting | undefined,\n): ResolvedRetryOptions | undefined {\n if (options === undefined || options === false) {\n return undefined;\n }\n return resolveRetryOptions({\n ...options,\n shouldRetry: options.shouldRetry ?? (() => true),\n });\n}\n\nfunction extractSubmittedData<Output>(\n content: readonly AssistantContentPart[],\n schema: ZodSchema<Output>,\n): Output {\n const submitted = content\n .filter((item) => item.type === \"tool-call\")\n .filter((toolCall) => toolCall.toolName === SUBMIT_TOOL_NAME)\n .at(-1);\n\n if (submitted === undefined) {\n throw new Error(\"The model did not call the submit tool\");\n }\n\n try {\n return schema.parse(submit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C;AAAA,EAC1D;AAEA,MAAI;AACF,WAAO,OAAO,MAAM,UAAU,KAAK;AAAA,EACrC,SAAS,OAAO;AACd,UAAM,IAAI,MAAM,kDAAkD,EAAE,OAAO,MAAM,CAAC;AAAA,EACpF;AACF;","names":[]}
@@ -0,0 +1,164 @@
1
+ import {
2
+ isJsonValue
3
+ } from "./chunk-3XQGVDU5.js";
4
+
5
+ // src/agent/interactions.ts
6
+ import { z } from "zod";
7
+ var nonblank = z.string().trim().min(1);
8
+ var jsonValueSchema = z.custom(isJsonValue, {
9
+ message: "Expected a strict JSON value"
10
+ });
11
+ var jsonObjectSchema = z.custom(
12
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value),
13
+ { message: "Expected a strict JSON object" }
14
+ );
15
+ var questionChoiceSchema = z.object({
16
+ label: nonblank,
17
+ value: nonblank
18
+ }).strict();
19
+ var questionPromptSchema = z.object({
20
+ id: nonblank,
21
+ text: nonblank,
22
+ choices: z.array(questionChoiceSchema).min(1).optional(),
23
+ allowCustom: z.boolean().optional()
24
+ }).strict().superRefine((question, context) => {
25
+ if (question.choices === void 0 && question.allowCustom === false) {
26
+ context.addIssue({
27
+ code: "custom",
28
+ message: "A free-text question cannot disable custom answers.",
29
+ path: ["allowCustom"]
30
+ });
31
+ }
32
+ const values = /* @__PURE__ */ new Set();
33
+ for (const [index, choice] of (question.choices ?? []).entries()) {
34
+ if (values.has(choice.value)) {
35
+ context.addIssue({
36
+ code: "custom",
37
+ message: "Question choice values must be unique.",
38
+ path: ["choices", index, "value"]
39
+ });
40
+ }
41
+ values.add(choice.value);
42
+ }
43
+ });
44
+ var questionAnswerSchema = z.object({
45
+ questionId: nonblank,
46
+ value: nonblank
47
+ }).strict();
48
+ var interactionBase = {
49
+ id: nonblank,
50
+ toolName: nonblank,
51
+ toolCallId: nonblank,
52
+ callId: z.string().optional(),
53
+ internalCallId: nonblank
54
+ };
55
+ var approvalRequestSchema = z.object({
56
+ type: z.literal("tool-approval"),
57
+ ...interactionBase,
58
+ input: jsonValueSchema,
59
+ reason: z.string().optional()
60
+ }).strict();
61
+ var questionRequestSchema = z.object({
62
+ type: z.literal("tool-question"),
63
+ ...interactionBase,
64
+ questions: z.array(questionPromptSchema).min(1)
65
+ }).strict().superRefine((request, context) => {
66
+ const ids = /* @__PURE__ */ new Set();
67
+ for (const [index, question] of request.questions.entries()) {
68
+ if (ids.has(question.id)) {
69
+ context.addIssue({
70
+ code: "custom",
71
+ message: "Question IDs must be unique.",
72
+ path: ["questions", index, "id"]
73
+ });
74
+ }
75
+ ids.add(question.id);
76
+ }
77
+ });
78
+ var agentInteractionRequestSchema = z.discriminatedUnion("type", [
79
+ approvalRequestSchema,
80
+ questionRequestSchema
81
+ ]);
82
+ var agentInteractionResponseSchema = z.discriminatedUnion("type", [
83
+ z.object({
84
+ type: z.literal("tool-approval"),
85
+ approved: z.boolean(),
86
+ reason: z.string().optional()
87
+ }).strict(),
88
+ z.object({
89
+ type: z.literal("tool-question"),
90
+ answers: z.array(questionAnswerSchema)
91
+ }).strict()
92
+ ]);
93
+ var agentContinuationSchema = z.object({
94
+ version: z.literal(1),
95
+ agentId: nonblank,
96
+ sourceRunId: nonblank,
97
+ interaction: agentInteractionRequestSchema,
98
+ state: jsonObjectSchema
99
+ }).strict();
100
+ function parseAgentInteractionRequest(value) {
101
+ return freeze(agentInteractionRequestSchema.parse(value));
102
+ }
103
+ function parseAgentInteractionResponse(value) {
104
+ return freeze(agentInteractionResponseSchema.parse(value));
105
+ }
106
+ function parseAgentQuestionPrompts(value) {
107
+ const request = questionRequestSchema.parse({
108
+ type: "tool-question",
109
+ id: "validation",
110
+ toolName: "validation",
111
+ toolCallId: "validation",
112
+ internalCallId: "validation",
113
+ questions: value
114
+ });
115
+ return freeze(request.questions);
116
+ }
117
+ function parseAgentContinuation(value) {
118
+ return freeze(agentContinuationSchema.parse(value));
119
+ }
120
+ function assertAgentInteractionResponse(request, response) {
121
+ if (request.type !== response.type) {
122
+ throw new TypeError("Interaction response type does not match the pending request.");
123
+ }
124
+ if (request.type === "tool-question" && response.type === "tool-question") {
125
+ assertQuestionAnswers(request, response.answers);
126
+ }
127
+ }
128
+ function assertQuestionAnswers(request, answers) {
129
+ const parsed = answers.map((answer) => questionAnswerSchema.parse(answer));
130
+ const byId = new Map(parsed.map((answer) => [answer.questionId, answer]));
131
+ if (byId.size !== parsed.length) {
132
+ throw new TypeError("Question answers must not contain duplicate question IDs.");
133
+ }
134
+ if (byId.size !== request.questions.length) {
135
+ throw new TypeError("Question responses must answer every question exactly once.");
136
+ }
137
+ for (const question of request.questions) {
138
+ const answer = byId.get(question.id);
139
+ if (answer === void 0) {
140
+ throw new TypeError(`Question response is missing an answer for "${question.id}".`);
141
+ }
142
+ const choices = question.choices;
143
+ if (choices !== void 0 && question.allowCustom !== true && !choices.some((choice) => choice.value === answer.value)) {
144
+ throw new TypeError(`Question "${question.id}" requires one of its configured choices.`);
145
+ }
146
+ }
147
+ }
148
+ function freeze(value) {
149
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
150
+ for (const child of Object.values(value)) freeze(child);
151
+ return Object.freeze(value);
152
+ }
153
+
154
+ export {
155
+ agentInteractionRequestSchema,
156
+ agentInteractionResponseSchema,
157
+ agentContinuationSchema,
158
+ parseAgentInteractionRequest,
159
+ parseAgentInteractionResponse,
160
+ parseAgentQuestionPrompts,
161
+ parseAgentContinuation,
162
+ assertAgentInteractionResponse
163
+ };
164
+ //# sourceMappingURL=chunk-OJBFDBLG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/interactions.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { isJsonValue } from \"../completion/json\";\nimport type { JsonObject, JsonValue, ToolQuestionAnswer } from \"../completion/types\";\n\nexport type AgentQuestionChoice = Readonly<{\n label: string;\n value: string;\n}>;\n\nexport type AgentQuestionPrompt = Readonly<{\n id: string;\n text: string;\n choices?: readonly AgentQuestionChoice[];\n allowCustom?: boolean;\n}>;\n\nexport type AgentQuestionAnswer = ToolQuestionAnswer;\n\ntype AgentInteractionRequestBase = Readonly<{\n id: string;\n toolName: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n}>;\n\nexport type AgentToolApprovalRequest = AgentInteractionRequestBase &\n Readonly<{\n type: \"tool-approval\";\n input: JsonValue;\n reason?: string;\n }>;\n\nexport type AgentToolQuestionRequest = AgentInteractionRequestBase &\n Readonly<{\n type: \"tool-question\";\n questions: readonly AgentQuestionPrompt[];\n }>;\n\nexport type AgentInteractionRequest = AgentToolApprovalRequest | AgentToolQuestionRequest;\n\nexport type AgentInteractionResponse =\n | Readonly<{\n type: \"tool-approval\";\n approved: boolean;\n reason?: string;\n }>\n | Readonly<{\n type: \"tool-question\";\n answers: readonly AgentQuestionAnswer[];\n }>;\n\nexport type AgentContinuation = Readonly<{\n version: 1;\n agentId: string;\n sourceRunId: string;\n interaction: AgentInteractionRequest;\n state: JsonObject;\n}>;\n\nconst nonblank = z.string().trim().min(1);\nconst jsonValueSchema = z.custom<JsonValue>(isJsonValue, {\n message: \"Expected a strict JSON value\",\n});\nconst jsonObjectSchema = z.custom<JsonObject>(\n (value) =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && isJsonValue(value),\n { message: \"Expected a strict JSON object\" },\n);\n\nconst questionChoiceSchema = z\n .object({\n label: nonblank,\n value: nonblank,\n })\n .strict();\n\nconst questionPromptSchema = z\n .object({\n id: nonblank,\n text: nonblank,\n choices: z.array(questionChoiceSchema).min(1).optional(),\n allowCustom: z.boolean().optional(),\n })\n .strict()\n .superRefine((question, context) => {\n if (question.choices === undefined && question.allowCustom === false) {\n context.addIssue({\n code: \"custom\",\n message: \"A free-text question cannot disable custom answers.\",\n path: [\"allowCustom\"],\n });\n }\n const values = new Set<string>();\n for (const [index, choice] of (question.choices ?? []).entries()) {\n if (values.has(choice.value)) {\n context.addIssue({\n code: \"custom\",\n message: \"Question choice values must be unique.\",\n path: [\"choices\", index, \"value\"],\n });\n }\n values.add(choice.value);\n }\n });\n\nconst questionAnswerSchema = z\n .object({\n questionId: nonblank,\n value: nonblank,\n })\n .strict();\n\nconst interactionBase = {\n id: nonblank,\n toolName: nonblank,\n toolCallId: nonblank,\n callId: z.string().optional(),\n internalCallId: nonblank,\n};\n\nconst approvalRequestSchema = z\n .object({\n type: z.literal(\"tool-approval\"),\n ...interactionBase,\n input: jsonValueSchema,\n reason: z.string().optional(),\n })\n .strict();\n\nconst questionRequestSchema = z\n .object({\n type: z.literal(\"tool-question\"),\n ...interactionBase,\n questions: z.array(questionPromptSchema).min(1),\n })\n .strict()\n .superRefine((request, context) => {\n const ids = new Set<string>();\n for (const [index, question] of request.questions.entries()) {\n if (ids.has(question.id)) {\n context.addIssue({\n code: \"custom\",\n message: \"Question IDs must be unique.\",\n path: [\"questions\", index, \"id\"],\n });\n }\n ids.add(question.id);\n }\n });\n\nexport const agentInteractionRequestSchema = z.discriminatedUnion(\"type\", [\n approvalRequestSchema,\n questionRequestSchema,\n]);\n\nexport const agentInteractionResponseSchema = z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"tool-approval\"),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"tool-question\"),\n answers: z.array(questionAnswerSchema),\n })\n .strict(),\n]);\n\nexport const agentContinuationSchema = z\n .object({\n version: z.literal(1),\n agentId: nonblank,\n sourceRunId: nonblank,\n interaction: agentInteractionRequestSchema,\n state: jsonObjectSchema,\n })\n .strict();\n\nexport function parseAgentInteractionRequest(value: unknown): AgentInteractionRequest {\n return freeze(agentInteractionRequestSchema.parse(value)) as AgentInteractionRequest;\n}\n\nexport function parseAgentInteractionResponse(value: unknown): AgentInteractionResponse {\n return freeze(agentInteractionResponseSchema.parse(value)) as AgentInteractionResponse;\n}\n\nexport function parseAgentQuestionPrompts(value: unknown): readonly AgentQuestionPrompt[] {\n const request = questionRequestSchema.parse({\n type: \"tool-question\",\n id: \"validation\",\n toolName: \"validation\",\n toolCallId: \"validation\",\n internalCallId: \"validation\",\n questions: value,\n });\n return freeze(request.questions) as readonly AgentQuestionPrompt[];\n}\n\nexport function parseAgentContinuation(value: unknown): AgentContinuation {\n return freeze(agentContinuationSchema.parse(value)) as AgentContinuation;\n}\n\nexport function assertAgentInteractionResponse(\n request: AgentInteractionRequest,\n response: AgentInteractionResponse,\n): void {\n if (request.type !== response.type) {\n throw new TypeError(\"Interaction response type does not match the pending request.\");\n }\n if (request.type === \"tool-question\" && response.type === \"tool-question\") {\n assertQuestionAnswers(request, response.answers);\n }\n}\n\nfunction assertQuestionAnswers(\n request: AgentToolQuestionRequest,\n answers: readonly AgentQuestionAnswer[],\n): void {\n const parsed = answers.map((answer) => questionAnswerSchema.parse(answer));\n const byId = new Map(parsed.map((answer) => [answer.questionId, answer]));\n if (byId.size !== parsed.length) {\n throw new TypeError(\"Question answers must not contain duplicate question IDs.\");\n }\n if (byId.size !== request.questions.length) {\n throw new TypeError(\"Question responses must answer every question exactly once.\");\n }\n for (const question of request.questions) {\n const answer = byId.get(question.id);\n if (answer === undefined) {\n throw new TypeError(`Question response is missing an answer for \"${question.id}\".`);\n }\n const choices = question.choices;\n if (\n choices !== undefined &&\n question.allowCustom !== true &&\n !choices.some((choice) => choice.value === answer.value)\n ) {\n throw new TypeError(`Question \"${question.id}\" requires one of its configured choices.`);\n }\n }\n}\n\nfunction freeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n for (const child of Object.values(value)) freeze(child);\n return Object.freeze(value);\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS;AA4DlB,IAAM,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;AACxC,IAAM,kBAAkB,EAAE,OAAkB,aAAa;AAAA,EACvD,SAAS;AACX,CAAC;AACD,IAAM,mBAAmB,EAAE;AAAA,EACzB,CAAC,UACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,YAAY,KAAK;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,2CAA2C;AAAA,IACzF;AAAA,EACF;AACF;AAEA,SAAS,OAAU,OAAa;AAC9B,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,SAAS,KAAK,EAAG,QAAO;AAClF,aAAW,SAAS,OAAO,OAAO,KAAK,EAAG,QAAO,KAAK;AACtD,SAAO,OAAO,OAAO,KAAK;AAC5B;","names":[]}
@@ -0,0 +1,177 @@
1
+ import {
2
+ isJsonValue
3
+ } from "./chunk-3XQGVDU5.js";
4
+
5
+ // src/completion/message-schema.ts
6
+ import { z } from "zod";
7
+ var jsonValueSchema = z.custom(isJsonValue, {
8
+ message: "Expected a strict JSON value"
9
+ });
10
+ var jsonObjectSchema = z.custom(
11
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value),
12
+ { message: "Expected a strict JSON object" }
13
+ );
14
+ var textPartSchema = z.object({
15
+ type: z.literal("text"),
16
+ text: z.string(),
17
+ signature: z.string().optional()
18
+ }).strict();
19
+ var urlDataSchema = z.object({ type: z.literal("url"), url: z.url() }).strict();
20
+ var binaryDataSchema = z.object({
21
+ type: z.literal("data"),
22
+ data: z.string().refine(isBase64, { message: "Expected base64 data" })
23
+ }).strict();
24
+ var textDataSchema = z.object({ type: z.literal("text"), text: z.string() }).strict();
25
+ var fileDataSchema = z.union([urlDataSchema, binaryDataSchema, textDataSchema]);
26
+ var mediaTypeSchema = z.string().regex(/^[^\s/]+\/[^\s/]+(?:\s*;.*)?$/, "Expected a media type");
27
+ var imagePartSchema = z.object({
28
+ type: z.literal("image"),
29
+ image: z.union([urlDataSchema, binaryDataSchema]),
30
+ mediaType: mediaTypeSchema.optional(),
31
+ detail: z.enum(["auto", "low", "high"]).optional()
32
+ }).strict();
33
+ var filePartSchema = z.object({
34
+ type: z.literal("file"),
35
+ data: fileDataSchema,
36
+ mediaType: mediaTypeSchema,
37
+ filename: z.string().optional()
38
+ }).strict();
39
+ var reasoningDetailSchema = z.union([
40
+ z.object({ type: z.literal("text"), text: z.string(), signature: z.string().optional() }).strict(),
41
+ z.object({ type: z.literal("summary"), text: z.string() }).strict(),
42
+ z.object({ type: z.literal("encrypted"), data: z.string() }).strict(),
43
+ z.object({ type: z.literal("redacted"), data: z.string() }).strict()
44
+ ]);
45
+ var reasoningPartSchema = z.object({
46
+ type: z.literal("reasoning"),
47
+ text: z.string(),
48
+ id: z.string().optional(),
49
+ details: z.array(reasoningDetailSchema).optional()
50
+ }).strict();
51
+ var toolCallPartSchema = z.object({
52
+ type: z.literal("tool-call"),
53
+ toolCallId: z.string().min(1),
54
+ callId: z.string().optional(),
55
+ toolName: z.string().min(1),
56
+ input: jsonValueSchema,
57
+ signature: z.string().optional()
58
+ }).strict();
59
+ var toolResultOutputSchema = z.union([
60
+ z.object({ type: z.literal("text"), value: z.string() }).strict(),
61
+ z.object({ type: z.literal("json"), value: jsonValueSchema }).strict(),
62
+ z.object({
63
+ type: z.literal("content"),
64
+ value: z.array(z.union([textPartSchema, filePartSchema]))
65
+ }).strict(),
66
+ z.object({ type: z.literal("execution-denied"), reason: z.string().optional() }).strict(),
67
+ z.object({ type: z.literal("error-text"), value: z.string() }).strict(),
68
+ z.object({ type: z.literal("error-json"), value: jsonValueSchema }).strict()
69
+ ]);
70
+ var toolResultPartSchema = z.object({
71
+ type: z.literal("tool-result"),
72
+ toolCallId: z.string().min(1),
73
+ callId: z.string().optional(),
74
+ toolName: z.string().min(1),
75
+ output: toolResultOutputSchema
76
+ }).strict();
77
+ var toolApprovalResponsePartSchema = z.object({
78
+ type: z.literal("tool-approval-response"),
79
+ interactionId: z.string().min(1),
80
+ toolCallId: z.string().min(1),
81
+ callId: z.string().optional(),
82
+ toolName: z.string().min(1),
83
+ approved: z.boolean(),
84
+ reason: z.string().optional()
85
+ }).strict();
86
+ var toolQuestionAnswerSchema = z.object({
87
+ questionId: z.string().min(1),
88
+ value: z.string()
89
+ }).strict();
90
+ var toolQuestionResponsePartSchema = z.object({
91
+ type: z.literal("tool-question-response"),
92
+ interactionId: z.string().min(1),
93
+ toolCallId: z.string().min(1),
94
+ callId: z.string().optional(),
95
+ toolName: z.string().min(1),
96
+ answers: z.array(toolQuestionAnswerSchema)
97
+ }).strict();
98
+ function createMessageSchema(options) {
99
+ const metadata = options.metadataSchema.optional();
100
+ const system = z.object({ role: z.literal("system"), content: z.string(), metadata }).strict();
101
+ const user = z.object({
102
+ role: z.literal("user"),
103
+ content: z.union([
104
+ z.string(),
105
+ z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
106
+ ]),
107
+ metadata
108
+ }).strict();
109
+ const assistant = z.object({
110
+ role: z.literal("assistant"),
111
+ id: z.string().optional(),
112
+ content: z.union([
113
+ z.string(),
114
+ z.array(
115
+ z.union([
116
+ textPartSchema,
117
+ imagePartSchema,
118
+ filePartSchema,
119
+ reasoningPartSchema,
120
+ toolCallPartSchema
121
+ ])
122
+ )
123
+ ]),
124
+ metadata
125
+ }).strict();
126
+ const tool = z.object({
127
+ role: z.literal("tool"),
128
+ content: z.array(
129
+ z.union([
130
+ toolResultPartSchema,
131
+ toolApprovalResponsePartSchema,
132
+ toolQuestionResponsePartSchema
133
+ ])
134
+ ),
135
+ metadata
136
+ }).strict();
137
+ const message = z.union([system, user, assistant, tool]);
138
+ return z.custom(isJsonValue, { message: "Expected a strict JSON message" }).pipe(message).refine(isJsonValue, { message: "Expected a strict JSON message" });
139
+ }
140
+ var messageSchema = createMessageSchema({ metadataSchema: jsonObjectSchema });
141
+ var messagesSchema = z.array(messageSchema);
142
+ function parseMessage(value) {
143
+ return messageSchema.parse(value);
144
+ }
145
+ function parseMessages(value) {
146
+ return messagesSchema.parse(value);
147
+ }
148
+ function isMessage(value) {
149
+ return messageSchema.safeParse(value).success;
150
+ }
151
+ function isBase64(value) {
152
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return false;
153
+ const firstPadding = value.indexOf("=");
154
+ if (firstPadding !== -1 && firstPadding < value.length - 2) return false;
155
+ const rawLength = value.replace(/=+$/, "").length;
156
+ if (rawLength % 4 === 1) return false;
157
+ return firstPadding === -1 || value.length % 4 === 0;
158
+ }
159
+
160
+ // src/schema/zod-schema.ts
161
+ import { z as z2 } from "zod";
162
+ function toProviderJsonSchema(schema, options = {}) {
163
+ const jsonSchema = z2.toJSONSchema(schema, options);
164
+ const { $schema: _schema, ...providerSchema } = jsonSchema;
165
+ return providerSchema;
166
+ }
167
+
168
+ export {
169
+ createMessageSchema,
170
+ messageSchema,
171
+ messagesSchema,
172
+ parseMessage,
173
+ parseMessages,
174
+ isMessage,
175
+ toProviderJsonSchema
176
+ };
177
+ //# sourceMappingURL=chunk-QGX73TSQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/completion/message-schema.ts","../src/schema/zod-schema.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { isJsonValue } from \"./json\";\nimport type { JsonObject, JsonValue, Message } from \"./types\";\n\nconst jsonValueSchema = z.custom<JsonValue>(isJsonValue, {\n message: \"Expected a strict JSON value\",\n});\n\nconst jsonObjectSchema = z.custom<JsonObject>(\n (value) =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && isJsonValue(value),\n { message: \"Expected a strict JSON object\" },\n);\n\nconst textPartSchema = z\n .object({\n type: z.literal(\"text\"),\n text: z.string(),\n signature: z.string().optional(),\n })\n .strict();\n\nconst urlDataSchema = z.object({ type: z.literal(\"url\"), url: z.url() }).strict();\nconst binaryDataSchema = z\n .object({\n type: z.literal(\"data\"),\n data: z.string().refine(isBase64, { message: \"Expected base64 data\" }),\n })\n .strict();\nconst textDataSchema = z.object({ type: z.literal(\"text\"), text: z.string() }).strict();\nconst fileDataSchema = z.union([urlDataSchema, binaryDataSchema, textDataSchema]);\nconst mediaTypeSchema = z.string().regex(/^[^\\s/]+\\/[^\\s/]+(?:\\s*;.*)?$/, \"Expected a media type\");\n\nconst imagePartSchema = z\n .object({\n type: z.literal(\"image\"),\n image: z.union([urlDataSchema, binaryDataSchema]),\n mediaType: mediaTypeSchema.optional(),\n detail: z.enum([\"auto\", \"low\", \"high\"]).optional(),\n })\n .strict();\n\nconst filePartSchema = z\n .object({\n type: z.literal(\"file\"),\n data: fileDataSchema,\n mediaType: mediaTypeSchema,\n filename: z.string().optional(),\n })\n .strict();\n\nconst reasoningDetailSchema = z.union([\n z\n .object({ type: z.literal(\"text\"), text: z.string(), signature: z.string().optional() })\n .strict(),\n z.object({ type: z.literal(\"summary\"), text: z.string() }).strict(),\n z.object({ type: z.literal(\"encrypted\"), data: z.string() }).strict(),\n z.object({ type: z.literal(\"redacted\"), data: z.string() }).strict(),\n]);\n\nconst reasoningPartSchema = z\n .object({\n type: z.literal(\"reasoning\"),\n text: z.string(),\n id: z.string().optional(),\n details: z.array(reasoningDetailSchema).optional(),\n })\n .strict();\n\nconst toolCallPartSchema = z\n .object({\n type: z.literal(\"tool-call\"),\n toolCallId: z.string().min(1),\n callId: z.string().optional(),\n toolName: z.string().min(1),\n input: jsonValueSchema,\n signature: z.string().optional(),\n })\n .strict();\n\nconst toolResultOutputSchema = z.union([\n z.object({ type: z.literal(\"text\"), value: z.string() }).strict(),\n z.object({ type: z.literal(\"json\"), value: jsonValueSchema }).strict(),\n z\n .object({\n type: z.literal(\"content\"),\n value: z.array(z.union([textPartSchema, filePartSchema])),\n })\n .strict(),\n z.object({ type: z.literal(\"execution-denied\"), reason: z.string().optional() }).strict(),\n z.object({ type: z.literal(\"error-text\"), value: z.string() }).strict(),\n z.object({ type: z.literal(\"error-json\"), value: jsonValueSchema }).strict(),\n]);\n\nconst toolResultPartSchema = z\n .object({\n type: z.literal(\"tool-result\"),\n toolCallId: z.string().min(1),\n callId: z.string().optional(),\n toolName: z.string().min(1),\n output: toolResultOutputSchema,\n })\n .strict();\n\nconst toolApprovalResponsePartSchema = z\n .object({\n type: z.literal(\"tool-approval-response\"),\n interactionId: z.string().min(1),\n toolCallId: z.string().min(1),\n callId: z.string().optional(),\n toolName: z.string().min(1),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .strict();\n\nconst toolQuestionAnswerSchema = z\n .object({\n questionId: z.string().min(1),\n value: z.string(),\n })\n .strict();\n\nconst toolQuestionResponsePartSchema = z\n .object({\n type: z.literal(\"tool-question-response\"),\n interactionId: z.string().min(1),\n toolCallId: z.string().min(1),\n callId: z.string().optional(),\n toolName: z.string().min(1),\n answers: z.array(toolQuestionAnswerSchema),\n })\n .strict();\n\nexport type MessageMetadataSchema<Metadata extends JsonObject> = z.ZodType<Metadata>;\n\nexport function createMessageSchema<Metadata extends JsonObject>(options: {\n metadataSchema: MessageMetadataSchema<Metadata>;\n}): z.ZodType<Message<Metadata>> {\n const metadata = options.metadataSchema.optional();\n const system = z.object({ role: z.literal(\"system\"), content: z.string(), metadata }).strict();\n const user = z\n .object({\n role: z.literal(\"user\"),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n metadata,\n })\n .strict();\n const assistant = z\n .object({\n role: z.literal(\"assistant\"),\n id: z.string().optional(),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n imagePartSchema,\n filePartSchema,\n reasoningPartSchema,\n toolCallPartSchema,\n ]),\n ),\n ]),\n metadata,\n })\n .strict();\n const tool = z\n .object({\n role: z.literal(\"tool\"),\n content: z.array(\n z.union([\n toolResultPartSchema,\n toolApprovalResponsePartSchema,\n toolQuestionResponsePartSchema,\n ]),\n ),\n metadata,\n })\n .strict();\n\n const message = z.union([system, user, assistant, tool]);\n return z\n .custom<z.input<typeof message>>(isJsonValue, { message: \"Expected a strict JSON message\" })\n .pipe(message)\n .refine(isJsonValue, { message: \"Expected a strict JSON message\" }) as unknown as z.ZodType<\n Message<Metadata>\n >;\n}\n\nexport const messageSchema = createMessageSchema({ metadataSchema: jsonObjectSchema });\nexport const messagesSchema = z.array(messageSchema);\n\nexport function parseMessage(value: unknown): Message {\n return messageSchema.parse(value);\n}\n\nexport function parseMessages(value: unknown): Message[] {\n return messagesSchema.parse(value);\n}\n\nexport function isMessage(value: unknown): value is Message {\n return messageSchema.safeParse(value).success;\n}\n\nfunction isBase64(value: string): boolean {\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return false;\n const firstPadding = value.indexOf(\"=\");\n if (firstPadding !== -1 && firstPadding < value.length - 2) return false;\n const rawLength = value.replace(/=+$/, \"\").length;\n if (rawLength % 4 === 1) return false;\n return firstPadding === -1 || value.length % 4 === 0;\n}\n","import { z } from \"zod\";\nimport type { JsonObject } from \"../completion/index\";\n\nexport type ZodSchema<T = unknown> = z.ZodType<T>;\n\nexport function toProviderJsonSchema(\n schema: z.ZodType,\n options: { io?: \"input\" | \"output\" } = {},\n): JsonObject {\n const jsonSchema = z.toJSONSchema(schema, options) as JsonObject;\n const { $schema: _schema, ...providerSchema } = jsonSchema;\n return providerSchema;\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS;AAIlB,IAAM,kBAAkB,EAAE,OAAkB,aAAa;AAAA,EACvD,SAAS;AACX,CAAC;AAED,IAAM,mBAAmB,EAAE;AAAA,EACzB,CAAC,UACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,YAAY,KAAK;AAAA,EAC3F,EAAE,SAAS,gCAAgC;AAC7C;AAEA,IAAM,iBAAiB,EACpB,OAAO;AAAA,EACN,MAAM,EAAE,QAAQ,MAAM;AAAA,EACtB,MAAM,EAAE,OAAO;AAAA,EACf,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC,EACA,OAAO;AAEV,IAAM,gBAAgB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,KAAK,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO;AAChF,IAAM,mBAAmB,EACtB,OAAO;AAAA,EACN,MAAM,EAAE,QAAQ,MAAM;AAAA,EACtB,MAAM,EAAE,OAAO,EAAE,OAAO,UAAU,EAAE,SAAS,uBAAuB,CAAC;AACvE,CAAC,EACA,OAAO;AACV,IAAM,iBAAiB,EAAE,OAAO,EAAE,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AC,yBAAyB,KAAK,KAAK,EAAG,QAAO;AAClD,QAAM,eAAe,MAAM,QAAQ,GAAG;AACtC,MAAI,iBAAiB,MAAM,eAAe,MAAM,SAAS,EAAG,QAAO;AACnE,QAAM,YAAY,MAAM,QAAQ,OAAO,EAAE,EAAE;AAC3C,MAAI,YAAY,MAAM,EAAG,QAAO;AAChC,SAAO,iBAAiB,MAAM,MAAM,SAAS,MAAM;AACrD;;;ACvNA,SAAS,KAAAA,UAAS;AAKX,SAAS,qBACd,QACA,UAAuC,CAAC,GAC5B;AACZ,QAAM,aAAaA,GAAE,aAAa,QAAQ,OAAO;AACjD,QAAM,EAAE,SAAS,SAAS,GAAG,eAAe,IAAI;AAChD,SAAO;AACT;","names":["z"]}
@@ -0,0 +1,29 @@
1
+ // src/memory/scope-key.ts
2
+ function createMemoryScopeKey(options) {
3
+ const values = [options.scope.sessionId];
4
+ if (options.includeUserId ?? true) {
5
+ values.push(options.scope.userId ?? null);
6
+ }
7
+ for (const key of options.metadataKeys ?? []) {
8
+ values.push(metadataValue(options.scope.metadata, key) ?? null);
9
+ }
10
+ return JSON.stringify(values);
11
+ }
12
+ function metadataValue(metadata, path) {
13
+ let current = metadata;
14
+ for (const part of path.split(".")) {
15
+ if (!isJsonObject(current)) {
16
+ return void 0;
17
+ }
18
+ current = current[part];
19
+ }
20
+ return current;
21
+ }
22
+ function isJsonObject(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+
26
+ export {
27
+ createMemoryScopeKey
28
+ };
29
+ //# sourceMappingURL=chunk-QOUPWOGW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory/scope-key.ts"],"sourcesContent":["import type { JsonObject, JsonValue } from \"../completion/types\";\nimport type { CreateMemoryScopeKeyOptions } from \"./types\";\n\nexport function createMemoryScopeKey(options: CreateMemoryScopeKeyOptions): string {\n const values: JsonValue[] = [options.scope.sessionId];\n\n if (options.includeUserId ?? true) {\n values.push(options.scope.userId ?? null);\n }\n\n for (const key of options.metadataKeys ?? []) {\n values.push(metadataValue(options.scope.metadata, key) ?? null);\n }\n\n return JSON.stringify(values);\n}\n\nfunction metadataValue(metadata: JsonObject | undefined, path: string): JsonValue | undefined {\n let current: JsonValue | undefined = metadata;\n for (const part of path.split(\".\")) {\n if (!isJsonObject(current)) {\n return undefined;\n }\n current = current[part];\n }\n return current;\n}\n\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAGO,SAAS,qBAAqB,SAA8C;AACjF,QAAM,SAAsB,CAAC,QAAQ,MAAM,SAAS;AAEpD,MAAI,QAAQ,iBAAiB,MAAM;AACjC,WAAO,KAAK,QAAQ,MAAM,UAAU,IAAI;AAAA,EAC1C;AAEA,aAAW,OAAO,QAAQ,gBAAgB,CAAC,GAAG;AAC5C,WAAO,KAAK,cAAc,QAAQ,MAAM,UAAU,GAAG,KAAK,IAAI;AAAA,EAChE;AAEA,SAAO,KAAK,UAAU,MAAM;AAC9B;AAEA,SAAS,cAAc,UAAkC,MAAqC;AAC5F,MAAI,UAAiC;AACrC,aAAW,QAAQ,KAAK,MAAM,GAAG,GAAG;AAClC,QAAI,CAAC,aAAa,OAAO,GAAG;AAC1B,aAAO;AAAA,IACT;AACA,cAAU,QAAQ,IAAI;AAAA,EACxB;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAmD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":[]}