llmz 0.6.0 → 0.6.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 (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-CFhWe_W6.js +48 -0
  3. package/dist/_baseForOwn-buOZDFbK.cjs +103 -0
  4. package/dist/_baseIteratee-CF4qP2a8.cjs +2377 -0
  5. package/dist/_baseIteratee-P_firB7b.js +2138 -0
  6. package/dist/_getPrototype-CG7Dxrrz.js +6 -0
  7. package/dist/_getPrototype-DQDlNVVM.cjs +10 -0
  8. package/dist/_overArg-C5Hy7oCi.cjs +196 -0
  9. package/dist/_overArg-CRYbj1NH.js +155 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-BwixNVH8.cjs +73 -0
  12. package/dist/component-DGG7d_Mz.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-BPmEoWKu.cjs +2618 -0
  15. package/dist/custom-client-NUoxrFQh.js +2547 -0
  16. package/dist/dual-modes-D_p-jedw.js +2750 -0
  17. package/dist/dual-modes-wAOAlaBS.cjs +2840 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-BEaq3jkV.cjs +1003 -0
  21. package/dist/execute-DYvFRs54.js +1001 -0
  22. package/dist/exit-BGi0Kk0y.cjs +428 -0
  23. package/dist/exit-CDdxDBRT.js +417 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17534 -16875
  28. package/dist/isEmpty-BhJRCqIF.js +52 -0
  29. package/dist/isEmpty-LY533Wmh.cjs +57 -0
  30. package/dist/isPlainObject-CSxXVKCk.cjs +56 -0
  31. package/dist/isPlainObject-D39AzPO2.js +51 -0
  32. package/dist/jsx-BWvT6ukg.cjs +75 -0
  33. package/dist/jsx-CIgdGGVs.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-CAo-BQHs.js +643 -0
  49. package/dist/tool-DdPZb0JW.cjs +654 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-B6aaJaN1.cjs +276 -0
  52. package/dist/truncator-DZqEqnpD.js +253 -0
  53. package/dist/typings-BwAz_TM9.cjs +784 -0
  54. package/dist/typings-CrBa7Tyy.js +743 -0
  55. package/dist/uniq-BYQ7GWwb.js +183 -0
  56. package/dist/uniq-G872RWmE.cjs +200 -0
  57. package/dist/utils-UBeAFeEI.js +950 -0
  58. package/dist/utils-ZpJm00ed.cjs +1075 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BjkJqSQH.cjs +3438 -0
  61. package/dist/vm-C5vf1LH3.js +3436 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -1,1530 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } var _class; var _class2; var _class3;
