@anvia/core 0.12.0 → 0.12.2

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 (57) hide show
  1. package/dist/agent/index.d.ts +8 -8
  2. package/dist/agent/index.js +6 -6
  3. package/dist/{agent-BWF8_O8k.d.ts → agent-BBj3jvBi.d.ts} +4 -4
  4. package/dist/{chunk-KTTIPWE7.js → chunk-4NCRFQHS.js} +20 -140
  5. package/dist/chunk-4NCRFQHS.js.map +1 -0
  6. package/dist/{chunk-YRERPIA5.js → chunk-CWUJUSOS.js} +4 -164
  7. package/dist/chunk-CWUJUSOS.js.map +1 -0
  8. package/dist/{chunk-ZGIE73BH.js → chunk-J3ROUB3P.js} +2 -2
  9. package/dist/{chunk-JNO4AR7Q.js → chunk-LKLKEECY.js} +93 -5
  10. package/dist/chunk-LKLKEECY.js.map +1 -0
  11. package/dist/{chunk-PGFYN5ZX.js → chunk-QKA6OQTH.js} +2 -4
  12. package/dist/chunk-QKA6OQTH.js.map +1 -0
  13. package/dist/{chunk-MIJUAWHU.js → chunk-QNVLGAPV.js} +4 -4
  14. package/dist/{chunk-4AJJIIAQ.js → chunk-TUDZBJGF.js} +4 -4
  15. package/dist/{chunk-TIH4QM55.js → chunk-XUO3KR5T.js} +4 -4
  16. package/dist/{chunk-R7F2JF7J.js → chunk-YVQBC3SJ.js} +2 -2
  17. package/dist/chunk-YVQBC3SJ.js.map +1 -0
  18. package/dist/evals/index.d.ts +5 -5
  19. package/dist/evals/index.js +7 -7
  20. package/dist/extractor/index.d.ts +5 -5
  21. package/dist/extractor/index.js +7 -7
  22. package/dist/guardrails/index.d.ts +6 -84
  23. package/dist/guardrails/index.js +3 -11
  24. package/dist/{index-DsWWqP0Q.d.ts → index-Oucb3Ljj.d.ts} +1 -1
  25. package/dist/index.d.ts +10 -10
  26. package/dist/index.js +8 -12
  27. package/dist/internal/agent.d.ts +5 -5
  28. package/dist/internal/agent.js +5 -5
  29. package/dist/mcp/index.d.ts +3 -4
  30. package/dist/{middleware-BTR0eRtx.d.ts → middleware-ByyL6Rj0.d.ts} +2 -2
  31. package/dist/observability/index.d.ts +2 -2
  32. package/dist/pipeline/index.d.ts +5 -5
  33. package/dist/request/index.d.ts +5 -5
  34. package/dist/request/index.js +4 -4
  35. package/dist/skills/index.d.ts +3 -4
  36. package/dist/skills/index.js +3 -3
  37. package/dist/{think-tool-Bn3HHu_z.d.ts → think-tool-B065hm73.d.ts} +1 -4
  38. package/dist/tool/index.d.ts +4 -5
  39. package/dist/tool/index.js +2 -2
  40. package/dist/{tool-DGELXD2z.d.ts → tool-B8K543oQ.d.ts} +0 -3
  41. package/dist/{types-Dc83Qzch.d.ts → types-7F_IKQQW.d.ts} +1 -1
  42. package/dist/{types-Bx_ZtjPi.d.ts → types-BzUuhjKr.d.ts} +1 -1
  43. package/dist/{types-9VPKg7ih.d.ts → types-Pl4PFQWL.d.ts} +1 -1
  44. package/dist/ui/index.d.ts +20 -2
  45. package/dist/ui/index.js +1 -1
  46. package/dist/vector-store/index.d.ts +3 -4
  47. package/dist/vector-store/index.js +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-JNO4AR7Q.js.map +0 -1
  50. package/dist/chunk-KTTIPWE7.js.map +0 -1
  51. package/dist/chunk-PGFYN5ZX.js.map +0 -1
  52. package/dist/chunk-R7F2JF7J.js.map +0 -1
  53. package/dist/chunk-YRERPIA5.js.map +0 -1
  54. /package/dist/{chunk-ZGIE73BH.js.map → chunk-J3ROUB3P.js.map} +0 -0
  55. /package/dist/{chunk-MIJUAWHU.js.map → chunk-QNVLGAPV.js.map} +0 -0
  56. /package/dist/{chunk-4AJJIIAQ.js.map → chunk-TUDZBJGF.js.map} +0 -0
  57. /package/dist/{chunk-TIH4QM55.js.map → chunk-XUO3KR5T.js.map} +0 -0
@@ -4,20 +4,12 @@ function defineGuardrailPolicy(options) {
4
4
  id: options.id,
5
5
  mode: options.mode ?? "enforce",
6
6
  input: options.input ?? [],
7
- tools: options.tools ?? [],
8
- toolResults: options.toolResults ?? [],
9
7
  output: options.output ?? []
10
8
  };
11
9
  }
12
10
  function defineInputGuardrail(guardrail) {
13
11
  return guardrail;
14
12
  }
15
- function defineToolGuardrail(guardrail) {
16
- return guardrail;
17
- }
18
- function defineToolResultGuardrail(guardrail) {
19
- return guardrail;
20
- }
21
13
  function defineOutputGuardrail(guardrail) {
22
14
  return guardrail;
23
15
  }
@@ -82,89 +74,6 @@ async function runInputGuardrails(policies, context) {
82
74
  }
83
75
  return { prompt, inputText, blocked: false, decisions };
84
76
  }
85
- async function runToolGuardrails(policies, toolGuardrails, context) {
86
- let rawArgs = context.rawArgs;
87
- let args = context.args;
88
- const decisions = [];
89
- for (const entry of toolGuardrailEntries(policies, toolGuardrails, context.toolName)) {
90
- const currentContext = { ...context, rawArgs, args };
91
- const result = await runGuardrail(
92
- entry.policy,
93
- entry.guardrail.id,
94
- "tool",
95
- () => entry.guardrail.check(currentContext, toolActions)
96
- );
97
- decisions.push(result.decision);
98
- if (entry.policy.mode === "observe") {
99
- continue;
100
- }
101
- if (result.action.action === "block") {
102
- return {
103
- rawArgs,
104
- blocked: true,
105
- message: result.action.message,
106
- decisions
107
- };
108
- }
109
- if (result.action.action === "request_approval") {
110
- return {
111
- rawArgs,
112
- blocked: false,
113
- approval: {
114
- reason: result.action.reason,
115
- rejectMessage: result.action.rejectMessage
116
- },
117
- decisions
118
- };
119
- }
120
- if (result.action.action === "rewrite") {
121
- rawArgs = typeof result.action.args === "string" ? result.action.args : JSON.stringify(result.action.args);
122
- try {
123
- args = JSON.parse(rawArgs);
124
- } catch {
125
- args = rawArgs;
126
- }
127
- }
128
- }
129
- return { rawArgs, blocked: false, decisions };
130
- }
131
- async function runToolResultGuardrails(policies, toolGuardrails, context) {
132
- let result = context.result;
133
- let structuredResult = context.structuredResult;
134
- const decisions = [];
135
- for (const entry of toolResultGuardrailEntries(policies, toolGuardrails, context.toolName)) {
136
- const currentContext = { ...context, result, structuredResult };
137
- const guardrailResult = await runGuardrail(
138
- entry.policy,
139
- entry.guardrail.id,
140
- "tool_result",
141
- () => entry.guardrail.check(currentContext, toolResultActions)
142
- );
143
- decisions.push(guardrailResult.decision);
144
- if (entry.policy.mode === "observe") {
145
- continue;
146
- }
147
- if (guardrailResult.action.action === "block") {
148
- return {
149
- result,
150
- structuredResult,
151
- blocked: true,
152
- message: guardrailResult.action.message,
153
- decisions
154
- };
155
- }
156
- if (guardrailResult.action.action === "rewrite") {
157
- if (guardrailResult.action.structuredResult !== void 0) {
158
- structuredResult = guardrailResult.action.structuredResult;
159
- result = textFromToolResultContent(structuredResult);
160
- } else if (guardrailResult.action.result !== void 0) {
161
- result = guardrailResult.action.result;
162
- structuredResult = void 0;
163
- }
164
- }
165
- }
166
- return { result, structuredResult, blocked: false, decisions };
167
- }
168
77
  async function runOutputGuardrails(policies, context) {
169
78
  let outputText = context.outputText;
170
79
  const decisions = [];
@@ -258,61 +167,12 @@ var inputActions = {
258
167
  return { action: "rewrite", ...options };
259
168
  }
260
169
  };
