llmz 0.0.2 → 0.0.5

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 (87) hide show
  1. package/dist/chat.d.ts +17 -0
  2. package/dist/chunk-3U57H7GT.js +608 -0
  3. package/dist/{chunk-RB2L33ZR.js → chunk-4EWY34YA.js} +24 -24
  4. package/dist/{chunk-R2N2UUKC.cjs → chunk-4I7UPBLN.cjs} +14 -8
  5. package/dist/{chunk-YPOOKE3A.cjs → chunk-4QTK5ALH.cjs} +59 -28
  6. package/dist/{chunk-BKGPO722.cjs → chunk-5NVNEEYW.cjs} +55 -55
  7. package/dist/{chunk-DFZ6GX5C.js → chunk-5TRUJES5.js} +1 -1
  8. package/dist/{chunk-E2B5DRIC.cjs → chunk-6WT5VZBG.cjs} +362 -26
  9. package/dist/{chunk-7S3UY52U.js → chunk-7WRN4E42.js} +36 -8
  10. package/dist/{chunk-E5W3P7EO.cjs → chunk-EJRCDWBA.cjs} +64 -7
  11. package/dist/{chunk-VP6WWAE2.cjs → chunk-FIVFS4HG.cjs} +2 -2
  12. package/dist/{chunk-3T465BEW.js → chunk-HP7RKM25.js} +63 -6
  13. package/dist/{chunk-YUDUY7XW.cjs → chunk-HYVKY3W6.cjs} +23 -24
  14. package/dist/{chunk-PQN6HW7A.cjs → chunk-IKSIOIIP.cjs} +3 -3
  15. package/dist/{chunk-ZUAFUOUR.cjs → chunk-JDABP4SD.cjs} +3 -3
  16. package/dist/{chunk-RJHDQL4C.js → chunk-JKVVQN2P.js} +1 -1
  17. package/dist/{chunk-MSTBEKOQ.js → chunk-JQBT7UWN.js} +3 -3
  18. package/dist/{chunk-BOLDQGES.cjs → chunk-KMZDFWYZ.cjs} +3 -3
  19. package/dist/chunk-MU4LFVY7.cjs +608 -0
  20. package/dist/{chunk-7FIPXMZR.js → chunk-ORQP26SZ.js} +1 -1
  21. package/dist/{chunk-ENFB45AI.cjs → chunk-P7J2WCBB.cjs} +7 -7
  22. package/dist/{chunk-DILHJIMP.js → chunk-QBXIE6EY.js} +49 -18
  23. package/dist/{chunk-UVSOAH2H.js → chunk-QT4QF3YA.js} +1 -1
  24. package/dist/{chunk-6QDFMQHA.js → chunk-S6FOL2HY.js} +8 -2
  25. package/dist/{chunk-ZSRC3TN4.js → chunk-UNMKB2DA.js} +9 -10
  26. package/dist/{chunk-3CGLDS5T.cjs → chunk-UQOBUJIQ.cjs} +38 -10
  27. package/dist/{chunk-QPSUMPLP.js → chunk-WLUVY5QU.js} +345 -9
  28. package/dist/citations.d.ts +63 -0
  29. package/dist/component-R2Y74VUI.js +16 -0
  30. package/dist/component-TSNW3SC7.cjs +16 -0
  31. package/dist/component.d.ts +26 -17
  32. package/dist/component.default.d.ts +314 -8
  33. package/dist/context.d.ts +9 -6
  34. package/dist/dual-modes-UHNDHNIF.cjs +12 -0
  35. package/dist/dual-modes-ZUQKPJFH.js +12 -0
  36. package/dist/exit-KJ4COC5N.cjs +8 -0
  37. package/dist/exit-OIYZLBVJ.js +8 -0
  38. package/dist/exit.d.ts +6 -0
  39. package/dist/getter.d.ts +1 -1
  40. package/dist/index.cjs +256 -160
  41. package/dist/index.d.ts +7 -4
  42. package/dist/index.js +242 -146
  43. package/dist/{jsx-CJ2RBODH.js → jsx-AEHVFB3L.js} +2 -3
  44. package/dist/jsx-AJAXBWFE.cjs +13 -0
  45. package/dist/llmz-VDA4M42R.cjs +604 -0
  46. package/dist/llmz-YE5N54IU.js +604 -0
  47. package/dist/llmz.d.ts +8 -10
  48. package/dist/snapshots.d.ts +9 -1
  49. package/dist/tool-LY77IWV2.js +11 -0
  50. package/dist/tool-SWJYOR2Z.cjs +11 -0
  51. package/dist/tool.d.ts +34 -9
  52. package/dist/truncator-NYN7BGKJ.cjs +10 -0
  53. package/dist/truncator-WAL2GCUY.js +10 -0
  54. package/dist/types.d.ts +9 -1
  55. package/dist/typings-AIV2OASX.js +10 -0
  56. package/dist/typings-XR6CYHW4.cjs +10 -0
  57. package/dist/{utils-TS23YJPE.js → utils-L5GLCS3C.js} +2 -3
  58. package/dist/utils-QC4I2L6R.cjs +37 -0
  59. package/dist/vm-GJ5R72AP.cjs +12 -0
  60. package/dist/vm-ZUQOSRRM.js +12 -0
  61. package/dist/vm.d.ts +1 -1
  62. package/package.json +8 -6
  63. package/dist/chunk-A7BDFLAE.cjs +0 -30
  64. package/dist/chunk-C2TSWGYC.cjs +0 -91
  65. package/dist/chunk-Q4DEJGXD.js +0 -344
  66. package/dist/chunk-QZGFCB4T.cjs +0 -344
  67. package/dist/chunk-UG2GCPHF.js +0 -91
  68. package/dist/chunk-YSQDPG26.js +0 -30
  69. package/dist/component-DWBRHLEN.cjs +0 -9
  70. package/dist/component-R3ZAVXUC.js +0 -9
  71. package/dist/dual-modes-2VDEOJ5D.js +0 -13
  72. package/dist/dual-modes-3MH5N6RY.cjs +0 -13
  73. package/dist/exit-GYMXZZ4I.js +0 -9
  74. package/dist/exit-PQHMJEOG.cjs +0 -9
  75. package/dist/jsx-PPLE5YTB.cjs +0 -14
  76. package/dist/llmz-EGTGPSTX.cjs +0 -1049
  77. package/dist/llmz-WY74UVE3.js +0 -1049
  78. package/dist/tool-AY47ML65.cjs +0 -12
  79. package/dist/tool-WVIPESKN.js +0 -12
  80. package/dist/truncator-MTONQESU.js +0 -11
  81. package/dist/truncator-ZKPOW2I3.cjs +0 -11
  82. package/dist/typings-HTYLRNIC.js +0 -11
  83. package/dist/typings-QRJGGNUM.cjs +0 -11
  84. package/dist/utils-UR4IMUHC.cjs +0 -38
  85. package/dist/vm-4JFSZAMR.cjs +0 -13
  86. package/dist/vm-SMMA664M.js +0 -13
  87. package/patches/source-map-js@1.2.1.patch +0 -16
