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.
package/dist/exit.d.ts CHANGED
@@ -1,20 +1,334 @@
1
1
  import { JSONSchema7 } from 'json-schema';
2
2
  import { 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
  };
14
+ /**
15
+ * Defines how LLMz agent execution can terminate.
16
+ *
17
+ * Exits are the primary mechanism for controlling how and when agent execution completes.
18
+ * They define the possible outcomes of an execution and provide type-safe result handling.
19
+ * When an agent calls `return { action: 'exit_name', ...data }`, the execution terminates
20
+ * with the corresponding Exit.
21
+ *
22
+ * ## Core Concepts
23
+ *
24
+ * **Termination Control**: Exits define the valid ways an agent execution can end.
25
+ * Unlike traditional functions that just return values, LLMz agents must explicitly
26
+ * exit through predefined exits, ensuring controlled and predictable termination.
27
+ *
28
+ * **Type Safety**: Each exit can define a Zod/Zui schema that validates the return data,
29
+ * providing compile-time and runtime type safety for execution results.
30
+ *
31
+ * **Flow Control**: Different exits allow for different execution paths and result
32
+ * handling, enabling complex decision-making and branching logic.
33
+ *
34
+ * **Built-in vs Custom**: LLMz provides built-in exits (ThinkExit, ListenExit, DefaultExit)
35
+ * for common patterns, while custom exits enable domain-specific termination logic.
36
+ *
37
+ * ## Usage Patterns
38
+ *
39
+ * ### Simple Exit (No Data)
40
+ *
41
+ * For basic flow control without additional data:
42
+ *
43
+ * ```typescript
44
+ * const exit = new Exit({
45
+ * name: 'exit',
46
+ * description: 'When the user wants to exit the program',
47
+ * })
48
+ *
49
+ * // Agent usage: return { action: 'exit' }
50
+ *
51
+ * // Result handling
52
+ * if (result.is(exit)) {
53
+ * console.log('User chose to exit')
54
+ * process.exit(0)
55
+ * }
56
+ * ```
57
+ *
58
+ * ### Exit with Schema (Typed Data)
59
+ *
60
+ * For structured data extraction with validation:
61
+ *
62
+ * ```typescript
63
+ * const escalation = new Exit({
64
+ * name: 'escalation',
65
+ * description: 'Escalate the issue to a human agent',
66
+ * schema: z.object({
67
+ * reason: z.enum(['Frustrated user', 'Technical issue', 'Sensitive topic', 'Other']),
68
+ * priority: z.enum(['low', 'medium', 'high']).default('medium'),
69
+ * details: z.string(),
70
+ * }),
71
+ * })
72
+ *
73
+ * // Agent usage: return { action: 'escalation', reason: 'Technical issue', details: '...' }
74
+ *
75
+ * // Type-safe result handling
76
+ * if (result.is(escalation)) {
77
+ * console.log(`Escalation: ${result.output.reason}`)
78
+ * console.log(`Priority: ${result.output.priority}`)
79
+ * console.log(`Details: ${result.output.details}`)
80
+ * }
81
+ * ```
82
+ *
83
+ * ### Multiple Exits for Decision Making
84
+ *
85
+ * Enabling different execution paths:
86
+ *
87
+ * ```typescript
88
+ * const approved = new Exit({
89
+ * name: 'approved',
90
+ * description: 'Request was approved',
91
+ * schema: z.object({
92
+ * amount: z.number(),
93
+ * reference: z.string(),
94
+ * }),
95
+ * })
96
+ *
97
+ * const rejected = new Exit({
98
+ * name: 'rejected',
99
+ * description: 'Request was rejected',
100
+ * schema: z.object({
101
+ * reason: z.string(),
102
+ * }),
103
+ * })
104
+ *
105
+ * const result = await execute({
106
+ * instructions: 'Process the loan application',
107
+ * exits: [approved, rejected],
108
+ * tools: [reviewTool, creditCheckTool],
109
+ * client,
110
+ * })
111
+ *
112
+ * if (result.is(approved)) {
113
+ * console.log(`Approved: $${result.output.amount} (${result.output.reference})`)
114
+ * } else if (result.is(rejected)) {
115
+ * console.log(`Rejected: ${result.output.reason}`)
116
+ * }
117
+ * ```
118
+ *
119
+ * ## Advanced Features
120
+ *
121
+ * ### Exit Aliases
122
+ *
123
+ * Multiple names for the same exit:
124
+ *
125
+ * ```typescript
126
+ * const exit = new Exit({
127
+ * name: 'complete',
128
+ * aliases: ['done', 'finished', 'end'],
129
+ * description: 'Task completed successfully',
130
+ * })
131
+ *
132
+ * // Agent can use any alias: return { action: 'done' } or { action: 'finished' }
133
+ * ```
134
+ *
135
+ * ### Exit Metadata for Orchestration
136
+ *
137
+ * Additional data for complex systems:
138
+ *
139
+ * ```typescript
140
+ * const handoff = new Exit({
141
+ * name: 'handoff_sales',
142
+ * description: 'Handoff to sales agent',
143
+ * metadata: {
144
+ * type: 'handoff',
145
+ * agent: 'sales',
146
+ * department: 'customer_service',
147
+ * },
148
+ * schema: z.object({
149
+ * reason: z.string(),
150
+ * context: z.record(z.any()),
151
+ * }),
152
+ * })
153
+ *
154
+ * // Use metadata in exit callbacks
155
+ * onExit: async (result) => {
156
+ * if (result.exit.metadata?.type === 'handoff') {
157
+ * await routeToAgent(result.exit.metadata.agent, result.result)
158
+ * }
159
+ * }
160
+ * ```
161
+ *
162
+ * ### Exit Callbacks and Hooks
163
+ *
164
+ * Custom logic when exits are triggered:
165
+ *
166
+ * ```typescript
167
+ * const result = await execute({
168
+ * instructions: 'Process customer request',
169
+ * exits: [approved, rejected],
170
+ * onExit: async (exitResult) => {
171
+ * // Called before execution completes
172
+ * await logOutcome(exitResult.exit.name, exitResult.result)
173
+ *
174
+ * // Can throw to prevent exit and force retry
175
+ * if (needsManagerApproval(exitResult)) {
176
+ * throw new Error('Manager approval required')
177
+ * }
178
+ * },
179
+ * client,
180
+ * })
181
+ * ```
182
+ *
183
+ * ## Exit Cloning and Modification
184
+ *
185
+ * Create variations of existing exits:
186
+ *
187
+ * ```typescript
188
+ * const baseExit = new Exit({
189
+ * name: 'base',
190
+ * description: 'Base exit',
191
+ * schema: z.object({ status: z.string() }),
192
+ * })
193
+ *
194
+ * const customExit = baseExit.clone().rename('custom')
195
+ * // Creates independent copy with new name
196
+ * ```
197
+ *
198
+ * ## Best Practices
199
+ *
200
+ * 1. **Descriptive Names**: Use clear, action-oriented names that describe the outcome
201
+ * 2. **Comprehensive Schemas**: Define complete data structures with descriptions
202
+ * 3. **Multiple Exits**: Design multiple exits for different execution paths
203
+ * 4. **Type Safety**: Always use `result.is(exit)` for type-safe result handling
204
+ * 5. **Documentation**: Provide clear descriptions for both the exit and schema fields
205
+ * 6. **Validation**: Use Zod's validation features (enums, constraints, defaults)
206
+ *
207
+ * @template T - The type of data this exit returns (inferred from schema)
208
+ *
209
+ * @see {@link ExecutionResult} For result handling
210
+ * @see {@link ThinkExit} Built-in thinking exit
211
+ * @see {@link ListenExit} Built-in chat listening exit
212
+ * @see {@link DefaultExit} Built-in completion exit
213
+ */
7
214
  export declare class Exit<T = unknown> {
215
+ /** The primary name of the exit (used in return statements) */
8
216
  name: string;
217
+ /** Alternative names that can be used to reference this exit */
9
218
  aliases: string[];
219
+ /** Human-readable description of when this exit should be used */
10
220
  description: string;
221
+ /** Additional metadata for orchestration and custom logic */
11
222
  metadata: Record<string, unknown>;
223
+ /** JSON Schema for validating exit result data */
12
224
  schema?: JSONSchema7;
225
+ /**
226
+ * Returns the Zod schema equivalent of the JSON schema (if available).
227
+ * Used internally for validation and type inference.
228
+ */
13
229
  get zSchema(): import("@bpinternal/zui").ZodTypeAny | undefined;
230
+ /**
231
+ * Renames the exit and updates aliases accordingly.
232
+ *
233
+ * @param name - The new name for the exit (must be a valid identifier)
234
+ * @returns This exit instance for chaining
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * const exit = new Exit({ name: 'old_name', description: 'Test exit' })
239
+ * exit.rename('new_name')
240
+ * console.log(exit.name) // 'new_name'
241
+ * ```
242
+ */
14
243
  rename(name: string): this;
244
+ /**
245
+ * Creates a deep copy of this exit.
246
+ *
247
+ * The clone is completely independent and can be modified without affecting
248
+ * the original exit. This is useful for creating variations of existing exits.
249
+ *
250
+ * @returns A new Exit instance with the same configuration
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * const originalExit = new Exit({
255
+ * name: 'base',
256
+ * description: 'Base exit',
257
+ * schema: z.object({ status: z.string() }),
258
+ * })
259
+ *
260
+ * const customExit = originalExit.clone().rename('custom')
261
+ * // customExit is independent of originalExit
262
+ * ```
263
+ */
15
264
  clone(): Exit<any>;
265
+ /**
266
+ * Type guard to check if this exit matches another exit by name.
267
+ *
268
+ * Used internally for type narrowing and exit comparison.
269
+ *
270
+ * @param exit - The exit to compare against
271
+ * @returns True if the exits have the same name
272
+ */
16
273
  is<T>(exit: Exit<T>): this is Exit<T>;
274
+ /**
275
+ * Type guard to check if an ExitResult matches this exit.
276
+ *
277
+ * @param result - The exit result to check
278
+ * @returns True if the result was created by this exit
279
+ */
17
280
  match(result: ExitResult): result is ExitResult<T>;
281
+ /**
282
+ * Creates a new Exit instance.
283
+ *
284
+ * @param props - Exit configuration
285
+ * @param props.name - Primary name for the exit (must be valid identifier)
286
+ * @param props.description - Human-readable description of the exit's purpose
287
+ * @param props.aliases - Alternative names that can be used to reference this exit
288
+ * @param props.metadata - Additional data for orchestration and custom logic
289
+ * @param props.schema - Zod schema for validating exit result data
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * // Simple exit without data validation
294
+ * const exit = new Exit({
295
+ * name: 'complete',
296
+ * description: 'Task completed successfully',
297
+ * })
298
+ * ```
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * // Exit with typed result data
303
+ * const approval = new Exit({
304
+ * name: 'approved',
305
+ * description: 'Request approved by system',
306
+ * schema: z.object({
307
+ * amount: z.number().positive(),
308
+ * reference: z.string().min(1),
309
+ * timestamp: z.date().default(() => new Date()),
310
+ * }),
311
+ * })
312
+ * ```
313
+ *
314
+ * @example
315
+ * ```typescript
316
+ * // Exit with aliases and metadata
317
+ * const handoff = new Exit({
318
+ * name: 'handoff_support',
319
+ * aliases: ['escalate', 'transfer'],
320
+ * description: 'Transfer to human support agent',
321
+ * metadata: {
322
+ * department: 'customer_service',
323
+ * priority: 'high',
324
+ * },
325
+ * schema: z.object({
326
+ * reason: z.string(),
327
+ * customerData: z.record(z.any()),
328
+ * }),
329
+ * })
330
+ * ```
331
+ */
18
332
  constructor(props: {
19
333
  name: string;
20
334
  aliases?: string[];
@@ -22,5 +336,24 @@ export declare class Exit<T = unknown> {
22
336
  metadata?: Record<string, unknown>;
23
337
  schema?: ZuiType<T>;
24
338
  });
339
+ /**
340
+ * Ensures all exits in an array have unique names by renaming duplicates.
341
+ *
342
+ * When multiple exits have the same name, this method appends numbers to
343
+ * create unique names (e.g., 'exit1', 'exit2'). This prevents naming conflicts
344
+ * in execution contexts with multiple exits.
345
+ *
346
+ * @param exits - Array of exits that may have duplicate names
347
+ * @returns Array of exits with guaranteed unique names
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * const exit1 = new Exit({ name: 'done', description: 'First done' })
352
+ * const exit2 = new Exit({ name: 'done', description: 'Second done' })
353
+ *
354
+ * const uniqueExits = Exit.withUniqueNames([exit1, exit2])
355
+ * // Result: [{ name: 'done' }, { name: 'done1' }]
356
+ * ```
357
+ */
25
358
  static withUniqueNames: (exits: Exit[]) => Exit<unknown>[];
26
359
  }
package/dist/index.cjs CHANGED
@@ -8,11 +8,11 @@
8
8
 
9
9
 
10
10
 
11
- var _chunkHJKOSEH2cjs = require('./chunk-HJKOSEH2.cjs');
11
+ var _chunkGOJY4GRLcjs = require('./chunk-GOJY4GRL.cjs');
12
12
  require('./chunk-SHJDRZF5.cjs');
13
13
 
14
14
 
15
- var _chunkC6WNNTEVcjs = require('./chunk-C6WNNTEV.cjs');
15
+ var _chunkKG7DT7WDcjs = require('./chunk-KG7DT7WD.cjs');
16
16
 
17
17
 
18
18
 
@@ -26,7 +26,7 @@ var _chunkJDABP4SDcjs = require('./chunk-JDABP4SD.cjs');
26
26
  require('./chunk-IKSIOIIP.cjs');
27
27
 
28
28
 
29
- var _chunkGWFYZDURcjs = require('./chunk-GWFYZDUR.cjs');
29
+ var _chunkWL7ZIMYDcjs = require('./chunk-WL7ZIMYD.cjs');
30
30
 
31
31
 
32
32
 
@@ -307,6 +307,62 @@ var ObjectInstance = class {
307
307
 
308
308
 
309
309
 
310
+ /**
311
+ * Creates a new ObjectInstance.
312
+ *
313
+ * @param props - Object configuration
314
+ * @param props.name - Unique object name (must be valid TypeScript identifier)
315
+ * @param props.description - Human-readable description of the object
316
+ * @param props.tools - Array of tools to group under this object namespace
317
+ * @param props.properties - Array of stateful properties for this object
318
+ * @param props.metadata - Additional metadata for the object
319
+ *
320
+ * @throws Error if name is not a valid identifier
321
+ * @throws Error if description is not a string
322
+ * @throws Error if metadata is not an object
323
+ * @throws Error if properties/tools are not arrays
324
+ * @throws Error if properties exceed 100 limit
325
+ * @throws Error if property names are duplicated or invalid
326
+ * @throws Error if property descriptions exceed 5000 characters
327
+ *
328
+ * @example
329
+ * ```typescript
330
+ * const userProfile = new ObjectInstance({
331
+ * name: 'user',
332
+ * description: 'User profile management',
333
+ * properties: [
334
+ * {
335
+ * name: 'name',
336
+ * value: 'John Doe',
337
+ * type: z.string().min(1),
338
+ * description: 'User full name',
339
+ * writable: true,
340
+ * },
341
+ * {
342
+ * name: 'email',
343
+ * value: null,
344
+ * type: z.string().email().nullable(),
345
+ * description: 'User email address',
346
+ * writable: true,
347
+ * },
348
+ * ],
349
+ * tools: [
350
+ * new Tool({
351
+ * name: 'updateProfile',
352
+ * input: z.object({ name: z.string(), email: z.string() }),
353
+ * handler: async ({ name, email }) => {
354
+ * // Update external system
355
+ * await updateUserInDatabase({ name, email })
356
+ * },
357
+ * }),
358
+ * ],
359
+ * metadata: {
360
+ * version: '1.0',
361
+ * category: 'user-management',
362
+ * },
363
+ * })
364
+ * ```
365
+ */
310
366
  constructor(props) {
311
367
  var _a;
312
368
  if (!_chunk276Q6EWPcjs.isValidIdentifier.call(void 0, props.name)) {
@@ -366,8 +422,45 @@ var ObjectInstance = class {
366
422
  this.description = props.description;
367
423
  this.metadata = _nullishCoalesce(props.metadata, () => ( {}));
368
424
  this.properties = props.properties;
369
- this.tools = _chunkC6WNNTEVcjs.Tool.withUniqueNames(_nullishCoalesce(props.tools, () => ( [])));
425
+ this.tools = _chunkKG7DT7WDcjs.Tool.withUniqueNames(_nullishCoalesce(props.tools, () => ( [])));
370
426
  }
427
+ /**
428
+ * Generates TypeScript namespace declarations for this object.
429
+ *
430
+ * This method creates TypeScript definitions that are included in the LLM context
431
+ * to help it understand the available properties and tools. Properties become
432
+ * const declarations with appropriate Readonly/Writable types, and tools become
433
+ * function signatures.
434
+ *
435
+ * @returns Promise resolving to TypeScript namespace declaration
436
+ *
437
+ * @example
438
+ * ```typescript
439
+ * const obj = new ObjectInstance({
440
+ * name: 'user',
441
+ * properties: [
442
+ * { name: 'name', value: 'John', writable: true },
443
+ * { name: 'id', value: 123, writable: false },
444
+ * ],
445
+ * tools: [
446
+ * new Tool({
447
+ * name: 'save',
448
+ * input: z.object({ data: z.string() }),
449
+ * handler: async ({ data }) => { /* ... *\/ },
450
+ * }),
451
+ * ],
452
+ * })
453
+ *
454
+ * const typings = await obj.getTypings()
455
+ * console.log(typings)
456
+ * // Output:
457
+ * // export namespace user {
458
+ * // const name: Writable<string> = "John"
459
+ * // const id: Readonly<number> = 123
460
+ * // function save(args: { data: string }): Promise<void>
461
+ * // }
462
+ * ```
463
+ */
371
464
  async getTypings() {
372
465
  return getObjectTypings(this).withProperties().withTools().build();
373
466
  }
@@ -866,25 +959,129 @@ var Chat = class {
866
959
 
867
960
 
868
961
 
962
+ /**
963
+ * Creates a new Chat instance.
964
+ *
965
+ * @param props - Chat configuration
966
+ * @param props.handler - Function to handle agent messages (called for every agent output)
967
+ * @param props.components - Available UI components (static array or dynamic function)
968
+ * @param props.transcript - Conversation history (static array or dynamic function, defaults to empty)
969
+ *
970
+ * @example
971
+ * ```typescript
972
+ * // Basic chat with static configuration
973
+ * const chat = new Chat({
974
+ * handler: async (input) => {
975
+ * if (isComponent(input, DefaultComponents.Text)) {
976
+ * console.log('Agent:', input.children.join(''))
977
+ * }
978
+ * },
979
+ * components: [DefaultComponents.Text, DefaultComponents.Button],
980
+ * transcript: [
981
+ * { role: 'user', content: 'Hello', timestamp: Date.now() }
982
+ * ],
983
+ * })
984
+ * ```
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * // Dynamic chat with functions for real-time updates
989
+ * class MyChat extends Chat {
990
+ * private messages: Transcript.Message[] = []
991
+ *
992
+ * constructor() {
993
+ * super({
994
+ * handler: (input) => this.handleMessage(input),
995
+ *
996
+ * // Dynamic components - can change during execution
997
+ * components: () => [
998
+ * DefaultComponents.Text,
999
+ * DefaultComponents.Button,
1000
+ * ...this.getCustomComponents()
1001
+ * ],
1002
+ *
1003
+ * // Dynamic transcript - always reflects current state
1004
+ * transcript: () => this.messages,
1005
+ * })
1006
+ * }
1007
+ * }
1008
+ * ```
1009
+ */
869
1010
  constructor(props) {
870
1011
  this.handler = props.handler;
871
1012
  this.components = props.components;
872
1013
  this.transcript = props.transcript || [];
873
1014
  }
1015
+ /**
1016
+ * Called when an execution cycle completes, regardless of the outcome.
1017
+ *
1018
+ * Override this method to handle execution results, manage conversation flow,
1019
+ * or perform cleanup tasks. This is called after each `execute()` call completes,
1020
+ * whether it succeeds, fails, or is interrupted.
1021
+ *
1022
+ * @param result - The execution result containing status, iterations, and exit information
1023
+ *
1024
+ * @example
1025
+ * ```typescript
1026
+ * class MyChat extends Chat {
1027
+ * public result?: ExecutionResult
1028
+ *
1029
+ * onExecutionDone(result: ExecutionResult) {
1030
+ * // Store result for conversation flow control
1031
+ * this.result = result
1032
+ *
1033
+ * // Handle different result types
1034
+ * if (result.isSuccess()) {
1035
+ * console.log('✅ Execution completed successfully')
1036
+ * console.log('Exit:', result.output.exit_name)
1037
+ * } else if (result.isError()) {
1038
+ * console.error('❌ Execution failed:', result.output.error)
1039
+ * } else if (result.isInterrupted()) {
1040
+ * console.log('⏸️ Execution interrupted (partial result)')
1041
+ * }
1042
+ * }
1043
+ *
1044
+ * // Use stored result for conversation flow
1045
+ * isWaitingForInput(): boolean {
1046
+ * return this.result?.is(ListenExit) ?? false
1047
+ * }
1048
+ * }
1049
+ * ```
1050
+ *
1051
+ * @example
1052
+ * ```typescript
1053
+ * // CLIChat implementation example
1054
+ * class CLIChat extends Chat {
1055
+ * public status?: IterationStatus
1056
+ * public result?: ExecutionResult
1057
+ *
1058
+ * onExecutionDone(result: ExecutionResult) {
1059
+ * this.result = result
1060
+ * this.status = result.iterations.at(-1)?.status
1061
+ * }
1062
+ *
1063
+ * // Check if agent exited with specific exit type
1064
+ * hasExitedWith<R>(exit: Exit<R>): boolean {
1065
+ * return this.status?.type === 'exit_success' &&
1066
+ * this.status.exit_success.exit_name === exit.name
1067
+ * }
1068
+ * }
1069
+ * ```
1070
+ */
874
1071
  onExecutionDone(_result) {
875
1072
  }
876
1073
  };
877
1074
 
878
1075
  // src/index.ts
879
1076
  var execute = async (props) => {
880
- const { executeContext } = await Promise.resolve().then(() => _interopRequireWildcard(require("./llmz-QLZBDG2Z.cjs")));
1077
+ const { executeContext } = await Promise.resolve().then(() => _interopRequireWildcard(require("./llmz-TR4CQK4F.cjs")));
881
1078
  return executeContext(props);
882
1079
  };
883
1080
  var init = async () => {
884
- await Promise.resolve().then(() => _interopRequireWildcard(require("./llmz-QLZBDG2Z.cjs")));
1081
+ await Promise.resolve().then(() => _interopRequireWildcard(require("./llmz-TR4CQK4F.cjs")));
885
1082
  await Promise.resolve().then(() => _interopRequireWildcard(require("./component-R4WTW6DZ.cjs")));
886
- await Promise.resolve().then(() => _interopRequireWildcard(require("./tool-QP4MVRWI.cjs")));
887
- await Promise.resolve().then(() => _interopRequireWildcard(require("./exit-TRXEU4OU.cjs")));
1083
+ await Promise.resolve().then(() => _interopRequireWildcard(require("./tool-NS7EGK7Z.cjs")));
1084
+ await Promise.resolve().then(() => _interopRequireWildcard(require("./exit-O2WZUEFS.cjs")));
888
1085
  await Promise.resolve().then(() => _interopRequireWildcard(require("./jsx-AJAXBWFE.cjs")));
889
1086
  await Promise.resolve().then(() => _interopRequireWildcard(require("./vm-2DLG7V4G.cjs")));
890
1087
  await Promise.resolve().then(() => _interopRequireWildcard(require("./utils-A7WNEFTA.cjs")));
@@ -918,4 +1115,4 @@ var init = async () => {
918
1115
 
919
1116
 
920
1117
 
921
- exports.Chat = Chat; exports.CitationsManager = CitationsManager; exports.Component = _chunkZRCU35UVcjs.Component; exports.DefaultComponents = DefaultComponents; exports.DefaultExit = _chunkHJKOSEH2cjs.DefaultExit; exports.ErrorExecutionResult = _chunkHJKOSEH2cjs.ErrorExecutionResult; exports.ExecutionResult = _chunkHJKOSEH2cjs.ExecutionResult; exports.Exit = _chunkGWFYZDURcjs.Exit; exports.ListenExit = _chunkHJKOSEH2cjs.ListenExit; exports.LoopExceededError = _chunkJDABP4SDcjs.LoopExceededError; exports.ObjectInstance = ObjectInstance; exports.PartialExecutionResult = _chunkHJKOSEH2cjs.PartialExecutionResult; exports.Snapshot = _chunkHJKOSEH2cjs.Snapshot; exports.SnapshotSignal = _chunkJDABP4SDcjs.SnapshotSignal; exports.SuccessExecutionResult = _chunkHJKOSEH2cjs.SuccessExecutionResult; exports.ThinkExit = _chunkHJKOSEH2cjs.ThinkExit; exports.ThinkSignal = _chunkJDABP4SDcjs.ThinkSignal; exports.Tool = _chunkC6WNNTEVcjs.Tool; exports.assertValidComponent = _chunkZRCU35UVcjs.assertValidComponent; exports.execute = execute; exports.getValue = _chunkHJKOSEH2cjs.getValue; exports.init = init; exports.isAnyComponent = _chunkZRCU35UVcjs.isAnyComponent; exports.isComponent = _chunkZRCU35UVcjs.isComponent; exports.renderToTsx = _chunkZRCU35UVcjs.renderToTsx;
1118
+ exports.Chat = Chat; exports.CitationsManager = CitationsManager; exports.Component = _chunkZRCU35UVcjs.Component; exports.DefaultComponents = DefaultComponents; exports.DefaultExit = _chunkGOJY4GRLcjs.DefaultExit; exports.ErrorExecutionResult = _chunkGOJY4GRLcjs.ErrorExecutionResult; exports.ExecutionResult = _chunkGOJY4GRLcjs.ExecutionResult; exports.Exit = _chunkWL7ZIMYDcjs.Exit; exports.ListenExit = _chunkGOJY4GRLcjs.ListenExit; exports.LoopExceededError = _chunkJDABP4SDcjs.LoopExceededError; exports.ObjectInstance = ObjectInstance; exports.PartialExecutionResult = _chunkGOJY4GRLcjs.PartialExecutionResult; exports.Snapshot = _chunkGOJY4GRLcjs.Snapshot; exports.SnapshotSignal = _chunkJDABP4SDcjs.SnapshotSignal; exports.SuccessExecutionResult = _chunkGOJY4GRLcjs.SuccessExecutionResult; exports.ThinkExit = _chunkGOJY4GRLcjs.ThinkExit; exports.ThinkSignal = _chunkJDABP4SDcjs.ThinkSignal; exports.Tool = _chunkKG7DT7WDcjs.Tool; exports.assertValidComponent = _chunkZRCU35UVcjs.assertValidComponent; exports.execute = execute; exports.getValue = _chunkGOJY4GRLcjs.getValue; exports.init = init; exports.isAnyComponent = _chunkZRCU35UVcjs.isAnyComponent; exports.isComponent = _chunkZRCU35UVcjs.isComponent; exports.renderToTsx = _chunkZRCU35UVcjs.renderToTsx;
package/dist/index.d.ts CHANGED
@@ -14,6 +14,68 @@ export { ErrorExecutionResult, ExecutionResult, PartialExecutionResult, SuccessE
14
14
  export { Trace } from './types.js';
15
15
  export { type Iteration, ListenExit, ThinkExit, DefaultExit, IterationStatuses, IterationStatus } from './context.js';
16
16
  export { type ValueOrGetter, getValue } from './getter.js';
17
+ /**
18
+ * Executes an LLMz agent in either Chat Mode or Worker Mode.
19
+ *
20
+ * LLMz is a code-first AI agent framework that generates and runs TypeScript code
21
+ * in a sandbox rather than using traditional JSON tool calling. This enables complex
22
+ * logic, multi-tool orchestration, and native LLM thinking via comments and code structure.
23
+ *
24
+ * @param props - Configuration object for the execution
25
+ * @param props.client - Botpress Client or Cognitive Client instance for LLM generation
26
+ * @param props.instructions - System prompt/instructions for the LLM (static string or dynamic function)
27
+ * @param props.chat - Optional Chat instance to enable Chat Mode with user interaction
28
+ * @param props.tools - Array of Tool instances available to the agent (static or dynamic)
29
+ * @param props.objects - Array of ObjectInstance for namespaced tools and variables (static or dynamic)
30
+ * @param props.exits - Array of Exit definitions for structured completion (static or dynamic)
31
+ * @param props.snapshot - Optional Snapshot to resume paused execution
32
+ * @param props.signal - Optional AbortSignal to cancel execution
33
+ * @param props.options - Optional execution options (loop limit, temperature, model, timeout)
34
+ * @param props.onTrace - Optional non-blocking hook for monitoring traces during execution
35
+ * @param props.onIterationEnd - Optional blocking hook called after each iteration
36
+ * @param props.onExit - Optional blocking hook called when an exit is reached (can prevent exit)
37
+ * @param props.onBeforeExecution - Optional blocking hook to modify code before VM execution
38
+ * @param props.onBeforeTool - Optional blocking hook to modify tool inputs before execution
39
+ * @param props.onAfterTool - Optional blocking hook to modify tool outputs after execution
40
+ *
41
+ * @returns Promise<ExecutionResult> - Result containing success/error/interrupted status with type-safe exit checking
42
+ *
43
+ * @example
44
+ * // Worker Mode - Automated execution
45
+ * const result = await execute({
46
+ * client: cognitiveClient,
47
+ * instructions: 'Calculate the sum of numbers 1 to 100',
48
+ * exits: [myExit]
49
+ * })
50
+ *
51
+ * if (result.is(myExit)) {
52
+ * console.log('Result:', result.output)
53
+ * }
54
+ *
55
+ * @example
56
+ * // Chat Mode - Interactive conversation
57
+ * const result = await execute({
58
+ * client: cognitiveClient,
59
+ * instructions: 'You are a helpful assistant',
60
+ * chat: myChatInstance,
61
+ * tools: [searchTool, calculatorTool]
62
+ * })
63
+ *
64
+ * if (result.is(ListenExit)) {
65
+ * // Agent is waiting for user input
66
+ * }
67
+ *
68
+ * @example
69
+ * // With dynamic instructions and hooks
70
+ * const result = await execute({
71
+ * client: cognitiveClient,
72
+ * instructions: (ctx) => `Process ${ctx.variables.dataCount} records`,
73
+ * tools: async (ctx) => await getContextualTools(ctx),
74
+ * options: { loop: 10, temperature: 0.1 },
75
+ * onTrace: ({ trace, iteration }) => console.log(trace),
76
+ * onExit: async (result) => await validateResult(result)
77
+ * })
78
+ */
17
79
  export declare const execute: (props: ExecutionProps) => Promise<ExecutionResult>;
18
80
  /**
19
81
  * Loads the necessary dependencies for the library to work