261
- var toolActions = {
262
- ...commonActions,
263
- rewrite(options) {
264
- return { action: "rewrite", ...options };
265
- },
266
- requestApproval(options = {}) {
267
- return { action: "request_approval", ...options };
268
- }
269
- };
270
- var toolResultActions = {
271
- ...commonActions,
272
- rewrite(options) {
273
- return { action: "rewrite", ...options };
274
- }
275
- };
276
170
  var outputActions = {
277
171
  ...commonActions,
278
172
  rewrite(options) {
279
173
  return { action: "rewrite", ...options };
280
174
  }
281
175
  };
282
- function toolGuardrailEntries(policies, toolGuardrails, toolName) {
283
- return [
284
- ...policies.flatMap(
285
- (policy) => policy.tools.filter((guardrail) => matchesTool(guardrail.tool, toolName)).map((guardrail) => ({ policy, guardrail }))
286
- ),
287
- ...toolGuardrails.map((guardrail) => ({
288
- policy: defineGuardrailPolicy({
289
- id: `tool:${toolName}:${guardrail.id}`,
290
- tools: [guardrail]
291
- }),
292
- guardrail
293
- }))
294
- ];
295
- }
296
- function toolResultGuardrailEntries(policies, toolGuardrails, toolName) {
297
- return [
298
- ...policies.flatMap(
299
- (policy) => policy.toolResults.filter((guardrail) => matchesTool(guardrail.tool, toolName)).map((guardrail) => ({ policy, guardrail }))
300
- ),
301
- ...toolGuardrails.map((guardrail) => ({
302
- policy: defineGuardrailPolicy({
303
- id: `tool:${toolName}:${guardrail.id}`,
304
- toolResults: [guardrail]
305
- }),
306
- guardrail
307
- }))
308
- ];
309
- }
310
- function matchesTool(tool, toolName) {
311
- if (tool === void 0) {
312
- return true;
313
- }
314
- return Array.isArray(tool) ? tool.includes(toolName) : tool === toolName;
315
- }
316
176
  function blockText(options) {
317
177
  return textPatternGuardrail(options, "block");
318
178
  }
@@ -333,27 +193,14 @@ function textPatternGuardrail(options, action) {
333
193
  }
334
194
  });
335
195
  }