package/dist/chat.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Component, RenderedComponent } from './component.js';
2
+ import { Context } from './context.js';
3
+ import { ValueOrGetter } from './getter.js';
4
+ import { TranscriptArray, TranscriptMessage } from './transcript.js';
5
+ import { ExecutionResult } from './types.js';
6
+ export type MessageHandler = (input: RenderedComponent) => Promise<void> | void;
7
+ export declare class Chat {
8
+ readonly handler: MessageHandler;
9
+ readonly transcript: ValueOrGetter<TranscriptArray, Context>;
10
+ readonly components: ValueOrGetter<Component[], Context>;
11
+ constructor(props: {
12
+ handler: MessageHandler;
13
+ components: ValueOrGetter<Component[], Context>;
14
+ transcript?: ValueOrGetter<TranscriptMessage[], Context>;
15
+ });
16
+ onExecutionDone(_result: ExecutionResult): void;
17
+ }
@@ -0,0 +1,608 @@
1
+ import {
2
+ DualModePrompt,
3
+ extractType,
4
+ inspect
5
+ } from "./chunk-WLUVY5QU.js";
6
+ import {
7
+ Tool
8
+ } from "./chunk-QBXIE6EY.js";
9
+ import {
10
+ LoopExceededError
11
+ } from "./chunk-JKVVQN2P.js";
12
+ import {
13
+ Exit
14
+ } from "./chunk-S6FOL2HY.js";
15
+ import {
16
+ assertValidComponent
17
+ } from "./chunk-HP7RKM25.js";
18
+ import {
19
+ wrapContent
20
+ } from "./chunk-QT4QF3YA.js";
21
+ import {
22
+ cloneDeep_default,
23
+ isPlainObject_default
24
+ } from "./chunk-7WRN4E42.js";
25
+
26
+ // src/snapshots.ts
27
+ import { ulid } from "ulid";
28
+ var MAX_SNAPSHOT_SIZE_BYTES = 4e3;
29
+ var Snapshot = class _Snapshot {
30
+ id;
31
+ reason;
32
+ stack;
33
+ variables;
34
+ toolCall;
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 = extractType(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: inspect(value, name) ?? "N/A" } : { name, type, bytes, truncated: false, value };
53
+ });
54
+ return new _Snapshot({
55
+ id: "snapshot_" + ulid(),
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/getter.ts
111
+ var getValue = async (valueOrGetter, ctx) => {
112
+ if (typeof valueOrGetter === "function") {
113
+ try {
114
+ return await valueOrGetter(ctx);
115
+ } catch (e) {
116
+ throw new Error(`Error while getting value for ${valueOrGetter}: ${e}`);
117
+ }
118
+ } else {
119
+ return valueOrGetter;
120
+ }
121
+ };
122
+
123
+ // src/context.ts
124
+ import { ulid as ulid2 } from "ulid";
125
+
126
+ // src/handlers.ts
127
+ var Emitter = class {
128
+ _handlers = [];
129
+ subscribe = (fn) => {
130
+ this._handlers.push(fn);
131
+ return () => {
132
+ this._handlers = this._handlers.filter((handler) => handler !== fn);
133
+ };
134
+ };
135
+ emit(event) {
136
+ this._handlers.forEach((handler) => handler(event));
137
+ }
138
+ };
139
+ var HookedArray = class extends Array {
140
+ #listeners = new Emitter();
141
+ constructor(...items) {
142
+ super(...items);
143
+ Object.setPrototypeOf(this, new.target.prototype);
144
+ }
145
+ push(...items) {
146
+ try {
147
+ this.#listeners.emit(items);
148
+ } finally {
149
+ return super.push(...items);
150
+ }
151
+ }
152
+ onPush(fn) {
153
+ return this.#listeners.subscribe(fn);
154
+ }
155
+ };
156
+
157
+ // src/transcript.ts
158
+ var MAX_MESSAGE_LENGTH = 5e3;
159
+ var TranscriptArray = class extends Array {
160
+ constructor(items = []) {
161
+ items = Array.isArray(items) ? items : [];
162
+ super(...items);
163
+ items.forEach((item) => {
164
+ if (!["user", "assistant"].includes(item.role)) {
165
+ throw new Error(`Invalid role "${item.role}" in transcript message`);
166
+ }
167
+ if (item.name && typeof item.name !== "string") {
168
+ throw new Error(`Invalid name for transcript message. Expected a string, but got type "${typeof item.name}"`);
169
+ }
170
+ if (typeof item.content !== "string") {
171
+ throw new Error(
172
+ `Invalid content for transcript message. Expected a string, but got type "${typeof item.content}"`
173
+ );
174
+ }
175
+ });
176
+ Object.setPrototypeOf(this, new.target.prototype);
177
+ }
178
+ toString() {
179
+ if (!this.length) {
180
+ return "";
181
+ }
182
+ return this.map((item, idx) => {
183
+ var _a;
184
+ const msgIdx = "message-" + String(idx + 1).padStart(3, "0");
185
+ const shouldTruncate = item.content.length > MAX_MESSAGE_LENGTH;
186
+ const preview = shouldTruncate ? item.content.slice(0, MAX_MESSAGE_LENGTH) + "\n... (truncated)" : item.content;
187
+ const tags = [];
188
+ tags.push({ key: "role", value: item.role });
189
+ if ((_a = item.name) == null ? void 0 : _a.length) {
190
+ tags.push({ key: "name", value: item.name });
191
+ }
192
+ const tagsString = tags.map(({ key, value }) => `${key}="${value}"`).join(" ");
193
+ return `<${msgIdx} ${tagsString}>
194
+ ${preview.trim()}
195
+ </${msgIdx}>`;
196
+ }).join("\n");
197
+ }
198
+ };
199
+
200
+ // src/context.ts
201
+ var ThinkExit = new Exit({
202
+ name: "think",
203
+ description: "Think about the current situation and provide a response"
204
+ });
205
+ var ListenExit = new Exit({
206
+ name: "listen",
207
+ description: "Listen to the user and provide a response"
208
+ });
209
+ var Iteration = class {
210
+ id;
211
+ messages;
212
+ code;
213
+ traces;
214
+ variables;
215
+ started_ts;
216
+ ended_ts;
217
+ status;
218
+ _mutations;
219
+ get mutations() {
220
+ return [...this._mutations.values()];
221
+ }
222
+ trackMutation(mutation) {
223
+ this._mutations.set(`${mutation.object ?? "global"}:${mutation.property}`, mutation);
224
+ }
225
+ _parameters;
226
+ get transcript() {
227
+ return this._parameters.transcript;
228
+ }
229
+ get tools() {
230
+ return this._parameters.tools;
231
+ }
232
+ get objects() {
233
+ return this._parameters.objects;
234
+ }
235
+ get exits() {
236
+ const exits = [...this._parameters.exits, ThinkExit];
237
+ if (this.isChatEnabled) {
238
+ exits.push(ListenExit);
239
+ }
240
+ return exits;
241
+ }
242
+ get instructions() {
243
+ return this._parameters.instructions;
244
+ }
245
+ llm;
246
+ hasExited() {
247
+ return ["exit_success"].includes(this.status.type);
248
+ }
249
+ hasExitedWith(exit) {
250
+ return this.status.type === "exit_success" && this.status.exit_success.exit_name === exit.name;
251
+ }
252
+ isSuccessful() {
253
+ return ["callback_requested", "exit_success", "thinking_requested"].includes(
254
+ this.status.type
255
+ );
256
+ }
257
+ isFailed() {
258
+ return [
259
+ "generation_error",
260
+ "invalid_code_error",
261
+ "execution_error",
262
+ "exit_error",
263
+ "aborted"
264
+ ].includes(this.status.type);
265
+ }
266
+ get duration() {
267
+ const ms = (this.ended_ts ?? Date.now()) - this.started_ts;
268
+ const trailing = this.ended_ts ? "" : " (still running)";
269
+ return ms.toLocaleString("en-US", { style: "unit", unit: "millisecond" }) + trailing;
270
+ }
271
+ get error() {
272
+ if (this.status.type === "generation_error") {
273
+ return `CodeGenerationError: ${this.status.generation_error.message}`;
274
+ }
275
+ if (this.status.type === "invalid_code_error") {
276
+ return `InvalidCodeError: ${this.status.invalid_code_error.message}`;
277
+ }
278
+ if (this.status.type === "execution_error") {
279
+ return `CodeExecutionError: ${this.status.execution_error.message}`;
280
+ }
281
+ if (this.status.type === "exit_error") {
282
+ return `ExitError: ${this.status.exit_error.message}`;
283
+ }
284
+ if (this.status.type === "aborted") {
285
+ return `Aborted: ${this.status.aborted.reason}`;
286
+ }
287
+ return null;
288
+ }
289
+ get isChatEnabled() {
290
+ return this._parameters.tools.find((x) => x.name.toLowerCase() === "message") !== void 0;
291
+ }
292
+ constructor(props) {
293
+ this.id = props.id;
294
+ this.status = { type: "pending" };
295
+ this.traces = new HookedArray();
296
+ this._mutations = /* @__PURE__ */ new Map();
297
+ this.messages = props.messages;
298
+ this.variables = props.variables;
299
+ this._parameters = props.parameters;
300
+ this.started_ts = Date.now();
301
+ }
302
+ end(status) {
303
+ if (this.status.type !== "pending") {
304
+ throw new Error(`Iteration ${this.id} has already ended with status ${this.status.type}`);
305
+ }
306
+ this.ended_ts = Date.now();
307
+ this.status = status;
308
+ }
309
+ };
310
+ var Context = class {
311
+ id;
312
+ chat;
313
+ instructions;
314
+ objects;
315
+ tools;
316
+ exits;
317
+ version = DualModePrompt;
318
+ timeout = 6e4;
319
+ // Default timeout of 60 seconds
320
+ loop;
321
+ temperature;
322
+ model;
323
+ metadata;
324
+ snapshot;
325
+ iteration = 0;
326
+ iterations;
327
+ async nextIteration() {
328
+ if (this.iterations.length >= this.loop) {
329
+ throw new LoopExceededError();
330
+ }
331
+ if (this.snapshot && this.snapshot.status.type === "pending") {
332
+ throw new Error(
333
+ `Cannot resume execution from a snapshot that is still pending: ${this.snapshot.id}. Please resolve() or reject() it first.`
334
+ );
335
+ }
336
+ const parameters = await this._refreshIterationParameters();
337
+ const messages = await this._getIterationMessages(parameters);
338
+ const iteration = new Iteration({
339
+ id: `${this.id}_${this.iterations.length + 1}`,
340
+ variables: this._getIterationVariables(),
341
+ parameters,
342
+ messages
343
+ });
344
+ this.iterations.push(iteration);
345
+ this.iteration = this.iterations.length;
346
+ this.snapshot = void 0;
347
+ return iteration;
348
+ }
349
+ _getIterationVariables() {
350
+ const lastIteration = this.iterations.at(-1);
351
+ const variables = {};
352
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
353
+ const lastThinkingVariables = lastIteration.status.thinking_requested.variables;
354
+ if (isPlainObject_default(lastThinkingVariables)) {
355
+ Object.assign(variables, cloneDeep_default(lastThinkingVariables));
356
+ }
357
+ }
358
+ if (isPlainObject_default(lastIteration == null ? void 0 : lastIteration.variables)) {
359
+ Object.assign(variables, cloneDeep_default((lastIteration == null ? void 0 : lastIteration.variables) ?? {}));
360
+ }
361
+ return variables;
362
+ }
363
+ async _getIterationMessages(parameters) {
364
+ var _a, _b, _c, _d, _e, _f;
365
+ const lastIteration = this.iterations.at(-1);
366
+ if (((_a = this.snapshot) == null ? void 0 : _a.status.type) === "resolved") {
367
+ return [
368
+ await this.version.getSystemMessage({
369
+ globalTools: parameters.tools,
370
+ objects: parameters.objects,
371
+ instructions: parameters.instructions,
372
+ transcript: parameters.transcript,
373
+ exits: parameters.exits,
374
+ components: parameters.components
375
+ }),
376
+ this.version.getSnapshotResolvedMessage({
377
+ snapshot: this.snapshot
378
+ })
379
+ ];
380
+ }
381
+ if (((_b = this.snapshot) == null ? void 0 : _b.status.type) === "rejected") {
382
+ return [
383
+ await this.version.getSystemMessage({
384
+ globalTools: parameters.tools,
385
+ objects: parameters.objects,
386
+ instructions: parameters.instructions,
387
+ transcript: parameters.transcript,
388
+ exits: parameters.exits,
389
+ components: parameters.components
390
+ }),
391
+ this.version.getSnapshotRejectedMessage({
392
+ snapshot: this.snapshot
393
+ })
394
+ ];
395
+ }
396
+ if (!lastIteration) {
397
+ return [
398
+ await this.version.getSystemMessage({
399
+ globalTools: parameters.tools,
400
+ objects: parameters.objects,
401
+ instructions: parameters.instructions,
402
+ transcript: parameters.transcript,
403
+ exits: parameters.exits,
404
+ components: parameters.components
405
+ }),
406
+ await this.version.getInitialUserMessage({
407
+ globalTools: parameters.tools,
408
+ objects: parameters.objects,
409
+ instructions: parameters.instructions,
410
+ transcript: parameters.transcript,
411
+ exits: parameters.exits,
412
+ components: parameters.components
413
+ })
414
+ ];
415
+ }
416
+ const lastIterationMessages = [
417
+ await this.version.getSystemMessage({
418
+ globalTools: parameters.tools,
419
+ objects: parameters.objects,
420
+ instructions: parameters.instructions,
421
+ transcript: parameters.transcript,
422
+ exits: parameters.exits,
423
+ components: parameters.components
424
+ }),
425
+ ...lastIteration.messages.filter((x) => x.role !== "system")
426
+ ];
427
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
428
+ return [
429
+ ...lastIterationMessages,
430
+ {
431
+ role: "assistant",
432
+ content: wrapContent(((_c = lastIteration.llm) == null ? void 0 : _c.output) ?? "", { preserve: "top", flex: 4, minTokens: 25 })
433
+ },
434
+ await this.version.getThinkingMessage({
435
+ reason: lastIteration.status.thinking_requested.reason,
436
+ variables: lastIteration.status.thinking_requested.variables
437
+ })
438
+ ];
439
+ }
440
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "exit_error") {
441
+ return [
442
+ ...lastIterationMessages,
443
+ {
444
+ role: "assistant",
445
+ content: wrapContent(((_d = lastIteration.llm) == null ? void 0 : _d.output) ?? "", { preserve: "top", flex: 4, minTokens: 25 })
446
+ },
447
+ await this.version.getInvalidCodeMessage({
448
+ code: lastIteration.code ?? "// No code generated",
449
+ message: `Invalid return statement (action: ${lastIteration.status.exit_error.exit}): ${lastIteration.status.exit_error.message}`
450
+ })
451
+ ];
452
+ }
453
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "invalid_code_error") {
454
+ return [
455
+ ...lastIterationMessages,
456
+ {
457
+ role: "assistant",
458
+ content: wrapContent(((_e = lastIteration.llm) == null ? void 0 : _e.output) ?? "", { preserve: "top", flex: 4, minTokens: 25 })
459
+ },
460
+ await this.version.getInvalidCodeMessage({
461
+ code: lastIteration.code ?? "// No code generated",
462
+ message: lastIteration.status.invalid_code_error.message
463
+ })
464
+ ];
465
+ }
466
+ if ((lastIteration == null ? void 0 : lastIteration.status.type) === "execution_error") {
467
+ return [
468
+ ...lastIterationMessages,
469
+ {
470
+ role: "assistant",
471
+ content: wrapContent(((_f = lastIteration.llm) == null ? void 0 : _f.output) ?? "", { preserve: "top", flex: 4, minTokens: 25 })
472
+ },
473
+ await this.version.getCodeExecutionErrorMessage({
474
+ message: lastIteration.status.execution_error.message,
475
+ stacktrace: lastIteration.status.execution_error.stack
476
+ })
477
+ ];
478
+ }
479
+ throw new Error(
480
+ `Unexpected iteration status: ${lastIteration == null ? void 0 : lastIteration.status.type}. This is likely a bug, please report it.`
481
+ );
482
+ }
483
+ async _refreshIterationParameters() {
484
+ var _a, _b;
485
+ const instructions = await getValue(this.instructions, this);
486
+ const transcript = new TranscriptArray(await getValue(((_a = this.chat) == null ? void 0 : _a.transcript) ?? [], this));
487
+ const tools = Tool.withUniqueNames(await getValue(this.tools, this) ?? []);
488
+ const objects = await getValue(this.objects, this) ?? [];
489
+ const exits = await getValue(this.exits, this) ?? [];
490
+ const components = await getValue(((_b = this.chat) == null ? void 0 : _b.components) ?? [], this);
491
+ if (objects && objects.length > 100) {
492
+ throw new Error("Too many objects. Expected at most 100 objects.");
493
+ }
494
+ if (tools && tools.length > 100) {
495
+ throw new Error("Too many tools. Expected at most 100 tools.");
496
+ }
497
+ for (const component of components) {
498
+ assertValidComponent(component.definition);
499
+ }
500
+ const ReservedToolNames = [
501
+ "think",
502
+ "listen",
503
+ "return",
504
+ "exit",
505
+ "action",
506
+ "function",
507
+ "callback",
508
+ "code",
509
+ "execute",
510
+ "jsx",
511
+ "object",
512
+ "string",
513
+ "number",
514
+ "boolean",
515
+ "array"
516
+ ];
517
+ const MessageTool = this.chat && components.length ? new Tool({
518
+ name: "Message",
519
+ description: "Send a message to the user",
520
+ aliases: Array.from(
521
+ /* @__PURE__ */ new Set(["message", ...components.flatMap((x) => [x.definition.name, ...x.definition.aliases ?? []])])
522
+ ),
523
+ handler: async (message) => {
524
+ var _a2, _b2;
525
+ return await ((_b2 = (_a2 = this.chat) == null ? void 0 : _a2.handler) == null ? void 0 : _b2.call(_a2, message));
526
+ }
527
+ }) : null;
528
+ const allTools = MessageTool ? [MessageTool, ...tools] : tools;
529
+ for (const tool of tools) {
530
+ for (let name of [...tool.aliases, tool.name]) {
531
+ name = name.toLowerCase();
532
+ if (ReservedToolNames.includes(name)) {
533
+ throw new Error(`Tool name "${name}" (${tool.name}) is reserved. Please choose a different name.`);
534
+ }
535
+ if (components.find(
536
+ (x) => {
537
+ var _a2;
538
+ return x.definition.name.toLowerCase() === name || ((_a2 = x.definition.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name));
539
+ }
540
+ )) {
541
+ throw new Error(
542
+ `Tool name "${name}" (${tool.name}) is already used by a component. Please choose a different name.`
543
+ );
544
+ }
545
+ if (exits.find((x) => x.name.toLowerCase() === name) || exits.find((x) => {
546
+ var _a2;
547
+ return (_a2 = x.aliases) == null ? void 0 : _a2.map((x2) => x2.toLowerCase()).includes(name);
548
+ })) {
549
+ throw new Error(
550
+ `Tool name "${name}" (${tool.name}) is already used by an exit. Please choose a different name.`
551
+ );
552
+ }
553
+ }
554
+ }
555
+ if (exits && exits.length > 100) {
556
+ throw new Error("Too many exits. Expected at most 100 exits.");
557
+ }
558
+ if (components && components.length > 100) {
559
+ throw new Error("Too many components. Expected at most 100 components.");
560
+ }
561
+ if (instructions && instructions.length > 1e6) {
562
+ throw new Error("Instructions are too long. Expected at most 1,000,000 characters.");
563
+ }
564
+ if (transcript && transcript.length > 250) {
565
+ throw new Error("Too many transcript messages. Expected at most 250 messages.");
566
+ }
567
+ if (!components.length && !exits.length) {
568
+ throw new Error("When no components are provided, at least one exit is required.");
569
+ }
570
+ return {
571
+ transcript,
572
+ tools: allTools,
573
+ objects,
574
+ exits,
575
+ instructions,
576
+ components
577
+ };
578
+ }
579
+ constructor(props) {
580
+ this.id = `llmz_${ulid2()}`;
581
+ this.instructions = props.instructions;
582
+ this.objects = props.objects;
583
+ this.tools = props.tools;
584
+ this.exits = props.exits;
585
+ this.chat = props.chat;
586
+ this.timeout = Math.min(999999999, Math.max(0, props.timeout ?? 6e4));
587
+ this.loop = props.loop ?? 3;
588
+ this.temperature = props.temperature ?? 0.7;
589
+ this.model = props.model;
590
+ this.iterations = [];
591
+ this.metadata = props.metadata ?? {};
592
+ this.snapshot = props.snapshot;
593
+ if (this.loop < 1 || this.loop > 100) {
594
+ throw new Error("Invalid loop. Expected a number between 1 and 100.");
595
+ }
596
+ if (this.temperature < 0 || this.temperature > 2) {
597
+ throw new Error("Invalid temperature. Expected a number between 0 and 2.");
598
+ }
599
+ }
600
+ };
601
+
602
+ export {
603
+ Snapshot,
604
+ getValue,
605
+ ThinkExit,
606
+ ListenExit,
607
+ Context
608
+ };