llmz 0.9.0 → 1.0.2

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 (238) hide show
  1. package/DOCS.md +232 -1794
  2. package/ERRORS.md +101 -0
  3. package/README.md +96 -582
  4. package/dist/chat/chat.d.ts +63 -0
  5. package/dist/chat/component.d.ts +31 -0
  6. package/dist/chat/component.default.d.ts +58 -0
  7. package/dist/chat/response.d.ts +15 -0
  8. package/dist/compiler/compiler.d.ts +2 -7
  9. package/dist/compiler/plugins/dynamic-code.d.ts +7 -0
  10. package/dist/compiler/plugins/replace-comment.d.ts +2 -3
  11. package/dist/compiler/plugins/return-async.d.ts +5 -4
  12. package/dist/compiler/plugins/termination.d.ts +8 -0
  13. package/dist/compiler/plugins/tool-resolution.d.ts +4 -0
  14. package/dist/compiler/plugins/variable-extraction.d.ts +2 -8
  15. package/dist/component-CMFoCHyu.cjs +649 -0
  16. package/dist/component-DncqP4fB.js +614 -0
  17. package/dist/context.d.ts +71 -378
  18. package/dist/custom-client-C-WXvLD9.js +1655 -0
  19. package/dist/custom-client-Cgt9_0r1.cjs +1732 -0
  20. package/dist/custom-client.d.ts +12 -2
  21. package/dist/errors/catalog.d.ts +294 -0
  22. package/dist/errors/hooks.d.ts +2 -0
  23. package/dist/errors-C6ppQUZX.cjs +893 -0
  24. package/dist/errors-Crk5P8jo.js +636 -0
  25. package/dist/errors.d.ts +24 -36
  26. package/dist/execute-CiYvPs5Q.js +2061 -0
  27. package/dist/execute-DTTfacsi.cjs +2062 -0
  28. package/dist/{exit-DUM96DN1.cjs → exit-BOtKWPuT.cjs} +38 -28
  29. package/dist/{exit-CDdxDBRT.js → exit-DMPwCSba.js} +37 -27
  30. package/dist/exit.d.ts +19 -16
  31. package/dist/index.cjs +177 -1237
  32. package/dist/index.d.ts +25 -28
  33. package/dist/index.js +137 -1213
  34. package/dist/index.workerd.js +8974 -11145
  35. package/dist/inspect.d.ts +18 -4
  36. package/dist/inspection.d.ts +40 -0
  37. package/dist/native-0bq5ATZM.cjs +212 -0
  38. package/dist/native-n_718Z-T.js +177 -0
  39. package/dist/objects.d.ts +2 -57
  40. package/dist/prompts/native.d.ts +2 -0
  41. package/dist/prompts/prompt.d.ts +10 -101
  42. package/dist/quickjs-variant-21IO97PF.cjs +1080 -0
  43. package/dist/quickjs-variant-CtuGagsb.js +985 -0
  44. package/dist/result.d.ts +30 -861
  45. package/dist/runtime/execute.d.ts +3 -2
  46. package/dist/runtime/execution-activity.d.ts +11 -0
  47. package/dist/runtime/execution-diagnostics.d.ts +11 -0
  48. package/dist/runtime/execution-report.d.ts +51 -0
  49. package/dist/runtime/fixtures/chat.d.ts +8 -0
  50. package/dist/runtime/fixtures/long-search.d.ts +1 -1
  51. package/dist/runtime/fixtures/native-client.d.ts +33 -0
  52. package/dist/runtime/fixtures/protocol-languages.d.ts +1 -1
  53. package/dist/runtime/forced-inspection.d.ts +13 -0
  54. package/dist/runtime/forced-inspection.test.d.ts +1 -0
  55. package/dist/runtime/generate.d.ts +23 -20
  56. package/dist/runtime/generate.test.d.ts +1 -0
  57. package/dist/runtime/hook-provenance.test.d.ts +1 -0
  58. package/dist/runtime/inspection-hook.test.d.ts +1 -0
  59. package/dist/runtime/inspection-values.d.ts +14 -0
  60. package/dist/runtime/inspection-values.test.d.ts +1 -0
  61. package/dist/runtime/interruption-control-flow.test.d.ts +1 -0
  62. package/dist/runtime/interruption-settings.test.d.ts +1 -0
  63. package/dist/runtime/javascript-api.d.ts +62 -0
  64. package/dist/runtime/javascript-api.test.d.ts +1 -0
  65. package/dist/runtime/native-review.test.d.ts +1 -0
  66. package/dist/runtime/native-tools.d.ts +18 -0
  67. package/dist/runtime/native-tools.test.d.ts +1 -0
  68. package/dist/runtime/object-memory.test.d.ts +1 -0
  69. package/dist/runtime/single-tool.test.d.ts +1 -0
  70. package/dist/runtime/think-signal.test.d.ts +1 -0
  71. package/dist/runtime/token-budget.d.ts +22 -0
  72. package/dist/runtime/token-budget.test.d.ts +1 -0
  73. package/dist/runtime/tool-wrapper.d.ts +6 -5
  74. package/dist/runtime/traces.test.d.ts +1 -0
  75. package/dist/runtime/truncation.test.d.ts +1 -0
  76. package/dist/runtime/types.d.ts +47 -31
  77. package/dist/runtime/variable-recovery.test.d.ts +1 -0
  78. package/dist/runtime/vm-context.d.ts +6 -1
  79. package/dist/runtime/worker-completion.test.d.ts +1 -0
  80. package/dist/runtime-names.d.ts +4 -0
  81. package/dist/schema-CXlnbb3n.cjs +68 -0
  82. package/dist/schema-GE4ISPCR.js +45 -0
  83. package/dist/schema.d.ts +10 -0
  84. package/dist/schema.test.d.ts +1 -0
  85. package/dist/session/compactor.d.ts +51 -0
  86. package/dist/session/compactor.test.d.ts +1 -0
  87. package/dist/session/history.d.ts +36 -0
  88. package/dist/session/history.test.d.ts +1 -0
  89. package/dist/session/json.d.ts +3 -0
  90. package/dist/session/json.test.d.ts +1 -0
  91. package/dist/session/memory-codec.d.ts +9 -0
  92. package/dist/session/memory-codec.test.d.ts +1 -0
  93. package/dist/session/memory-render.d.ts +15 -0
  94. package/dist/session/memory-render.test.d.ts +1 -0
  95. package/dist/session/memory.d.ts +112 -0
  96. package/dist/session/memory.test.d.ts +1 -0
  97. package/dist/session/messages.d.ts +19 -0
  98. package/dist/session/messages.test.d.ts +1 -0
  99. package/dist/session/serialization.d.ts +36 -0
  100. package/dist/session/serialization.test.d.ts +1 -0
  101. package/dist/session/session-memory.test.d.ts +1 -0
  102. package/dist/session/session.d.ts +121 -0
  103. package/dist/session/session.test.d.ts +1 -0
  104. package/dist/session/speaker.test.d.ts +1 -0
  105. package/dist/{transcript.d.ts → session/transcript.d.ts} +4 -8
  106. package/dist/session/transcript.test.d.ts +1 -0
  107. package/dist/{tool-Bv8N4IPj.js → tool-DstssiAs.js} +144 -92
  108. package/dist/{tool-Dy6AJpJH.cjs → tool-_wK9hQOb.cjs} +146 -94
  109. package/dist/tool.d.ts +25 -17
  110. package/dist/truncate-BEKbdo3t.js +79 -0
  111. package/dist/truncate-uomAMGPs.cjs +102 -0
  112. package/dist/truncate.d.ts +24 -0
  113. package/dist/truncate.test.d.ts +1 -0
  114. package/dist/types.d.ts +33 -9
  115. package/dist/{typings-3lsqCbkn.cjs → typings-BA_XxAcY.cjs} +38 -193
  116. package/dist/{typings-CrBa7Tyy.js → typings-BEVDvtuk.js} +38 -175
  117. package/dist/typings-formatter.d.ts +1 -1
  118. package/dist/typings.d.ts +3 -0
  119. package/dist/{uniq-BYQ7GWwb.js → uniq-DfUeSNaX.js} +2 -2
  120. package/dist/{uniq-G872RWmE.cjs → uniq-DiXgysNV.cjs} +6 -18
  121. package/dist/{_baseIteratee-P_firB7b.js → utils-BOFzb8Ok.js} +1134 -16
  122. package/dist/{_baseIteratee-CF4qP2a8.cjs → utils-CTlsXvdj.cjs} +1281 -84
  123. package/dist/vm/drivers/node.d.ts +1 -1
  124. package/dist/vm/drivers/quickjs.d.ts +1 -1
  125. package/dist/vm/errors.d.ts +4 -4
  126. package/dist/vm/index.d.ts +3 -4
  127. package/dist/vm/instrument.d.ts +14 -6
  128. package/dist/vm/member-proxy.d.ts +4 -0
  129. package/dist/vm/member-proxy.test.d.ts +1 -0
  130. package/dist/vm/memory.test.d.ts +1 -0
  131. package/dist/vm/return-semantics.test.d.ts +1 -0
  132. package/dist/vm/types.d.ts +20 -3
  133. package/dist/{vm-BLsHw1da.js → vm-C7SfutHn.js} +1187 -180
  134. package/dist/{vm-D6s1zF6M.cjs → vm-gmekHc0i.cjs} +1221 -207
  135. package/package.json +13 -6
  136. package/dist/_baseForOwn-BfWDTL8L.cjs +0 -53
  137. package/dist/_baseForOwn-CFhWe_W6.js +0 -48
  138. package/dist/_getPrototype-CG7Dxrrz.js +0 -6
  139. package/dist/_getPrototype-DQDlNVVM.cjs +0 -10
  140. package/dist/_overArg-C5Hy7oCi.cjs +0 -196
  141. package/dist/_overArg-CRYbj1NH.js +0 -155
  142. package/dist/chat.d.ts +0 -401
  143. package/dist/common-BlRFtdf2.js +0 -807
  144. package/dist/common-BnvrDnIT.cjs +0 -860
  145. package/dist/compiler/plugins/track-tool-calls.d.ts +0 -33
  146. package/dist/compiler-C-OI9sim.cjs +0 -547
  147. package/dist/compiler-CW1VjQsn.js +0 -473
  148. package/dist/component-C6Agl2ns.cjs +0 -73
  149. package/dist/component-DGG7d_Mz.js +0 -44
  150. package/dist/component.d.ts +0 -88
  151. package/dist/component.default.d.ts +0 -278
  152. package/dist/custom-client-ChuZ63zp.js +0 -2658
  153. package/dist/custom-client-DAsGRnYc.cjs +0 -2729
  154. package/dist/dual-modes-DDkoCp3R.js +0 -3006
  155. package/dist/dual-modes-DPXiuvNe.cjs +0 -3090
  156. package/dist/errors-C962uJdS.cjs +0 -220
  157. package/dist/errors-Cg1G0Awu.js +0 -161
  158. package/dist/example-format.d.ts +0 -8
  159. package/dist/example.d.ts +0 -45
  160. package/dist/execute-BWcdv9so.js +0 -1059
  161. package/dist/execute-DM2-7y86.cjs +0 -1060
  162. package/dist/exit-parser.d.ts +0 -39
  163. package/dist/handlers.d.ts +0 -10
  164. package/dist/hoist.d.ts +0 -2
  165. package/dist/isEmpty-BhJRCqIF.js +0 -52
  166. package/dist/isEmpty-LY533Wmh.cjs +0 -57
  167. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  168. package/dist/isPlainObject-D39AzPO2.js +0 -51
  169. package/dist/jsx-CIgdGGVs.js +0 -52
  170. package/dist/jsx-owqxrquU.cjs +0 -75
  171. package/dist/jsx.d.ts +0 -11
  172. package/dist/message-stream/index.d.ts +0 -9
  173. package/dist/message-stream/instructions.d.ts +0 -30
  174. package/dist/message-stream/normalizer.d.ts +0 -21
  175. package/dist/message-stream/parser.d.ts +0 -89
  176. package/dist/message-stream/registry.d.ts +0 -14
  177. package/dist/message-stream/replayable.d.ts +0 -27
  178. package/dist/message-stream/response-parser.d.ts +0 -24
  179. package/dist/message-stream/sanitize.d.ts +0 -10
  180. package/dist/message-stream/stream.d.ts +0 -54
  181. package/dist/message-stream/types.d.ts +0 -97
  182. package/dist/message-stream/validator.d.ts +0 -23
  183. package/dist/prompts/chat-mode/protocol.d.ts +0 -2
  184. package/dist/prompts/chat-mode/system.d.ts +0 -2
  185. package/dist/prompts/chat-mode/system.md.d.ts +0 -2
  186. package/dist/prompts/chat-mode/user.d.ts +0 -2
  187. package/dist/prompts/chat-mode/user.md.d.ts +0 -2
  188. package/dist/prompts/code-examples.d.ts +0 -2
  189. package/dist/prompts/common.d.ts +0 -7
  190. package/dist/prompts/dual-modes.d.ts +0 -2
  191. package/dist/prompts/execution-history.d.ts +0 -6
  192. package/dist/prompts/execution-state.d.ts +0 -3
  193. package/dist/prompts/protocol-basics.d.ts +0 -5
  194. package/dist/prompts/protocol.d.ts +0 -31
  195. package/dist/prompts/worker-mode/protocol.d.ts +0 -2
  196. package/dist/prompts/worker-mode/system.d.ts +0 -2
  197. package/dist/prompts/worker-mode/system.md.d.ts +0 -2
  198. package/dist/prompts/worker-mode/user.d.ts +0 -2
  199. package/dist/prompts/worker-mode/user.md.d.ts +0 -2
  200. package/dist/quickjs-variant-BYhMBpwU.js +0 -45
  201. package/dist/quickjs-variant-CsIwTVFC.cjs +0 -56
  202. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  203. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +0 -29
  204. package/dist/runtime/interpret-result.d.ts +0 -22
  205. package/dist/snapshots.d.ts +0 -249
  206. package/dist/stack-traces-BIE_5Xwf.js +0 -21
  207. package/dist/stack-traces-ntw_qhoy.cjs +0 -26
  208. package/dist/truncator-CLkouTCO.cjs +0 -276
  209. package/dist/truncator-DZqEqnpD.js +0 -253
  210. package/dist/truncator.d.ts +0 -118
  211. package/dist/utils-3ESwP3yg.cjs +0 -1075
  212. package/dist/utils-UBeAFeEI.js +0 -950
  213. /package/dist/{citations.d.ts → chat/citations.d.ts} +0 -0
  214. /package/dist/{citations.test.d.ts → chat/citations.test.d.ts} +0 -0
  215. /package/dist/{component.default.test.d.ts → chat/component.default.test.d.ts} +0 -0
  216. /package/dist/{compiler/plugins/track-tool-calls.test.d.ts → chat/component.test.d.ts} +0 -0
  217. /package/dist/{example.test.d.ts → chat/response.test.d.ts} +0 -0
  218. /package/dist/{exit-parser.test.d.ts → compiler/plugins/dynamic-code.test.d.ts} +0 -0
  219. /package/dist/{handlers.test.d.ts → compiler/plugins/tool-resolution.test.d.ts} +0 -0
  220. /package/dist/{hoist.test.d.ts → errors/catalog.test.d.ts} +0 -0
  221. /package/dist/{message-stream/instructions.test.d.ts → exit.test.d.ts} +0 -0
  222. /package/dist/{message-stream/normalizer.test.d.ts → inspection.test.d.ts} +0 -0
  223. /package/dist/{message-stream/parser.test.d.ts → prompts/native.test.d.ts} +0 -0
  224. /package/dist/{message-stream/response-parser.test.d.ts → result.test.d.ts} +0 -0
  225. /package/dist/{message-stream/stream.test.d.ts → runtime/chat-completion.test.d.ts} +0 -0
  226. /package/dist/{message-stream/validator.test.d.ts → runtime/chat-delivery.test.d.ts} +0 -0
  227. /package/dist/{prompts/adherence.test.d.ts → runtime/chat-last-speaker.test.d.ts} +0 -0
  228. /package/dist/{prompts/catalogue-examples.test.d.ts → runtime/compatibility-regressions.test.d.ts} +0 -0
  229. /package/dist/{prompts/code-examples.test.d.ts → runtime/context-registration.test.d.ts} +0 -0
  230. /package/dist/{prompts/common.test.d.ts → runtime/empty-completion.test.d.ts} +0 -0
  231. /package/dist/{prompts/concrete-patterns.test.d.ts → runtime/error-recovery.test.d.ts} +0 -0
  232. /package/dist/{prompts/long-search.test.d.ts → runtime/errors.test.d.ts} +0 -0
  233. /package/dist/{prompts/protocol-simple.test.d.ts → runtime/execution-activity.test.d.ts} +0 -0
  234. /package/dist/{prompts/protocol.test.d.ts → runtime/execution-diagnostics.test.d.ts} +0 -0
  235. /package/dist/{prompts/sections.test.d.ts → runtime/execution-report.test.d.ts} +0 -0
  236. /package/dist/runtime/{interpret-result.test.d.ts → execution-safety.test.d.ts} +0 -0
  237. /package/dist/{transcript.test.d.ts → runtime/exit-control-flow.test.d.ts} +0 -0
  238. /package/dist/{truncator.test.d.ts → runtime/fixtures/long-search.test.d.ts} +0 -0