336
- if (options.boundary === "output") {
337
- return defineOutputGuardrail({
338
- id: options.id,
339
- check(ctx, actions) {
340
- return textPatternAction(
341
- ctx.outputText,
342
- options,
343
- action,
344
- (value) => actions.rewrite({ outputText: value, reason: options.reason })
345
- );
346
- }
347
- });
348
- }
349
- return defineToolResultGuardrail({
196
+ return defineOutputGuardrail({
350
197
  id: options.id,
351
198
  check(ctx, actions) {
352
199
  return textPatternAction(
353
- ctx.result,
200
+ ctx.outputText,
354
201
  options,
355
202
  action,
356
- (value) => actions.rewrite({ result: value, reason: options.reason })
203
+ (value) => actions.rewrite({ outputText: value, reason: options.reason })
357
204
  );
358
205
  }
359
206
  });
@@ -427,15 +274,10 @@ function rewriteMessageText(message, text) {
427
274
  }
428
275
  return message;
429
276
  }
430
- function textFromToolResultContent(content) {
431
- return content.map((item) => item.type === "text" ? item.text : "[image]").join("\n");
432
- }
433
277
 
434
278
  export {
435
279
  defineGuardrailPolicy,
436
280
  defineInputGuardrail,
437
- defineToolGuardrail,
438
- defineToolResultGuardrail,
439
281
  defineOutputGuardrail,
440
282
  allow,
441
283
  block,
@@ -444,8 +286,6 @@ export {
444
286
  appendGuardrailPolicies,
445
287
  hasEnforcedOutputGuardrails,
446
288
  runInputGuardrails,
447
- runToolGuardrails,
448
- runToolResultGuardrails,
449
289
  runOutputGuardrails
450
290
  };
451
- //# sourceMappingURL=chunk-YRERPIA5.js.map
291
+ //# sourceMappingURL=chunk-CWUJUSOS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/guardrails/index.ts"],"sourcesContent":["import type { JsonObject, Message, Usage } from \"../completion\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type GuardrailMode = \"enforce\" | \"observe\";\n\nexport type GuardrailBoundary = \"input\" | \"output\";\n\nexport type GuardrailRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailDecisionRecord = {\n policyId: string;\n guardrailId: string;\n boundary: GuardrailBoundary;\n mode: GuardrailMode;\n action: GuardrailActionName;\n applied: boolean;\n reason?: string | undefined;\n message?: string | undefined;\n metadata?: JsonObject | undefined;\n latencyMs: number;\n};\n\nexport type GuardrailActionName = \"allow\" | \"block\" | \"rewrite\" | \"error\";\n\nexport type GuardrailActionBase = {\n reason?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailAllow = GuardrailActionBase & {\n action: \"allow\";\n};\n\nexport type GuardrailBlock = GuardrailActionBase & {\n action: \"block\";\n reason: string;\n message?: string | undefined;\n};\n\nexport type InputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n prompt?: Message | undefined;\n inputText?: string | undefined;\n};\n\nexport type OutputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n outputText: string;\n};\n\nexport type InputGuardrailResult = GuardrailAllow | GuardrailBlock | InputGuardrailRewrite;\nexport type OutputGuardrailResult = GuardrailAllow | GuardrailBlock | OutputGuardrailRewrite;\n\nexport type GuardrailCommonActions = {\n allow(options?: GuardrailActionBase): GuardrailAllow;\n block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock;\n};\n\nexport type InputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<InputGuardrailRewrite, \"action\">): InputGuardrailRewrite;\n};\n\nexport type OutputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<OutputGuardrailRewrite, \"action\">): OutputGuardrailRewrite;\n};\n\nexport type InputGuardrailContext = {\n prompt: Message;\n history: Message[];\n inputText: string;\n run: GuardrailRunContext;\n};\n\nexport type OutputGuardrailContext = {\n outputText: string;\n messages: Message[];\n usage: Usage;\n run: GuardrailRunContext;\n};\n\nexport type InputGuardrail = {\n id: string;\n check(\n context: InputGuardrailContext,\n actions: InputGuardrailActions,\n ): MaybePromise<InputGuardrailResult | undefined>;\n};\n\nexport type OutputGuardrail = {\n id: string;\n check(\n context: OutputGuardrailContext,\n actions: OutputGuardrailActions,\n ): MaybePromise<OutputGuardrailResult | undefined>;\n};\n\nexport type GuardrailPolicy = {\n id: string;\n mode: GuardrailMode;\n input: InputGuardrail[];\n output: OutputGuardrail[];\n};\n\nexport type GuardrailPolicyOptions = {\n id: string;\n mode?: GuardrailMode | undefined;\n input?: InputGuardrail[] | undefined;\n output?: OutputGuardrail[] | undefined;\n};\n\nexport type GuardrailPolicyInput = GuardrailPolicy | GuardrailPolicy[];\n\nexport type InputGuardrailRunResult = {\n prompt: Message;\n inputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport type OutputGuardrailRunResult = {\n outputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport function defineGuardrailPolicy(options: GuardrailPolicyOptions): GuardrailPolicy {\n return {\n id: options.id,\n mode: options.mode ?? \"enforce\",\n input: options.input ?? [],\n output: options.output ?? [],\n };\n}\n\nexport function defineInputGuardrail(guardrail: InputGuardrail): InputGuardrail {\n return guardrail;\n}\n\nexport function defineOutputGuardrail(guardrail: OutputGuardrail): OutputGuardrail {\n return guardrail;\n}\n\nexport function allow(options: GuardrailActionBase = {}): GuardrailAllow {\n return { action: \"allow\", ...options };\n}\n\nexport function block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock {\n return { action: \"block\", ...options };\n}\n\nexport const guardrails = {\n blockText,\n redactText,\n};\n\nexport function normalizeGuardrailPolicies(\n policies: GuardrailPolicyInput | undefined,\n): GuardrailPolicy[] {\n if (policies === undefined) {\n return [];\n }\n return Array.isArray(policies) ? policies : [policies];\n}\n\nexport function appendGuardrailPolicies(\n current: GuardrailPolicy[],\n next: GuardrailPolicyInput,\n): GuardrailPolicy[] {\n return [...current, ...normalizeGuardrailPolicies(next)];\n}\n\nexport function hasEnforcedOutputGuardrails(policies: GuardrailPolicy[]): boolean {\n return policies.some((policy) => policy.mode === \"enforce\" && policy.output.length > 0);\n}\n\nexport async function runInputGuardrails(\n policies: GuardrailPolicy[],\n context: InputGuardrailContext,\n): Promise<InputGuardrailRunResult> {\n let prompt = context.prompt;\n let inputText = context.inputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.input) {\n const currentContext = { ...context, prompt, inputText };\n const result = await runGuardrail(policy, guardrail.id, \"input\", () =>\n guardrail.check(currentContext, inputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n prompt,\n inputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n if (result.action.prompt !== undefined) {\n prompt = result.action.prompt;\n inputText = textFromMessage(prompt);\n } else if (result.action.inputText !== undefined) {\n inputText = result.action.inputText;\n prompt = rewriteMessageText(prompt, inputText);\n }\n }\n }\n }\n\n return { prompt, inputText, blocked: false, decisions };\n}\n\nexport async function runOutputGuardrails(\n policies: GuardrailPolicy[],\n context: OutputGuardrailContext,\n): Promise<OutputGuardrailRunResult> {\n let outputText = context.outputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.output) {\n const currentContext = { ...context, outputText };\n const result = await runGuardrail(policy, guardrail.id, \"output\", () =>\n guardrail.check(currentContext, outputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n outputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n outputText = result.action.outputText;\n }\n }\n }\n\n return { outputText, blocked: false, decisions };\n}\n\ntype RunGuardrailResult<TAction extends { action: GuardrailActionName }> = {\n action: TAction;\n decision: GuardrailDecisionRecord;\n};\n\nasync function runGuardrail<TAction extends { action: GuardrailActionName } & GuardrailActionBase>(\n policy: GuardrailPolicy,\n guardrailId: string,\n boundary: GuardrailBoundary,\n run: () => MaybePromise<TAction | undefined>,\n): Promise<RunGuardrailResult<TAction | GuardrailAllow>> {\n const startedAt = Date.now();\n try {\n const action = (await run()) ?? allow();\n return {\n action,\n decision: decisionRecord({\n policy,\n guardrailId,\n boundary,\n action,\n latencyMs: Date.now() - startedAt,\n }),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (policy.mode === \"observe\") {\n return {\n action: allow(),\n decision: {\n policyId: policy.id,\n guardrailId,\n boundary,\n mode: policy.mode,\n action: \"error\",\n applied: false,\n reason: message,\n latencyMs: Date.now() - startedAt,\n },\n };\n }\n throw error;\n }\n}\n\nfunction decisionRecord(args: {\n policy: GuardrailPolicy;\n guardrailId: string;\n boundary: GuardrailBoundary;\n action: GuardrailAllow | GuardrailBlock | ({ action: GuardrailActionName } & GuardrailActionBase);\n latencyMs: number;\n}): GuardrailDecisionRecord {\n const applied = args.policy.mode === \"enforce\" && args.action.action !== \"allow\";\n const record: GuardrailDecisionRecord = {\n policyId: args.policy.id,\n guardrailId: args.guardrailId,\n boundary: args.boundary,\n mode: args.policy.mode,\n action: args.action.action,\n applied,\n latencyMs: args.latencyMs,\n };\n if (args.action.reason !== undefined) record.reason = args.action.reason;\n if (\"message\" in args.action && typeof args.action.message === \"string\") {\n record.message = args.action.message;\n }\n if (args.action.metadata !== undefined) record.metadata = args.action.metadata;\n return record;\n}\n\nconst commonActions: GuardrailCommonActions = {\n allow,\n block,\n};\n\nconst inputActions: InputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\nconst outputActions: OutputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\ntype TextPatternBoundary = \"input\" | \"output\";\n\ntype TextPatternGuardrailFor<Boundary extends TextPatternBoundary> = Boundary extends \"input\"\n ? InputGuardrail\n : OutputGuardrail;\n\ntype TextPatternGuardrailOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> = {\n id: string;\n boundary: Boundary;\n patterns: Array<string | RegExp>;\n reason: string;\n message?: string | undefined;\n};\n\ntype TextPatternRedactOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> =\n TextPatternGuardrailOptions<Boundary> & { replacement?: string | undefined };\n\nfunction blockText<Boundary extends TextPatternBoundary>(\n options: TextPatternGuardrailOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"block\");\n}\n\nfunction redactText<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"rewrite\");\n}\n\nfunction textPatternGuardrail<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n action: \"block\" | \"rewrite\",\n): TextPatternGuardrailFor<Boundary> {\n if (options.boundary === \"input\") {\n return defineInputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.inputText, options, action, (value) =>\n actions.rewrite({ inputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n }\n return defineOutputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.outputText, options, action, (value) =>\n actions.rewrite({ outputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n}\n\nfunction textPatternAction<TRewrite>(\n text: string,\n options: TextPatternGuardrailOptions & { replacement?: string | undefined },\n action: \"block\" | \"rewrite\",\n rewrite: (value: string) => TRewrite,\n): GuardrailAllow | GuardrailBlock | TRewrite {\n const matched = options.patterns.some((pattern) => textPatternMatches(text, pattern));\n if (!matched) {\n return allow();\n }\n if (action === \"block\") {\n return block({\n reason: options.reason,\n message: options.message,\n });\n }\n let current = text;\n for (const pattern of options.patterns) {\n current = replaceTextPattern(current, pattern, options.replacement ?? \"[redacted]\");\n }\n return rewrite(current);\n}\n\nfunction textPatternMatches(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.includes(pattern);\n }\n pattern.lastIndex = 0;\n const matched = pattern.test(text);\n pattern.lastIndex = 0;\n return matched;\n}\n\nfunction replaceTextPattern(text: string, pattern: string | RegExp, replacement: string): string {\n if (typeof pattern === \"string\") {\n return text.split(pattern).join(replacement);\n }\n pattern.lastIndex = 0;\n const flags = pattern.flags.replace(\"y\", \"\");\n const globalFlags = flags.includes(\"g\") ? flags : `${flags}g`;\n return text.replace(new RegExp(pattern.source, globalFlags), replacement);\n}\n\nfunction textFromMessage(message: Message): string {\n if (message.role === \"system\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"document\" && content.source.type === \"text\") {\n return [content.source.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction rewriteMessageText(message: Message, text: string): Message {\n if (message.role === \"system\") {\n return { ...message, content: text };\n }\n if (message.role === \"user\") {\n return {\n ...message,\n content: [\n { type: \"text\", text },\n ...message.content.filter(\n (item) =>\n item.type !== \"text\" && !(item.type === \"document\" && item.source.type === \"text\"),\n ),\n ],\n };\n }\n if (message.role === \"assistant\") {\n return { ...message, content: [{ type: \"text\", text }] };\n }\n return message;\n}\n"],"mappings":";AAqIO,SAAS,sBAAsB,SAAkD;AACtF,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,MAAM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ACC,KAAK,SAAS,UAAU,EAAE,KAAK,SAAS,cAAc,KAAK,OAAO,SAAS;AAAA,QAC/E;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,SAAS,aAAa;AAChC,WAAO,EAAE,GAAG,SAAS,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,EAAE;AAAA,EACzD;AACA,SAAO;AACT;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-YK4WAAS4.js";
4
4
  import {
5
5
  createTool
6
- } from "./chunk-PGFYN5ZX.js";
6
+ } from "./chunk-QKA6OQTH.js";
7
7
  import {
8
8
  isRecord
9
9
  } from "./chunk-MMHG7WAM.js";
@@ -395,4 +395,4 @@ export {
395
395
  SkillValidationError,
396
396
  skill
397
397
  };
398
- //# sourceMappingURL=chunk-ZGIE73BH.js.map
398
+ //# sourceMappingURL=chunk-J3ROUB3P.js.map
@@ -25,12 +25,16 @@ function uiMessagesToCoreMessages(messages) {
25
25
  content.push(UserContent.text(part.text));
26
26
  continue;
27
27
  }
28
+ if (part.type === "attachment") {
29
+ content.push(attachmentToUserContent(part.attachment));
30
+ continue;
31
+ }
28
32
  if (part.type === "data" && isUserContent(part.data)) {
29
33
  content.push(part.data);
30
34
  continue;
31
35
  }
32
36
  throw new TypeError(
33
- "User UI messages can only be converted from text parts or image/document data parts."
37
+ "User UI messages can only be converted from text, attachment, or image/document data parts."
34
38
  );
35
39
  }