2
-
3
-
4
-
5
- var _chunkKTDBAJBBcjs = require('./chunk-KTDBAJBB.cjs');
6
-
7
-
8
- var _chunkPZE6PIPGcjs = require('./chunk-PZE6PIPG.cjs');
9
-
10
-
11
- var _chunkPK72FAKDcjs = require('./chunk-PK72FAKD.cjs');
12
-
13
-
14
- var _chunkDDSJTR6Qcjs = require('./chunk-DDSJTR6Q.cjs');
15
-
16
-
17
- var _chunkI56MPOVGcjs = require('./chunk-I56MPOVG.cjs');
18
-
19
-
20
-
21
- var _chunkHEAQAEFZcjs = require('./chunk-HEAQAEFZ.cjs');
22
-
23
-
24
- var _chunkGOWPACSKcjs = require('./chunk-GOWPACSK.cjs');
25
-
26
-
27
-
28
-
29
- var _chunkHC2QZTVTcjs = require('./chunk-HC2QZTVT.cjs');
30
-
31
- // src/exit-parser.ts
32
- function isValuePrimitive(value) {
33
- return value === null || value === void 0 || typeof value !== "object" || Array.isArray(value);
34
- }
35
- function generatePossibleWraps(value, shape, discriminator) {
36
- const possibleWraps = [];
37
- const commonNames = ["result", "value", "data", "message", "error", "output", "response"];
38
- if (shape && typeof shape === "object") {
39
- for (const key of Object.keys(shape)) {
40
- if (key !== discriminator) {
41
- const wrap = discriminator ? { [discriminator]: shape[discriminator]._def.value, [key]: value } : { [key]: value };
42
- possibleWraps.push(wrap);
43
- }
44
- }
45
- }
46
- for (const name of commonNames) {
47
- const hasName = possibleWraps.some((w) => Object.keys(w).includes(name));
48
- if (!hasName) {
49
- const wrap = discriminator && (shape == null ? void 0 : shape[discriminator]) ? { [discriminator]: shape[discriminator]._def.value, [name]: value } : { [name]: value };
50
- possibleWraps.push(wrap);
51
- }
52
- }
53
- return possibleWraps;
54
- }
55
- function tryObjectWrapping(schema, candidateValue) {
56
- const possibleWraps = generatePossibleWraps(candidateValue, schema.shape);
57
- for (const wrap of possibleWraps) {
58
- const testParse = schema.safeParse(wrap);
59
- if (testParse.success) {
60
- return { success: true, valueToValidate: wrap, parsed: testParse };
61
- }
62
- }
63
- return { success: false, valueToValidate: candidateValue, parsed: { success: false } };
64
- }
65
- function detectDiscriminator(options) {
66
- if (options.length === 0 || options[0]._def.typeName !== "ZodObject") {
67
- return void 0;
68
- }
69
- const firstShape = options[0].shape;
70
- for (const key in firstShape) {
71
- const firstFieldType = firstShape[key]._def.typeName;
72
- if (firstFieldType === "ZodLiteral") {
73
- const allHaveLiteral = options.every((opt) => {
74
- var _a;
75
- return ((_a = opt.shape[key]) == null ? void 0 : _a._def.typeName) === "ZodLiteral";
76
- });
77
- if (allHaveLiteral) {
78
- return key;
79
- }
80
- }
81
- }
82
- return void 0;
83
- }
84
- function tryAddDiscriminator(schema, options, discriminator, valueToValidate) {
85
- const matchingOptions = [];
86
- for (const option of options) {
87
- if (option._def.typeName === "ZodObject" && option.shape[discriminator]) {
88
- const discriminatorValue = option.shape[discriminator]._def.value;
89
- const wrappedValue = { [discriminator]: discriminatorValue, ...valueToValidate };
90
- const testParse = schema.safeParse(wrappedValue);
91
- if (testParse.success) {
92
- matchingOptions.push({ wrappedValue });
93
- }
94
- }
95
- }
96
- if (matchingOptions.length === 1) {
97
- const wrapped = matchingOptions[0].wrappedValue;
98
- return { success: true, valueToValidate: wrapped, parsed: schema.safeParse(wrapped) };
99
- }
100
- return { success: false, valueToValidate, parsed: { success: false } };
101
- }
102
- function tryUnionPrimitiveWrapping(schema, options, discriminator, valueToValidate) {
103
- const allSuccessfulWraps = [];
104
- for (const option of options) {
105
- if (option._def.typeName === "ZodObject" && option.shape[discriminator]) {
106
- const discriminatorValue = option.shape[discriminator]._def.value;
107
- const possibleWraps = generatePossibleWraps(valueToValidate, option.shape, discriminator);
108
- for (const wrap of possibleWraps) {
109
- const finalWrap = { [discriminator]: discriminatorValue, ...wrap };
110
- const testParse = schema.safeParse(finalWrap);
111
- if (testParse.success) {
112
- allSuccessfulWraps.push({ wrap: finalWrap });
113
- break;
114
- }
115
- }
116
- }
117
- }
118
- if (allSuccessfulWraps.length === 1) {
119
- const wrapped = allSuccessfulWraps[0].wrap;
120
- return { success: true, valueToValidate: wrapped, parsed: schema.safeParse(wrapped) };
121
- }
122
- return { success: false, valueToValidate, parsed: { success: false } };
123
- }
124
- function tryUnionWrapping(schema, valueToValidate) {
125
- const options = schema._def.options;
126
- let discriminator = schema._def.discriminator;
127
- if (!discriminator) {
128
- discriminator = detectDiscriminator(options);
129
- }
130
- if (!discriminator) {
131
- return { success: false, valueToValidate, parsed: { success: false } };
132
- }
133
- const isValueObject = valueToValidate !== null && typeof valueToValidate === "object" && !Array.isArray(valueToValidate);
134
- const isPrimitive = isValuePrimitive(valueToValidate);
135
- if (isValueObject && !(discriminator in valueToValidate)) {
136
- const result = tryAddDiscriminator(schema, options, discriminator, valueToValidate);
137
- if (result.success) {
138
- return result;
139
- }
140
- }
141
- if (isPrimitive) {
142
- return tryUnionPrimitiveWrapping(schema, options, discriminator, valueToValidate);
143
- }
144
- return { success: false, valueToValidate, parsed: { success: false } };
145
- }
146
- function trySmartWrapping(schema, schemaType, valueToValidate, alternativeValue) {
147
- const valuesToTry = [valueToValidate];
148
- if (alternativeValue !== void 0 && alternativeValue !== valueToValidate) {
149
- valuesToTry.push(alternativeValue);
150
- }
151
- for (const candidateValue of valuesToTry) {
152
- const isPrimitive = isValuePrimitive(candidateValue);
153
- if (schemaType === "ZodObject" && isPrimitive) {
154
- const result = tryObjectWrapping(schema, candidateValue);
155
- if (result.success) {
156
- return result;
157
- }
158
- }
159
- }
160
- if (alternativeValue !== void 0 && alternativeValue !== valueToValidate) {
161
- valueToValidate = alternativeValue;
162
- }
163
- if (schemaType === "ZodDiscriminatedUnion" || schemaType === "ZodUnion") {
164
- const result = tryUnionWrapping(schema, valueToValidate);
165
- if (result.success) {
166
- return result;
167
- }
168
- }
169
- return { valueToValidate, parsed: { success: false } };
170
- }
171
- function parseExit(returnValue, exits) {
172
- if (!returnValue) {
173
- return {
174
- success: false,
175
- error: "No return value provided",
176
- returnValue
177
- };
178
- }
179
- const returnAction = returnValue.action;
180
- if (!returnAction) {
181
- return {
182
- success: false,
183
- error: `Code did not return an action. Valid actions are: ${exits.map((x) => x.name).join(", ")}`,
184
- returnValue
185
- };
186
- }
187
- const returnExit = _nullishCoalesce(exits.find((x) => x.name.toLowerCase() === returnAction.toLowerCase()), () => ( exits.find((x) => x.aliases.some((a) => a.toLowerCase() === returnAction.toLowerCase()))));
188
- if (!returnExit) {
189
- return {
190
- success: false,
191
- error: `Exit "${returnAction}" not found. Valid actions are: ${exits.map((x) => x.name).join(", ")}`,
192
- returnValue
193
- };
194
- }
195
- if (!returnExit.zSchema) {
196
- const otherProps = _chunkHC2QZTVTcjs.omit_default.call(void 0, returnValue, "action");
197
- const value = Object.keys(otherProps).length === 1 ? Object.values(otherProps)[0] : otherProps;
198
- return {
199
- success: true,
200
- exit: returnExit,
201
- value
202
- };
203
- }
204
- let valueToValidate = returnValue.value;
205
- let alternativeValue = void 0;
206
- if (valueToValidate === void 0) {
207
- const otherProps = _chunkHC2QZTVTcjs.omit_default.call(void 0, returnValue, "action");
208
- if (Object.keys(otherProps).length > 0) {
209
- valueToValidate = otherProps;
210
- if (Object.keys(otherProps).length === 1) {
211
- alternativeValue = Object.values(otherProps)[0];
212
- }
213
- }
214
- }
215
- const schema = returnExit.zSchema;
216
- const schemaType = schema._def.typeName;
217
- let parsed = schema.safeParse(valueToValidate);
218
- if (!parsed.success && alternativeValue !== void 0 && alternativeValue !== valueToValidate) {
219
- const altParsed = schema.safeParse(alternativeValue);
220
- if (altParsed.success) {
221
- parsed = altParsed;
222
- valueToValidate = alternativeValue;
223
- }
224
- }
225
- if (!parsed.success) {
226
- const result = trySmartWrapping(schema, schemaType, valueToValidate, alternativeValue);
227
- valueToValidate = result.valueToValidate;
228
- parsed = result.parsed;
229
- }
230
- if (!parsed.success) {
231
- const getValueTypeDescription = (val) => {
232
- if (val === null)
233
- return "null";
234
- if (val === void 0)
235
- return "undefined";
236
- if (Array.isArray(val))
237
- return "array";
238
- return typeof val;
239
- };
240
- const generatedType = getValueTypeDescription(valueToValidate);
241
- let generatedStatement = `return { action: '${returnAction}'`;
242
- if (returnValue.value !== void 0) {
243
- generatedStatement += `, value: ${generatedType}`;
244
- } else {
245
- const otherProps = _chunkHC2QZTVTcjs.omit_default.call(void 0, returnValue, "action");
246
- const propKeys = Object.keys(otherProps);
247
- if (propKeys.length === 1) {
248
- generatedStatement += `, ${propKeys[0]}: ${generatedType}`;
249
- } else if (propKeys.length > 1) {
250
- generatedStatement += `, ${propKeys.join(", ")}`;
251
- }
252
- }
253
- generatedStatement += " }";
254
- const expectedStatements = [];
255
- for (const exit of exits) {
256
- let statement = `return { action: '${exit.name}'`;
257
- if (exit.zSchema) {
258
- const schema2 = exit.zSchema;
259
- const typeName = schema2._def.typeName;
260
- if (typeName === "ZodObject") {
261
- const shape = schema2.shape;
262
- const properties = Object.keys(shape).map((key) => {
263
- var _a;
264
- const field = shape[key];
265
- const fieldType = field._def.typeName || "unknown";
266
- const isOptional = ((_a = field.isOptional) == null ? void 0 : _a.call(field)) || false;
267
- return `${key}${isOptional ? "?" : ""}: ${fieldType.replace("Zod", "").toLowerCase()}`;
268
- });
269
- statement += `, value: { ${properties.join(", ")} }`;
270
- } else if (typeName === "ZodUnion" || typeName === "ZodDiscriminatedUnion") {
271
- const options = schema2._def.options || [];
272
- const variants = options.map((opt) => {
273
- if (opt._def.typeName === "ZodObject") {
274
- const shape = opt.shape;
275
- const properties = Object.keys(shape).map((key) => {
276
- const field = shape[key];
277
- const fieldType = field._def.typeName || "unknown";
278
- return `${key}: ${fieldType.replace("Zod", "").toLowerCase()}`;
279
- });
280
- return `{ ${properties.join(", ")} }`;
281
- }
282
- return "unknown";
283
- });
284
- statement += `, value: ${variants.join(" | ")}`;
285
- } else {
286
- const schemaTypeName = (typeName == null ? void 0 : typeName.replace("Zod", "").toLowerCase()) || "unknown";
287
- statement += `, value: ${schemaTypeName}`;
288
- }
289
- }
290
- statement += " }";
291
- expectedStatements.push(statement);
292
- }
293
- const errorMessage = [
294
- `Invalid return value for exit "${returnExit.name}"`,
295
- "",
296
- "You generated:",
297
- ` ${generatedStatement}`,
298
- "",
299
- "But expected one of:",
300
- ...expectedStatements.map((s) => ` ${s}`)
301
- ].join("\n");
302
- return {
303
- success: false,
304
- error: errorMessage,
305
- returnValue
306
- };
307
- }
308
- return {
309
- success: true,
310
- exit: returnExit,
311
- value: parsed.data
312
- };
313
- }
314
-
315
- // src/snapshots.ts
316
- var _ulid = require('ulid');
317
- var MAX_SNAPSHOT_SIZE_BYTES = 4e3;
318
- var Snapshot = class _Snapshot {
319
-
320
-
321
-
322
-
323
-
324
- #status;
325
- /**
326
- * Gets the current status of the snapshot.
327
- *
328
- * @returns The snapshot status (pending, resolved, or rejected)
329
- */
330
- get status() {
331
- return Object.freeze({ ...this.#status });
332
- }
333
- constructor(props) {
334
- this.id = props.id;
335
- this.stack = props.stack;
336
- this.reason = props.reason;
337
- this.variables = props.variables;
338
- this.toolCall = props.toolCall;
339
- this.#status = props.status;
340
- }
341
- /**
342
- * Creates a new Snapshot from a SnapshotSignal.
343
- *
344
- * This method is called internally by the LLMz execution engine when a SnapshotSignal
345
- * is thrown during execution. It captures the current execution state including
346
- * variables, stack trace, and tool context.
347
- *
348
- * @param signal The SnapshotSignal containing execution state
349
- * @returns A new Snapshot instance in pending status
350
- * @internal
351
- */
352
- static fromSignal(signal) {
353
- return new _Snapshot({
354
- id: "snapshot_" + _ulid.ulid.call(void 0, ),
355
- reason: signal.message,
356
- stack: signal.truncatedCode,
357
- variables: parseVariables(signal.variables),
358
- toolCall: signal.toolCall,
359
- status: { type: "pending" }
360
- });
361
- }
362
- /**
363
- * Serializes the snapshot to a JSON-compatible object for persistence.
364
- *
365
- * Use this method to save snapshots to databases, files, or other storage systems.
366
- * The serialized snapshot can be restored later using fromJSON().
367
- *
368
- * @returns A JSON-serializable representation of the snapshot
369
- * @example
370
- * ```typescript
371
- * const snapshot = result.snapshot
372
- * const serialized = snapshot.toJSON()
373
- * await database.save('snapshots', snapshot.id, serialized)
374
- * ```
375
- */
376
- toJSON() {
377
- return {
378
- id: this.id,
379
- reason: this.reason,
380
- stack: this.stack,
381
- variables: this.variables,
382
- toolCall: this.toolCall,
383
- status: this.#status
384
- };
385
- }
386
- /**
387
- * Restores a snapshot from its JSON representation.
388
- *
389
- * Use this method to recreate snapshots from persistent storage. The restored
390
- * snapshot will maintain its original state and can be resolved/rejected as needed.
391
- *
392
- * @param json The serialized snapshot data from toJSON()
393
- * @returns A restored Snapshot instance
394
- * @example
395
- * ```typescript
396
- * const serialized = await database.get('snapshots', snapshotId)
397
- * const snapshot = Snapshot.fromJSON(serialized)
398
- * ```
399
- */
400
- static fromJSON(json) {
401
- return new _Snapshot({
402
- id: json.id,
403
- reason: json.reason,
404
- stack: json.stack,
405
- variables: json.variables,
406
- toolCall: json.toolCall,
407
- status: json.status
408
- });
409
- }
410
- /**
411
- * Creates a deep copy of the snapshot.
412
- *
413
- * @returns A new Snapshot instance with identical data
414
- */
415
- clone() {
416
- return new _Snapshot({
417
- id: this.id,
418
- reason: this.reason,
419
- stack: this.stack,
420
- variables: this.variables,
421
- toolCall: this.toolCall,
422
- status: this.#status
423
- });
424
- }
425
- /**
426
- * Resets the snapshot status back to pending.
427
- *
428
- * This allows a previously resolved or rejected snapshot to be resolved/rejected
429
- * again with different data. Useful for retry scenarios.
430
- */
431
- reset() {
432
- this.#status = { type: "pending" };
433
- }
434
- /**
435
- * Resolves the snapshot with a successful result value.
436
- *
437
- * Call this method when the long-running operation that caused the snapshot
438
- * has completed successfully. The provided value will be returned as the
439
- * result of the original tool call when execution resumes.
440
- *
441
- * @param value The result value from the completed operation
442
- * @throws Error if the snapshot is not in pending status
443
- * @example
444
- * ```typescript
445
- * // After a background job completes
446
- * const result = await backgroundJob.getResult()
447
- * snapshot.resolve(result)
448
- *
449
- * // Continue execution
450
- * const continuation = await execute({ snapshot, ... })
451
- * ```
452
- */
453
- resolve(value) {
454
- var _a;
455
- if (this.#status.type !== "pending") {
456
- throw new Error(`Cannot resolve snapshot because it is already settled: ${this.#status.type}`);
457
- }
458
- const assignment = (_a = this.toolCall) == null ? void 0 : _a.assignment;
459
- if (assignment) {
460
- try {
461
- const fn = new Function(assignment.evalFn);
462
- const assignmentValue = fn(value);
463
- this.variables = [...this.variables, ...parseVariables(assignmentValue)];
464
- } catch (e2) {
465
- }
466
- }
467
- this.#status = { type: "resolved", value };
468
- }
469
- /**
470
- * Rejects the snapshot with an error.
471
- *
472
- * Call this method when the long-running operation that caused the snapshot
473
- * has failed or encountered an error. The provided error will be thrown
474
- * when execution resumes, allowing the generated code to handle it.
475
- *
476
- * @param error The error that occurred during the operation
477
- * @throws Error if the snapshot is not in pending status
478
- * @example
479
- * ```typescript
480
- * try {
481
- * const result = await externalAPI.call()
482
- * snapshot.resolve(result)
483
- * } catch (error) {
484
- * snapshot.reject(error)
485
- * }
486
- *
487
- * // Continue execution (will throw the error)
488
- * const continuation = await execute({ snapshot, ... })
489
- * ```
490
- */
491
- reject(error) {
492
- if (this.#status.type !== "pending") {
493
- throw new Error(`Cannot reject snapshot because it is already settled: ${this.#status.type}`);
494
- }
495
- this.#status = { type: "rejected", error };
496
- }
497
- };
498
- function parseVariables(variableMap) {
499
- return Object.entries(variableMap).map(([name, value]) => {
500
- const type = _chunkKTDBAJBBcjs.extractType.call(void 0, value);
501
- const bytes = JSON.stringify(value || "").length;
502
- const truncated = bytes > MAX_SNAPSHOT_SIZE_BYTES;
503
- return truncated ? { name, type, bytes, truncated: true, preview: _nullishCoalesce(_chunkKTDBAJBBcjs.inspect.call(void 0, value, name), () => ( "N/A")) } : { name, type, bytes, truncated: false, value };
504
- });
505
- }
506
-
507
- // src/transcript.ts
508
- var MAX_MESSAGE_LENGTH = 5e3;
509
- function getMessagePreview(message) {
510
- if (message.role === "assistant" || message.role === "user" || message.role === "summary") {
511
- return message.content;
512
- }
513
- if (message.role === "event") {
514
- return _chunkKTDBAJBBcjs.inspect.call(void 0, message.payload, message.name, { tokens: 1e3 });
515
- }
516
- return _chunkKTDBAJBBcjs.inspect.call(void 0, message, void 0, { tokens: 1e3 });
517
- }
518
- function getMessageType(message) {
519
- if (message.role === "assistant" || message.role === "user" || message.role === "summary") {
520
- return message.role;
521
- }
522
- if (message.role === "event") {
523
- return `event:${message.name}`;
524
- }
525
- return "unknown";
526
- }
527
- function isVoiceMessage(message) {
528
- var _a;
529
- if (message.role === "user" && message.modality === "voice") {
530
- return true;
531
- }
532
- if (message.role === "user" || message.role === "event") {
533
- return _nullishCoalesce(((_a = message.attachments) == null ? void 0 : _a.some((attachment) => attachment.type === "audio")), () => ( false));
534
- }
535
- return false;
536
- }
537
- var TranscriptArray = class extends Array {
538
- constructor(items = []) {
539
- items = Array.isArray(items) ? items : [];
540
- super(...items);
541
- items.forEach((item) => {
542
- if (!["user", "assistant", "event", "summary"].includes(item.role)) {
543
- throw new Error(`Invalid role "${item.role}" in transcript message`);
544
- }
545
- if ("name" in item && item.name && typeof item.name !== "string") {
546
- throw new Error(`Invalid name for transcript message. Expected a string, but got type "${typeof item.name}"`);
547
- }
548
- if ("content" in item && typeof item.content !== "string") {
549
- throw new Error(
550
- `Invalid content for transcript message. Expected a string, but got type "${typeof item.content}"`
551
- );
552
- }
553
- if ("modality" in item && item.modality !== void 0 && !["text", "voice"].includes(item.modality)) {
554
- throw new Error(`Invalid modality "${item.modality}" in transcript message. Expected "text" or "voice"`);
555
- }
556
- });
557
- Object.setPrototypeOf(this, new.target.prototype);
558
- }
559
- toString() {
560
- if (!this.length) {
561
- return "";
562
- }
563
- return this.map((item, idx) => {
564
- var _a, _b;
565
- const msgIdx = getMessageType(item) + "-" + String(idx + 1).padStart(3, "0");
566
- let preview = getMessagePreview(item);
567
- if (preview.length > MAX_MESSAGE_LENGTH) {
568
- preview = preview.slice(0, MAX_MESSAGE_LENGTH) + "\n... (truncated)";
569
- }
570
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
571
- if ((item.role === "event" || item.role === "user") && ((_a = item.attachments) == null ? void 0 : _a.length)) {
572
- for (let i = 0; i < item.attachments.length; i++) {
573
- const attachment = item.attachments[i];
574
- const ref = _nullishCoalesce(attachment.id, () => ( `${msgIdx}-${alphabet[i % alphabet.length]}`));
575
- const alt = attachment.alt ? `: ${attachment.alt}` : "";
576
- preview += attachment.type === "audio" ? `
577
- [Voice message ${ref}${alt}]` : `
578
- [Attachment ${ref}${alt}]`;
579
- }
580
- }
581
- const tags = [];
582
- tags.push({ key: "role", value: item.role });
583
- if (isVoiceMessage(item)) {
584
- tags.push({ key: "modality", value: "voice" });
585
- }
586
- if ("name" in item && ((_b = item.name) == null ? void 0 : _b.length)) {
587
- tags.push({ key: "name", value: item.name });
588
- }
589
- const tagsString = tags.map(({ key, value }) => `${key}="${value}"`).join(" ");
590
- return `<${msgIdx} ${tagsString}>
591
- ${preview.trim()}
592
- </${msgIdx}>`;
593
- }).join("\n");
594
- }
595
- };
596
-
597
- // src/result.ts
598
- var ExecutionResult = class {
599
-
600
-
601
- constructor(status, context) {
602
- this.status = status;
603
- this.context = context;
604
- }
605
- /**
606
- * Type guard to check if the execution completed successfully.
607
- *
608
- * @returns True if the execution completed with an Exit, false otherwise
609
- * @example
610
- * ```typescript
611
- * const result = await execute({ ... })
612
- *
613
- * if (result.isSuccess()) {
614
- * // TypeScript knows this is SuccessExecutionResult
615
- * console.log('Output:', result.output)
616
- * console.log('Exit name:', result.result.exit.name)
617
- * }
618
- * ```
619
- */
620
- isSuccess() {
621
- return this.status === "success" && this instanceof SuccessExecutionResult;
622
- }
623
- /**
624
- * Type guard to check if the execution failed with an error.
625
- *
626
- * @returns True if the execution failed with an unrecoverable error, false otherwise
627
- * @example
628
- * ```typescript
629
- * const result = await execute({ ... })
630
- *
631
- * if (result.isError()) {
632
- * // TypeScript knows this is ErrorExecutionResult
633
- * console.error('Execution failed:', result.error)
634
- *
635
- * // Access error details from the last iteration
636
- * const lastIteration = result.iteration
637
- * if (lastIteration?.status.type === 'execution_error') {
638
- * console.error('Stack trace:', lastIteration.status.execution_error.stack)
639
- * }
640
- * }
641
- * ```
642
- */
643
- isError() {
644
- return this.status === "error" && this instanceof ErrorExecutionResult;
645
- }
646
- /**
647
- * Type guard to check if the execution was interrupted.
648
- * Interrupted means there's a snapshot available and the execution was paused and needs resuming.
649
- *
650
- * @returns True if the execution was interrupted, false otherwise
651
- * @example
652
- * ```typescript
653
- * const result = await execute({ ... })
654
- *
655
- * if (result.isInterrupted()) {
656
- * // TypeScript knows this is PartialExecutionResult
657
- * console.log('Execution paused:', result.signal.message)
658
- *
659
- * // Access snapshot for later resumption
660
- * const snapshot = result.snapshot
661
- * const serialized = snapshot.toJSON()
662
- * await storage.save('execution-state', serialized)
663
- * }
664
- * ```
665
- */
666
- isInterrupted() {
667
- return this.status === "interrupted" && this instanceof PartialExecutionResult;
668
- }
669
- /**
670
- * Type guard to check if the execution completed with a specific exit.
671
- *
672
- * This method provides type-safe access to the output data based on the exit's schema.
673
- * It's the recommended way to handle different exit types in complex agents.
674
- *
675
- * @param exit - The Exit instance to check against
676
- * @returns True if the execution completed with the specified exit, false otherwise
677
- * @template T - The output type of the exit
678
- *
679
- * @example
680
- * ```typescript
681
- * // Define typed exits
682
- * const successExit = new Exit({
683
- * name: 'success',
684
- * schema: z.object({
685
- * message: z.string(),
686
- * count: z.number(),
687
- * }),
688
- * })
689
- *
690
- * const errorExit = new Exit({
691
- * name: 'error',
692
- * schema: z.object({
693
- * errorCode: z.string(),
694
- * details: z.string(),
695
- * }),
696
- * })
697
- *
698
- * const result = await execute({
699
- * instructions: 'Process the data',
700
- * exits: [successExit, errorExit],
701
- * client,
702
- * })
703
- *
704
- * // Type-safe exit handling
705
- * if (result.is(successExit)) {
706
- * // TypeScript knows result.output has { message: string, count: number }
707
- * console.log(`Success: ${result.output.message}`)
708
- * console.log(`Processed ${result.output.count} items`)
709
- * } else if (result.is(errorExit)) {
710
- * // TypeScript knows result.output has { errorCode: string, details: string }
711
- * console.error(`Error ${result.output.errorCode}: ${result.output.details}`)
712
- * }
713
- * ```
714
- */
715
- is(exit) {
716
- return this.status === "success" && this instanceof SuccessExecutionResult && this.result.exit === exit;
717
- }
718
- /**
719
- * Gets the output data from the last successful iteration.
720
- *
721
- * For successful executions, returns the data produced by the exit.
722
- * For failed or interrupted executions, returns null.
723
- *
724
- * @returns The output data for successful executions, null otherwise
725
- * @example
726
- * ```typescript
727
- * const result = await execute({ ... })
728
- *
729
- * // Generic output access
730
- * if (result.isSuccess()) {
731
- * console.log('Output:', result.output)
732
- * }
733
- *
734
- * // Type-safe output access with specific exits
735
- * if (result.is(myExit)) {
736
- * // result.output is now typed based on myExit's schema
737
- * console.log(result.output.specificField)
738
- * }
739
- * ```
740
- */
741
- get output() {
742
- return this.isSuccess() ? this.result.result : null;
743
- }
744
- /**
745
- * Gets the most recent (last) iteration from the execution.
746
- *
747
- * Iterations represent individual steps in the execution loop where the LLM
748
- * generates code, executes it, and processes the results. The last iteration
749
- * contains the final generated code and execution status.
750
- *
751
- * @returns The last iteration, or null if no iterations were completed
752
- * @example
753
- * ```typescript
754
- * const result = await execute({ ... })
755
- *
756
- * const lastIteration = result.iteration
757
- * if (lastIteration) {
758
- * console.log('Generated code:', lastIteration.code)
759
- * console.log('Status:', lastIteration.status.type)
760
- * console.log('Variables:', lastIteration.variables)
761
- * console.log('Tool calls:', lastIteration.toolCalls)
762
- * }
763
- * ```
764
- */
765
- get iteration() {
766
- return this.context.iterations.at(-1) || null;
767
- }
768
- /**
769
- * Gets all iterations from the execution.
770
- *
771
- * This provides access to the complete execution history, showing how the agent
772
- * progressed through multiple iterations to reach the final result. Useful for
773
- * debugging, logging, or understanding the agent's reasoning process.
774
- *
775
- * @returns Array of all iterations in execution order
776
- * @example
777
- * ```typescript
778
- * const result = await execute({ ... })
779
- *
780
- * // Analyze the full execution flow
781
- * result.iterations.forEach((iteration, index) => {
782
- * console.log(`Iteration ${index + 1}:`)
783
- * console.log(' Status:', iteration.status.type)
784
- * console.log(' Code length:', iteration.code?.length || 0)
785
- * console.log(' Tool calls:', iteration.toolCalls.length)
786
- * console.log(' Variables:', Object.keys(iteration.variables).length)
787
- * })
788
- *
789
- * // Find iterations with specific characteristics
790
- * const iterationsWithErrors = result.iterations.filter(
791
- * iter => iter.status.type === 'execution_error'
792
- * )
793
- *
794
- * // Calculate total execution time
795
- * const totalTime = result.iterations.reduce(
796
- * (sum, iter) => sum + (iter.duration || 0), 0
797
- * )
798
- * ```
799
- */
800
- get iterations() {
801
- return _nullishCoalesce(this.context.iterations, () => ( []));
802
- }
803
- /**
804
- * Gets the total token usage of the execution, aggregated across all iterations.
805
- *
806
- * `input`/`output` are the provider-reported token counts of every LLM call made
807
- * during the execution. Per-iteration detail (including the measured context size
808
- * breakdown by prompt part) is available on each iteration's `tokens` property.
809
- *
810
- * @example
811
- * ```typescript
812
- * const result = await execute({ ... })
813
- * console.log(`Execution used ${result.tokens.total} tokens`)
814
- *
815
- * for (const iteration of result.iterations) {
816
- * console.log(iteration.id, iteration.tokens?.context)
817
- * }
818
- * ```
819
- */
820
- get tokens() {
821
- var _a, _b;
822
- let input = 0;
823
- let output = 0;
824
- for (const iteration of this.iterations) {
825
- input += _nullishCoalesce(((_a = iteration.tokens) == null ? void 0 : _a.input), () => ( 0));
826
- output += _nullishCoalesce(((_b = iteration.tokens) == null ? void 0 : _b.output), () => ( 0));
827
- }
828
- return { input, output, total: input + output };
829
- }
830
- };
831
- var SuccessExecutionResult = class extends ExecutionResult {
832
-
833
- constructor(context, result) {
834
- super("success", context);
835
- this.result = result;
836
- }
837
- /**
838
- * Gets the typed output data from the successful execution.
839
- *
840
- * This overrides the base class output property to provide proper typing
841
- * based on the exit schema. The output is guaranteed to match the schema
842
- * of the exit that was triggered.
843
- *
844
- * @returns The typed output data
845
- */
846
- get output() {
847
- return this.result.result;
848
- }
849
- /**
850
- * Gets the final iteration from the successful execution.
851
- *
852
- * For successful executions, there is always at least one iteration,
853
- * so this method returns the guaranteed non-null final iteration.
854
- *
855
- * @returns The final iteration (guaranteed to exist)
856
- */
857
- get iteration() {
858
- return this.context.iterations.at(-1);
859
- }
860
- /**
861
- * Serializes the execution result to JSON.
862
- *
863
- * This method converts the execution result into a JSON format that includes
864
- * the execution status, context, and exit information. It is used for serialization
865
- * and transmission of the execution result.
866
- *
867
- * @returns The JSON representation of the execution result.
868
- */
869
- toJSON() {
870
- return {
871
- status: "success",
872
- context: this.context.toJSON(),
873
- result: {
874
- exit: this.result.exit.toJSON(),
875
- result: this.result.result
876
- }
877
- };
878
- }
879
- };
880
- var ErrorExecutionResult = class extends ExecutionResult {
881
-
882
- constructor(context, error) {
883
- super("error", context);
884
- this.error = error;
885
- }
886
- /**
887
- * Gets the output data (always null for error results).
888
- *
889
- * @returns Always null since error executions don't produce output
890
- */
891
- get output() {
892
- return null;
893
- }
894
- toJSON() {
895
- return {
896
- status: "error",
897
- context: this.context.toJSON(),
898
- error: this.error
899
- };
900
- }
901
- };
902
- var PartialExecutionResult = class extends ExecutionResult {
903
-
904
-
905
- constructor(context, signal, snapshot) {
906
- super("interrupted", context);
907
- this.signal = signal;
908
- this.snapshot = snapshot;
909
- }
910
- /**
911
- * Gets the output data (always null for interrupted results).
912
- *
913
- * @returns Always null since interrupted executions don't produce final output
914
- */
915
- get output() {
916
- return null;
917
- }
918
- /**
919
- * Serializes the execution result to JSON.
920
- *
921
- * @returns The JSON representation of the execution result.
922
- */
923
- toJSON() {
924
- return {
925
- status: "interrupted",
926
- context: this.context.toJSON(),
927
- snapshot: this.snapshot.toJSON(),
928
- signal: {
929
- message: this.signal.message,
930
- truncatedCode: this.signal.truncatedCode,
931
- variables: this.signal.variables
932
- }
933
- };
934
- }
935
- };
936
-
937
- // src/getter.ts
938
- var getValue = async (valueOrGetter, ctx) => {
939
- if (typeof valueOrGetter === "function") {
940
- try {
941
- return await valueOrGetter(ctx);
942
- } catch (e) {
943
- throw new Error(`Error while getting value for ${valueOrGetter}: ${e}`);
944
- }
945
- } else {
946
- return valueOrGetter;
947
- }
948
- };
949
-
950
- // src/context.ts
951
- var _zui = require('@bpinternal/zui');
952
-
953
-
954
- // src/handlers.ts
955
- var Emitter = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this); }
956
- __init() {this._handlers = []}
957
- __init2() {this.subscribe = (fn) => {
958
- this._handlers.push(fn);
959
- return () => {
960
- this._handlers = this._handlers.filter((handler) => handler !== fn);
961
- };
962
- }}
963
- emit(event) {
964
- this._handlers.forEach((handler) => handler(event));
965
- }
966
- }, _class);
967
- var HookedArray = class extends Array {
968
- #listeners = new Emitter();
969
- constructor(...items) {
970
- super(...items);
971
- Object.setPrototypeOf(this, new.target.prototype);
972
- }
973
- push(...items) {
974
- try {
975
- this.#listeners.emit(items);
976
- } finally {
977
- return super.push(...items);
978
- }
979
- }
980
- onPush(fn) {
981
- return this.#listeners.subscribe(fn);
982
- }
983
- };
984
-
985
- // src/context.ts
986
- var ThinkExit = new (0, _chunkDDSJTR6Qcjs.Exit)({
987
- name: "think",
988
- description: "Think about the current situation and provide a response"
989
- });
990
- var ListenExit = new (0, _chunkDDSJTR6Qcjs.Exit)({
991
- name: "listen",
992
- description: "Listen to the user and provide a response"
993
- });
994
- var DefaultExit = new (0, _chunkDDSJTR6Qcjs.Exit)({
995
- name: "done",
996
- description: "When the execution is sucessfully completed or when error recovery is not possible",
997
- schema: _zui.z.discriminatedUnion("success", [
998
- _zui.z.object({
999
- success: _zui.z.literal(true),
1000
- result: _zui.z.any().describe("The result of the execution")
1001
- }),
1002
- _zui.z.object({
1003
- success: _zui.z.literal(false),
1004
- error: _zui.z.string().describe("The error message if the execution failed")
1005
- })
1006
- ])
1007
- });
1008
- var Iteration = class {
1009
-
1010
-
1011
-
1012
- /** Messages (`■send` blocks) parsed from the assistant response, in order. */
1013
-
1014
- /** The `■next` exit parsed from the assistant response, if any. */
1015
-
1016
-
1017
-
1018
- /**
1019
- * Token usage of this iteration's LLM call. The `context` breakdown is measured
1020
- * when the prompt is assembled; `input`/`output` are filled in once the LLM call
1021
- * completes, from the provider-reported usage.
1022
- */
1023
-
1024
-
1025
-
1026
-
1027
-
1028
- get mutations() {
1029
- return [...this._mutations.values()];
1030
- }
1031
- trackMutation(mutation) {
1032
- this._mutations.set(`${_nullishCoalesce(mutation.object, () => ( "global"))}:${mutation.property}`, mutation);
1033
- }
1034
-
1035
- get transcript() {
1036
- return this._parameters.transcript;
1037
- }
1038
- get tools() {
1039
- return this._parameters.tools;
1040
- }
1041
- get objects() {
1042
- return this._parameters.objects;
1043
- }
1044
- get model() {
1045
- return this._parameters.model;
1046
- }
1047
- set model(value) {
1048
- this._parameters.model = value;
1049
- }
1050
- get temperature() {
1051
- return this._parameters.temperature;
1052
- }
1053
- get reasoningEffort() {
1054
- return this._parameters.reasoningEffort;
1055
- }
1056
- get exits() {
1057
- const exits = [...this._parameters.exits];
1058
- if (this.isChatEnabled) {
1059
- exits.push(ListenExit);
1060
- }
1061
- return exits;
1062
- }
1063
- get instructions() {
1064
- return this._parameters.instructions;
1065
- }
1066
-
1067
- hasExited() {
1068
- return ["exit_success"].includes(this.status.type);
1069
- }
1070
- hasExitedWith(exit) {
1071
- return this.status.type === "exit_success" && this.status.exit_success.exit_name === exit.name;
1072
- }
1073
- isSuccessful() {
1074
- return ["callback_requested", "exit_success", "thinking_requested"].includes(
1075
- this.status.type
1076
- );
1077
- }
1078
- isFailed() {
1079
- return [
1080
- "generation_error",
1081
- "invalid_code_error",
1082
- "execution_error",
1083
- "exit_error",
1084
- "aborted"
1085
- ].includes(this.status.type);
1086
- }
1087
- get duration() {
1088
- const ms = (_nullishCoalesce(this.ended_ts, () => ( Date.now()))) - this.started_ts;
1089
- const trailing = this.ended_ts ? "" : " (still running)";
1090
- return ms.toLocaleString("en-US", { style: "unit", unit: "millisecond" }) + trailing;
1091
- }
1092
- get error() {
1093
- if (this.status.type === "generation_error") {
1094
- return `CodeGenerationError: ${this.status.generation_error.message}`;
1095
- }
1096
- if (this.status.type === "invalid_code_error") {
1097
- return `InvalidCodeError: ${this.status.invalid_code_error.message}`;
1098
- }
1099
- if (this.status.type === "execution_error") {
1100
- return `CodeExecutionError: ${this.status.execution_error.message}`;
1101
- }
1102
- if (this.status.type === "exit_error") {
1103
- return `ExitError: ${this.status.exit_error.message}`;
1104
- }
1105
- if (this.status.type === "aborted") {
1106
- return `Aborted: ${this.status.aborted.reason}`;
1107
- }
1108
- return null;
1109
- }
1110
- get isChatEnabled() {
1111
- return this._parameters.components.length > 0;
1112
- }
1113
- constructor(props) {
1114
- this.id = props.id;
1115
- this.status = { type: "pending" };
1116
- this.traces = new HookedArray();
1117
- this._mutations = /* @__PURE__ */ new Map();
1118
- this.messages = props.messages;
1119
- this.variables = props.variables;
1120
- this._parameters = props.parameters;
1121
- this.started_ts = Date.now();
1122
- }
1123
- end(status) {
1124
- if (this.status.type !== "pending") {
1125
- throw new Error(`Iteration ${this.id} has already ended with status ${this.status.type}`);
1126
- }
1127
- this.ended_ts = Date.now();
1128
- this.status = status;
1129
- }
1130
- toJSON() {
1131
- return {
1132
- id: this.id,
1133
- messages: [...this.messages],
1134
- code: this.code,
1135
- model: this.model,
1136
- temperature: this.temperature,
1137
- reasoningEffort: this.reasoningEffort,
1138
- traces: [...this.traces],
1139
- variables: this.variables,
1140
- started_ts: this.started_ts,
1141
- ended_ts: this.ended_ts,
1142
- status: this.status,
1143
- mutations: [...this._mutations.values()],
1144
- llm: this.llm,
1145
- tokens: this.tokens,
1146
- transcript: [...this._parameters.transcript],
1147
- tools: this._parameters.tools.map((tool) => tool.toJSON()),
1148
- objects: this._parameters.objects.map((obj) => obj.toJSON()),
1149
- exits: this._parameters.exits.map((exit) => exit.toJSON()),
1150
- instructions: this._parameters.instructions,
1151
- duration: this.duration,
1152
- error: this.error,
1153
- isChatEnabled: this.isChatEnabled
1154
- };
1155
- }
1156
- };
1157
- var Context = (_class2 = class {
1158
-
1159
-
1160
-
1161
-
1162
-
1163
-
1164
-
1165
-
1166
-
1167
- __init3() {this.version = _chunkKTDBAJBBcjs.DualModePrompt}
1168
- __init4() {this.timeout = 6e4}
1169
- // Default timeout of 60 seconds
1170
-
1171
- /**
1172
- * Optional cap on the model's context window. The effective limit is
1173
- * `min(maxTokens, model's max input tokens)`.
1174
- */
1175
-
1176
- /**
1177
- * Maximum time to wait for the first streamed token, in milliseconds,
1178
- * before the cognitive service falls back to the next model/provider.
1179
- */
1180
-
1181
- /**
1182
- * STT model used by the cognitive service to transcribe audio attachments
1183
- * when the target LLM does not support audio natively. Defaults to 'fast'.
1184
- */
1185
-
1186
-
1187
-
1188
- __init5() {this.iteration = 0}
1189
-
1190
- async nextIteration() {
1191
- if (this.iterations.length >= this.loop) {
1192
- throw new (0, _chunkPK72FAKDcjs.LoopExceededError)();
1193
- }
1194
- if (this.snapshot && this.snapshot.status.type === "pending") {
1195
- throw new Error(
1196
- `Cannot resume execution from a snapshot that is still pending: ${this.snapshot.id}. Please resolve() or reject() it first.`
1197
- );
1198
- }
1199
- const parameters = await this._refreshIterationParameters();
1200
- const { messages, parts } = await this._getIterationMessages(parameters);
1201
- const contextTokens = this._measureContextTokens(messages, parts);
1202
- const iteration = new Iteration({
1203
- id: `${this.id}_${this.iterations.length + 1}`,
1204
- variables: this._getIterationVariables(),
1205
- parameters,
1206
- messages
1207
- });
1208
- iteration.tokens = { input: 0, output: 0, total: 0, context: contextTokens };
1209
- this.iterations.push(iteration);
1210
- this.iteration = this.iterations.length;
1211
- this.snapshot = void 0;
1212
- return iteration;
1213
- }
1214
- _getIterationVariables() {
1215
- var _a;
1216
- const lastIteration = this.iterations.at(-1);
1217
- const variables = {};
1218
- if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
1219
- const lastThinkingVariables = lastIteration.status.thinking_requested.variables;
1220
- if (_chunkHC2QZTVTcjs.isPlainObject_default.call(void 0, lastThinkingVariables)) {
1221
- Object.assign(variables, _chunkHC2QZTVTcjs.cloneDeep_default.call(void 0, lastThinkingVariables));
1222
- }
1223
- }
1224
- if (_chunkHC2QZTVTcjs.isPlainObject_default.call(void 0, lastIteration == null ? void 0 : lastIteration.variables)) {
1225
- Object.assign(variables, _chunkHC2QZTVTcjs.cloneDeep_default.call(void 0, _nullishCoalesce((lastIteration == null ? void 0 : lastIteration.variables), () => ( {}))));
1226
- }
1227
- if (((_a = this.snapshot) == null ? void 0 : _a.status.type) === "resolved") {
1228
- for (const v of this.snapshot.variables) {
1229
- if (!v.truncated && v.value !== void 0) {
1230
- variables[v.name] = v.value;
1231
- }
1232
- }
1233
- }
1234
- return variables;
1235
- }
1236
- /**
1237
- * Measures the token size of each part of the prompt (pre-truncation).
1238
- * The named parts come from the system prompt; everything else in the system
1239
- * message is `framework`. Non-system messages count towards `iterations`,
1240
- * except the very first user message of a fresh execution (task recap),
1241
- * which is prompt scaffolding.
1242
- */
1243
- _measureContextTokens(messages, parts) {
1244
- const tokenizer = _chunkGOWPACSKcjs.getTokenizer.call(void 0, );
1245
- const countText = (text) => (text == null ? void 0 : text.length) ? tokenizer.count(_chunkHEAQAEFZcjs.stripTruncationTags.call(void 0, text)) : 0;
1246
- const countMessage = (message) => {
1247
- if (typeof message.content === "string") {
1248
- return countText(message.content);
1249
- }
1250
- if (Array.isArray(message.content)) {
1251
- return message.content.reduce((acc, part) => acc + (part.type === "text" ? countText(part.text) : 0), 0);
1252
- }
1253
- return 0;
1254
- };
1255
- const instructions = countText(parts.instructions);
1256
- const tools = countText(parts.tools);
1257
- const transcript = countText(parts.transcript);
1258
- const protocol = countText(parts.protocol);
1259
- const systemTokens = messages.filter((x) => x.role === "system").reduce((acc, x) => acc + countMessage(x), 0);
1260
- const otherTokens = messages.filter((x) => x.role !== "system").reduce((acc, x) => acc + countMessage(x), 0);
1261
- const isFirstIteration = this.iterations.length === 0 && !this.snapshot;
1262
- const framework = Math.max(0, systemTokens - (instructions + tools + transcript + protocol));
1263
- const iterations = isFirstIteration ? 0 : otherTokens;
1264
- return {
1265
- total: framework + instructions + tools + transcript + protocol + iterations + (isFirstIteration ? otherTokens : 0),
1266
- framework: framework + (isFirstIteration ? otherTokens : 0),
1267
- instructions,
1268
- tools,
1269
- transcript,
1270
- protocol,
1271
- iterations
1272
- };
1273
- }
1274
- async _getIterationMessages(parameters) {
1275
- var _a, _b, _c, _d, _e, _f;
1276
- const lastIteration = this.iterations.at(-1);
1277
- const promptProps = {
1278
- globalTools: parameters.tools,
1279
- objects: parameters.objects,
1280
- instructions: parameters.instructions,
1281
- transcript: parameters.transcript,
1282
- // ListenExit is protocol-level in chat mode: it must be documented alongside user-defined exits
1283
- exits: parameters.components.length ? [...parameters.exits, ListenExit] : parameters.exits,
1284
- components: parameters.components
1285
- };
1286
- const { message: systemMessage, parts } = await this.version.getSystemMessage(promptProps);
1287
- const withParts = (messages) => ({ messages, parts });
1288
- if (((_a = this.snapshot) == null ? void 0 : _a.status.type) === "resolved") {
1289
- return withParts([
1290
- systemMessage,
1291
- this.version.getSnapshotResolvedMessage({
1292
- snapshot: this.snapshot
1293
- })
1294
- ]);
1295
- }
1296
- if (((_b = this.snapshot) == null ? void 0 : _b.status.type) === "rejected") {
1297
- return withParts([
1298
- systemMessage,
1299
- this.version.getSnapshotRejectedMessage({
1300
- snapshot: this.snapshot
1301
- })
1302
- ]);
1303
- }
1304
- if (!lastIteration) {
1305
- return withParts([systemMessage, await this.version.getInitialUserMessage(promptProps)]);
1306
- }
1307
- const lastIterationMessages = [systemMessage, ...lastIteration.messages.filter((x) => x.role !== "system")];
1308
- if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
1309
- return withParts([
1310
- ...lastIterationMessages,
1311
- {
1312
- role: "assistant",
1313
- content: _chunkHEAQAEFZcjs.wrapContent.call(void 0, _nullishCoalesce(((_c = lastIteration.llm) == null ? void 0 : _c.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
1314
- },
1315
- await this.version.getThinkingMessage({
1316
- reason: lastIteration.status.thinking_requested.reason,
1317
- variables: lastIteration.status.thinking_requested.variables
1318
- })
1319
- ]);
1320
- }
1321
- if ((lastIteration == null ? void 0 : lastIteration.status.type) === "exit_error") {
1322
- return withParts([
1323
- ...lastIterationMessages,
1324
- {
1325
- role: "assistant",
1326
- content: _chunkHEAQAEFZcjs.wrapContent.call(void 0, _nullishCoalesce(((_d = lastIteration.llm) == null ? void 0 : _d.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
1327
- },
1328
- await this.version.getInvalidCodeMessage({
1329
- code: _nullishCoalesce(lastIteration.code, () => ( "// No code generated")),
1330
- message: `Invalid return statement (action: ${lastIteration.status.exit_error.exit}): ${lastIteration.status.exit_error.message}`
1331
- })
1332
- ]);
1333
- }
1334
- if ((lastIteration == null ? void 0 : lastIteration.status.type) === "invalid_code_error") {
1335
- return withParts([
1336
- ...lastIterationMessages,
1337
- {
1338
- role: "assistant",
1339
- content: _chunkHEAQAEFZcjs.wrapContent.call(void 0, _nullishCoalesce(((_e = lastIteration.llm) == null ? void 0 : _e.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
1340
- },
1341
- await this.version.getInvalidCodeMessage({
1342
- code: _nullishCoalesce(lastIteration.code, () => ( "// No code generated")),
1343
- message: lastIteration.status.invalid_code_error.message
1344
- })
1345
- ]);
1346
- }
1347
- if ((lastIteration == null ? void 0 : lastIteration.status.type) === "execution_error") {
1348
- return withParts([
1349
- ...lastIterationMessages,
1350
- {
1351
- role: "assistant",
1352
- content: _chunkHEAQAEFZcjs.wrapContent.call(void 0, _nullishCoalesce(((_f = lastIteration.llm) == null ? void 0 : _f.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
1353
- },
1354
- await this.version.getCodeExecutionErrorMessage({
1355
- message: lastIteration.status.execution_error.message,
1356
- stacktrace: lastIteration.status.execution_error.stack
1357
- })
1358
- ]);
1359
- }
1360
- throw new Error(
1361
- `Unexpected iteration status: ${lastIteration == null ? void 0 : lastIteration.status.type}. This is likely a bug, please report it.`
1362
- );
1363
- }
1364
- async _refreshIterationParameters() {
1365
- var _a, _b;
1366
- const instructions = await getValue(this.instructions, this);
1367
- const transcript = new TranscriptArray(await getValue(_nullishCoalesce(((_a = this.chat) == null ? void 0 : _a.transcript), () => ( [])), this));
1368
- const tools = _chunkPZE6PIPGcjs.Tool.withUniqueNames(await _asyncNullishCoalesce(await getValue(this.tools, this), async () => ( [])));
1369
- const objects = await _asyncNullishCoalesce(await getValue(this.objects, this), async () => ( []));
1370
- const exits = await _asyncNullishCoalesce(await getValue(this.exits, this), async () => ( []));
1371
- const components = await getValue(_nullishCoalesce(((_b = this.chat) == null ? void 0 : _b.components), () => ( [])), this);
1372
- const model = await _asyncNullishCoalesce(await getValue(this.model, this), async () => ( "best"));
1373
- const temperature = await getValue(this.temperature, this);
1374
- const reasoningEffort = await getValue(this.reasoningEffort, this);
1375
- if (objects && objects.length > 100) {
1376
- throw new Error("Too many objects. Expected at most 100 objects.");
1377
- }
1378
- if (tools && tools.length > 100) {
1379
- throw new Error("Too many tools. Expected at most 100 tools.");
1380
- }
1381
- for (const component of components) {
1382
- _chunkI56MPOVGcjs.assertValidComponent.call(void 0, component.definition);
1383
- }
1384
- const ReservedToolNames = [
1385
- "think",
1386
- "listen",
1387
- "return",
1388
- "exit",
1389
- "action",
1390
- "function",
1391
- "callback",
1392
- "code",
1393
- "execute",
1394
- "jsx",
1395
- "object",
1396
- "string",
1397
- "number",
1398
- "boolean",
1399
- "array"
1400
- ];
1401
- for (const tool of tools) {
1402
- for (let name of [...tool.aliases, tool.name]) {
1403
- name = name.toLowerCase();
1404
- if (ReservedToolNames.includes(name)) {
1405
- throw new Error(`Tool name "${name}" (${tool.name}) is reserved. Please choose a different name.`);
1406
- }
1407
- if (components.find(
1408
- (x) => {
1409
- var _a2;
1410
- return x.definition.name.toLowerCase() === name || ((_a2 = x.definition.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name));
1411
- }
1412
- )) {
1413
- throw new Error(
1414
- `Tool name "${name}" (${tool.name}) is already used by a component. Please choose a different name.`
1415
- );
1416
- }
1417
- if (exits.find((x) => x.name.toLowerCase() === name) || exits.find((x) => {
1418
- var _a2;
1419
- return (_a2 = x.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name);
1420
- })) {
1421
- throw new Error(
1422
- `Tool name "${name}" (${tool.name}) is already used by an exit. Please choose a different name.`
1423
- );
1424
- }
1425
- }
1426
- }
1427
- if (exits && exits.length > 100) {
1428
- throw new Error("Too many exits. Expected at most 100 exits.");
1429
- }
1430
- if (components && components.length > 100) {
1431
- throw new Error("Too many components. Expected at most 100 components.");
1432
- }
1433
- if (instructions && instructions.length > 1e6) {
1434
- throw new Error("Instructions are too long. Expected at most 1,000,000 characters.");
1435
- }
1436
- if (transcript && transcript.length > 250) {
1437
- throw new Error("Too many transcript messages. Expected at most 250 messages.");
1438
- }
1439
- if (!components.length && !exits.length) {
1440
- exits.push(DefaultExit);
1441
- }
1442
- if (typeof temperature !== "number" || isNaN(temperature) || temperature < 0 || temperature > 2) {
1443
- throw new Error("Invalid temperature. Expected a number between 0 and 2.");
1444
- }
1445
- const isValidModel = (m) => typeof m === "string" && (m === "best" || m === "fast" || m === "auto" || m.includes(":"));
1446
- if (Array.isArray(model)) {
1447
- if (model.length === 0 || !model.every(isValidModel)) {
1448
- throw new Error(
1449
- "Invalid model. Expected a non-empty array of model strings ('best'/'fast'/'auto' or 'provider:model')."
1450
- );
1451
- }
1452
- } else if (!isValidModel(model)) {
1453
- throw new Error("Invalid model. Expected 'best'/'fast'/'auto' or 'provider:model'.");
1454
- }
1455
- return {
1456
- transcript,
1457
- tools,
1458
- objects,
1459
- exits,
1460
- instructions,
1461
- components,
1462
- model,
1463
- temperature,
1464
- reasoningEffort
1465
- };
1466
- }
1467
- constructor(props) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);
1468
- this.id = `llmz_${_ulid.ulid.call(void 0, )}`;
1469
- this.instructions = props.instructions;
1470
- this.objects = props.objects;
1471
- this.tools = props.tools;
1472
- this.exits = props.exits;
1473
- this.chat = props.chat;
1474
- this.timeout = Math.min(999999999, Math.max(0, _nullishCoalesce(props.timeout, () => ( 6e4))));
1475
- this.loop = _nullishCoalesce(props.loop, () => ( 3));
1476
- this.temperature = _nullishCoalesce(props.temperature, () => ( 0.7));
1477
- this.reasoningEffort = props.reasoningEffort;
1478
- this.model = _nullishCoalesce(props.model, () => ( "best"));
1479
- this.iterations = [];
1480
- this.metadata = _nullishCoalesce(props.metadata, () => ( {}));
1481
- this.snapshot = props.snapshot;
1482
- this.maxTokens = props.maxTokens;
1483
- this.maxTimeToFirstToken = props.maxTimeToFirstToken;
1484
- this.transcriptionModel = props.transcriptionModel;
1485
- if (this.loop < 1 || this.loop > 100) {
1486
- throw new Error("Invalid loop. Expected a number between 1 and 100.");
1487
- }
1488
- if (this.maxTokens !== void 0 && (!Number.isFinite(this.maxTokens) || this.maxTokens < 1)) {
1489
- throw new Error("Invalid maxTokens. Expected a positive number.");
1490
- }
1491
- if (this.maxTimeToFirstToken !== void 0 && (!Number.isFinite(this.maxTimeToFirstToken) || this.maxTimeToFirstToken < 1)) {
1492
- throw new Error("Invalid maxTimeToFirstToken. Expected a positive number of milliseconds.");
1493
- }
1494
- }
1495
- toJSON() {
1496
- var _a;
1497
- return {
1498
- id: this.id,
1499
- iterations: this.iterations.map((iteration) => iteration.toJSON()),
1500
- iteration: this.iteration,
1501
- timeout: this.timeout,
1502
- loop: this.loop,
1503
- metadata: this.metadata,
1504
- snapshot: (_a = this.snapshot) == null ? void 0 : _a.toJSON()
1505
- };
1506
- }
1507
- }, _class2);
1508
-
1509
- // src/custom-client.ts
1510
- var _CustomModelClient = (_class3 = class __CustomModelClient {constructor() { _class3.prototype.__init6.call(this); }
1511
- __init6() {this["$$COGNITIVE"] = "runtime"}
1512
- static isCustomClient(obj) {
1513
- return obj instanceof __CustomModelClient || (obj == null ? void 0 : obj["$$COGNITIVE"]) === "runtime";
1514
- }
1515
- }, _class3);
1516
-
1517
-
1518
-
1519
-
1520
-
1521
-
1522
-
1523
-
1524
-
1525
-
1526
-
1527
-
1528
-
1529
-
1530
- exports.parseExit = parseExit; exports.Snapshot = Snapshot; exports.ExecutionResult = ExecutionResult; exports.SuccessExecutionResult = SuccessExecutionResult; exports.ErrorExecutionResult = ErrorExecutionResult; exports.PartialExecutionResult = PartialExecutionResult; exports.getValue = getValue; exports.ThinkExit = ThinkExit; exports.ListenExit = ListenExit; exports.DefaultExit = DefaultExit; exports.Context = Context; exports._CustomModelClient = _CustomModelClient;