llmz 0.0.13 → 0.0.15

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 (52) hide show
  1. package/CLAUDE.md +363 -0
  2. package/README.md +61 -34
  3. package/dist/abort-signal.d.ts +40 -0
  4. package/dist/chat.d.ts +325 -0
  5. package/dist/{chunk-KH6JQYQA.js → chunk-2D2DE7CD.js} +2 -2
  6. package/dist/chunk-3G3BS5IA.cjs +256 -0
  7. package/dist/{chunk-SNDVQU5A.js → chunk-3JYCCI4S.js} +1 -1
  8. package/dist/chunk-A7QHWVD7.js +493 -0
  9. package/dist/{chunk-IH2WQFO5.js → chunk-EE6NVDID.js} +1 -1
  10. package/dist/{chunk-4L6D2A6O.cjs → chunk-FZJHYLM2.cjs} +14 -14
  11. package/dist/{chunk-JGVAZO4X.cjs → chunk-GZPN7RGH.cjs} +2 -2
  12. package/dist/{chunk-SHJDRZF5.cjs → chunk-PIDLNYIP.cjs} +25 -25
  13. package/dist/{chunk-PRVFVXT4.js → chunk-RBRTK37G.js} +383 -4
  14. package/dist/{chunk-HJKOSEH2.cjs → chunk-TCRRSS44.cjs} +397 -18
  15. package/dist/chunk-VPTFUOIK.js +256 -0
  16. package/dist/{chunk-276Q6EWP.cjs → chunk-WHNOR4ZU.cjs} +3 -0
  17. package/dist/chunk-XGJOEQMW.cjs +493 -0
  18. package/dist/{chunk-4MNIJGK6.js → chunk-ZORRILUV.js} +3 -0
  19. package/dist/context.d.ts +412 -4
  20. package/dist/{dual-modes-T53P72CH.js → dual-modes-7FI4T35O.js} +3 -3
  21. package/dist/{dual-modes-VLIGPIHX.cjs → dual-modes-OFHV2C3X.cjs} +4 -4
  22. package/dist/exit-XAYKJ6TR.cjs +8 -0
  23. package/dist/{exit-YORW76T3.js → exit-YLO7BY7Z.js} +2 -2
  24. package/dist/exit.d.ts +369 -2
  25. package/dist/index.cjs +253 -28
  26. package/dist/index.d.ts +71 -1
  27. package/dist/index.js +242 -17
  28. package/dist/{llmz-ROOX7RYI.js → llmz-67EZPJ4E.js} +113 -39
  29. package/dist/{llmz-QLZBDG2Z.cjs → llmz-WVNKAMCP.cjs} +123 -49
  30. package/dist/llmz.d.ts +142 -5
  31. package/dist/objects.d.ts +350 -1
  32. package/dist/result.d.ts +809 -6
  33. package/dist/snapshots.d.ts +181 -1
  34. package/dist/{tool-QP4MVRWI.cjs → tool-O4SFRIE4.cjs} +4 -4
  35. package/dist/{tool-N6ODRRGH.js → tool-PCOYOCRH.js} +3 -3
  36. package/dist/tool.d.ts +470 -2
  37. package/dist/{truncator-IY2MXOMC.js → truncator-BSP6PQPC.js} +2 -2
  38. package/dist/truncator-W3NXBLYJ.cjs +10 -0
  39. package/dist/types.d.ts +3 -0
  40. package/dist/{typings-GDMY6VY2.js → typings-WYHEFCYB.js} +2 -2
  41. package/dist/{typings-2CPHOFDN.cjs → typings-Y45GMPZT.cjs} +3 -3
  42. package/dist/utils-L5QAQXV2.cjs +39 -0
  43. package/dist/{utils-N24IHDFA.js → utils-RQHQ2KOG.js} +1 -1
  44. package/docs/TODO.md +919 -0
  45. package/package.json +3 -3
  46. package/dist/chunk-C6WNNTEV.cjs +0 -212
  47. package/dist/chunk-GWFYZDUR.cjs +0 -105
  48. package/dist/chunk-JAGB2AOU.js +0 -212
  49. package/dist/chunk-JMSZKB4T.js +0 -105
  50. package/dist/exit-TRXEU4OU.cjs +0 -8
  51. package/dist/truncator-DUMWEGQO.cjs +0 -10
  52. package/dist/utils-A7WNEFTA.cjs +0 -39
package/dist/exit.d.ts CHANGED
@@ -1,20 +1,368 @@
1
1
  import { JSONSchema7 } from 'json-schema';
2
- import { ZuiType } from './types.js';
2
+ import { Serializable, ZuiType } from './types.js';
3
+ /**
4
+ * Represents the result of an agent execution that exited with a specific Exit.
5
+ *
6
+ * @template T - The type of the exit result data
7
+ */
3
8
  export type ExitResult<T = unknown> = {
9
+ /** The Exit instance that was used to terminate execution */
4
10
  exit: Exit<T>;
11
+ /** The result data returned by the exit (validated against the exit's schema) */
5
12
  result: T;
6
13
  };