package/dist/result.d.ts CHANGED
@@ -1,891 +1,60 @@
1
- import { Context, Iteration } from './context.js';
2
- import { SnapshotSignal } from './errors.js';
3
- import { Exit, ExitResult } from './exit.js';
4
- import { Snapshot } from './snapshots.js';
5
- import { Serializable } from './types.js';
6
- type ExecutionStatus = 'success' | 'error' | 'interrupted';
1
+ import type { Context, Iteration } from './context.js';
2
+ import { type LLMzFailure } from './errors.js';
3
+ import type { Exit, ExitResult } from './exit.js';
4
+ import type { Session } from './session/session.js';
5
+ type ExecutionStatus = 'success' | 'error';
6
+ type ResultSummary = {
7
+ sessionId: string;
8
+ tokens: {
9
+ input: number;
10
+ output: number;
11
+ total: number;
12
+ };
13
+ };
7
14
  export declare namespace ExecutionResult {
8
- type JSON = SuccessExecutionResult.JSON | ErrorExecutionResult.JSON | PartialExecutionResult.JSON;
15
+ type JSON = SuccessExecutionResult.JSON | ErrorExecutionResult.JSON;
9
16
  }
10
- /**
11
- * Base class for all execution results returned by the `execute()` function.
12
- *
13
- * ExecutionResult provides a type-safe way to handle the different outcomes of LLMz
14
- * agent execution. All results contain the execution context and provide methods
15
- * to check the final status and access relevant data.
16
- *
17
- * ## Result Types
18
- *
19
- * LLMz execution can result in three different outcomes:
20
- * - **Success**: Agent completed with an Exit (SuccessExecutionResult)
21
- * - **Error**: Execution failed with an unrecoverable error (ErrorExecutionResult)
22
- * - **Interrupted**: Execution was paused for snapshots or cancellation (PartialExecutionResult)
23
- *
24
- * ## Usage Patterns
25
- *
26
- * ### Basic Status Checking
27
- * ```typescript
28
- * const result = await execute({
29
- * instructions: 'Calculate the sum of numbers 1 to 100',
30
- * client,
31
- * })
32
- *
33
- * if (result.isSuccess()) {
34
- * console.log('Success:', result.output)
35
- * } else if (result.isError()) {
36
- * console.error('Error:', result.error)
37
- * } else if (result.isInterrupted()) {
38
- * console.log('Interrupted - snapshot available:', !!result.snapshot)
39
- * }
40
- * ```
41
- *
42
- * ### Type-Safe Exit Checking
43
- * ```typescript
44
- * const dataExit = new Exit({
45
- * name: 'dataProcessed',
46
- * schema: z.object({
47
- * recordCount: z.number(),
48
- * processingTime: z.number(),
49
- * }),
50
- * })
51
- *
52
- * const result = await execute({
53
- * instructions: 'Process the data',
54
- * exits: [dataExit],
55
- * client,
56
- * })
57
- *
58
- * // Type-safe exit checking with typed output access
59
- * if (result.is(dataExit)) {
60
- * console.log(`Processed ${result.output.recordCount} records`)
61
- * console.log(`Processing took ${result.output.processingTime}ms`)
62
- * }
63
- * ```
64
- *
65
- * ### Accessing Execution Details
66
- * ```typescript
67
- * if (result.isSuccess()) {
68
- * // Access the generated code from the final iteration
69
- * console.log('Generated code:', result.iteration.code)
70
- *
71
- * // Access all iterations to see the full execution flow
72
- * result.iterations.forEach((iteration, index) => {
73
- * console.log(`Iteration ${index + 1}:`, iteration.status.type)
74
- * })
75
- *
76
- * // Access execution context
77
- * console.log('Original instructions:', result.context.instructions)
78
- * }
79
- * ```
80
- *
81
- * ### Snapshot Handling
82
- * ```typescript
83
- * if (result.isInterrupted()) {
84
- * // Serialize snapshot for persistence
85
- * const serialized = result.snapshot.toJSON()
86
- * await database.saveSnapshot(serialized)
87
- *
88
- * // Later, resume from snapshot
89
- * const snapshot = Snapshot.fromJSON(serialized)
90
- * snapshot.resolve({ data: 'resolved data' })
91
- *
92
- * const continuation = await execute({
93
- * snapshot,
94
- * instructions: result.context.instructions,
95
- * tools: result.context.tools,
96
- * exits: result.context.exits,
97
- * client,
98
- * })
99
- * }
100
- * ```
101
- *
102
- * @see {@link SuccessExecutionResult} For successful execution results
103
- * @see {@link ErrorExecutionResult} For failed execution results
104
- * @see {@link PartialExecutionResult} For interrupted execution results
105
- */
106
- export declare abstract class ExecutionResult implements Serializable<ExecutionResult.JSON> {
17
+ /** An execution outcome. Persist Session separately; diagnostics belong to this run. */
18
+ export declare abstract class ExecutionResult {
107
19
  readonly status: ExecutionStatus;
108
20
  readonly context: Context;
109
21
  protected constructor(status: ExecutionStatus, context: Context);
110
- /**
111
- * Type guard to check if the execution completed successfully.
112
- *
113
- * @returns True if the execution completed with an Exit, false otherwise
114
- * @example
115
- * ```typescript
116
- * const result = await execute({ ... })
117
- *
118
- * if (result.isSuccess()) {
119
- * // TypeScript knows this is SuccessExecutionResult
120
- * console.log('Output:', result.output)
121
- * console.log('Exit name:', result.result.exit.name)
122
- * }
123
- * ```
124
- */
125
22
  isSuccess(): this is SuccessExecutionResult;
126
- /**
127
- * Type guard to check if the execution failed with an error.
128
- *
129
- * @returns True if the execution failed with an unrecoverable error, false otherwise
130
- * @example
131
- * ```typescript
132
- * const result = await execute({ ... })
133
- *
134
- * if (result.isError()) {
135
- * // TypeScript knows this is ErrorExecutionResult
136
- * console.error('Execution failed:', result.error)
137
- *
138
- * // Access error details from the last iteration
139
- * const lastIteration = result.iteration
140
- * if (lastIteration?.status.type === 'execution_error') {
141
- * console.error('Stack trace:', lastIteration.status.execution_error.stack)
142
- * }
143
- * }
144
- * ```
145
- */
146
23
  isError(): this is ErrorExecutionResult;
147
- /**
148
- * Type guard to check if the execution was interrupted.
149
- * Interrupted means there's a snapshot available and the execution was paused and needs resuming.
150
- *
151
- * @returns True if the execution was interrupted, false otherwise
152
- * @example
153
- * ```typescript
154
- * const result = await execute({ ... })
155
- *
156
- * if (result.isInterrupted()) {
157
- * // TypeScript knows this is PartialExecutionResult
158
- * console.log('Execution paused:', result.signal.message)
159
- *
160
- * // Access snapshot for later resumption
161
- * const snapshot = result.snapshot
162
- * const serialized = snapshot.toJSON()
163
- * await storage.save('execution-state', serialized)
164
- * }
165
- * ```
166
- */
167
- isInterrupted(): this is PartialExecutionResult;
168
- /**
169
- * Type guard to check if the execution completed with a specific exit.
170
- *
171
- * This method provides type-safe access to the output data based on the exit's schema.
172
- * It's the recommended way to handle different exit types in complex agents.
173
- *
174
- * @param exit - The Exit instance to check against
175
- * @returns True if the execution completed with the specified exit, false otherwise
176
- * @template T - The output type of the exit
177
- *
178
- * @example
179
- * ```typescript
180
- * // Define typed exits
181
- * const successExit = new Exit({
182
- * name: 'success',
183
- * schema: z.object({
184
- * message: z.string(),
185
- * count: z.number(),
186
- * }),
187
- * })
188
- *
189
- * const errorExit = new Exit({
190
- * name: 'error',
191
- * schema: z.object({
192
- * errorCode: z.string(),
193
- * details: z.string(),
194
- * }),
195
- * })
196
- *
197
- * const result = await execute({
198
- * instructions: 'Process the data',
199
- * exits: [successExit, errorExit],
200
- * client,
201
- * })
202
- *
203
- * // Type-safe exit handling
204
- * if (result.is(successExit)) {
205
- * // TypeScript knows result.output has { message: string, count: number }
206
- * console.log(`Success: ${result.output.message}`)
207
- * console.log(`Processed ${result.output.count} items`)
208
- * } else if (result.is(errorExit)) {
209
- * // TypeScript knows result.output has { errorCode: string, details: string }
210
- * console.error(`Error ${result.output.errorCode}: ${result.output.details}`)
211
- * }
212
- * ```
213
- */
214
24
  is<T>(exit: Exit<T>): this is SuccessExecutionResult<T>;
215
- /**
216
- * Gets the output data from the last successful iteration.
217
- *
218
- * For successful executions, returns the data produced by the exit.
219
- * For failed or interrupted executions, returns null.
220
- *
221
- * @returns The output data for successful executions, null otherwise
222
- * @example
223
- * ```typescript
224
- * const result = await execute({ ... })
225
- *
226
- * // Generic output access
227
- * if (result.isSuccess()) {
228
- * console.log('Output:', result.output)
229
- * }
230
- *
231
- * // Type-safe output access with specific exits
232
- * if (result.is(myExit)) {
233
- * // result.output is now typed based on myExit's schema
234
- * console.log(result.output.specificField)
235
- * }
236
- * ```
237
- */
238
- get output(): unknown | null;
239
- /**
240
- * Gets the most recent (last) iteration from the execution.
241
- *
242
- * Iterations represent individual steps in the execution loop where the LLM
243
- * generates code, executes it, and processes the results. The last iteration
244
- * contains the final generated code and execution status.
245
- *
246
- * @returns The last iteration, or null if no iterations were completed
247
- * @example
248
- * ```typescript
249
- * const result = await execute({ ... })
250
- *
251
- * const lastIteration = result.iteration
252
- * if (lastIteration) {
253
- * console.log('Generated code:', lastIteration.code)
254
- * console.log('Status:', lastIteration.status.type)
255
- * console.log('Variables:', lastIteration.variables)
256
- * console.log('Tool calls:', lastIteration.toolCalls)
257
- * }
258
- * ```
259
- */
25
+ get session(): Session;
26
+ get output(): unknown;
260
27
  get iteration(): Iteration | null;
261
- /**
262
- * Gets all iterations from the execution.
263
- *
264
- * This provides access to the complete execution history, showing how the agent
265
- * progressed through multiple iterations to reach the final result. Useful for
266
- * debugging, logging, or understanding the agent's reasoning process.
267
- *
268
- * @returns Array of all iterations in execution order
269
- * @example
270
- * ```typescript
271
- * const result = await execute({ ... })
272
- *
273
- * // Analyze the full execution flow
274
- * result.iterations.forEach((iteration, index) => {
275
- * console.log(`Iteration ${index + 1}:`)
276
- * console.log(' Status:', iteration.status.type)
277
- * console.log(' Code length:', iteration.code?.length || 0)
278
- * console.log(' Tool calls:', iteration.toolCalls.length)
279
- * console.log(' Variables:', Object.keys(iteration.variables).length)
280
- * })
281
- *
282
- * // Find iterations with specific characteristics
283
- * const iterationsWithErrors = result.iterations.filter(
284
- * iter => iter.status.type === 'execution_error'
285
- * )
286
- *
287
- * // Calculate total execution time
288
- * const totalTime = result.iterations.reduce(
289
- * (sum, iter) => sum + (iter.duration || 0), 0
290
- * )
291
- * ```
292
- */
293
28
  get iterations(): Iteration[];
294
- /**
295
- * Gets the total token usage of the execution, aggregated across all iterations.
296
- *
297
- * `input`/`output` are the provider-reported token counts of every LLM call made
298
- * during the execution. Per-iteration detail (including the measured context size
299
- * breakdown by prompt part) is available on each iteration's `tokens` property.
300
- *
301
- * @example
302
- * ```typescript
303
- * const result = await execute({ ... })
304
- * console.log(`Execution used ${result.tokens.total} tokens`)
305
- *
306
- * for (const iteration of result.iterations) {
307
- * console.log(iteration.id, iteration.tokens?.context)
308
- * }
309
- * ```
310
- */
311
- get tokens(): {
312
- input: number;
313
- output: number;
314
- total: number;
315
- };
29
+ get tokens(): ResultSummary['tokens'];
30
+ /** Explicit diagnostic export without conversation or memory persistence. */
31
+ diagnostics(): Context.JSON;
316
32
  abstract toJSON(): ExecutionResult.JSON;
317
33
  }
318
34
  export declare namespace SuccessExecutionResult {
319
- type JSON = {
35
+ type JSON = ResultSummary & {
320
36
  status: 'success';
321
- context: Context.JSON;
322
- result: {
323
- exit: Exit.JSON;
324
- result: unknown;
325
- };
37
+ exit: string;
38
+ output: unknown;
326
39
  };
327
40
  }
328
- /**
329
- * Result for successful executions that completed with an Exit.
330
- *
331
- * SuccessExecutionResult indicates that the agent successfully completed its task
332
- * and returned structured data through one of the provided exits. This is the
333
- * most common positive outcome for LLMz executions.
334
- *
335
- * In *Worker Mode* (ie. no `chat` provided), if no exits were provided, the "DefaultExit" will be used.
336
- * If *Chat Mode* is enabled, most likely the "ListenExit" will be used if no exits were provided.
337
- *
338
- * You can check for a specific exit using the `is()` method, which provides type-safe access to the output data of the exit.
339
- * You can import "ListenExit" and "DefaultExit" from `llmz`.
340
- *
341
- * @template TOutput - The type of the output data based on the exit schema
342
- *
343
- * @example
344
- * ```typescript
345
- * import { execute, Exit, DefaultExit, ListenExit } from 'llmz'
346
- *
347
- * const exit = new Exit({
348
- * name: 'dataProcessed',
349
- * schema: z.object({
350
- * recordCount: z.number(),
351
- * summary: z.string(),
352
- * }),
353
- * })
354
- *
355
- * const result = await execute({
356
- * instructions: 'Process the user data',
357
- * exits: [exit],
358
- * client,
359
- * })
360
- *
361
- * if (result.isSuccess() && result.is(exit)) {
362
- * // Access the exit information
363
- * console.log('Exit name:', result.result.exit.name)
364
- *
365
- * // Access typed output data
366
- * console.log('Records processed:', result.output.recordCount)
367
- * console.log('Summary:', result.output.summary)
368
- *
369
- * // Access the final iteration (guaranteed to exist)
370
- * console.log('Generated code:', result.iteration.code)
371
- * }
372
- * ```
373
- */
374
- export declare class SuccessExecutionResult<TOutput = unknown> extends ExecutionResult implements Serializable<SuccessExecutionResult.JSON> {
41
+ export declare class SuccessExecutionResult<TOutput = unknown> extends ExecutionResult {
375
42
  readonly result: ExitResult<TOutput>;
376
43
  constructor(context: Context, result: ExitResult<TOutput>);
377
- /**
378
- * Gets the typed output data from the successful execution.
379
- *
380
- * This overrides the base class output property to provide proper typing
381
- * based on the exit schema. The output is guaranteed to match the schema
382
- * of the exit that was triggered.
383
- *
384
- * @returns The typed output data
385
- */
386
44
  get output(): TOutput;
387
- /**
388
- * Gets the final iteration from the successful execution.
389
- *
390
- * For successful executions, there is always at least one iteration,
391
- * so this method returns the guaranteed non-null final iteration.
392
- *
393
- * @returns The final iteration (guaranteed to exist)
394
- */
395
45
  get iteration(): Iteration;
396
- /**
397
- * Serializes the execution result to JSON.
398
- *
399
- * This method converts the execution result into a JSON format that includes
400
- * the execution status, context, and exit information. It is used for serialization
401
- * and transmission of the execution result.
402
- *
403
- * @returns The JSON representation of the execution result.
404
- */
405
- toJSON(): {
406
- status: 'success';
407
- context: {
408
- id: string;
409
- iterations: {
410
- id: string;
411
- messages: import("@botpress/cognitive").CognitiveMessage[];
412
- code: string | undefined;
413
- model: import("@botpress/cognitive").Models[] | import("@botpress/cognitive").Models;
414
- temperature: number;
415
- reasoningEffort: "dynamic" | "high" | "low" | "medium" | "none" | undefined;
416
- traces: import("./types.js").Traces.Trace[];
417
- variables: Record<string, any>;
418
- started_ts: number;
419
- ended_ts: number | undefined;
420
- status: import("./context.js").IterationStatus;
421
- mutations: import("./types.js").ObjectMutation[];
422
- llm: {
423
- started_at: number;
424
- ended_at: number;
425
- status: 'success' | 'error';
426
- cached: boolean;
427
- tokens: number;
428
- spend: number;
429
- output: string;
430
- diagnostics?: import("./index.js").Diagnostic[];
431
- model: string;
432
- time_to_first_token?: number;
433
- time_to_last_token?: number;
434
- usage: {
435
- inputCost: number;
436
- outputCost: number;
437
- inputTokens: number;
438
- outputTokens: number;
439
- };
440
- } | undefined;
441
- tokens: import("./context.js").TokenUsage | undefined;
442
- transcript: import("./transcript.js").Transcript.Message[];
443
- tools: {
444
- name: string;
445
- aliases: string[];
446
- description: string | undefined;
447
- metadata: Record<string, unknown>;
448
- input: import("json-schema").JSONSchema7 | undefined;
449
- output: import("json-schema").JSONSchema7 | undefined;
450
- staticInputValues: unknown;
451
- maxRetries: number;
452
- }[];
453
- objects: {
454
- name: string;
455
- description: string | undefined;
456
- properties: import("./objects.js").ObjectProperty[] | undefined;
457
- tools: {
458
- name: string;
459
- aliases: string[];
460
- description: string | undefined;
461
- metadata: Record<string, unknown>;
462
- input: import("json-schema").JSONSchema7 | undefined;
463
- output: import("json-schema").JSONSchema7 | undefined;
464
- staticInputValues: unknown;
465
- maxRetries: number;
466
- }[];
467
- metadata: Record<string, unknown> | undefined;
468
- }[];
469
- exits: {
470
- name: string;
471
- aliases: string[];
472
- description: string;
473
- metadata: {
474
- [x: string]: unknown;
475
- };
476
- schema: import("json-schema").JSONSchema7 | undefined;
477
- }[];
478
- instructions: string | undefined;
479
- duration: string;
480
- error: string | null;
481
- isChatEnabled: boolean;
482
- }[];
483
- iteration: number;
484
- timeout: number;
485
- loop: number;
486
- metadata: Record<string, any>;
487
- snapshot: {
488
- id: string;
489
- reason: string | undefined;
490
- stack: string;
491
- variables: ({
492
- name: string;
493
- type: string;
494
- bytes: number;
495
- preview?: string;
496
- value?: unknown;
497
- truncated: boolean;
498
- } & ({
499
- truncated: true;
500
- preview: string;
501
- } | {
502
- truncated: false;
503
- value: unknown;
504
- }))[];
505
- toolCall: import("./errors.js").ToolCall | undefined;
506
- status: import("./snapshots.js").SnapshotStatus;
507
- } | undefined;
508
- };
509
- result: {
510
- exit: {
511
- name: string;
512
- aliases: string[];
513
- description: string;
514
- metadata: {
515
- [x: string]: unknown;
516
- };
517
- schema: import("json-schema").JSONSchema7 | undefined;
518
- };
519
- result: TOutput;
520
- };
521
- };
46
+ toJSON(): SuccessExecutionResult.JSON;
522
47
  }
523
48
  export declare namespace ErrorExecutionResult {
524
- type JSON = {
49
+ type JSON = ResultSummary & {
525
50
  status: 'error';
526
- context: Context.JSON;
527
51
  error: unknown;
528
52
  };
529
53
  }
530
- /**
531
- * Result for executions that failed with an unrecoverable error.
532
- *
533
- * ErrorExecutionResult indicates that the execution encountered an error that could not be recovered from, such as:
534
- * - Execution has been aborted by the user (eg. via the `signal` AbortSignal parameter)
535
- * - Iterations exceeded the maximum allowed limit
536
- *
537
- * Upon iteration failure, the execution will continue until the maximum iteration limit is reached or an exit is triggered.
538
- *
539
- * @example
540
- * ```typescript
541
- * const result = await execute({
542
- * instructions: 'Call a non-existent function',
543
- * client,
544
- * })
545
- *
546
- * if (result.isError()) {
547
- * console.error('Execution failed:', result.error)
548
- *
549
- * // Access error details from the last iteration
550
- * const lastIteration = result.iteration
551
- * if (lastIteration?.status.type === 'execution_error') {
552
- * console.error('Error type:', lastIteration.status.execution_error.type)
553
- * console.error('Stack trace:', lastIteration.status.execution_error.stack)
554
- * console.error('Generated code:', lastIteration.code)
555
- * }
556
- *
557
- * // Access all iterations to understand the failure progression
558
- * console.log('Total iterations before failure:', result.iterations.length)
559
- * }
560
- * ```
561
- */
562
- export declare class ErrorExecutionResult extends ExecutionResult implements Serializable<ErrorExecutionResult.JSON> {
563
- readonly error: unknown;
54
+ export declare class ErrorExecutionResult extends ExecutionResult {
55
+ readonly error: LLMzFailure;
564
56
  constructor(context: Context, error: unknown);
565
- /**
566
- * Gets the output data (always null for error results).
567
- *
568
- * @returns Always null since error executions don't produce output
569
- */
570
57
  get output(): null;
571
- toJSON(): {
572
- status: 'error';
573
- context: {
574
- id: string;
575
- iterations: {
576
- id: string;
577
- messages: import("@botpress/cognitive").CognitiveMessage[];
578
- code: string | undefined;
579
- model: import("@botpress/cognitive").Models[] | import("@botpress/cognitive").Models;
580
- temperature: number;
581
- reasoningEffort: "dynamic" | "high" | "low" | "medium" | "none" | undefined;
582
- traces: import("./types.js").Traces.Trace[];
583
- variables: Record<string, any>;
584
- started_ts: number;
585
- ended_ts: number | undefined;
586
- status: import("./context.js").IterationStatus;
587
- mutations: import("./types.js").ObjectMutation[];
588
- llm: {
589
- started_at: number;
590
- ended_at: number;
591
- status: 'success' | 'error';
592
- cached: boolean;
593
- tokens: number;
594
- spend: number;
595
- output: string;
596
- diagnostics?: import("./index.js").Diagnostic[];
597
- model: string;
598
- time_to_first_token?: number;
599
- time_to_last_token?: number;
600
- usage: {
601
- inputCost: number;
602
- outputCost: number;
603
- inputTokens: number;
604
- outputTokens: number;
605
- };
606
- } | undefined;
607
- tokens: import("./context.js").TokenUsage | undefined;
608
- transcript: import("./transcript.js").Transcript.Message[];
609
- tools: {
610
- name: string;
611
- aliases: string[];
612
- description: string | undefined;
613
- metadata: Record<string, unknown>;
614
- input: import("json-schema").JSONSchema7 | undefined;
615
- output: import("json-schema").JSONSchema7 | undefined;
616
- staticInputValues: unknown;
617
- maxRetries: number;
618
- }[];
619
- objects: {
620
- name: string;
621
- description: string | undefined;
622
- properties: import("./objects.js").ObjectProperty[] | undefined;
623
- tools: {
624
- name: string;
625
- aliases: string[];
626
- description: string | undefined;
627
- metadata: Record<string, unknown>;
628
- input: import("json-schema").JSONSchema7 | undefined;
629
- output: import("json-schema").JSONSchema7 | undefined;
630
- staticInputValues: unknown;
631
- maxRetries: number;
632
- }[];
633
- metadata: Record<string, unknown> | undefined;
634
- }[];
635
- exits: {
636
- name: string;
637
- aliases: string[];
638
- description: string;
639
- metadata: {
640
- [x: string]: unknown;
641
- };
642
- schema: import("json-schema").JSONSchema7 | undefined;
643
- }[];
644
- instructions: string | undefined;
645
- duration: string;
646
- error: string | null;
647
- isChatEnabled: boolean;
648
- }[];
649
- iteration: number;
650
- timeout: number;
651
- loop: number;
652
- metadata: Record<string, any>;
653
- snapshot: {
654
- id: string;
655
- reason: string | undefined;
656
- stack: string;
657
- variables: ({
658
- name: string;
659
- type: string;
660
- bytes: number;
661
- preview?: string;
662
- value?: unknown;
663
- truncated: boolean;
664
- } & ({
665
- truncated: true;
666
- preview: string;
667
- } | {
668
- truncated: false;
669
- value: unknown;
670
- }))[];
671
- toolCall: import("./errors.js").ToolCall | undefined;
672
- status: import("./snapshots.js").SnapshotStatus;
673
- } | undefined;
674
- };
675
- error: unknown;
676
- };
677
- }
678
- export declare namespace PartialExecutionResult {
679
- type JSON = {
680
- status: 'interrupted';
681
- context: Context.JSON;
682
- snapshot: Snapshot.JSON;
683
- signal: {
684
- message: string;
685
- truncatedCode?: string;
686
- variables: Record<string, any>;
687
- };
688
- };
689
- }
690
- /**
691
- * Result for executions that were interrupted before completion.
692
- *
693
- * PartialExecutionResult indicates that a snapshot was created during the execution.
694
- * Interrupted executions can be resumed using the provided snapshot.
695
- *
696
- * @example
697
- * ```typescript
698
- * // Tool that throws SnapshotSignal for long-running operations
699
- * const longRunningTool = new Tool({
700
- * name: 'processLargeDataset',
701
- * async handler({ datasetId }) {
702
- * // Start background processing
703
- * const jobId = await startBackgroundJob(datasetId)
704
- *
705
- * // Pause execution until job completes
706
- * throw new SnapshotSignal('Processing dataset', 'Waiting for background job completion', {
707
- * jobId,
708
- * datasetId,
709
- * startTime: Date.now(),
710
- * })
711
- * },
712
- * })
713
- *
714
- * const result = await execute({
715
- * instructions: 'Process the large dataset',
716
- * tools: [longRunningTool],
717
- * client,
718
- * })
719
- *
720
- * if (result.isInterrupted()) {
721
- * console.log('Execution paused:', result.signal.message)
722
- * console.log('Reason:', result.signal.longMessage)
723
- *
724
- * // Serialize snapshot for later resumption
725
- * const serialized = result.snapshot.toJSON()
726
- * await database.saveSnapshot('job-123', serialized)
727
- *
728
- * // Later, when the background job completes...
729
- * const snapshot = Snapshot.fromJSON(serialized)
730
- * snapshot.resolve({ jobResult: 'Processing completed successfully' })
731
- *
732
- * const continuation = await execute({
733
- * snapshot,
734
- * instructions: result.context.instructions,
735
- * tools: result.context.tools,
736
- * exits: result.context.exits,
737
- * client,
738
- * })
739
- * }
740
- * ```
741
- */
742
- export declare class PartialExecutionResult extends ExecutionResult implements Serializable<PartialExecutionResult.JSON> {
743
- readonly signal: SnapshotSignal;
744
- readonly snapshot: Snapshot;
745
- constructor(context: Context, signal: SnapshotSignal, snapshot: Snapshot);
746
- /**
747
- * Gets the output data (always null for interrupted results).
748
- *
749
- * @returns Always null since interrupted executions don't produce final output
750
- */
751
- get output(): null;
752
- /**
753
- * Serializes the execution result to JSON.
754
- *
755
- * @returns The JSON representation of the execution result.
756
- */
757
- toJSON(): {
758
- status: 'interrupted';
759
- context: {
760
- id: string;
761
- iterations: {
762
- id: string;
763
- messages: import("@botpress/cognitive").CognitiveMessage[];
764
- code: string | undefined;
765
- model: import("@botpress/cognitive").Models[] | import("@botpress/cognitive").Models;
766
- temperature: number;
767
- reasoningEffort: "dynamic" | "high" | "low" | "medium" | "none" | undefined;
768
- traces: import("./types.js").Traces.Trace[];
769
- variables: Record<string, any>;
770
- started_ts: number;
771
- ended_ts: number | undefined;
772
- status: import("./context.js").IterationStatus;
773
- mutations: import("./types.js").ObjectMutation[];
774
- llm: {
775
- started_at: number;
776
- ended_at: number;
777
- status: 'success' | 'error';
778
- cached: boolean;
779
- tokens: number;
780
- spend: number;
781
- output: string;
782
- diagnostics?: import("./index.js").Diagnostic[];
783
- model: string;
784
- time_to_first_token?: number;
785
- time_to_last_token?: number;
786
- usage: {
787
- inputCost: number;
788
- outputCost: number;
789
- inputTokens: number;
790
- outputTokens: number;
791
- };
792
- } | undefined;
793
- tokens: import("./context.js").TokenUsage | undefined;
794
- transcript: import("./transcript.js").Transcript.Message[];
795
- tools: {
796
- name: string;
797
- aliases: string[];
798
- description: string | undefined;
799
- metadata: Record<string, unknown>;
800
- input: import("json-schema").JSONSchema7 | undefined;
801
- output: import("json-schema").JSONSchema7 | undefined;
802
- staticInputValues: unknown;
803
- maxRetries: number;
804
- }[];
805
- objects: {
806
- name: string;
807
- description: string | undefined;
808
- properties: import("./objects.js").ObjectProperty[] | undefined;
809
- tools: {
810
- name: string;
811
- aliases: string[];
812
- description: string | undefined;
813
- metadata: Record<string, unknown>;
814
- input: import("json-schema").JSONSchema7 | undefined;
815
- output: import("json-schema").JSONSchema7 | undefined;
816
- staticInputValues: unknown;
817
- maxRetries: number;
818
- }[];
819
- metadata: Record<string, unknown> | undefined;
820
- }[];
821
- exits: {
822
- name: string;
823
- aliases: string[];
824
- description: string;
825
- metadata: {
826
- [x: string]: unknown;
827
- };
828
- schema: import("json-schema").JSONSchema7 | undefined;
829
- }[];
830
- instructions: string | undefined;
831
- duration: string;
832
- error: string | null;
833
- isChatEnabled: boolean;
834
- }[];
835
- iteration: number;
836
- timeout: number;
837
- loop: number;
838
- metadata: Record<string, any>;
839
- snapshot: {
840
- id: string;
841
- reason: string | undefined;
842
- stack: string;
843
- variables: ({
844
- name: string;
845
- type: string;
846
- bytes: number;
847
- preview?: string;
848
- value?: unknown;
849
- truncated: boolean;
850
- } & ({
851
- truncated: true;
852
- preview: string;
853
- } | {
854
- truncated: false;
855
- value: unknown;
856
- }))[];
857
- toolCall: import("./errors.js").ToolCall | undefined;
858
- status: import("./snapshots.js").SnapshotStatus;
859
- } | undefined;
860
- };
861
- snapshot: {
862
- id: string;
863
- reason: string | undefined;
864
- stack: string;
865
- variables: ({
866
- name: string;
867
- type: string;
868
- bytes: number;
869
- preview?: string;
870
- value?: unknown;
871
- truncated: boolean;
872
- } & ({
873
- truncated: true;
874
- preview: string;
875
- } | {
876
- truncated: false;
877
- value: unknown;
878
- }))[];
879
- toolCall: import("./errors.js").ToolCall | undefined;
880
- status: import("./snapshots.js").SnapshotStatus;
881
- };
882
- signal: {
883
- message: string;
884
- truncatedCode: string;
885
- variables: {
886
- [key: string]: any;
887
- };
888
- };
889
- };
58
+ toJSON(): ErrorExecutionResult.JSON;
890
59
  }
891
60
  export {};