llmz 0.0.13 → 0.0.14

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.
@@ -5,13 +5,13 @@ import {
5
5
  } from "./chunk-KH6JQYQA.js";
6
6
  import {
7
7
  Tool
8
- } from "./chunk-JAGB2AOU.js";
8
+ } from "./chunk-OKTHMXRT.js";
9
9
  import {
10
10
  LoopExceededError
11
11
  } from "./chunk-JKVVQN2P.js";
12
12
  import {
13
13
  Exit
14
- } from "./chunk-JMSZKB4T.js";
14
+ } from "./chunk-XAN7HQP5.js";
15
15
  import {
16
16
  assertValidComponent
17
17
  } from "./chunk-GGWM6X2K.js";
@@ -33,6 +33,11 @@ var Snapshot = class _Snapshot {
33
33
  variables;
34
34
  toolCall;
35
35
  #status;
36
+ /**
37
+ * Gets the current status of the snapshot.
38
+ *
39
+ * @returns The snapshot status (pending, resolved, or rejected)
40
+ */
36
41
  get status() {
37
42
  return Object.freeze({ ...this.#status });
38
43
  }
@@ -44,6 +49,17 @@ var Snapshot = class _Snapshot {
44
49
  this.toolCall = props.toolCall;
45
50
  this.#status = props.status;
46
51
  }
52
+ /**
53
+ * Creates a new Snapshot from a SnapshotSignal.
54
+ *
55
+ * This method is called internally by the LLMz execution engine when a SnapshotSignal
56
+ * is thrown during execution. It captures the current execution state including
57
+ * variables, stack trace, and tool context.
58
+ *
59
+ * @param signal The SnapshotSignal containing execution state
60
+ * @returns A new Snapshot instance in pending status
61
+ * @internal
62
+ */
47
63
  static fromSignal(signal) {
48
64
  const variables = Object.entries(signal.variables).map(([name, value]) => {
49
65
  const type = extractType(value);
@@ -60,6 +76,20 @@ var Snapshot = class _Snapshot {
60
76
  status: { type: "pending" }
61
77
  });
62
78
  }
79
+ /**
80
+ * Serializes the snapshot to a JSON-compatible object for persistence.
81
+ *
82
+ * Use this method to save snapshots to databases, files, or other storage systems.
83
+ * The serialized snapshot can be restored later using fromJSON().
84
+ *
85
+ * @returns A JSON-serializable representation of the snapshot
86
+ * @example
87
+ * ```typescript
88
+ * const snapshot = result.snapshot
89
+ * const serialized = snapshot.toJSON()
90
+ * await database.save('snapshots', snapshot.id, serialized)
91
+ * ```
92
+ */
63
93
  toJSON() {
64
94
  return {
65
95
  id: this.id,
@@ -70,6 +100,20 @@ var Snapshot = class _Snapshot {
70
100
  status: this.#status
71
101
  };
72
102
  }
103
+ /**
104
+ * Restores a snapshot from its JSON representation.
105
+ *
106
+ * Use this method to recreate snapshots from persistent storage. The restored
107
+ * snapshot will maintain its original state and can be resolved/rejected as needed.
108
+ *
109
+ * @param json The serialized snapshot data from toJSON()
110
+ * @returns A restored Snapshot instance
111
+ * @example
112
+ * ```typescript
113
+ * const serialized = await database.get('snapshots', snapshotId)
114
+ * const snapshot = Snapshot.fromJSON(serialized)
115
+ * ```
116
+ */
73
117
  static fromJSON(json) {
74
118
  return new _Snapshot({
75
119
  id: json.id,
@@ -80,6 +124,11 @@ var Snapshot = class _Snapshot {
80
124
  status: json.status
81
125
  });
82
126
  }
127
+ /**
128
+ * Creates a deep copy of the snapshot.
129
+ *
130
+ * @returns A new Snapshot instance with identical data
131
+ */
83
132
  clone() {
84
133
  return new _Snapshot({
85
134
  id: this.id,
@@ -90,15 +139,62 @@ var Snapshot = class _Snapshot {
90
139
  status: this.#status
91
140
  });
92
141
  }
142
+ /**
143
+ * Resets the snapshot status back to pending.
144
+ *
145
+ * This allows a previously resolved or rejected snapshot to be resolved/rejected
146
+ * again with different data. Useful for retry scenarios.
147
+ */
93
148
  reset() {
94
149
  this.#status = { type: "pending" };
95
150
  }
151
+ /**
152
+ * Resolves the snapshot with a successful result value.
153
+ *
154
+ * Call this method when the long-running operation that caused the snapshot
155
+ * has completed successfully. The provided value will be returned as the
156
+ * result of the original tool call when execution resumes.
157
+ *
158
+ * @param value The result value from the completed operation
159
+ * @throws Error if the snapshot is not in pending status
160
+ * @example
161
+ * ```typescript
162
+ * // After a background job completes
163
+ * const result = await backgroundJob.getResult()
164
+ * snapshot.resolve(result)
165
+ *
166
+ * // Continue execution
167
+ * const continuation = await execute({ snapshot, ... })
168
+ * ```
169
+ */
96
170
  resolve(value) {
97
171
  if (this.#status.type !== "pending") {
98
172
  throw new Error(`Cannot resolve snapshot because it is already settled: ${this.#status.type}`);
99
173
  }
100
174
  this.#status = { type: "resolved", value };
101
175
  }
176
+ /**
177
+ * Rejects the snapshot with an error.
178
+ *
179
+ * Call this method when the long-running operation that caused the snapshot
180
+ * has failed or encountered an error. The provided error will be thrown
181
+ * when execution resumes, allowing the generated code to handle it.
182
+ *
183
+ * @param error The error that occurred during the operation
184
+ * @throws Error if the snapshot is not in pending status
185
+ * @example
186
+ * ```typescript
187
+ * try {
188
+ * const result = await externalAPI.call()
189
+ * snapshot.resolve(result)
190
+ * } catch (error) {
191
+ * snapshot.reject(error)
192
+ * }
193
+ *
194
+ * // Continue execution (will throw the error)
195
+ * const continuation = await execute({ snapshot, ... })
196
+ * ```
197
+ */
102
198
  reject(error) {
103
199
  if (this.#status.type !== "pending") {
104
200
  throw new Error(`Cannot reject snapshot because it is already settled: ${this.#status.type}`);
@@ -186,24 +282,201 @@ var ExecutionResult = class {
186
282
  this.status = status;
187
283
  this.context = context;
188
284
  }
285
+ /**
286
+ * Type guard to check if the execution completed successfully.
287
+ *
288
+ * @returns True if the execution completed with an Exit, false otherwise
289
+ * @example
290
+ * ```typescript
291
+ * const result = await execute({ ... })
292
+ *
293
+ * if (result.isSuccess()) {
294
+ * // TypeScript knows this is SuccessExecutionResult
295
+ * console.log('Output:', result.output)
296
+ * console.log('Exit name:', result.result.exit.name)
297
+ * }
298
+ * ```
299
+ */
189
300
  isSuccess() {
190
301
  return this.status === "success" && this instanceof SuccessExecutionResult;
191
302
  }
303
+ /**
304
+ * Type guard to check if the execution failed with an error.
305
+ *
306
+ * @returns True if the execution failed with an unrecoverable error, false otherwise
307
+ * @example
308
+ * ```typescript
309
+ * const result = await execute({ ... })
310
+ *
311
+ * if (result.isError()) {
312
+ * // TypeScript knows this is ErrorExecutionResult
313
+ * console.error('Execution failed:', result.error)
314
+ *
315
+ * // Access error details from the last iteration
316
+ * const lastIteration = result.iteration
317
+ * if (lastIteration?.status.type === 'execution_error') {
318
+ * console.error('Stack trace:', lastIteration.status.execution_error.stack)
319
+ * }
320
+ * }
321
+ * ```
322
+ */
192
323
  isError() {
193
324
  return this.status === "error" && this instanceof ErrorExecutionResult;
194
325
  }
326
+ /**
327
+ * Type guard to check if the execution was interrupted.
328
+ * Interrupted means there's a snapshot available and the execution was paused and needs resuming.
329
+ *
330
+ * @returns True if the execution was interrupted, false otherwise
331
+ * @example
332
+ * ```typescript
333
+ * const result = await execute({ ... })
334
+ *
335
+ * if (result.isInterrupted()) {
336
+ * // TypeScript knows this is PartialExecutionResult
337
+ * console.log('Execution paused:', result.signal.message)
338
+ *
339
+ * // Access snapshot for later resumption
340
+ * const snapshot = result.snapshot
341
+ * const serialized = snapshot.toJSON()
342
+ * await storage.save('execution-state', serialized)
343
+ * }
344
+ * ```
345
+ */
195
346
  isInterrupted() {
196
347
  return this.status === "interrupted" && this instanceof PartialExecutionResult;
197
348
  }
349
+ /**
350
+ * Type guard to check if the execution completed with a specific exit.
351
+ *
352
+ * This method provides type-safe access to the output data based on the exit's schema.
353
+ * It's the recommended way to handle different exit types in complex agents.
354
+ *
355
+ * @param exit - The Exit instance to check against
356
+ * @returns True if the execution completed with the specified exit, false otherwise
357
+ * @template T - The output type of the exit
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * // Define typed exits
362
+ * const successExit = new Exit({
363
+ * name: 'success',
364
+ * schema: z.object({
365
+ * message: z.string(),
366
+ * count: z.number(),
367
+ * }),
368
+ * })
369
+ *
370
+ * const errorExit = new Exit({
371
+ * name: 'error',
372
+ * schema: z.object({
373
+ * errorCode: z.string(),
374
+ * details: z.string(),
375
+ * }),
376
+ * })
377
+ *
378
+ * const result = await execute({
379
+ * instructions: 'Process the data',
380
+ * exits: [successExit, errorExit],
381
+ * client,
382
+ * })
383
+ *
384
+ * // Type-safe exit handling
385
+ * if (result.is(successExit)) {
386
+ * // TypeScript knows result.output has { message: string, count: number }
387
+ * console.log(`Success: ${result.output.message}`)
388
+ * console.log(`Processed ${result.output.count} items`)
389
+ * } else if (result.is(errorExit)) {
390
+ * // TypeScript knows result.output has { errorCode: string, details: string }
391
+ * console.error(`Error ${result.output.errorCode}: ${result.output.details}`)
392
+ * }
393
+ * ```
394
+ */
198
395
  is(exit) {
199
396
  return this.status === "success" && this instanceof SuccessExecutionResult && this.result.exit === exit;
200
397
  }
398
+ /**
399
+ * Gets the output data from the last successful iteration.
400
+ *
401
+ * For successful executions, returns the data produced by the exit.
402
+ * For failed or interrupted executions, returns null.
403
+ *
404
+ * @returns The output data for successful executions, null otherwise
405
+ * @example
406
+ * ```typescript
407
+ * const result = await execute({ ... })
408
+ *
409
+ * // Generic output access
410
+ * if (result.isSuccess()) {
411
+ * console.log('Output:', result.output)
412
+ * }
413
+ *
414
+ * // Type-safe output access with specific exits
415
+ * if (result.is(myExit)) {
416
+ * // result.output is now typed based on myExit's schema
417
+ * console.log(result.output.specificField)
418
+ * }
419
+ * ```
420
+ */
201
421
  get output() {
202
422
  return this.isSuccess() ? this.result.result : null;
203
423
  }
424
+ /**
425
+ * Gets the most recent (last) iteration from the execution.
426
+ *
427
+ * Iterations represent individual steps in the execution loop where the LLM
428
+ * generates code, executes it, and processes the results. The last iteration
429
+ * contains the final generated code and execution status.
430
+ *
431
+ * @returns The last iteration, or null if no iterations were completed
432
+ * @example
433
+ * ```typescript
434
+ * const result = await execute({ ... })
435
+ *
436
+ * const lastIteration = result.iteration
437
+ * if (lastIteration) {
438
+ * console.log('Generated code:', lastIteration.code)
439
+ * console.log('Status:', lastIteration.status.type)
440
+ * console.log('Variables:', lastIteration.variables)
441
+ * console.log('Tool calls:', lastIteration.toolCalls)
442
+ * }
443
+ * ```
444
+ */
204
445
  get iteration() {
205
446
  return this.context.iterations.at(-1) || null;
206
447
  }
448
+ /**
449
+ * Gets all iterations from the execution.
450
+ *
451
+ * This provides access to the complete execution history, showing how the agent
452
+ * progressed through multiple iterations to reach the final result. Useful for
453
+ * debugging, logging, or understanding the agent's reasoning process.
454
+ *
455
+ * @returns Array of all iterations in execution order
456
+ * @example
457
+ * ```typescript
458
+ * const result = await execute({ ... })
459
+ *
460
+ * // Analyze the full execution flow
461
+ * result.iterations.forEach((iteration, index) => {
462
+ * console.log(`Iteration ${index + 1}:`)
463
+ * console.log(' Status:', iteration.status.type)
464
+ * console.log(' Code length:', iteration.code?.length || 0)
465
+ * console.log(' Tool calls:', iteration.toolCalls.length)
466
+ * console.log(' Variables:', Object.keys(iteration.variables).length)
467
+ * })
468
+ *
469
+ * // Find iterations with specific characteristics
470
+ * const iterationsWithErrors = result.iterations.filter(
471
+ * iter => iter.status.type === 'execution_error'
472
+ * )
473
+ *
474
+ * // Calculate total execution time
475
+ * const totalTime = result.iterations.reduce(
476
+ * (sum, iter) => sum + (iter.duration || 0), 0
477
+ * )
478
+ * ```
479
+ */
207
480
  get iterations() {
208
481
  return this.context.iterations ?? [];
209
482
  }
@@ -214,9 +487,26 @@ var SuccessExecutionResult = class extends ExecutionResult {
214
487
  super("success", context);
215
488
  this.result = result;
216
489
  }
490
+ /**
491
+ * Gets the typed output data from the successful execution.
492
+ *
493
+ * This overrides the base class output property to provide proper typing
494
+ * based on the exit schema. The output is guaranteed to match the schema
495
+ * of the exit that was triggered.
496
+ *
497
+ * @returns The typed output data
498
+ */
217
499
  get output() {
218
500
  return this.result.result;
219
501
  }
502
+ /**
503
+ * Gets the final iteration from the successful execution.
504
+ *
505
+ * For successful executions, there is always at least one iteration,
506
+ * so this method returns the guaranteed non-null final iteration.
507
+ *
508
+ * @returns The final iteration (guaranteed to exist)
509
+ */
220
510
  get iteration() {
221
511
  return this.context.iterations.at(-1);
222
512
  }
@@ -227,6 +517,11 @@ var ErrorExecutionResult = class extends ExecutionResult {
227
517
  super("error", context);
228
518
  this.error = error;
229
519
  }
520
+ /**
521
+ * Gets the output data (always null for error results).
522
+ *
523
+ * @returns Always null since error executions don't produce output
524
+ */
230
525
  get output() {
231
526
  return null;
232
527
  }
@@ -239,6 +534,11 @@ var PartialExecutionResult = class extends ExecutionResult {
239
534
  this.signal = signal;
240
535
  this.snapshot = snapshot;
241
536
  }
537
+ /**
538
+ * Gets the output data (always null for interrupted results).
539
+ *
540
+ * @returns Always null since interrupted executions don't produce final output
541
+ */
242
542
  get output() {
243
543
  return null;
244
544
  }