36
40
  if (content.length > 0) {
@@ -116,9 +120,8 @@ function coreMessagesToUIMessages(messages) {
116
120
  } else {
117
121
  parts2.push({
118
122
  id: createId("part"),
119
- type: "data",
120
- name: content.type,
121
- data: content
123
+ type: "attachment",
124
+ attachment: userContentToAttachment(content)
122
125
  });
123
126
  }
124
127
  }
@@ -194,6 +197,91 @@ function textFromUIParts(parts) {
194
197
  function outputToToolResultContent(output) {
195
198
  return [{ type: "text", text: serializeToolResultOutput(output ?? null) }];
196
199
  }
200
+ function attachmentToUserContent(attachment) {
201
+ if (attachment.type === "image" || isImageFileAttachment(attachment)) {
202
+ if (attachment.url !== void 0) {
203
+ return UserContent.imageUrl(attachment.url, imageOptions(attachment));
204
+ }
205
+ if (attachment.data !== void 0 && attachment.mediaType !== void 0) {
206
+ return UserContent.imageBase64(
207
+ attachment.data,
208
+ attachment.mediaType,
209
+ imageOptions(attachment)
210
+ );
211
+ }
212
+ throw new TypeError("Image attachments require a url or base64 data with mediaType.");
213
+ }
214
+ if (attachment.text !== void 0) {
215
+ return {
216
+ type: "document",
217
+ source: {
218
+ type: "text",
219
+ text: attachment.text,
220
+ ...attachment.mediaType === void 0 ? {} : { mediaType: attachment.mediaType },
221
+ ...attachment.name === void 0 ? {} : { filename: attachment.name }
222
+ }
223
+ };
224
+ }
225
+ const mediaType = attachment.mediaType ?? "application/octet-stream";
226
+ if (attachment.url !== void 0) {
227
+ return UserContent.documentUrl(attachment.url, mediaType, documentOptions(attachment));
228
+ }
229
+ if (attachment.data !== void 0) {
230
+ return UserContent.documentBase64(attachment.data, mediaType, documentOptions(attachment));
231
+ }
232
+ throw new TypeError("Document attachments require a url, base64 data, or text.");
233
+ }
234
+ function userContentToAttachment(content) {
235
+ if (content.type === "image") {
236
+ const attachment2 = {
237
+ id: createId("attachment"),
238
+ type: "image",
239
+ ...content.detail === void 0 ? {} : { detail: content.detail }
240
+ };
241
+ if (content.source.type === "url") {
242
+ attachment2.url = content.source.url;
243
+ } else {
244
+ attachment2.data = content.source.data;
245
+ attachment2.mediaType = content.source.mediaType;
246
+ }
247
+ return attachment2;
248
+ }
249
+ const attachment = {
250
+ id: createId("attachment"),
251
+ type: "document"
252
+ };
253
+ if (content.source.type === "url") {
254
+ attachment.url = content.source.url;
255
+ attachment.mediaType = content.source.mediaType;
256
+ if (content.source.filename !== void 0) {
257
+ attachment.name = content.source.filename;
258
+ }
259
+ } else if (content.source.type === "base64") {
260
+ attachment.data = content.source.data;
261
+ attachment.mediaType = content.source.mediaType;
262
+ if (content.source.filename !== void 0) {
263
+ attachment.name = content.source.filename;
264
+ }
265
+ } else {
266
+ attachment.text = content.source.text;
267
+ if (content.source.mediaType !== void 0) {
268
+ attachment.mediaType = content.source.mediaType;
269
+ }
270
+ if (content.source.filename !== void 0) {
271
+ attachment.name = content.source.filename;
272
+ }
273
+ }
274
+ return attachment;
275
+ }
276
+ function isImageFileAttachment(attachment) {
277
+ return attachment.type === "file" && attachment.mediaType?.startsWith("image/") === true;
278
+ }
279
+ function imageOptions(attachment) {
280
+ return attachment.detail === void 0 ? {} : { detail: attachment.detail };
281
+ }
282
+ function documentOptions(attachment) {
283
+ return attachment.name === void 0 ? {} : { filename: attachment.name };
284
+ }
197
285
  function toolResultContentToJson(content) {
198
286
  if (content.length === 1 && content[0]?.type === "text") {
199
287
  return content[0].text;
@@ -262,4 +350,4 @@ export {
262
350
  uiMessagesToCoreMessages,
263
351
  coreMessagesToUIMessages
264
352
  };
265
- //# sourceMappingURL=chunk-JNO4AR7Q.js.map
353
+ //# sourceMappingURL=chunk-LKLKEECY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui/messages.ts"],"sourcesContent":["import {\n AssistantContent,\n type AssistantContent as AssistantContentType,\n type Message as CoreMessage,\n type DocumentContent,\n type ImageContent,\n type ImageDetail,\n type JsonValue,\n Message,\n reasoningDisplayText,\n serializeToolResultOutput,\n ToolContent,\n type ToolContent as ToolContentType,\n type ToolResultContent,\n UserContent,\n type UserContent as UserContentType,\n} from \"../completion/types\";\nimport type { UIAttachment, UIMessage, UIMessagePart } from \"./types\";\n\nexport function uiMessagesToCoreMessages(messages: UIMessage[]): CoreMessage[] {\n const coreMessages: CoreMessage[] = [];\n\n for (const message of messages) {\n const text = textFromUIParts(message.parts);\n\n if (message.role === \"system\") {\n if (text.length > 0) {\n coreMessages.push(Message.system(text));\n }\n continue;\n }\n\n if (message.role === \"user\") {\n const content: UserContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\") {\n content.push(UserContent.text(part.text));\n continue;\n }\n if (part.type === \"attachment\") {\n content.push(attachmentToUserContent(part.attachment));\n continue;\n }\n if (part.type === \"data\" && isUserContent(part.data)) {\n content.push(part.data);\n continue;\n }\n throw new TypeError(\n \"User UI messages can only be converted from text, attachment, or image/document data parts.\",\n );\n }\n if (content.length > 0) {\n coreMessages.push(Message.user(content));\n }\n continue;\n }\n\n if (message.role === \"assistant\") {\n const content: AssistantContentType[] = [];\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\" && part.text.length > 0) {\n content.push(AssistantContent.text(part.text));\n continue;\n }\n if (part.type === \"reasoning\" && part.text.length > 0) {\n content.push(AssistantContent.reasoning(part.text, part.reasoningId));\n continue;\n }\n if (\n part.type === \"tool\" &&\n (part.state === \"input-streaming\" ||\n part.state === \"input-available\" ||\n part.state === \"output-available\")\n ) {\n content.push(\n AssistantContent.toolCall(\n part.toolCallId,\n part.toolName,\n part.input ?? {},\n part.callId,\n ),\n );\n if (part.state === \"output-available\") {\n toolResults.push(\n ToolContent.toolResult(\n part.toolCallId,\n outputToToolResultContent(part.output),\n part.callId,\n ),\n );\n }\n }\n }\n if (content.length > 0) {\n coreMessages.push(Message.assistant(content, message.id));\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults));\n }\n continue;\n }\n\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type !== \"tool\" || part.state !== \"output-available\") {\n continue;\n }\n toolResults.push(\n ToolContent.toolResult(\n part.toolCallId,\n outputToToolResultContent(part.output),\n part.callId,\n ),\n );\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults));\n }\n }\n\n return coreMessages;\n}\n\nexport function coreMessagesToUIMessages(messages: CoreMessage[]): UIMessage[] {\n const uiMessages: UIMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"system\",\n parts: [{ id: createId(\"part\"), type: \"text\", text: message.content }],\n });\n continue;\n }\n\n if (message.role === \"user\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n } else {\n parts.push({\n id: createId(\"part\"),\n type: \"attachment\",\n attachment: userContentToAttachment(content),\n });\n }\n }\n uiMessages.push({ id: createId(\"msg\"), role: \"user\", parts });\n continue;\n }\n\n if (message.role === \"assistant\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n continue;\n }\n if (content.type === \"reasoning\") {\n const part: UIMessagePart = {\n id: createId(\"part\"),\n type: \"reasoning\",\n text: reasoningDisplayText(content),\n };\n if (content.id !== undefined) {\n part.reasoningId = content.id;\n }\n parts.push(part);\n continue;\n }\n if (content.type === \"tool_call\") {\n const part: UIMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: content.function.name,\n toolCallId: content.id,\n state: \"input-available\",\n input: content.function.arguments,\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n parts.push(part);\n continue;\n }\n parts.push({\n id: createId(\"part\"),\n type: \"data\",\n name: content.type,\n data: content as JsonValue,\n });\n }\n uiMessages.push({ id: message.id ?? createId(\"msg\"), role: \"assistant\", parts });\n continue;\n }\n\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n const part: UIMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: \"tool\",\n toolCallId: content.id,\n state: \"output-available\",\n output: toolResultContentToJson(content.content),\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n parts.push(part);\n }\n uiMessages.push({ id: createId(\"msg\"), role: \"tool\", parts });\n }\n\n return uiMessages;\n}\n\nexport function isUIMessage(value: unknown): value is UIMessage {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n isUIMessageRole(value.role) &&\n Array.isArray(value.parts)\n );\n}\n\nexport function isUIMessageArray(value: unknown): value is UIMessage[] {\n return Array.isArray(value) && value.every(isUIMessage);\n}\n\nfunction textFromUIParts(parts: UIMessagePart[]): string {\n return parts.flatMap((part) => (part.type === \"text\" ? [part.text] : [])).join(\"\");\n}\n\nfunction outputToToolResultContent(output: JsonValue | undefined): ToolResultContent[] {\n return [{ type: \"text\", text: serializeToolResultOutput(output ?? null) }];\n}\n\nfunction attachmentToUserContent(attachment: UIAttachment): UserContentType {\n if (attachment.type === \"image\" || isImageFileAttachment(attachment)) {\n if (attachment.url !== undefined) {\n return UserContent.imageUrl(attachment.url, imageOptions(attachment));\n }\n if (attachment.data !== undefined && attachment.mediaType !== undefined) {\n return UserContent.imageBase64(\n attachment.data,\n attachment.mediaType,\n imageOptions(attachment),\n );\n }\n throw new TypeError(\"Image attachments require a url or base64 data with mediaType.\");\n }\n\n if (attachment.text !== undefined) {\n return {\n type: \"document\",\n source: {\n type: \"text\",\n text: attachment.text,\n ...(attachment.mediaType === undefined ? {} : { mediaType: attachment.mediaType }),\n ...(attachment.name === undefined ? {} : { filename: attachment.name }),\n },\n };\n }\n\n const mediaType = attachment.mediaType ?? \"application/octet-stream\";\n if (attachment.url !== undefined) {\n return UserContent.documentUrl(attachment.url, mediaType, documentOptions(attachment));\n }\n if (attachment.data !== undefined) {\n return UserContent.documentBase64(attachment.data, mediaType, documentOptions(attachment));\n }\n\n throw new TypeError(\"Document attachments require a url, base64 data, or text.\");\n}\n\nfunction userContentToAttachment(content: ImageContent | DocumentContent): UIAttachment {\n if (content.type === \"image\") {\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"image\",\n ...(content.detail === undefined ? {} : { detail: content.detail }),\n };\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n } else {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n }\n return attachment;\n }\n\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"document\",\n };\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else if (content.source.type === \"base64\") {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else {\n attachment.text = content.source.text;\n if (content.source.mediaType !== undefined) {\n attachment.mediaType = content.source.mediaType;\n }\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n }\n return attachment;\n}\n\nfunction isImageFileAttachment(attachment: UIAttachment): boolean {\n return attachment.type === \"file\" && attachment.mediaType?.startsWith(\"image/\") === true;\n}\n\nfunction imageOptions(attachment: UIAttachment): { detail?: ImageDetail } {\n return attachment.detail === undefined ? {} : { detail: attachment.detail };\n}\n\nfunction documentOptions(attachment: UIAttachment): { filename?: string } {\n return attachment.name === undefined ? {} : { filename: attachment.name };\n}\n\nfunction toolResultContentToJson(content: ToolResultContent[]): JsonValue {\n if (content.length === 1 && content[0]?.type === \"text\") {\n return content[0].text;\n }\n return content as JsonValue;\n}\n\nfunction isUserContent(value: unknown): value is UserContentType {\n if (!isRecord(value)) {\n return false;\n }\n\n if (value.type === \"text\") {\n return typeof value.text === \"string\";\n }\n\n if (value.type === \"image\") {\n return isImageContent(value);\n }\n\n if (value.type === \"document\") {\n return isDocumentContent(value);\n }\n\n return false;\n}\n\nfunction isImageContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n return false;\n}\n\nfunction isDocumentContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"text\") {\n return (\n typeof value.source.text === \"string\" &&\n (value.source.mediaType === undefined || typeof value.source.mediaType === \"string\")\n );\n }\n\n return false;\n}\n\nfunction toolPartId(toolCallId: string): string {\n return `tool_${toolCallId}`;\n}\n\nlet nextId = 0;\n\nfunction createId(prefix: string): string {\n const random = globalThis.crypto?.randomUUID?.();\n if (random !== undefined) {\n return `${prefix}_${random}`;\n }\n nextId += 1;\n return `${prefix}_${nextId.toString(36)}`;\n}\n\nfunction isUIMessageRole(value: unknown): value is UIMessage[\"role\"] {\n return value === \"system\" || value === \"user\" || value === \"assistant\" || value === \"tool\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"],"mappings":";;;;;;;;;;AAmBO,SAAS,yBAAyB,UAAsC;AAC7E,QAAM,eAA8B,CAAC;AAErC,aAAW,WAAW,UAAU;AAC9B,UAAM,OAAO,gBAAgB,QAAQ,KAAK;AAE1C,QAAI,QAAQ,SAAS,UAAU;AAC7B,UAAI,KAAK,SAAS,GAAG;AACnB,qBAAa,KAAK,QAAQ,OAAO,IAAI,CAAC;AAAA,MACxC;AACA;AAAA,IACF;AAEA,QAAI,QAAQ,SAAS,QAAQ;AAC3B,YAAM,UAA6B,CAAC;AACpC,iBAAW,QAAQ,QAAQ,OAAO;AAChC,YAAI,KAAK,SAAS,QAAQ;AACxB,kBAAQ,KAAK,YAAY,KAAK,KAAK,IAAI,CAAC;AACxC;AAAA,QACF;AACA,YAAI,KAAK,SAAS,cAAc;AAC9B,kBAAQ,KAAK,wBAAwB,KAAK,UAAU,CAAC;AACrD;AAAA,QACF;AACA,YAAI,KAAK,SAAS,UAAU,cAAc,KAAK,IAAI,GAAG;AACpD,kBAAQ,KAAK,KAAK,IAAI;AACtB;AAAA,QACF;AACA,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AACA,UAAI,QAAQ,SAAS,GAAG;AACtB,qBAAa,KAAK,QAAQ,KAAK,OAAO,CAAC;AAAA,MACzC;AACA;AAAA,IACF;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AAO,SAAS,QAAQ;AAChC,WACE,OAAO,MAAM,OAAO,SAAS,aAC5B,MAAM,OAAO,cAAc,UAAa,OAAO,MAAM,OAAO,cAAc;AAAA,EAE/E;AAEA,SAAO;AACT;AAEA,SAAS,WAAW,YAA4B;AAC9C,SAAO,QAAQ,UAAU;AAC3B;AAEA,IAAI,SAAS;AAEb,SAAS,SAAS,QAAwB;AACxC,QAAM,SAAS,WAAW,QAAQ,aAAa;AAC/C,MAAI,WAAW,QAAW;AACxB,WAAO,GAAG,MAAM,IAAI,MAAM;AAAA,EAC5B;AACA,YAAU;AACV,SAAO,GAAG,MAAM,IAAI,OAAO,SAAS,EAAE,CAAC;AACzC;AAMA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":["toolResults","parts","attachment"]}
@@ -18,9 +18,7 @@ function createTool(options) {
18
18
  return {
19
19
  ...compact({
20
20
  name: options.name,
21
- approval: options.approval,
22
- inputGuardrails: options.inputGuardrails === void 0 ? void 0 : [...options.inputGuardrails],
23
- outputGuardrails: options.outputGuardrails === void 0 ? void 0 : [...options.outputGuardrails]
21
+ approval: options.approval
24
22
  }),
25
23
  definition() {
26
24
  return {
@@ -330,4 +328,4 @@ export {
330
328
  InMemoryVectorIndex,
331
329
  createVectorSearchTool
332
330
  };
333
- //# sourceMappingURL=chunk-PGFYN5ZX.js.map
331
+ //# sourceMappingURL=chunk-QKA6OQTH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector-store/index.ts","../src/tool/create-tool.ts","../src/vector-store/filter.ts","../src/vector-store/lsh.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n cosineSimilarity,\n type EmbeddedDocument,\n type Embedding,\n type EmbeddingModel,\n embedText,\n type VectorMetadata,\n} from \"../embeddings\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool } from \"../tool/tool\";\nimport { matchesVectorFilter } from \"./filter\";\nimport { LshIndex } from \"./lsh\";\nimport type {\n IndexStrategy,\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchIndex,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n} from \"./types\";\n\nexport { vectorFilter } from \"./filter\";\nexport type * from \"./types\";\n\ntype StoredDocument<T, Metadata extends VectorMetadata> = EmbeddedDocument<T, Metadata>;\n\nexport class InMemoryVectorStore<T, Metadata extends VectorMetadata = VectorMetadata> {\n private readonly documents = new Map<string, StoredDocument<T, Metadata>>();\n private indexStrategy: IndexStrategy;\n private lshIndex: LshIndex | undefined;\n private embeddingDimension: number | undefined;\n\n constructor(options: { index?: IndexStrategy } = {}) {\n this.indexStrategy = options.index ?? { type: \"bruteForce\" };\n }\n\n static fromDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n documents: Array<EmbeddedDocument<T, Metadata>>,\n options: { index?: IndexStrategy } = {},\n ): InMemoryVectorStore<T, Metadata> {\n const store = new InMemoryVectorStore<T, Metadata>(options);\n store.addDocuments(documents);\n return store;\n }\n\n addDocuments(documents: Array<EmbeddedDocument<T, Metadata>>): this {\n this.validateDocumentDimensions(documents);\n for (const document of documents) {\n this.documents.set(document.id, document);\n }\n this.rebuildLshIndex();\n return this;\n }\n\n get(id: string): StoredDocument<T, Metadata> | undefined {\n return this.documents.get(id);\n }\n\n values(): Array<StoredDocument<T, Metadata>> {\n return [...this.documents.values()];\n }\n\n len(): number {\n return this.documents.size;\n }\n\n isEmpty(): boolean {\n return this.documents.size === 0;\n }\n\n index(model: EmbeddingModel): InMemoryVectorIndex<T, Metadata> {\n return new InMemoryVectorIndex(model, this);\n }\n\n candidates(queryEmbedding: Embedding): Array<StoredDocument<T, Metadata>> {\n this.validateQueryDimension(queryEmbedding);\n if (this.indexStrategy.type !== \"lsh\" || this.lshIndex === undefined) {\n return this.values();\n }\n\n const candidateIds = this.lshIndex.query(queryEmbedding.vector);\n if (candidateIds.size === 0) {\n return this.values();\n }\n\n return [...candidateIds].flatMap((id) => {\n const document = this.documents.get(id);\n return document === undefined ? [] : [document];\n });\n }\n\n private rebuildLshIndex(): void {\n if (this.indexStrategy.type !== \"lsh\") {\n this.lshIndex = undefined;\n return;\n }\n\n const firstEmbedding = this.values().flatMap((document) => document.embeddings)[0];\n if (firstEmbedding === undefined) {\n this.lshIndex = undefined;\n return;\n }\n\n const index = new LshIndex(firstEmbedding.vector.length, this.indexStrategy);\n for (const document of this.documents.values()) {\n for (const embedding of document.embeddings) {\n index.insert(document.id, embedding.vector);\n }\n }\n this.lshIndex = index;\n }\n\n private validateDocumentDimensions(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n let dimension = this.embeddingDimension;\n for (const document of documents) {\n for (const embedding of document.embeddings) {\n dimension = validateEmbeddingDimension(dimension, embedding, document.id);\n }\n }\n this.embeddingDimension = dimension;\n }\n\n private validateQueryDimension(queryEmbedding: Embedding): void {\n if (this.embeddingDimension === undefined) {\n return;\n }\n validateEmbeddingDimension(this.embeddingDimension, queryEmbedding, \"query\");\n }\n}\n\nexport class InMemoryVectorIndex<T, Metadata extends VectorMetadata = VectorMetadata>\n implements VectorSearchIndex<T, Metadata>\n{\n constructor(\n private readonly model: EmbeddingModel,\n private readonly store: InMemoryVectorStore<T, Metadata>,\n ) {}\n\n async search(request: VectorSearchRequest): Promise<Array<VectorSearchResult<T, Metadata>>> {\n const queryEmbedding = await embedText(this.model, request.query);\n return this.store\n .candidates(queryEmbedding)\n .filter((document) => matchesVectorFilter(document.metadata, request.filter))\n .flatMap((document) => {\n const score = bestScore(queryEmbedding, document.embeddings);\n if (score === undefined) {\n return [];\n }\n if (request.threshold !== undefined && score < request.threshold) {\n return [];\n }\n return [\n {\n score,\n id: document.id,\n document: document.document,\n ...(document.metadata !== undefined && { metadata: document.metadata }),\n },\n ];\n })\n .sort((left, right) => right.score - left.score)\n .slice(0, Math.max(0, Math.trunc(request.topK)));\n }\n\n async searchIds(request: VectorSearchRequest): Promise<Array<{ score: number; id: string }>> {\n return (await this.search(request)).map(({ score, id }) => ({ score, id }));\n }\n\n async inspect(request: VectorInspectRequest): Promise<VectorInspectPage<T, Metadata>> {\n const limit = Math.max(0, Math.trunc(request.limit));\n const start = Math.max(0, Math.trunc(Number(request.cursor ?? \"0\")));\n const documents = this.store\n .values()\n .filter((document) => matchesVectorFilter(document.metadata, request.filter));\n const page = documents.slice(start, start + limit);\n const nextOffset = start + page.length;\n return {\n items: page.map((document) => ({\n id: document.id,\n document: document.document,\n ...(document.metadata !== undefined && { metadata: document.metadata }),\n })),\n ...(nextOffset < documents.length ? { nextCursor: String(nextOffset) } : {}),\n totalCount: documents.length,\n };\n }\n\n asTool(options: VectorSearchToolOptions): Tool<{ query: string; topK?: number }, unknown> {\n return createVectorSearchTool(this, options);\n }\n}\n\nexport function createVectorSearchTool<T, Metadata extends VectorMetadata>(\n index: VectorSearchIndex<T, Metadata>,\n options: VectorSearchToolOptions,\n): Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>> {\n return createTool({\n name: options.name,\n description:\n options.description ?? \"Search a vector store for documents relevant to the provided query.\",\n input: z.object({\n query: z.string().describe(\"The query string to search for relevant documents.\"),\n topK: z.number().int().positive().optional().describe(\"The maximum number of results.\"),\n }),\n output: z.array(\n z.object({\n score: z.number(),\n id: z.string(),\n document: z.any(),\n metadata: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))\n .optional(),\n }),\n ),\n execute: ({ query, topK }) =>\n index.search({\n query,\n topK: topK ?? options.topK ?? 5,\n threshold: options.threshold,\n filter: options.filter,\n }),\n }) as Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>>;\n}\n\nfunction bestScore(queryEmbedding: Embedding, embeddings: Embedding[]): number | undefined {\n let best: number | undefined;\n for (const embedding of embeddings) {\n const score = cosineSimilarity(queryEmbedding.vector, embedding.vector);\n best = best === undefined ? score : Math.max(best, score);\n }\n return best;\n}\n\nfunction validateEmbeddingDimension(\n expectedDimension: number | undefined,\n embedding: Embedding,\n id: string,\n): number {\n if (expectedDimension === undefined) {\n return embedding.vector.length;\n }\n if (embedding.vector.length !== expectedDimension) {\n throw new Error(\n `Vector dimension mismatch: expected ${expectedDimension} dimensions but received ${embedding.vector.length} for ${id}`,\n );\n }\n return expectedDimension;\n}\n","import type { z } from \"zod\";\nimport { compact } from \"../internal/compact\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { Tool, ToolApprovalPolicy, ToolCallContext } from \"./tool\";\n\nexport type CreateToolOptions<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n> = {\n name: string;\n description: string;\n input: InputSchema;\n output?: OutputSchema;\n approval?: ToolApprovalPolicy<z.output<InputSchema>>;\n execute(\n args: z.output<InputSchema>,\n context: ToolCallContext,\n ): OutputSchema extends ZodSchema\n ? z.input<OutputSchema> | Promise<z.input<OutputSchema>>\n : Output | Promise<Output>;\n};\n\ntype CreateToolOutput<\n OutputSchema extends ZodSchema | undefined,\n Output,\n> = OutputSchema extends ZodSchema ? z.output<OutputSchema> : Output;\n\nexport function createTool<InputSchema extends ZodSchema, Output = unknown>(\n options: CreateToolOptions<InputSchema, undefined, Output> & { output?: undefined },\n): Tool<z.output<InputSchema>, Output>;\n\nexport function createTool<InputSchema extends ZodSchema, OutputSchema extends ZodSchema>(\n options: CreateToolOptions<InputSchema, OutputSchema>,\n): Tool<z.output<InputSchema>, z.output<OutputSchema>>;\n\nexport function createTool<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n>(\n options: CreateToolOptions<InputSchema, OutputSchema, Output>,\n): Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> {\n const parameters = toProviderJsonSchema(options.input);\n\n return {\n ...compact({\n name: options.name,\n approval: options.approval,\n }),\n definition() {\n return {\n name: options.name,\n description: options.description,\n parameters,\n };\n },\n async call(args, context = {}): Promise<CreateToolOutput<OutputSchema, Output>> {\n const parsedArgs = options.input.parse(args);\n const result = await options.execute(parsedArgs, context);\n return (\n options.output === undefined ? result : options.output.parse(result)\n ) as CreateToolOutput<OutputSchema, Output>;\n },\n parseApprovalArgs(args): z.output<InputSchema> {\n return options.input.parse(args);\n },\n };\n}\n","import type { VectorMetadata, VectorMetadataValue } from \"../embeddings\";\nimport type { VectorFilter } from \"./types\";\n\nexport type { VectorFilter } from \"./types\";\n\nexport const vectorFilter = {\n eq(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"eq\", key, value };\n },\n gt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"gt\", key, value };\n },\n lt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"lt\", key, value };\n },\n and(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"and\", filters: [left, right] };\n },\n or(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"or\", filters: [left, right] };\n },\n};\n\nexport function matchesVectorFilter(\n metadata: VectorMetadata | undefined,\n filter: VectorFilter | undefined,\n): boolean {\n if (filter === undefined) {\n return true;\n }\n if (metadata === undefined) {\n return false;\n }\n\n switch (filter.type) {\n case \"eq\":\n return metadata[filter.key] === filter.value;\n case \"gt\":\n return compare(metadata[filter.key], filter.value) > 0;\n case \"lt\":\n return compare(metadata[filter.key], filter.value) < 0;\n case \"and\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) &&\n matchesVectorFilter(metadata, filter.filters[1])\n );\n case \"or\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) ||\n matchesVectorFilter(metadata, filter.filters[1])\n );\n }\n}\n\nfunction compare(left: VectorMetadataValue | undefined, right: VectorMetadataValue): number {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n if (typeof left === \"string\" && typeof right === \"string\") {\n return left.localeCompare(right);\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right);\n }\n return 0;\n}\n","import type { LshOptions } from \"./types\";\n\nexport type { LshOptions } from \"./types\";\n\nexport class LshIndex {\n private readonly hyperplanes: number[][];\n private readonly tables: Array<Map<string, Set<string>>>;\n\n constructor(\n dimensions: number,\n private readonly options: LshOptions,\n ) {\n const rng = seededRandom(options.seed ?? 42);\n this.hyperplanes = [];\n for (let index = 0; index < options.numTables * options.numHyperplanes; index += 1) {\n const plane = Array.from({ length: dimensions }, () => rng() * 2 - 1);\n const norm = Math.sqrt(plane.reduce((sum, value) => sum + value ** 2, 0));\n this.hyperplanes.push(norm === 0 ? plane : plane.map((value) => value / norm));\n }\n this.tables = Array.from({ length: options.numTables }, () => new Map());\n }\n\n insert(id: string, vector: number[]): void {\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n const bucket = this.tables[table]?.get(hash) ?? new Set<string>();\n bucket.add(id);\n this.tables[table]?.set(hash, bucket);\n }\n }\n\n query(vector: number[]): Set<string> {\n const candidates = new Set<string>();\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n for (const id of this.tables[table]?.get(hash) ?? []) {\n candidates.add(id);\n }\n }\n return candidates;\n }\n\n private hash(vector: number[], table: number): string {\n let hash = \"\";\n const start = table * this.options.numHyperplanes;\n for (let offset = 0; offset < this.options.numHyperplanes; offset += 1) {\n const plane = this.hyperplanes[start + offset] as number[];\n const dot = vector.reduce((sum, value, index) => sum + value * (plane[index] ?? 0), 0);\n hash += dot >= 0 ? \"1\" : \"0\";\n }\n return hash;\n }\n}\n\nfunction seededRandom(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (state * 1664525 + 1013904223) >>> 0;\n return state / 0x100000000;\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACoCX,SAAS,WAKd,SACqE;AACrE,QAAM,aAAa,qBAAqB,QAAQ,KAAK;AAErD,SAAO;AAAA,IACL,GAAG,QAAQ;AAAA,MACT,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,IACpB,CAAC;AAAA,IACD,aAAa;AACX,aAAO;AAAA,QACL,MA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ACvH;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "./chunk-TIH4QM55.js";
3
+ } from "./chunk-XUO3KR5T.js";
4
4
  import {
5
5
  extractRagText
6
- } from "./chunk-KTTIPWE7.js";
6
+ } from "./chunk-4NCRFQHS.js";
7
7
  import {
8
8
  createTool
9
- } from "./chunk-PGFYN5ZX.js";
9
+ } from "./chunk-QKA6OQTH.js";
10
10
  import {
11
11
  CompletionRequestBuilder
12
12
  } from "./chunk-SRBW3LD7.js";
@@ -138,4 +138,4 @@ export {
138
138
  Extractor,
139
139
  ExtractorBuilder
140
140
  };
141
- //# sourceMappingURL=chunk-MIJUAWHU.js.map
141
+ //# sourceMappingURL=chunk-QNVLGAPV.js.map
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  PromptRequest
3
- } from "./chunk-KTTIPWE7.js";
3
+ } from "./chunk-4NCRFQHS.js";
4
4
  import {
5
5
  isSkillTool
6
6
  } from "./chunk-YK4WAAS4.js";
7
7
  import {
8
8
  ToolSet
9
- } from "./chunk-R7F2JF7J.js";
9
+ } from "./chunk-YVQBC3SJ.js";
10
10
  import {
11
11
  createTool
12
- } from "./chunk-PGFYN5ZX.js";
12
+ } from "./chunk-QKA6OQTH.js";
13
13
  import {
14
14
  compact
15
15
  } from "./chunk-MMHG7WAM.js";