7
- export declare class Exit<T = unknown> {
14
+ export declare namespace Exit {
15
+ type JSON = {
16
+ name: string;
17
+ aliases: string[];
18
+ description: string;
19
+ metadata: Record<string, unknown>;
20
+ schema?: JSONSchema7;
21
+ };
22
+ }
23
+ /**
24
+ * Defines how LLMz agent execution can terminate.
25
+ *
26
+ * Exits are the primary mechanism for controlling how and when agent execution completes.
27
+ * They define the possible outcomes of an execution and provide type-safe result handling.
28
+ * When an agent calls `return { action: 'exit_name', ...data }`, the execution terminates
29
+ * with the corresponding Exit.
30
+ *
31
+ * ## Core Concepts
32
+ *
33
+ * **Termination Control**: Exits define the valid ways an agent execution can end.
34
+ * Unlike traditional functions that just return values, LLMz agents must explicitly
35
+ * exit through predefined exits, ensuring controlled and predictable termination.
36
+ *
37
+ * **Type Safety**: Each exit can define a Zod/Zui schema that validates the return data,
38
+ * providing compile-time and runtime type safety for execution results.
39
+ *
40
+ * **Flow Control**: Different exits allow for different execution paths and result
41
+ * handling, enabling complex decision-making and branching logic.
42
+ *
43
+ * **Built-in vs Custom**: LLMz provides built-in exits (ThinkExit, ListenExit, DefaultExit)
44
+ * for common patterns, while custom exits enable domain-specific termination logic.
45
+ *
46
+ * ## Usage Patterns
47
+ *
48
+ * ### Simple Exit (No Data)
49
+ *
50
+ * For basic flow control without additional data:
51
+ *
52
+ * ```typescript
53
+ * const exit = new Exit({
54
+ * name: 'exit',
55
+ * description: 'When the user wants to exit the program',
56
+ * })
57
+ *
58
+ * // Agent usage: return { action: 'exit' }
59
+ *
60
+ * // Result handling
61
+ * if (result.is(exit)) {
62
+ * console.log('User chose to exit')
63
+ * process.exit(0)
64
+ * }
65
+ * ```
66
+ *
67
+ * ### Exit with Schema (Typed Data)
68
+ *
69
+ * For structured data extraction with validation:
70
+ *
71
+ * ```typescript
72
+ * const escalation = new Exit({
73
+ * name: 'escalation',
74
+ * description: 'Escalate the issue to a human agent',
75
+ * schema: z.object({
76
+ * reason: z.enum(['Frustrated user', 'Technical issue', 'Sensitive topic', 'Other']),
77
+ * priority: z.enum(['low', 'medium', 'high']).default('medium'),
78
+ * details: z.string(),
79
+ * }),
80
+ * })
81
+ *
82
+ * // Agent usage: return { action: 'escalation', reason: 'Technical issue', details: '...' }
83
+ *
84
+ * // Type-safe result handling
85
+ * if (result.is(escalation)) {
86
+ * console.log(`Escalation: ${result.output.reason}`)
87
+ * console.log(`Priority: ${result.output.priority}`)
88
+ * console.log(`Details: ${result.output.details}`)
89
+ * }
90
+ * ```
91
+ *
92
+ * ### Multiple Exits for Decision Making
93
+ *
94
+ * Enabling different execution paths:
95
+ *
96
+ * ```typescript
97
+ * const approved = new Exit({
98
+ * name: 'approved',
99
+ * description: 'Request was approved',
100
+ * schema: z.object({
101
+ * amount: z.number(),
102
+ * reference: z.string(),
103
+ * }),
104
+ * })
105
+ *
106
+ * const rejected = new Exit({
107
+ * name: 'rejected',
108
+ * description: 'Request was rejected',
109
+ * schema: z.object({
110
+ * reason: z.string(),
111
+ * }),
112
+ * })
113
+ *
114
+ * const result = await execute({
115
+ * instructions: 'Process the loan application',
116
+ * exits: [approved, rejected],
117
+ * tools: [reviewTool, creditCheckTool],
118
+ * client,
119
+ * })
120
+ *
121
+ * if (result.is(approved)) {
122
+ * console.log(`Approved: $${result.output.amount} (${result.output.reference})`)
123
+ * } else if (result.is(rejected)) {
124
+ * console.log(`Rejected: ${result.output.reason}`)
125
+ * }
126
+ * ```
127
+ *
128
+ * ## Advanced Features
129
+ *
130
+ * ### Exit Aliases
131
+ *
132
+ * Multiple names for the same exit:
133
+ *
134
+ * ```typescript
135
+ * const exit = new Exit({
136
+ * name: 'complete',
137
+ * aliases: ['done', 'finished', 'end'],
138
+ * description: 'Task completed successfully',
139
+ * })
140
+ *
141
+ * // Agent can use any alias: return { action: 'done' } or { action: 'finished' }
142
+ * ```
143
+ *
144
+ * ### Exit Metadata for Orchestration
145
+ *
146
+ * Additional data for complex systems:
147
+ *
148
+ * ```typescript
149
+ * const handoff = new Exit({
150
+ * name: 'handoff_sales',
151
+ * description: 'Handoff to sales agent',
152
+ * metadata: {
153
+ * type: 'handoff',
154
+ * agent: 'sales',
155
+ * department: 'customer_service',
156
+ * },
157
+ * schema: z.object({
158
+ * reason: z.string(),
159
+ * context: z.record(z.any()),
160
+ * }),
161
+ * })
162
+ *
163
+ * // Use metadata in exit callbacks
164
+ * onExit: async (result) => {
165
+ * if (result.exit.metadata?.type === 'handoff') {
166
+ * await routeToAgent(result.exit.metadata.agent, result.result)
167
+ * }
168
+ * }
169
+ * ```
170
+ *
171
+ * ### Exit Callbacks and Hooks
172
+ *
173
+ * Custom logic when exits are triggered:
174
+ *
175
+ * ```typescript
176
+ * const result = await execute({
177
+ * instructions: 'Process customer request',
178
+ * exits: [approved, rejected],
179
+ * onExit: async (exitResult) => {
180
+ * // Called before execution completes
181
+ * await logOutcome(exitResult.exit.name, exitResult.result)
182
+ *
183
+ * // Can throw to prevent exit and force retry
184
+ * if (needsManagerApproval(exitResult)) {
185
+ * throw new Error('Manager approval required')
186
+ * }
187
+ * },
188
+ * client,
189
+ * })
190
+ * ```
191
+ *
192
+ * ## Exit Cloning and Modification
193
+ *
194
+ * Create variations of existing exits:
195
+ *
196
+ * ```typescript
197
+ * const baseExit = new Exit({
198
+ * name: 'base',
199
+ * description: 'Base exit',
200
+ * schema: z.object({ status: z.string() }),
201
+ * })
202
+ *
203
+ * const customExit = baseExit.clone().rename('custom')
204
+ * // Creates independent copy with new name
205
+ * ```
206
+ *
207
+ * ## Best Practices
208
+ *
209
+ * 1. **Descriptive Names**: Use clear, action-oriented names that describe the outcome
210
+ * 2. **Comprehensive Schemas**: Define complete data structures with descriptions
211
+ * 3. **Multiple Exits**: Design multiple exits for different execution paths
212
+ * 4. **Type Safety**: Always use `result.is(exit)` for type-safe result handling
213
+ * 5. **Documentation**: Provide clear descriptions for both the exit and schema fields
214
+ * 6. **Validation**: Use Zod's validation features (enums, constraints, defaults)
215
+ *
216
+ * @template T - The type of data this exit returns (inferred from schema)
217
+ *
218
+ * @see {@link ExecutionResult} For result handling
219
+ * @see {@link ThinkExit} Built-in thinking exit
220
+ * @see {@link ListenExit} Built-in chat listening exit
221
+ * @see {@link DefaultExit} Built-in completion exit
222
+ */
223
+ export declare class Exit<T = unknown> implements Serializable<Exit.JSON> {
224
+ /** The primary name of the exit (used in return statements) */
8
225
  name: string;
226
+ /** Alternative names that can be used to reference this exit */
9
227
  aliases: string[];
228
+ /** Human-readable description of when this exit should be used */
10
229
  description: string;
230
+ /** Additional metadata for orchestration and custom logic */
11
231
  metadata: Record<string, unknown>;
232
+ /** JSON Schema for validating exit result data */
12
233
  schema?: JSONSchema7;
234
+ /**
235
+ * Returns the Zod schema equivalent of the JSON schema (if available).
236
+ * Used internally for validation and type inference.
237
+ */
13
238
  get zSchema(): import("@bpinternal/zui").ZodTypeAny | undefined;
239
+ /**
240
+ * Renames the exit and updates aliases accordingly.
241
+ *
242
+ * @param name - The new name for the exit (must be a valid identifier)
243
+ * @returns This exit instance for chaining
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * const exit = new Exit({ name: 'old_name', description: 'Test exit' })
248
+ * exit.rename('new_name')
249
+ * console.log(exit.name) // 'new_name'
250
+ * ```
251
+ */
14
252
  rename(name: string): this;
253
+ /**
254
+ * Creates a deep copy of this exit.
255
+ *
256
+ * The clone is completely independent and can be modified without affecting
257
+ * the original exit. This is useful for creating variations of existing exits.
258
+ *
259
+ * @returns A new Exit instance with the same configuration
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * const originalExit = new Exit({
264
+ * name: 'base',
265
+ * description: 'Base exit',
266
+ * schema: z.object({ status: z.string() }),
267
+ * })
268
+ *
269
+ * const customExit = originalExit.clone().rename('custom')
270
+ * // customExit is independent of originalExit
271
+ * ```
272
+ */
15
273
  clone(): Exit<any>;
274
+ /**
275
+ * Type guard to check if this exit matches another exit by name.
276
+ *
277
+ * Used internally for type narrowing and exit comparison.
278
+ *
279
+ * @param exit - The exit to compare against
280
+ * @returns True if the exits have the same name
281
+ */
16
282
  is<T>(exit: Exit<T>): this is Exit<T>;
283
+ /**
284
+ * Type guard to check if an ExitResult matches this exit.
285
+ *
286
+ * @param result - The exit result to check
287
+ * @returns True if the result was created by this exit
288
+ */
17
289
  match(result: ExitResult): result is ExitResult<T>;
290
+ /**
291
+ * Serializes this exit to a JSON-compatible object.
292
+ *
293
+ * @returns JSON representation of the exit
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * const exit = new Exit({
298
+ * name: 'complete',
299
+ * description: 'Task completed successfully',
300
+ * })
301
+ *
302
+ * console.log(exit.toJSON())
303
+ * // { name: 'complete', aliases: [], description: 'Task completed successfully', metadata: {}, schema: undefined }
304
+ * ```
305
+ */
306
+ toJSON(): {
307
+ name: string;
308
+ aliases: string[];
309
+ description: string;
310
+ metadata: {
311
+ [x: string]: unknown;
312
+ };
313
+ schema: JSONSchema7 | undefined;
314
+ };
315
+ /**
316
+ * Creates a new Exit instance.
317
+ *
318
+ * @param props - Exit configuration
319
+ * @param props.name - Primary name for the exit (must be valid identifier)
320
+ * @param props.description - Human-readable description of the exit's purpose
321
+ * @param props.aliases - Alternative names that can be used to reference this exit
322
+ * @param props.metadata - Additional data for orchestration and custom logic
323
+ * @param props.schema - Zod schema for validating exit result data
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * // Simple exit without data validation
328
+ * const exit = new Exit({
329
+ * name: 'complete',
330
+ * description: 'Task completed successfully',
331
+ * })
332
+ * ```
333
+ *
334
+ * @example
335
+ * ```typescript
336
+ * // Exit with typed result data
337
+ * const approval = new Exit({
338
+ * name: 'approved',
339
+ * description: 'Request approved by system',
340
+ * schema: z.object({
341
+ * amount: z.number().positive(),
342
+ * reference: z.string().min(1),
343
+ * timestamp: z.date().default(() => new Date()),
344
+ * }),
345
+ * })
346
+ * ```
347
+ *
348
+ * @example
349
+ * ```typescript
350
+ * // Exit with aliases and metadata
351
+ * const handoff = new Exit({
352
+ * name: 'handoff_support',
353
+ * aliases: ['escalate', 'transfer'],
354
+ * description: 'Transfer to human support agent',
355
+ * metadata: {
356
+ * department: 'customer_service',
357
+ * priority: 'high',
358
+ * },
359
+ * schema: z.object({
360
+ * reason: z.string(),
361
+ * customerData: z.record(z.any()),
362
+ * }),
363
+ * })
364
+ * ```
365
+ */
18
366
  constructor(props: {
19
367
  name: string;
20
368
  aliases?: string[];
@@ -22,5 +370,24 @@ export declare class Exit<T = unknown> {
22
370
  metadata?: Record<string, unknown>;
23
371
  schema?: ZuiType<T>;
24
372
  });
373
+ /**
374
+ * Ensures all exits in an array have unique names by renaming duplicates.
375
+ *
376
+ * When multiple exits have the same name, this method appends numbers to
377
+ * create unique names (e.g., 'exit1', 'exit2'). This prevents naming conflicts
378
+ * in execution contexts with multiple exits.
379
+ *
380
+ * @param exits - Array of exits that may have duplicate names
381
+ * @returns Array of exits with guaranteed unique names
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * const exit1 = new Exit({ name: 'done', description: 'First done' })
386
+ * const exit2 = new Exit({ name: 'done', description: 'Second done' })
387
+ *
388
+ * const uniqueExits = Exit.withUniqueNames([exit1, exit2])
389
+ * // Result: [{ name: 'done' }, { name: 'done1' }]
390
+ * ```
391
+ */
25
392
  static withUniqueNames: (exits: Exit[]) => Exit<unknown>[];
26
393
  }