llmz 0.0.11 → 0.0.13

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 (92) hide show
  1. package/dist/chat.d.ts +17 -0
  2. package/dist/chunk-276Q6EWP.cjs +224 -0
  3. package/dist/chunk-4L6D2A6O.cjs +283 -0
  4. package/dist/chunk-4MNIJGK6.js +224 -0
  5. package/dist/chunk-7WRN4E42.js +3087 -0
  6. package/dist/chunk-BEPRLBPK.cjs +3123 -0
  7. package/dist/chunk-C6WNNTEV.cjs +212 -0
  8. package/dist/chunk-D3ESDRLH.js +3123 -0
  9. package/dist/chunk-GGWM6X2K.js +184 -0
  10. package/dist/chunk-GWFYZDUR.cjs +105 -0
  11. package/dist/chunk-HJKOSEH2.cjs +722 -0
  12. package/dist/chunk-IH2WQFO5.js +283 -0
  13. package/dist/chunk-IKSIOIIP.cjs +28 -0
  14. package/dist/chunk-JAGB2AOU.js +212 -0
  15. package/dist/chunk-JDABP4SD.cjs +161 -0
  16. package/dist/chunk-JGVAZO4X.cjs +152 -0
  17. package/dist/chunk-JKVVQN2P.js +161 -0
  18. package/dist/chunk-JMSZKB4T.js +105 -0
  19. package/dist/chunk-JQBT7UWN.js +28 -0
  20. package/dist/chunk-KH6JQYQA.js +796 -0
  21. package/dist/chunk-KMZDFWYZ.cjs +33 -0
  22. package/dist/chunk-ORQP26SZ.js +33 -0
  23. package/dist/chunk-PRVFVXT4.js +722 -0
  24. package/dist/chunk-SHJDRZF5.cjs +796 -0
  25. package/dist/chunk-SNDVQU5A.js +152 -0
  26. package/dist/chunk-UQOBUJIQ.cjs +3087 -0
  27. package/dist/chunk-ZRCU35UV.cjs +184 -0
  28. package/dist/citations.d.ts +63 -0
  29. package/dist/compiler/compiler.d.ts +28 -0
  30. package/dist/compiler/index.d.ts +2 -0
  31. package/dist/compiler/plugins/async-iterator.d.ts +4 -0
  32. package/dist/compiler/plugins/braces-tsx.d.ts +3 -0
  33. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +5 -0
  34. package/dist/compiler/plugins/line-tracking.d.ts +5 -0
  35. package/dist/compiler/plugins/replace-comment.d.ts +5 -0
  36. package/dist/compiler/plugins/return-async.d.ts +4 -0
  37. package/dist/compiler/plugins/track-tool-calls.d.ts +16 -0
  38. package/dist/compiler/plugins/variable-extraction.d.ts +5 -0
  39. package/dist/component-R4WTW6DZ.cjs +18 -0
  40. package/dist/component-WFVDVSDK.js +18 -0
  41. package/dist/component.d.ts +66 -0
  42. package/dist/component.default.d.ts +316 -0
  43. package/dist/context.d.ts +176 -0
  44. package/dist/dual-modes-T53P72CH.js +12 -0
  45. package/dist/dual-modes-VLIGPIHX.cjs +12 -0
  46. package/dist/errors.d.ts +64 -0
  47. package/dist/exit-TRXEU4OU.cjs +8 -0
  48. package/dist/exit-YORW76T3.js +8 -0
  49. package/dist/exit.d.ts +26 -0
  50. package/dist/formatting.d.ts +5 -0
  51. package/dist/getter.d.ts +2 -0
  52. package/dist/handlers.d.ts +10 -0
  53. package/dist/hoist.d.ts +2 -0
  54. package/dist/index.cjs +921 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +921 -0
  57. package/dist/inspect.d.ts +6 -0
  58. package/dist/jsx-AEHVFB3L.js +13 -0
  59. package/dist/jsx-AJAXBWFE.cjs +13 -0
  60. package/dist/jsx.d.ts +11 -0
  61. package/dist/llmz-QLZBDG2Z.cjs +576 -0
  62. package/dist/llmz-ROOX7RYI.js +576 -0
  63. package/dist/llmz.d.ts +40 -0
  64. package/dist/objects.d.ts +24 -0
  65. package/dist/prompts/chat-mode/system.md.d.ts +2 -0
  66. package/dist/prompts/chat-mode/user.md.d.ts +2 -0
  67. package/dist/prompts/common.d.ts +6 -0
  68. package/dist/prompts/dual-modes.d.ts +2 -0
  69. package/dist/prompts/prompt.d.ts +55 -0
  70. package/dist/prompts/worker-mode/system.md.d.ts +2 -0
  71. package/dist/prompts/worker-mode/user.md.d.ts +2 -0
  72. package/dist/result.d.ts +33 -0
  73. package/dist/snapshots.d.ts +69 -0
  74. package/dist/stack-traces.d.ts +1 -0
  75. package/dist/tool-N6ODRRGH.js +11 -0
  76. package/dist/tool-QP4MVRWI.cjs +11 -0
  77. package/dist/tool.d.ts +56 -0
  78. package/dist/transcript.d.ts +36 -0
  79. package/dist/truncator-DUMWEGQO.cjs +10 -0
  80. package/dist/truncator-IY2MXOMC.js +10 -0
  81. package/dist/truncator.d.ts +20 -0
  82. package/dist/types.d.ts +105 -0
  83. package/dist/typings-2CPHOFDN.cjs +10 -0
  84. package/dist/typings-GDMY6VY2.js +10 -0
  85. package/dist/typings.d.ts +5 -0
  86. package/dist/utils-A7WNEFTA.cjs +39 -0
  87. package/dist/utils-N24IHDFA.js +39 -0
  88. package/dist/utils.d.ts +23 -0
  89. package/dist/vm-2DLG7V4G.cjs +12 -0
  90. package/dist/vm-FLBMZUA2.js +12 -0
  91. package/dist/vm.d.ts +3 -0
  92. package/package.json +4 -4