@@ -204,4 +204,4 @@ export {
204
204
  Agent,
205
205
  AgentSession
206
206
  };
207
- //# sourceMappingURL=chunk-4AJJIIAQ.js.map
207
+ //# sourceMappingURL=chunk-TUDZBJGF.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  Agent,
3
3
  normalizeAgentId
4
- } from "./chunk-4AJJIIAQ.js";
4
+ } from "./chunk-TUDZBJGF.js";
5
5
  import {
6
6
  ToolSet
7
- } from "./chunk-R7F2JF7J.js";
7
+ } from "./chunk-YVQBC3SJ.js";
8
8
  import {
9
9
  resolveMemoryOptions
10
10
  } from "./chunk-M6RPFHG7.js";
@@ -13,7 +13,7 @@ import {
13
13
  } from "./chunk-WQKHFADH.js";
14
14
  import {
15
15
  appendGuardrailPolicies
16
- } from "./chunk-YRERPIA5.js";
16
+ } from "./chunk-CWUJUSOS.js";
17
17
 
18
18
  // src/agent/builder.ts
19
19
  var AgentBuilder = class {
@@ -212,4 +212,4 @@ var AgentBuilder = class {
212
212
  export {
213
213
  AgentBuilder
214
214
  };
215
- //# sourceMappingURL=chunk-TIH4QM55.js.map
215
+ //# sourceMappingURL=chunk-XUO3KR5T.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  InMemoryVectorStore,
3
3
  createTool
4
- } from "./chunk-PGFYN5ZX.js";
4
+ } from "./chunk-QKA6OQTH.js";
5
5
  import {
6
6
  compact
7
7
  } from "./chunk-MMHG7WAM.js";
@@ -225,4 +225,4 @@ export {
225
225
  createToolMiddleware,
226
226
  createThinkTool
227
227
  };
228
- //# sourceMappingURL=chunk-R7F2JF7J.js.map
228
+ //# sourceMappingURL=chunk-YVQBC3SJ.js.map