llmz 0.0.4 → 0.0.6

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 (41) hide show
  1. package/README.md +4 -0
  2. package/dist/chat.d.ts +17 -0
  3. package/dist/{chunk-LVKZYKTP.cjs → chunk-4I7UPBLN.cjs} +2 -2
  4. package/dist/{chunk-W6U2VXSF.cjs → chunk-6WT5VZBG.cjs} +348 -12
  5. package/dist/{chunk-5NVNEEYW.cjs → chunk-BEPRLBPK.cjs} +60 -16
  6. package/dist/chunk-CH5T6SPC.cjs +694 -0
  7. package/dist/{chunk-4EWY34YA.js → chunk-D3ESDRLH.js} +60 -16
  8. package/dist/{chunk-JK2LZW2G.cjs → chunk-EJRCDWBA.cjs} +45 -6
  9. package/dist/{chunk-ZCPQ3QOW.js → chunk-HP7RKM25.js} +45 -6
  10. package/dist/{chunk-S6WICIDW.js → chunk-S6FOL2HY.js} +2 -2
  11. package/dist/{chunk-TJQVC4CE.js → chunk-WLUVY5QU.js} +341 -5
  12. package/dist/chunk-XJNRORSK.js +694 -0
  13. package/dist/{component-LQDU72LX.js → component-R2Y74VUI.js} +3 -1
  14. package/dist/component-TSNW3SC7.cjs +16 -0
  15. package/dist/component.d.ts +6 -19
  16. package/dist/component.default.d.ts +131 -151
  17. package/dist/context.d.ts +13 -5
  18. package/dist/{dual-modes-YE4S2AIL.cjs → dual-modes-UHNDHNIF.cjs} +3 -4
  19. package/dist/{dual-modes-QHBOFWHM.js → dual-modes-ZUQKPJFH.js} +2 -3
  20. package/dist/{exit-IDKGZD7M.cjs → exit-KJ4COC5N.cjs} +2 -2
  21. package/dist/{exit-F6ZUL2NV.js → exit-OIYZLBVJ.js} +1 -1
  22. package/dist/exit.d.ts +5 -1
  23. package/dist/getter.d.ts +1 -1
  24. package/dist/index.cjs +85 -128
  25. package/dist/index.d.ts +11 -8
  26. package/dist/index.js +80 -123
  27. package/dist/llmz-CPMVYIOJ.cjs +581 -0
  28. package/dist/llmz-LAN4WDFW.js +581 -0
  29. package/dist/llmz.d.ts +8 -10
  30. package/dist/result.d.ts +33 -0
  31. package/dist/types.d.ts +1 -33
  32. package/dist/{vm-GJ5R72AP.cjs → vm-2DLG7V4G.cjs} +2 -2
  33. package/dist/{vm-ZUQOSRRM.js → vm-FLBMZUA2.js} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-4KB5WXHR.js +0 -92
  36. package/dist/chunk-6YWYCVAB.cjs +0 -92
  37. package/dist/chunk-EFGXTO64.js +0 -344
  38. package/dist/chunk-VAF2H6UD.cjs +0 -344
  39. package/dist/component-HQ5YQNRX.cjs +0 -14
  40. package/dist/llmz-AS5TGCQS.js +0 -1108
  41. package/dist/llmz-R6XZG3JQ.cjs +0 -1108