@@ -0,0 +1,283 @@
1
+ import {
2
+ CodeFormattingError
3
+ } from "./chunk-JKVVQN2P.js";
4
+ import {
5
+ escapeString,
6
+ getMultilineComment,
7
+ toPropertyKey
8
+ } from "./chunk-4MNIJGK6.js";
9
+
10
+ // src/typings.ts
11
+ import { z } from "@bpinternal/zui";
12
+
13
+ // src/formatting.ts
14
+ import { LRUCache } from "lru-cache";
15
+ import babel from "prettier/plugins/babel";
16
+ import estree from "prettier/plugins/estree";
17
+ import typescript from "prettier/plugins/typescript";
18
+ import { format } from "prettier/standalone";
19
+ var cache = new LRUCache({ max: 1e3 });
20
+ async function formatTypings(typings, options) {
21
+ if (cache.has(typings)) {
22
+ return cache.get(typings);
23
+ }
24
+ try {
25
+ options ??= {};
26
+ options.throwOnError ??= true;
27
+ const result = (await format(typings, {
28
+ singleAttributePerLine: true,
29
+ bracketSameLine: true,
30
+ semi: false,
31
+ ...options,
32
+ embeddedLanguageFormatting: "off",
33
+ plugins: [estree, babel, typescript],
34
+ parser: "typescript",
35
+ filepath: "tools.d.ts"
36
+ })).trim();
37
+ cache.set(typings, result);
38
+ return result;
39
+ } catch (err) {
40
+ if (options == null ? void 0 : options.throwOnError) {
41
+ throw new CodeFormattingError(err instanceof Error ? err.message : (err == null ? void 0 : err.toString()) ?? "Unknown Error", typings);
42
+ }
43
+ return typings;
44
+ }
45
+ }
46
+
47
+ // src/typings.ts
48
+ var Primitives = [
49
+ "string",
50
+ "number",
51
+ "boolean",
52
+ "unknown",
53
+ "void",
54
+ "any",
55
+ "null",
56
+ "undefined",
57
+ "never",
58
+ "bigint",
59
+ "symbol",
60
+ "object"
61
+ ];
62
+ var LARGE_DECLARATION_LINES = 5;
63
+ var isPrimitive = (type) => Primitives.includes(type);
64
+ var isArrayOfPrimitives = (type) => Primitives.map((p) => `${p}[]`).includes(type);
65
+ var stripSpaces = (typings) => typings.replace(/ +/g, " ").trim();
66
+ var KeyValue = class {
67
+ constructor(key, value) {
68
+ this.key = key;
69
+ this.value = value;
70
+ }
71
+ };
72
+ var FnParameters = class {
73
+ constructor(schema) {
74
+ this.schema = schema;
75
+ }
76
+ };
77
+ var FnReturn = class {
78
+ constructor(schema) {
79
+ this.schema = schema;
80
+ }
81
+ };
82
+ var Declaration = class {
83
+ constructor(schema, identifier) {
84
+ this.schema = schema;
85
+ this.identifier = identifier;
86
+ }
87
+ };
88
+ async function getTypings(schema, options) {
89
+ options ??= {};
90
+ options.declaration ??= false;
91
+ let wrappedSchema = schema;
92
+ if ((options == null ? void 0 : options.declaration) && schema instanceof z.Schema) {
93
+ const title = "title" in schema.ui ? schema.ui.title : null;
94
+ if (!title) {
95
+ throw new Error('Only schemas with "title" Zui property can be declared.');
96
+ }
97
+ wrappedSchema = new Declaration(schema, title);
98
+ }
99
+ let dts = await sUnwrapZodRecursive(wrappedSchema, { ...options });
100
+ dts = await formatTypings(dts, { throwOnError: false });
101
+ return dts;
102
+ }
103
+ async function sUnwrapZodRecursive(schema, options) {
104
+ return sUnwrapZod(schema, options);
105
+ }
106
+ async function sUnwrapZod(schema, options) {
107
+ var _a, _b;
108
+ const newOptions = {
109
+ ...options,
110
+ declaration: false,
111
+ parent: schema
112
+ };
113
+ if (schema instanceof Declaration) {
114
+ const description = getMultilineComment(schema.schema.description);
115
+ const withoutDesc = schema.schema.describe("");
116
+ const typings = await sUnwrapZodRecursive(withoutDesc, { ...newOptions, declaration: true });
117
+ const isLargeDeclaration = typings.split("\n").length >= LARGE_DECLARATION_LINES;
118
+ const closingTag = isLargeDeclaration ? `// end of ${schema.identifier}` : "";
119
+ if (schema.schema instanceof z.ZodFunction) {
120
+ return stripSpaces(`${description}
121
+ declare function ${schema.identifier}${typings};${closingTag}`);
122
+ }
123
+ return stripSpaces(`${description}
124
+ declare const ${schema.identifier}: ${typings};${closingTag}`);
125
+ }
126
+ if (schema instanceof KeyValue) {
127
+ if (schema.value instanceof z.ZodOptional) {
128
+ let innerType = schema.value._def.innerType;
129
+ if (innerType instanceof z.Schema && !innerType.description && schema.value.description) {
130
+ innerType = innerType == null ? void 0 : innerType.describe(schema.value.description);
131
+ }
132
+ const optionalToken = schema.key.endsWith("?") ? "" : "?";
133
+ return sUnwrapZodRecursive(new KeyValue(schema.key + optionalToken, innerType), newOptions);
134
+ }
135
+ const description = getMultilineComment(schema.value._def.description || schema.value.description);
136
+ const delimiter = (description == null ? void 0 : description.trim().length) > 0 ? "\n" : "";
137
+ const withoutDesc = schema.value.describe("");
138
+ return `${delimiter}${description}${delimiter}${schema.key}: ${await sUnwrapZodRecursive(withoutDesc, newOptions)}${delimiter}`;
139
+ }
140
+ if (schema instanceof FnParameters) {
141
+ if (schema.schema instanceof z.ZodTuple) {
142
+ let args = "";
143
+ for (let i = 0; i < schema.schema.items.length; i++) {
144
+ const argName = ((_b = (_a = schema.schema.items[i]) == null ? void 0 : _a.ui) == null ? void 0 : _b.title) ?? `arg${i}`;
145
+ const item = schema.schema.items[i];
146
+ args += `${await sUnwrapZodRecursive(new KeyValue(toPropertyKey(argName), item), newOptions)}, `;
147
+ }
148
+ return args;
149
+ }
150
+ const isLiteral = schema.schema.naked() instanceof z.ZodLiteral;
151
+ const typings = (await sUnwrapZodRecursive(schema.schema, newOptions)).trim();
152
+ const startsWithPairs = typings.startsWith("{") && typings.endsWith("}") || typings.startsWith("[") && typings.endsWith("]") || typings.startsWith("(") && typings.endsWith(")") || typings.startsWith("Array<") && typings.endsWith(">") || typings.startsWith("Record<") && typings.endsWith(">") || isArrayOfPrimitives(typings);
153
+ if (startsWithPairs || isLiteral) {
154
+ return `args: ${typings}`;
155
+ } else {
156
+ return typings;
157
+ }
158
+ }
159
+ if (schema instanceof FnReturn) {
160
+ if (schema.schema instanceof z.ZodOptional) {
161
+ return `${await sUnwrapZodRecursive(schema.schema.unwrap(), newOptions)} | undefined`;
162
+ }
163
+ return sUnwrapZodRecursive(schema.schema, newOptions);
164
+ }
165
+ if (schema instanceof z.ZodDefault) {
166
+ return sUnwrapZodRecursive(schema._def.innerType, options);
167
+ }
168
+ if (schema instanceof z.ZodVoid) {
169
+ return "void";
170
+ }
171
+ if (schema instanceof z.ZodUnknown) {
172
+ return "unknown";
173
+ }
174
+ if (schema instanceof z.ZodAny) {
175
+ return "any";
176
+ }
177
+ if (schema instanceof z.ZodPromise) {
178
+ return `Promise<${await sUnwrapZodRecursive(schema.unwrap(), newOptions)}>`;
179
+ }
180
+ if (schema instanceof z.ZodFunction) {
181
+ const description = getMultilineComment(schema._def.description);
182
+ const input = await sUnwrapZodRecursive(new FnParameters(schema._def.args), newOptions);
183
+ const output = await sUnwrapZodRecursive(new FnReturn(schema._def.returns), newOptions);
184
+ if (options == null ? void 0 : options.declaration) {
185
+ return `${description}
186
+ (${input}): ${output}`;
187
+ }
188
+ return `${description}
189
+ (${input}) => ${output}`;
190
+ }
191
+ if (schema instanceof z.ZodArray) {
192
+ const item = await sUnwrapZodRecursive(schema._def.type, newOptions);
193
+ if (isPrimitive(item)) {
194
+ return `${item}[]`;
195
+ }
196
+ return `Array<${item}>`;
197
+ }
198
+ if (schema instanceof z.ZodEnum) {
199
+ const values = schema._def.values.map(escapeString);
200
+ return values.join(" | ");
201
+ }
202
+ if (schema instanceof z.ZodTuple) {
203
+ if (schema.items.length === 0) {
204
+ return "[]";
205
+ }
206
+ const items = await Promise.all(schema.items.map((i) => sUnwrapZodRecursive(i, newOptions)));
207
+ return `[${items.join(", ")}]`;
208
+ }
209
+ if (schema instanceof z.ZodNullable) {
210
+ return `${await sUnwrapZodRecursive(schema.unwrap(), options)} | null`;
211
+ }
212
+ if (schema instanceof z.ZodOptional) {
213
+ if ((options == null ? void 0 : options.declaration) || (options == null ? void 0 : options.parent) instanceof z.ZodRecord) {
214
+ return `${await sUnwrapZodRecursive(schema._def.innerType, newOptions)} | undefined`;
215
+ }
216
+ const optionalToken = options.parent instanceof KeyValue ? "| undefined" : "";
217
+ const val = `${await sUnwrapZodRecursive(schema._def.innerType, newOptions)}${optionalToken}`;
218
+ return val;
219
+ }
220
+ if (schema instanceof z.ZodObject) {
221
+ const props = await Promise.all(
222
+ Object.entries(schema.shape).map(async ([key, value]) => {
223
+ if (value instanceof z.Schema) {
224
+ return sUnwrapZodRecursive(new KeyValue(toPropertyKey(key), value), newOptions);
225
+ }
226
+ return `${key}: unknown`;
227
+ })
228
+ );
229
+ return `{ ${props.join("; ")} }`;
230
+ }
231
+ if (schema instanceof z.ZodString) {
232
+ const description = getMultilineComment(schema._def.description);
233
+ return `${description} string`.trim();
234
+ }
235
+ if (schema instanceof z.ZodUnion) {
236
+ const description = getMultilineComment(schema._def.description);
237
+ const options2 = await Promise.all(
238
+ schema.options.map(async (option) => {
239
+ return sUnwrapZodRecursive(option, newOptions);
240
+ })
241
+ );
242
+ return `${description}
243
+ ${options2.join(" | ")}`;
244
+ }
245
+ if (schema instanceof z.ZodLiteral) {
246
+ const description = getMultilineComment(schema._def.description);
247
+ return `${description}
248
+ ${typeof schema.value === "string" ? escapeString(schema.value) : schema.value}`.trim();
249
+ }
250
+ if (schema instanceof z.ZodNumber) {
251
+ const description = getMultilineComment(schema._def.description);
252
+ return `${description} number`.trim();
253
+ }
254
+ if (schema instanceof z.ZodBoolean) {
255
+ const description = getMultilineComment(schema._def.description);
256
+ return `${description} boolean`.trim();
257
+ }
258
+ if (schema instanceof z.ZodCatch) {
259
+ return sUnwrapZodRecursive(schema.removeCatch(), newOptions);
260
+ }
261
+ if (schema instanceof z.ZodLazy) {
262
+ return sUnwrapZodRecursive(schema._def.getter(), newOptions);
263
+ }
264
+ if (schema instanceof z.ZodRecord) {
265
+ const description = getMultilineComment(schema._def.description);
266
+ const keyType = await sUnwrapZodRecursive(schema._def.keyType, newOptions);
267
+ const valueType = await sUnwrapZodRecursive(schema._def.valueType, newOptions);
268
+ return `${description} { [key: (${keyType})]: (${valueType}) }`;
269
+ }
270
+ try {
271
+ let typings = schema == null ? void 0 : schema.toTypescriptType();
272
+ typings ??= "unknown";
273
+ return stripSpaces(typings);
274
+ } catch (error) {
275
+ console.error("Error in sUnwrapZod", { error, schema, parent: options == null ? void 0 : options.parent });
276
+ return "unknown";
277
+ }
278
+ }
279
+
280
+ export {
281
+ formatTypings,
282
+ getTypings
283
+ };
@@ -0,0 +1,28 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/stack-traces.ts
2
+ var isInternalLine = (line) => {
3
+ return line.includes("/llmz/") || line.includes("\\llmz\\src\\") || line.includes("node_modules");
4
+ };
5
+ function cleanStackTrace(stack, cleanInternal = true) {
6
+ const lines = stack.split("\n");
7
+ for (let i = 0; i < lines.length; i++) {
8
+ const line = lines[i];
9
+ let llmzIndex = line.indexOf("/llmz/");
10
+ if (llmzIndex === -1) {
11
+ llmzIndex = line.indexOf("\\llmz\\");
12
+ }
13
+ if (llmzIndex === -1) {
14
+ continue;
15
+ }
16
+ let lastSpaceIndex = line.lastIndexOf(" ", llmzIndex);
17
+ if (lastSpaceIndex === -1) {
18
+ lastSpaceIndex = 0;
19
+ }
20
+ const maybeParen = line[lastSpaceIndex + 1] === "(" ? "(" : "";
21
+ lines[i] = line.slice(0, lastSpaceIndex + 1) + maybeParen + line.slice(llmzIndex);
22
+ }
23
+ return lines.filter((x) => !cleanInternal || !isInternalLine(x)).join("\n");
24
+ }
25
+
26
+
27
+
28
+ exports.cleanStackTrace = cleanStackTrace;
@@ -0,0 +1,212 @@
1
+ import {
2
+ getTypings
3
+ } from "./chunk-IH2WQFO5.js";
4
+ import {
5
+ convertObjectToZuiLiterals,
6
+ isJsonSchema,
7
+ isValidIdentifier,
8
+ isZuiSchema
9
+ } from "./chunk-4MNIJGK6.js";
10
+ import {
11
+ isEmpty_default,
12
+ uniq_default
13
+ } from "./chunk-7WRN4E42.js";
14
+
15
+ // src/tool.ts
16
+ import { z, transforms, ZodObject, ZodType } from "@bpinternal/zui";
17
+ var Tool = class _Tool {
18
+ _staticInputValues;
19
+ name;
20
+ aliases = [];
21
+ description;
22
+ metadata;
23
+ input;
24
+ output;
25
+ retry;
26
+ MAX_RETRIES = 1e3;
27
+ setStaticInputValues(values) {
28
+ if (values === null || values === void 0) {
29
+ this._staticInputValues = void 0;
30
+ return this;
31
+ }
32
+ const input = this.input ? transforms.fromJSONSchemaLegacy(this.input) : z.any();
33
+ if (input instanceof z.ZodObject && typeof values !== "object") {
34
+ throw new Error(
35
+ `Invalid static input values for tool ${this.name}. Expected an object, but got type "${typeof values}"`
36
+ );
37
+ }
38
+ if (input instanceof z.ZodArray && !Array.isArray(values)) {
39
+ throw new Error(
40
+ `Invalid static input values for tool ${this.name}. Expected an array, but got type "${typeof values}"`
41
+ );
42
+ }
43
+ this._staticInputValues = values;
44
+ return this;
45
+ }
46
+ get zInput() {
47
+ let input = this.input ? transforms.fromJSONSchemaLegacy(this.input) : z.any();
48
+ if (!isEmpty_default(this._staticInputValues)) {
49
+ const inputExtensions = convertObjectToZuiLiterals(this._staticInputValues);
50
+ if (input instanceof z.ZodObject) {
51
+ input = input.extend(inputExtensions);
52
+ } else if (input instanceof z.ZodArray) {
53
+ input = z.array(input.element.extend(inputExtensions));
54
+ } else {
55
+ input = inputExtensions;
56
+ }
57
+ }
58
+ return input;
59
+ }
60
+ get zOutput() {
61
+ return this.output ? transforms.fromJSONSchemaLegacy(this.output) : z.void();
62
+ }
63
+ rename(name) {
64
+ const before = this.name;
65
+ if (!isValidIdentifier(name)) {
66
+ throw new Error(
67
+ `Invalid name for tool ${name}. A tool name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
68
+ );
69
+ }
70
+ this.name = name;
71
+ this.aliases = uniq_default([name, ...this.aliases.map((alias) => alias === before ? name : alias)]);
72
+ return this;
73
+ }
74
+ clone(props = {}) {
75
+ var _a, _b;
76
+ try {
77
+ const zInput = this.input ? transforms.fromJSONSchemaLegacy(this.input) : void 0;
78
+ const zOutput = this.output ? transforms.fromJSONSchemaLegacy(this.output) : void 0;
79
+ return new _Tool({
80
+ name: props.name ?? this.name,
81
+ aliases: props.aliases ?? [...this.aliases],
82
+ description: props.description ?? this.description,
83
+ metadata: JSON.parse(JSON.stringify(props.metadata ?? this.metadata)),
84
+ input: typeof props.input === "function" ? (_a = props.input) == null ? void 0 : _a.call(props, zInput) : props.input instanceof ZodType ? props.input : zInput,
85
+ output: typeof props.output === "function" ? (_b = props.output) == null ? void 0 : _b.call(props, zOutput) : props.output instanceof ZodType ? props.output : zOutput,
86
+ handler: props.handler ?? this._handler,
87
+ retry: props.retry ?? this.retry
88
+ }).setStaticInputValues(props.staticInputValues ?? this._staticInputValues);
89
+ } catch (e) {
90
+ throw new Error(`Failed to clone tool "${this.name}": ${e}`);
91
+ }
92
+ }
93
+ _handler;
94
+ constructor(props) {
95
+ if (!isValidIdentifier(props.name)) {
96
+ throw new Error(
97
+ `Invalid name for tool ${props.name}. A tool name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
98
+ );
99
+ }
100
+ if (props.description !== void 0 && typeof props.description !== "string") {
101
+ throw new Error(
102
+ `Invalid description for tool ${props.name}. Expected a string, but got type "${typeof props.description}"`
103
+ );
104
+ }
105
+ if (props.metadata !== void 0 && typeof props.metadata !== "object") {
106
+ throw new Error(
107
+ `Invalid metadata for tool ${props.name}. Expected an object, but got type "${typeof props.metadata}"`
108
+ );
109
+ }
110
+ if (typeof props.handler !== "function") {
111
+ throw new Error(
112
+ `Invalid handler for tool ${props.name}. Expected a function, but got type "${typeof props.handler}"`
113
+ );
114
+ }
115
+ if (props.aliases !== void 0 && !Array.isArray(props.aliases)) {
116
+ throw new Error(
117
+ `Invalid aliases for tool ${props.name}. Expected an array, but got type "${typeof props.aliases}"`
118
+ );
119
+ }
120
+ if (props.aliases && props.aliases.some((alias) => !isValidIdentifier(alias))) {
121
+ throw new Error(`Invalid aliases for tool ${props.name}. Expected an array of valid identifiers.`);
122
+ }
123
+ if (typeof props.input !== "undefined") {
124
+ if (isZuiSchema(props.input)) {
125
+ this.input = transforms.toJSONSchemaLegacy(props.input);
126
+ } else if (isJsonSchema(props.input)) {
127
+ this.input = props.input;
128
+ } else {
129
+ throw new Error(
130
+ `Invalid input schema for tool ${props.name}. Expected a ZodType or JSONSchema, but got type "${typeof props.input}"`
131
+ );
132
+ }
133
+ }
134
+ if (typeof props.output !== "undefined") {
135
+ if (isZuiSchema(props.output)) {
136
+ this.output = transforms.toJSONSchemaLegacy(props.output);
137
+ } else if (isJsonSchema(props.output)) {
138
+ this.output = props.output;
139
+ } else {
140
+ throw new Error(
141
+ `Invalid output schema for tool ${props.name}. Expected a ZodType or JSONSchema, but got type "${typeof props.output}"`
142
+ );
143
+ }
144
+ }
145
+ this.name = props.name;
146
+ this.aliases = uniq_default([props.name, ...props.aliases ?? []]);
147
+ this.description = props.description;
148
+ this.metadata = props.metadata ?? {};
149
+ this._handler = props.handler;
150
+ this.setStaticInputValues(props.staticInputValues);
151
+ this.retry = props.retry;
152
+ }
153
+ async execute(input, ctx) {
154
+ var _a;
155
+ const pInput = this.zInput.safeParse(input);
156
+ if (!pInput.success) {
157
+ throw new Error(`Tool "${this.name}" received invalid input: ${pInput.error.message}`);
158
+ }
159
+ let attempt = 0;
160
+ while (attempt < this.MAX_RETRIES) {
161
+ try {
162
+ const result = await this._handler(pInput.data, ctx);
163
+ const pOutput = this.zOutput.safeParse(result);
164
+ return pOutput.success ? pOutput.data : result;
165
+ } catch (err) {
166
+ const shouldRetry = await ((_a = this.retry) == null ? void 0 : _a.call(this, {
167
+ input: pInput.data,
168
+ attempt: ++attempt,
169
+ error: err
170
+ }));
171
+ if (!shouldRetry) {
172
+ throw err;
173
+ }
174
+ }
175
+ }
176
+ throw new Error(
177
+ `Tool "${this.name}" failed after ${this.MAX_RETRIES} attempts. Last error: ${JSON.stringify(input)}`
178
+ );
179
+ }
180
+ async getTypings() {
181
+ let input = this.input ? transforms.fromJSONSchemaLegacy(this.input) : void 0;
182
+ const output = this.output ? transforms.fromJSONSchemaLegacy(this.output) : z.void();
183
+ if ((input == null ? void 0 : input.naked()) instanceof ZodObject && typeof this._staticInputValues === "object" && !isEmpty_default(this._staticInputValues)) {
184
+ const inputExtensions = convertObjectToZuiLiterals(this._staticInputValues);
185
+ input = input.extend(inputExtensions);
186
+ } else if (this._staticInputValues !== void 0) {
187
+ input = convertObjectToZuiLiterals(this._staticInputValues);
188
+ }
189
+ const fnType = z.function(input, z.promise(output)).title(this.name).describe(this.description ?? "");
190
+ return getTypings(fnType, {
191
+ declaration: true
192
+ });
193
+ }
194
+ static withUniqueNames = (tools) => {
195
+ const names = /* @__PURE__ */ new Set();
196
+ return tools.map((tool) => {
197
+ if (tools.filter((t) => t.name === tool.name).length === 1) {
198
+ return tool;
199
+ }
200
+ let counter = 1;
201
+ let toolName = tool.name + counter;
202
+ while (names.has(toolName)) {
203
+ toolName = `${tool.name}${++counter}`;
204
+ }
205
+ return tool.rename(toolName);
206
+ });
207
+ };
208
+ };
209
+
210
+ export {
211
+ Tool
212
+ };
@@ -0,0 +1,161 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;
2
+
3
+ var _chunkIKSIOIIPcjs = require('./chunk-IKSIOIIP.cjs');
4
+
5
+ // src/errors.ts
6
+ var errorClasses = {};
7
+ function registerErrorClass(name, errorClass) {
8
+ errorClasses[name] = errorClass;
9
+ }
10
+ var tryParseMessage = (str) => {
11
+ try {
12
+ return JSON.parse(str);
13
+ } catch (e) {
14
+ return str;
15
+ }
16
+ };
17
+ var Signals;
18
+ ((Signals2) => {
19
+ function isWrappedError(error) {
20
+ var _a, _b;
21
+ const isAlreadyWrapped = error.name === "Error" && ((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.startsWith("{")) && ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.endsWith("}"));
22
+ return isAlreadyWrapped;
23
+ }
24
+ Signals2.isWrappedError = isWrappedError;
25
+ function serializeError(error) {
26
+ if (isWrappedError(error)) {
27
+ const msg = tryParseMessage(error.message);
28
+ return JSON.stringify({
29
+ ...typeof msg === "object" ? msg : { message: msg },
30
+ properties: { ...error }
31
+ });
32
+ }
33
+ return JSON.stringify({
34
+ name: error.constructor.name,
35
+ message: error.message,
36
+ stack: _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce(error.stack, () => ( ""))),
37
+ properties: { ...error }
38
+ });
39
+ }
40
+ Signals2.serializeError = serializeError;
41
+ function maybeDeserializeError(error) {
42
+ const errorIsAlreadyDeserialized = error instanceof Error && error.name in errorClasses;
43
+ if (errorIsAlreadyDeserialized) {
44
+ return error;
45
+ }
46
+ const serializedError = error instanceof Error ? error.message : typeof error === "string" ? error : _nullishCoalesce((error == null ? void 0 : error.toString()), () => ( ""));
47
+ try {
48
+ const parsed = JSON.parse(serializedError);
49
+ if (parsed && parsed.name && parsed.message) {
50
+ const { name, message, properties = {} } = parsed;
51
+ const ErrorClass = errorClasses[name] || Error;
52
+ const errorInstance = new ErrorClass(message);
53
+ errorInstance.message = message;
54
+ errorInstance.name = name;
55
+ errorInstance.stack = _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce((error == null ? void 0 : error.stack), () => ( "")));
56
+ Object.assign(errorInstance, properties);
57
+ if (isWrappedError(errorInstance)) {
58
+ return maybeDeserializeError(errorInstance);
59
+ }
60
+ return errorInstance;
61
+ }
62
+ } catch (e2) {
63
+ }
64
+ return error;
65
+ }
66
+ Signals2.maybeDeserializeError = maybeDeserializeError;
67
+ })(Signals || (Signals = exports.Signals = {}));
68
+ var VMSignal = (_class = class extends Error {
69
+ constructor(message) {
70
+ super(message);_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
71
+ this.message = message;
72
+ this.message = Signals.serializeError(this);
73
+ }
74
+ /**
75
+ * The code that was executed by the VM up to the point of the signal
76
+ */
77
+ __init() {this.truncatedCode = ""}
78
+ /** The current tool call, if any */
79
+
80
+ /**
81
+ * Contains all the declared and executed variables during the VM execution
82
+ * See file plugins/variable-extraction.ts for more details
83
+ */
84
+ __init2() {this.variables = {}}
85
+ }, _class);
86
+ var SnapshotSignal = class extends VMSignal {
87
+ constructor(message) {
88
+ super(message);
89
+ this.message = Signals.serializeError(this);
90
+ }
91
+ };
92
+ var VMLoopSignal = class extends VMSignal {
93
+ constructor(message) {
94
+ super(message);
95
+ this.message = Signals.serializeError(this);
96
+ }
97
+ };
98
+ var ThinkSignal = class extends VMLoopSignal {
99
+ constructor(reason, context) {
100
+ super("Think signal received: " + reason);
101
+ this.reason = reason;
102
+ this.context = context;
103
+ this.message = Signals.serializeError(this);
104
+ }
105
+ toString() {
106
+ return Signals.serializeError(this);
107
+ }
108
+ };
109
+ var CodeExecutionError = class extends Error {
110
+ constructor(message, code, stacktrace) {
111
+ super(message);
112
+ this.code = code;
113
+ this.stacktrace = stacktrace;
114
+ this.message = Signals.serializeError(this);
115
+ }
116
+ };
117
+ var InvalidCodeError = class extends Error {
118
+ constructor(message, code) {
119
+ super(message);
120
+ this.code = code;
121
+ this.message = Signals.serializeError(this);
122
+ }
123
+ };
124
+ var LoopExceededError = class extends Error {
125
+ constructor() {
126
+ super("Loop exceeded error");
127
+ this.message = Signals.serializeError(this);
128
+ }
129
+ };
130
+ var CodeFormattingError = class extends Error {
131
+ constructor(message, code) {
132
+ super(message, {
133
+ cause: "Code formatting error"
134
+ });
135
+ this.code = code;
136
+ }
137
+ };
138
+ var AssignmentError = class extends Error {
139
+ constructor(message) {
140
+ super(message);
141
+ this.message = Signals.serializeError(this);
142
+ }
143
+ };
144
+ registerErrorClass("VMSignal", VMSignal);
145
+ registerErrorClass("SnapshotSignal", SnapshotSignal);
146
+ registerErrorClass("VMLoopSignal", VMLoopSignal);
147
+ registerErrorClass("ThinkSignal", ThinkSignal);
148
+ registerErrorClass("CodeExecutionError", CodeExecutionError);
149
+ registerErrorClass("AssignmentError", AssignmentError);
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+ exports.Signals = Signals; exports.VMSignal = VMSignal; exports.SnapshotSignal = SnapshotSignal; exports.ThinkSignal = ThinkSignal; exports.CodeExecutionError = CodeExecutionError; exports.InvalidCodeError = InvalidCodeError; exports.LoopExceededError = LoopExceededError; exports.CodeFormattingError = CodeFormattingError; exports.AssignmentError = AssignmentError;