@@ -0,0 +1,694 @@
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;
2
+
3
+
4
+
5
+ var _chunk6WT5VZBGcjs = require('./chunk-6WT5VZBG.cjs');
6
+
7
+
8
+ var _chunk4QTK5ALHcjs = require('./chunk-4QTK5ALH.cjs');
9
+
10
+
11
+ var _chunkJDABP4SDcjs = require('./chunk-JDABP4SD.cjs');
12
+
13
+
14
+ var _chunk4I7UPBLNcjs = require('./chunk-4I7UPBLN.cjs');
15
+
16
+
17
+ var _chunkEJRCDWBAcjs = require('./chunk-EJRCDWBA.cjs');
18
+
19
+
20
+ var _chunkFIVFS4HGcjs = require('./chunk-FIVFS4HG.cjs');
21
+
22
+
23
+
24
+ var _chunkUQOBUJIQcjs = require('./chunk-UQOBUJIQ.cjs');
25
+
26
+ // src/snapshots.ts
27
+ var _ulid = require('ulid');
28
+ var MAX_SNAPSHOT_SIZE_BYTES = 4e3;
29
+ var Snapshot = class _Snapshot {
30
+
31
+
32
+
33
+
34
+
35
+ #status;
36
+ get status() {
37
+ return Object.freeze({ ...this.#status });
38
+ }
39
+ constructor(props) {
40
+ this.id = props.id;
41
+ this.stack = props.stack;
42
+ this.reason = props.reason;
43
+ this.variables = props.variables;
44
+ this.toolCall = props.toolCall;
45
+ this.#status = props.status;
46
+ }
47
+ static fromSignal(signal) {
48
+ const variables = Object.entries(signal.variables).map(([name, value]) => {
49
+ const type = _chunk6WT5VZBGcjs.extractType.call(void 0, value);
50
+ const bytes = JSON.stringify(value || "").length;
51
+ const truncated = bytes > MAX_SNAPSHOT_SIZE_BYTES;
52
+ return truncated ? { name, type, bytes, truncated: true, preview: _nullishCoalesce(_chunk6WT5VZBGcjs.inspect.call(void 0, value, name), () => ( "N/A")) } : { name, type, bytes, truncated: false, value };
53
+ });
54
+ return new _Snapshot({
55
+ id: "snapshot_" + _ulid.ulid.call(void 0, ),
56
+ reason: signal.message,
57
+ stack: signal.truncatedCode,
58
+ variables,
59
+ toolCall: signal.toolCall,
60
+ status: { type: "pending" }
61
+ });
62
+ }
63
+ toJSON() {
64
+ return {
65
+ id: this.id,
66
+ reason: this.reason,
67
+ stack: this.stack,
68
+ variables: this.variables,
69
+ toolCall: this.toolCall,
70
+ status: this.#status
71
+ };
72
+ }
73
+ static fromJSON(json) {
74
+ return new _Snapshot({
75
+ id: json.id,
76
+ reason: json.reason,
77
+ stack: json.stack,
78
+ variables: json.variables,
79
+ toolCall: json.toolCall,
80
+ status: json.status
81
+ });
82
+ }
83
+ clone() {
84
+ return new _Snapshot({
85
+ id: this.id,
86
+ reason: this.reason,
87
+ stack: this.stack,
88
+ variables: this.variables,
89
+ toolCall: this.toolCall,
90
+ status: this.#status
91
+ });
92
+ }
93
+ reset() {
94
+ this.#status = { type: "pending" };
95
+ }
96
+ resolve(value) {
97
+ if (this.#status.type !== "pending") {
98
+ throw new Error(`Cannot resolve snapshot because it is already settled: ${this.#status.type}`);
99
+ }
100
+ this.#status = { type: "resolved", value };
101
+ }
102
+ reject(error) {
103
+ if (this.#status.type !== "pending") {
104
+ throw new Error(`Cannot reject snapshot because it is already settled: ${this.#status.type}`);
105
+ }
106
+ this.#status = { type: "rejected", error };
107
+ }
108
+ };
109
+
110
+ // src/result.ts
111
+ var ExecutionResult = class {
112
+
113
+
114
+ constructor(status, context) {
115
+ this.status = status;
116
+ this.context = context;
117
+ }
118
+ isSuccess() {
119
+ return this.status === "success" && this instanceof SuccessExecutionResult;
120
+ }
121
+ isError() {
122
+ return this.status === "error" && this instanceof ErrorExecutionResult;
123
+ }
124
+ isInterrupted() {
125
+ return this.status === "interrupted" && this instanceof PartialExecutionResult;
126
+ }
127
+ is(exit) {
128
+ return this.status === "success" && this instanceof SuccessExecutionResult && this.result.exit === exit;
129
+ }
130
+ get output() {
131
+ return this.isSuccess() ? this.result.result : null;
132
+ }
133
+ get iteration() {
134
+ return this.context.iterations.at(-1) || null;
135
+ }
136
+ get iterations() {
137
+ return _nullishCoalesce(this.context.iterations, () => ( []));
138
+ }
139
+ };
140
+ var SuccessExecutionResult = class extends ExecutionResult {
141
+
142
+ constructor(context, result) {
143
+ super("success", context);
144
+ this.result = result;
145
+ }
146
+ get output() {
147
+ return this.result.result;
148
+ }
149
+ get iteration() {
150
+ return this.context.iterations.at(-1);
151
+ }
152
+ };
153
+ var ErrorExecutionResult = class extends ExecutionResult {
154
+
155
+ constructor(context, error) {
156
+ super("error", context);
157
+ this.error = error;
158
+ }
159
+ get output() {
160
+ return null;
161
+ }
162
+ };
163
+ var PartialExecutionResult = class extends ExecutionResult {
164
+
165
+
166
+ constructor(context, signal, snapshot) {
167
+ super("interrupted", context);
168
+ this.signal = signal;
169
+ this.snapshot = snapshot;
170
+ }
171
+ get output() {
172
+ return null;
173
+ }
174
+ };
175
+
176
+ // src/getter.ts
177
+ var getValue = async (valueOrGetter, ctx) => {
178
+ if (typeof valueOrGetter === "function") {
179
+ try {
180
+ return await valueOrGetter(ctx);
181
+ } catch (e) {
182
+ throw new Error(`Error while getting value for ${valueOrGetter}: ${e}`);
183
+ }
184
+ } else {
185
+ return valueOrGetter;
186
+ }
187
+ };
188
+
189
+ // src/context.ts
190
+ var _zui = require('@bpinternal/zui');
191
+
192
+
193
+ // src/handlers.ts
194
+ var Emitter = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this); }
195
+ __init() {this._handlers = []}
196
+ __init2() {this.subscribe = (fn) => {
197
+ this._handlers.push(fn);
198
+ return () => {
199
+ this._handlers = this._handlers.filter((handler) => handler !== fn);
200
+ };
201
+ }}
202
+ emit(event) {
203
+ this._handlers.forEach((handler) => handler(event));
204
+ }
205
+ }, _class);
206
+ var HookedArray = class extends Array {
207
+ #listeners = new Emitter();
208
+ constructor(...items) {
209
+ super(...items);
210
+ Object.setPrototypeOf(this, new.target.prototype);
211
+ }
212
+ push(...items) {
213
+ try {
214
+ this.#listeners.emit(items);
215
+ } finally {
216
+ return super.push(...items);
217
+ }
218
+ }
219
+ onPush(fn) {
220
+ return this.#listeners.subscribe(fn);
221
+ }
222
+ };
223
+
224
+ // src/transcript.ts
225
+ var MAX_MESSAGE_LENGTH = 5e3;
226
+ var TranscriptArray = class extends Array {
227
+ constructor(items = []) {
228
+ items = Array.isArray(items) ? items : [];
229
+ super(...items);
230
+ items.forEach((item) => {
231
+ if (!["user", "assistant"].includes(item.role)) {
232
+ throw new Error(`Invalid role "${item.role}" in transcript message`);
233
+ }
234
+ if (item.name && typeof item.name !== "string") {
235
+ throw new Error(`Invalid name for transcript message. Expected a string, but got type "${typeof item.name}"`);
236
+ }
237
+ if (typeof item.content !== "string") {
238
+ throw new Error(
239
+ `Invalid content for transcript message. Expected a string, but got type "${typeof item.content}"`
240
+ );
241
+ }
242
+ });
243
+ Object.setPrototypeOf(this, new.target.prototype);
244
+ }
245
+ toString() {
246
+ if (!this.length) {
247
+ return "";
248
+ }
249
+ return this.map((item, idx) => {
250
+ var _a;
251
+ const msgIdx = "message-" + String(idx + 1).padStart(3, "0");
252
+ const shouldTruncate = item.content.length > MAX_MESSAGE_LENGTH;
253
+ const preview = shouldTruncate ? item.content.slice(0, MAX_MESSAGE_LENGTH) + "\n... (truncated)" : item.content;
254
+ const tags = [];
255
+ tags.push({ key: "role", value: item.role });
256
+ if ((_a = item.name) == null ? void 0 : _a.length) {
257
+ tags.push({ key: "name", value: item.name });
258
+ }
259
+ const tagsString = tags.map(({ key, value }) => `${key}="${value}"`).join(" ");
260
+ return `<${msgIdx} ${tagsString}>
261
+ ${preview.trim()}
262
+ </${msgIdx}>`;
263
+ }).join("\n");
264
+ }
265
+ };
266
+
267
+ // src/context.ts
268
+ var ThinkExit = new (0, _chunk4I7UPBLNcjs.Exit)({
269
+ name: "think",
270
+ description: "Think about the current situation and provide a response"
271
+ });
272
+ var ListenExit = new (0, _chunk4I7UPBLNcjs.Exit)({
273
+ name: "listen",
274
+ description: "Listen to the user and provide a response"
275
+ });
276
+ var DefaultExit = new (0, _chunk4I7UPBLNcjs.Exit)({
277
+ name: "done",
278
+ description: "When the execution is sucessfully completed or when error recovery is not possible",
279
+ schema: _zui.z.discriminatedUnion("success", [
280
+ _zui.z.object({
281
+ success: _zui.z.literal(true),
282
+ result: _zui.z.any().describe("The result of the execution")
283
+ }),
284
+ _zui.z.object({
285
+ success: _zui.z.literal(false),
286
+ error: _zui.z.string().describe("The error message if the execution failed")
287
+ })
288
+ ])
289
+ });
290
+ var Iteration = class {
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+
299
+
300
+ get mutations() {
301
+ return [...this._mutations.values()];
302
+ }
303
+ trackMutation(mutation) {
304
+ this._mutations.set(`${_nullishCoalesce(mutation.object, () => ( "global"))}:${mutation.property}`, mutation);
305
+ }
306
+
307
+ get transcript() {
308
+ return this._parameters.transcript;
309
+ }
310
+ get tools() {
311
+ return this._parameters.tools;
312
+ }
313
+ get objects() {
314
+ return this._parameters.objects;
315
+ }
316
+ get exits() {
317
+ const exits = [...this._parameters.exits, ThinkExit];
318
+ if (this.isChatEnabled) {
319
+ exits.push(ListenExit);
320
+ }
321
+ return exits;
322
+ }
323
+ get instructions() {
324
+ return this._parameters.instructions;
325
+ }
326
+
327
+ hasExited() {
328
+ return ["exit_success"].includes(this.status.type);
329
+ }
330
+ hasExitedWith(exit) {
331
+ return this.status.type === "exit_success" && this.status.exit_success.exit_name === exit.name;
332
+ }
333
+ isSuccessful() {
334
+ return ["callback_requested", "exit_success", "thinking_requested"].includes(
335
+ this.status.type
336
+ );
337
+ }
338
+ isFailed() {
339
+ return [
340
+ "generation_error",
341
+ "invalid_code_error",
342
+ "execution_error",
343
+ "exit_error",
344
+ "aborted"
345
+ ].includes(this.status.type);
346
+ }
347
+ get duration() {
348
+ const ms = (_nullishCoalesce(this.ended_ts, () => ( Date.now()))) - this.started_ts;
349
+ const trailing = this.ended_ts ? "" : " (still running)";
350
+ return ms.toLocaleString("en-US", { style: "unit", unit: "millisecond" }) + trailing;
351
+ }
352
+ get error() {
353
+ if (this.status.type === "generation_error") {
354
+ return `CodeGenerationError: ${this.status.generation_error.message}`;
355
+ }
356
+ if (this.status.type === "invalid_code_error") {
357
+ return `InvalidCodeError: ${this.status.invalid_code_error.message}`;
358
+ }
359
+ if (this.status.type === "execution_error") {
360
+ return `CodeExecutionError: ${this.status.execution_error.message}`;
361
+ }
362
+ if (this.status.type === "exit_error") {
363
+ return `ExitError: ${this.status.exit_error.message}`;
364
+ }
365
+ if (this.status.type === "aborted") {
366
+ return `Aborted: ${this.status.aborted.reason}`;
367
+ }
368
+ return null;
369
+ }
370
+ get isChatEnabled() {
371
+ return this._parameters.tools.find((x) => x.name.toLowerCase() === "message") !== void 0;
372
+ }
373
+ constructor(props) {
374
+ this.id = props.id;
375
+ this.status = { type: "pending" };
376
+ this.traces = new HookedArray();
377
+ this._mutations = /* @__PURE__ */ new Map();
378
+ this.messages = props.messages;
379
+ this.variables = props.variables;
380
+ this._parameters = props.parameters;
381
+ this.started_ts = Date.now();
382
+ }
383
+ end(status) {
384
+ if (this.status.type !== "pending") {
385
+ throw new Error(`Iteration ${this.id} has already ended with status ${this.status.type}`);
386
+ }
387
+ this.ended_ts = Date.now();
388
+ this.status = status;
389
+ }
390
+ };
391
+ var Context = (_class2 = class {
392
+
393
+
394
+
395
+
396
+
397
+
398
+ __init3() {this.version = _chunk6WT5VZBGcjs.DualModePrompt}
399
+ __init4() {this.timeout = 6e4}
400
+ // Default timeout of 60 seconds
401
+
402
+
403
+
404
+
405
+
406
+ __init5() {this.iteration = 0}
407
+
408
+ async nextIteration() {
409
+ if (this.iterations.length >= this.loop) {
410
+ throw new (0, _chunkJDABP4SDcjs.LoopExceededError)();
411
+ }
412
+ if (this.snapshot && this.snapshot.status.type === "pending") {
413
+ throw new Error(
414
+ `Cannot resume execution from a snapshot that is still pending: ${this.snapshot.id}. Please resolve() or reject() it first.`
415
+ );
416
+ }
417
+ const parameters = await this._refreshIterationParameters();
418
+ const messages = await this._getIterationMessages(parameters);
419
+ const iteration = new Iteration({
420
+ id: `${this.id}_${this.iterations.length + 1}`,
421
+ variables: this._getIterationVariables(),
422
+ parameters,
423
+ messages
424
+ });
425
+ this.iterations.push(iteration);
426
+ this.iteration = this.iterations.length;
427
+ this.snapshot = void 0;
428
+ return iteration;
429
+ }
430
+ _getIterationVariables() {
431
+ const lastIteration = this.iterations.at(-1);
432
+ const variables = {};
433
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
434
+ const lastThinkingVariables = lastIteration.status.thinking_requested.variables;
435
+ if (_chunkUQOBUJIQcjs.isPlainObject_default.call(void 0, lastThinkingVariables)) {
436
+ Object.assign(variables, _chunkUQOBUJIQcjs.cloneDeep_default.call(void 0, lastThinkingVariables));
437
+ }
438
+ }
439
+ if (_chunkUQOBUJIQcjs.isPlainObject_default.call(void 0, lastIteration == null ? void 0 : lastIteration.variables)) {
440
+ Object.assign(variables, _chunkUQOBUJIQcjs.cloneDeep_default.call(void 0, _nullishCoalesce((lastIteration == null ? void 0 : lastIteration.variables), () => ( {}))));
441
+ }
442
+ return variables;
443
+ }
444
+ async _getIterationMessages(parameters) {
445
+ var _a, _b, _c, _d, _e, _f;
446
+ const lastIteration = this.iterations.at(-1);
447
+ if (((_a = this.snapshot) == null ? void 0 : _a.status.type) === "resolved") {
448
+ return [
449
+ await this.version.getSystemMessage({
450
+ globalTools: parameters.tools,
451
+ objects: parameters.objects,
452
+ instructions: parameters.instructions,
453
+ transcript: parameters.transcript,
454
+ exits: parameters.exits,
455
+ components: parameters.components
456
+ }),
457
+ this.version.getSnapshotResolvedMessage({
458
+ snapshot: this.snapshot
459
+ })
460
+ ];
461
+ }
462
+ if (((_b = this.snapshot) == null ? void 0 : _b.status.type) === "rejected") {
463
+ return [
464
+ await this.version.getSystemMessage({
465
+ globalTools: parameters.tools,
466
+ objects: parameters.objects,
467
+ instructions: parameters.instructions,
468
+ transcript: parameters.transcript,
469
+ exits: parameters.exits,
470
+ components: parameters.components
471
+ }),
472
+ this.version.getSnapshotRejectedMessage({
473
+ snapshot: this.snapshot
474
+ })
475
+ ];
476
+ }
477
+ if (!lastIteration) {
478
+ return [
479
+ await this.version.getSystemMessage({
480
+ globalTools: parameters.tools,
481
+ objects: parameters.objects,
482
+ instructions: parameters.instructions,
483
+ transcript: parameters.transcript,
484
+ exits: parameters.exits,
485
+ components: parameters.components
486
+ }),
487
+ await this.version.getInitialUserMessage({
488
+ globalTools: parameters.tools,
489
+ objects: parameters.objects,
490
+ instructions: parameters.instructions,
491
+ transcript: parameters.transcript,
492
+ exits: parameters.exits,
493
+ components: parameters.components
494
+ })
495
+ ];
496
+ }
497
+ const lastIterationMessages = [
498
+ await this.version.getSystemMessage({
499
+ globalTools: parameters.tools,
500
+ objects: parameters.objects,
501
+ instructions: parameters.instructions,
502
+ transcript: parameters.transcript,
503
+ exits: parameters.exits,
504
+ components: parameters.components
505
+ }),
506
+ ...lastIteration.messages.filter((x) => x.role !== "system")
507
+ ];
508
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
509
+ return [
510
+ ...lastIterationMessages,
511
+ {
512
+ role: "assistant",
513
+ content: _chunkFIVFS4HGcjs.wrapContent.call(void 0, _nullishCoalesce(((_c = lastIteration.llm) == null ? void 0 : _c.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
514
+ },
515
+ await this.version.getThinkingMessage({
516
+ reason: lastIteration.status.thinking_requested.reason,
517
+ variables: lastIteration.status.thinking_requested.variables
518
+ })
519
+ ];
520
+ }
521
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "exit_error") {
522
+ return [
523
+ ...lastIterationMessages,
524
+ {
525
+ role: "assistant",
526
+ content: _chunkFIVFS4HGcjs.wrapContent.call(void 0, _nullishCoalesce(((_d = lastIteration.llm) == null ? void 0 : _d.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
527
+ },
528
+ await this.version.getInvalidCodeMessage({
529
+ code: _nullishCoalesce(lastIteration.code, () => ( "// No code generated")),
530
+ message: `Invalid return statement (action: ${lastIteration.status.exit_error.exit}): ${lastIteration.status.exit_error.message}`
531
+ })
532
+ ];
533
+ }
534
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "invalid_code_error") {
535
+ return [
536
+ ...lastIterationMessages,
537
+ {
538
+ role: "assistant",
539
+ content: _chunkFIVFS4HGcjs.wrapContent.call(void 0, _nullishCoalesce(((_e = lastIteration.llm) == null ? void 0 : _e.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
540
+ },
541
+ await this.version.getInvalidCodeMessage({
542
+ code: _nullishCoalesce(lastIteration.code, () => ( "// No code generated")),
543
+ message: lastIteration.status.invalid_code_error.message
544
+ })
545
+ ];
546
+ }
547
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "execution_error") {
548
+ return [
549
+ ...lastIterationMessages,
550
+ {
551
+ role: "assistant",
552
+ content: _chunkFIVFS4HGcjs.wrapContent.call(void 0, _nullishCoalesce(((_f = lastIteration.llm) == null ? void 0 : _f.output), () => ( "")), { preserve: "top", flex: 4, minTokens: 25 })
553
+ },
554
+ await this.version.getCodeExecutionErrorMessage({
555
+ message: lastIteration.status.execution_error.message,
556
+ stacktrace: lastIteration.status.execution_error.stack
557
+ })
558
+ ];
559
+ }
560
+ throw new Error(
561
+ `Unexpected iteration status: ${lastIteration == null ? void 0 : lastIteration.status.type}. This is likely a bug, please report it.`
562
+ );
563
+ }
564
+ async _refreshIterationParameters() {
565
+ var _a, _b;
566
+ const instructions = await getValue(this.instructions, this);
567
+ const transcript = new TranscriptArray(await getValue(_nullishCoalesce(((_a = this.chat) == null ? void 0 : _a.transcript), () => ( [])), this));
568
+ const tools = _chunk4QTK5ALHcjs.Tool.withUniqueNames(await _asyncNullishCoalesce(await getValue(this.tools, this), async () => ( [])));
569
+ const objects = await _asyncNullishCoalesce(await getValue(this.objects, this), async () => ( []));
570
+ const exits = await _asyncNullishCoalesce(await getValue(this.exits, this), async () => ( []));
571
+ const components = await getValue(_nullishCoalesce(((_b = this.chat) == null ? void 0 : _b.components), () => ( [])), this);
572
+ if (objects && objects.length > 100) {
573
+ throw new Error("Too many objects. Expected at most 100 objects.");
574
+ }
575
+ if (tools && tools.length > 100) {
576
+ throw new Error("Too many tools. Expected at most 100 tools.");
577
+ }
578
+ for (const component of components) {
579
+ _chunkEJRCDWBAcjs.assertValidComponent.call(void 0, component.definition);
580
+ }
581
+ const ReservedToolNames = [
582
+ "think",
583
+ "listen",
584
+ "return",
585
+ "exit",
586
+ "action",
587
+ "function",
588
+ "callback",
589
+ "code",
590
+ "execute",
591
+ "jsx",
592
+ "object",
593
+ "string",
594
+ "number",
595
+ "boolean",
596
+ "array"
597
+ ];
598
+ const MessageTool = this.chat && components.length ? new (0, _chunk4QTK5ALHcjs.Tool)({
599
+ name: "Message",
600
+ description: "Send a message to the user",
601
+ aliases: Array.from(
602
+ /* @__PURE__ */ new Set(["message", ...components.flatMap((x) => [x.definition.name, ..._nullishCoalesce(x.definition.aliases, () => ( []))])])
603
+ ),
604
+ handler: async (message) => {
605
+ var _a2, _b2;
606
+ return await ((_b2 = (_a2 = this.chat) == null ? void 0 : _a2.handler) == null ? void 0 : _b2.call(_a2, message));
607
+ }
608
+ }) : null;
609
+ const allTools = MessageTool ? [MessageTool, ...tools] : tools;
610
+ for (const tool of tools) {
611
+ for (let name of [...tool.aliases, tool.name]) {
612
+ name = name.toLowerCase();
613
+ if (ReservedToolNames.includes(name)) {
614
+ throw new Error(`Tool name "${name}" (${tool.name}) is reserved. Please choose a different name.`);
615
+ }
616
+ if (components.find(
617
+ (x) => {
618
+ var _a2;
619
+ return x.definition.name.toLowerCase() === name || ((_a2 = x.definition.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name));
620
+ }
621
+ )) {
622
+ throw new Error(
623
+ `Tool name "${name}" (${tool.name}) is already used by a component. Please choose a different name.`
624
+ );
625
+ }
626
+ if (exits.find((x) => x.name.toLowerCase() === name) || exits.find((x) => {
627
+ var _a2;
628
+ return (_a2 = x.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name);
629
+ })) {
630
+ throw new Error(
631
+ `Tool name "${name}" (${tool.name}) is already used by an exit. Please choose a different name.`
632
+ );
633
+ }
634
+ }
635
+ }
636
+ if (exits && exits.length > 100) {
637
+ throw new Error("Too many exits. Expected at most 100 exits.");
638
+ }
639
+ if (components && components.length > 100) {
640
+ throw new Error("Too many components. Expected at most 100 components.");
641
+ }
642
+ if (instructions && instructions.length > 1e6) {
643
+ throw new Error("Instructions are too long. Expected at most 1,000,000 characters.");
644
+ }
645
+ if (transcript && transcript.length > 250) {
646
+ throw new Error("Too many transcript messages. Expected at most 250 messages.");
647
+ }
648
+ if (!components.length && !exits.length) {
649
+ exits.push(DefaultExit);
650
+ }
651
+ return {
652
+ transcript,
653
+ tools: allTools,
654
+ objects,
655
+ exits,
656
+ instructions,
657
+ components
658
+ };
659
+ }
660
+ constructor(props) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);
661
+ this.id = `llmz_${_ulid.ulid.call(void 0, )}`;
662
+ this.instructions = props.instructions;
663
+ this.objects = props.objects;
664
+ this.tools = props.tools;
665
+ this.exits = props.exits;
666
+ this.chat = props.chat;
667
+ this.timeout = Math.min(999999999, Math.max(0, _nullishCoalesce(props.timeout, () => ( 6e4))));
668
+ this.loop = _nullishCoalesce(props.loop, () => ( 3));
669
+ this.temperature = _nullishCoalesce(props.temperature, () => ( 0.7));
670
+ this.model = props.model;
671
+ this.iterations = [];
672
+ this.metadata = _nullishCoalesce(props.metadata, () => ( {}));
673
+ this.snapshot = props.snapshot;
674
+ if (this.loop < 1 || this.loop > 100) {
675
+ throw new Error("Invalid loop. Expected a number between 1 and 100.");
676
+ }
677
+ if (this.temperature < 0 || this.temperature > 2) {
678
+ throw new Error("Invalid temperature. Expected a number between 0 and 2.");
679
+ }
680
+ }
681
+ }, _class2);
682
+
683
+
684
+
685
+
686
+
687
+
688
+
689
+
690
+
691
+
692
+
693
+
694
+ 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;