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
@@ -1,2658 +0,0 @@
1
- import { c as baseCreate, i as inspect, o as flatRest, r as extractType, s as copyArray, t as DualModePrompt } from "./dual-modes-DDkoCp3R.js";
2
- import { a as Symbol, n as isArray, o as root, r as isObjectLike } from "./_overArg-CRYbj1NH.js";
3
- import { D as isBuffer, E as baseUnary, M as baseAssignValue, R as isObject, T as nodeUtil, _ as baseGet, c as _getTag_default, f as getSymbols, h as Stack, k as isPrototype, s as Uint8Array, u as getAllKeys, v as toKey, x as keys, y as castPath, z as arrayMap } from "./_baseIteratee-P_firB7b.js";
4
- import { _ as getSymbolsIn, b as keysIn, g as getAllKeysIn, i as getErrorMessage, o as getTokenizer, x as assignValue, y as baseSlice } from "./utils-UBeAFeEI.js";
5
- import { t as getPrototype } from "./_getPrototype-CG7Dxrrz.js";
6
- import { t as isPlainObject } from "./isPlainObject-D39AzPO2.js";
7
- import { t as Tool } from "./tool-Bv8N4IPj.js";
8
- import { l as ThinkSignal, o as LoopExceededError } from "./errors-Cg1G0Awu.js";
9
- import { t as Exit } from "./exit-CDdxDBRT.js";
10
- import { n as assertValidComponent } from "./component-DGG7d_Mz.js";
11
- import { i as wrapContent, t as stripTruncationTags } from "./truncator-DZqEqnpD.js";
12
- import { z } from "@bpinternal/zui";
13
- import { ulid } from "ulid";
14
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayEach.js
15
- /**
16
- * A specialized version of `_.forEach` for arrays without support for
17
- * iteratee shorthands.
18
- *
19
- * @private
20
- * @param {Array} [array] The array to iterate over.
21
- * @param {Function} iteratee The function invoked per iteration.
22
- * @returns {Array} Returns `array`.
23
- */
24
- function arrayEach(array, iteratee) {
25
- var index = -1, length = array == null ? 0 : array.length;
26
- while (++index < length) if (iteratee(array[index], index, array) === false) break;
27
- return array;
28
- }
29
- //#endregion
30
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copyObject.js
31
- /**
32
- * Copies properties of `source` to `object`.
33
- *
34
- * @private
35
- * @param {Object} source The object to copy properties from.
36
- * @param {Array} props The property identifiers to copy.
37
- * @param {Object} [object={}] The object to copy properties to.
38
- * @param {Function} [customizer] The function to customize copied values.
39
- * @returns {Object} Returns `object`.
40
- */
41
- function copyObject(source, props, object, customizer) {
42
- var isNew = !object;
43
- object || (object = {});
44
- var index = -1, length = props.length;
45
- while (++index < length) {
46
- var key = props[index];
47
- var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
48
- if (newValue === void 0) newValue = source[key];
49
- if (isNew) baseAssignValue(object, key, newValue);
50
- else assignValue(object, key, newValue);
51
- }
52
- return object;
53
- }
54
- //#endregion
55
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssign.js
56
- /**
57
- * The base implementation of `_.assign` without support for multiple sources
58
- * or `customizer` functions.
59
- *
60
- * @private
61
- * @param {Object} object The destination object.
62
- * @param {Object} source The source object.
63
- * @returns {Object} Returns `object`.
64
- */
65
- function baseAssign(object, source) {
66
- return object && copyObject(source, keys(source), object);
67
- }
68
- //#endregion
69
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssignIn.js
70
- /**
71
- * The base implementation of `_.assignIn` without support for multiple sources
72
- * or `customizer` functions.
73
- *
74
- * @private
75
- * @param {Object} object The destination object.
76
- * @param {Object} source The source object.
77
- * @returns {Object} Returns `object`.
78
- */
79
- function baseAssignIn(object, source) {
80
- return object && copyObject(source, keysIn(source), object);
81
- }
82
- //#endregion
83
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneBuffer.js
84
- /** Detect free variable `exports`. */
85
- var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
86
- /** Detect free variable `module`. */
87
- var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
88
- /** Built-in value references. */
89
- var Buffer = freeModule && freeModule.exports === freeExports ? root.Buffer : void 0;
90
- var allocUnsafe = Buffer ? Buffer.allocUnsafe : void 0;
91
- /**
92
- * Creates a clone of `buffer`.
93
- *
94
- * @private
95
- * @param {Buffer} buffer The buffer to clone.
96
- * @param {boolean} [isDeep] Specify a deep clone.
97
- * @returns {Buffer} Returns the cloned buffer.
98
- */
99
- function cloneBuffer(buffer, isDeep) {
100
- if (isDeep) return buffer.slice();
101
- var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
102
- buffer.copy(result);
103
- return result;
104
- }
105
- //#endregion
106
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copySymbols.js
107
- /**
108
- * Copies own symbols of `source` to `object`.
109
- *
110
- * @private
111
- * @param {Object} source The object to copy symbols from.
112
- * @param {Object} [object={}] The object to copy symbols to.
113
- * @returns {Object} Returns `object`.
114
- */
115
- function copySymbols(source, object) {
116
- return copyObject(source, getSymbols(source), object);
117
- }
118
- //#endregion
119
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_copySymbolsIn.js
120
- /**
121
- * Copies own and inherited symbols of `source` to `object`.
122
- *
123
- * @private
124
- * @param {Object} source The object to copy symbols from.
125
- * @param {Object} [object={}] The object to copy symbols to.
126
- * @returns {Object} Returns `object`.
127
- */
128
- function copySymbolsIn(source, object) {
129
- return copyObject(source, getSymbolsIn(source), object);
130
- }
131
- //#endregion
132
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneArray.js
133
- /** Used to check objects for own properties. */
134
- var hasOwnProperty = Object.prototype.hasOwnProperty;
135
- /**
136
- * Initializes an array clone.
137
- *
138
- * @private
139
- * @param {Array} array The array to clone.
140
- * @returns {Array} Returns the initialized clone.
141
- */
142
- function initCloneArray(array) {
143
- var length = array.length, result = new array.constructor(length);
144
- if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) {
145
- result.index = array.index;
146
- result.input = array.input;
147
- }
148
- return result;
149
- }
150
- //#endregion
151
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneArrayBuffer.js
152
- /**
153
- * Creates a clone of `arrayBuffer`.
154
- *
155
- * @private
156
- * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
157
- * @returns {ArrayBuffer} Returns the cloned array buffer.
158
- */
159
- function cloneArrayBuffer(arrayBuffer) {
160
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
161
- new Uint8Array(result).set(new Uint8Array(arrayBuffer));
162
- return result;
163
- }
164
- //#endregion
165
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneDataView.js
166
- /**
167
- * Creates a clone of `dataView`.
168
- *
169
- * @private
170
- * @param {Object} dataView The data view to clone.
171
- * @param {boolean} [isDeep] Specify a deep clone.
172
- * @returns {Object} Returns the cloned data view.
173
- */
174
- function cloneDataView(dataView, isDeep) {
175
- var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
176
- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
177
- }
178
- //#endregion
179
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneRegExp.js
180
- /** Used to match `RegExp` flags from their coerced string values. */
181
- var reFlags = /\w*$/;
182
- /**
183
- * Creates a clone of `regexp`.
184
- *
185
- * @private
186
- * @param {Object} regexp The regexp to clone.
187
- * @returns {Object} Returns the cloned regexp.
188
- */
189
- function cloneRegExp(regexp) {
190
- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
191
- result.lastIndex = regexp.lastIndex;
192
- return result;
193
- }
194
- //#endregion
195
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneSymbol.js
196
- /** Used to convert symbols to primitives and strings. */
197
- var symbolProto = Symbol ? Symbol.prototype : void 0;
198
- var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
199
- /**
200
- * Creates a clone of the `symbol` object.
201
- *
202
- * @private
203
- * @param {Object} symbol The symbol object to clone.
204
- * @returns {Object} Returns the cloned symbol object.
205
- */
206
- function cloneSymbol(symbol) {
207
- return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
208
- }
209
- //#endregion
210
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cloneTypedArray.js
211
- /**
212
- * Creates a clone of `typedArray`.
213
- *
214
- * @private
215
- * @param {Object} typedArray The typed array to clone.
216
- * @param {boolean} [isDeep] Specify a deep clone.
217
- * @returns {Object} Returns the cloned typed array.
218
- */
219
- function cloneTypedArray(typedArray, isDeep) {
220
- var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
221
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
222
- }
223
- //#endregion
224
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneByTag.js
225
- /** `Object#toString` result references. */
226
- var boolTag$1 = "[object Boolean]";
227
- var dateTag$1 = "[object Date]";
228
- var mapTag$2 = "[object Map]";
229
- var numberTag$1 = "[object Number]";
230
- var regexpTag$1 = "[object RegExp]";
231
- var setTag$2 = "[object Set]";
232
- var stringTag$1 = "[object String]";
233
- var symbolTag$1 = "[object Symbol]";
234
- var arrayBufferTag$1 = "[object ArrayBuffer]";
235
- var dataViewTag$1 = "[object DataView]";
236
- var float32Tag$1 = "[object Float32Array]";
237
- var float64Tag$1 = "[object Float64Array]";
238
- var int8Tag$1 = "[object Int8Array]";
239
- var int16Tag$1 = "[object Int16Array]";
240
- var int32Tag$1 = "[object Int32Array]";
241
- var uint8Tag$1 = "[object Uint8Array]";
242
- var uint8ClampedTag$1 = "[object Uint8ClampedArray]";
243
- var uint16Tag$1 = "[object Uint16Array]";
244
- var uint32Tag$1 = "[object Uint32Array]";
245
- /**
246
- * Initializes an object clone based on its `toStringTag`.
247
- *
248
- * **Note:** This function only supports cloning values with tags of
249
- * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
250
- *
251
- * @private
252
- * @param {Object} object The object to clone.
253
- * @param {string} tag The `toStringTag` of the object to clone.
254
- * @param {boolean} [isDeep] Specify a deep clone.
255
- * @returns {Object} Returns the initialized clone.
256
- */
257
- function initCloneByTag(object, tag, isDeep) {
258
- var Ctor = object.constructor;
259
- switch (tag) {
260
- case arrayBufferTag$1: return cloneArrayBuffer(object);
261
- case boolTag$1:
262
- case dateTag$1: return new Ctor(+object);
263
- case dataViewTag$1: return cloneDataView(object, isDeep);
264
- case float32Tag$1:
265
- case float64Tag$1:
266
- case int8Tag$1:
267
- case int16Tag$1:
268
- case int32Tag$1:
269
- case uint8Tag$1:
270
- case uint8ClampedTag$1:
271
- case uint16Tag$1:
272
- case uint32Tag$1: return cloneTypedArray(object, isDeep);
273
- case mapTag$2: return new Ctor();
274
- case numberTag$1:
275
- case stringTag$1: return new Ctor(object);
276
- case regexpTag$1: return cloneRegExp(object);
277
- case setTag$2: return new Ctor();
278
- case symbolTag$1: return cloneSymbol(object);
279
- }
280
- }
281
- //#endregion
282
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_initCloneObject.js
283
- /**
284
- * Initializes an object clone.
285
- *
286
- * @private
287
- * @param {Object} object The object to clone.
288
- * @returns {Object} Returns the initialized clone.
289
- */
290
- function initCloneObject(object) {
291
- return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
292
- }
293
- //#endregion
294
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsMap.js
295
- /** `Object#toString` result references. */
296
- var mapTag$1 = "[object Map]";
297
- /**
298
- * The base implementation of `_.isMap` without Node.js optimizations.
299
- *
300
- * @private
301
- * @param {*} value The value to check.
302
- * @returns {boolean} Returns `true` if `value` is a map, else `false`.
303
- */
304
- function baseIsMap(value) {
305
- return isObjectLike(value) && _getTag_default(value) == mapTag$1;
306
- }
307
- //#endregion
308
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isMap.js
309
- var nodeIsMap = nodeUtil && nodeUtil.isMap;
310
- /**
311
- * Checks if `value` is classified as a `Map` object.
312
- *
313
- * @static
314
- * @memberOf _
315
- * @since 4.3.0
316
- * @category Lang
317
- * @param {*} value The value to check.
318
- * @returns {boolean} Returns `true` if `value` is a map, else `false`.
319
- * @example
320
- *
321
- * _.isMap(new Map);
322
- * // => true
323
- *
324
- * _.isMap(new WeakMap);
325
- * // => false
326
- */
327
- var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
328
- //#endregion
329
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsSet.js
330
- /** `Object#toString` result references. */
331
- var setTag$1 = "[object Set]";
332
- /**
333
- * The base implementation of `_.isSet` without Node.js optimizations.
334
- *
335
- * @private
336
- * @param {*} value The value to check.
337
- * @returns {boolean} Returns `true` if `value` is a set, else `false`.
338
- */
339
- function baseIsSet(value) {
340
- return isObjectLike(value) && _getTag_default(value) == setTag$1;
341
- }
342
- //#endregion
343
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isSet.js
344
- var nodeIsSet = nodeUtil && nodeUtil.isSet;
345
- /**
346
- * Checks if `value` is classified as a `Set` object.
347
- *
348
- * @static
349
- * @memberOf _
350
- * @since 4.3.0
351
- * @category Lang
352
- * @param {*} value The value to check.
353
- * @returns {boolean} Returns `true` if `value` is a set, else `false`.
354
- * @example
355
- *
356
- * _.isSet(new Set);
357
- * // => true
358
- *
359
- * _.isSet(new WeakSet);
360
- * // => false
361
- */
362
- var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
363
- //#endregion
364
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseClone.js
365
- /** Used to compose bitmasks for cloning. */
366
- var CLONE_DEEP_FLAG$2 = 1;
367
- var CLONE_FLAT_FLAG$1 = 2;
368
- var CLONE_SYMBOLS_FLAG$2 = 4;
369
- /** `Object#toString` result references. */
370
- var argsTag = "[object Arguments]";
371
- var arrayTag = "[object Array]";
372
- var boolTag = "[object Boolean]";
373
- var dateTag = "[object Date]";
374
- var errorTag = "[object Error]";
375
- var funcTag = "[object Function]";
376
- var genTag = "[object GeneratorFunction]";
377
- var mapTag = "[object Map]";
378
- var numberTag = "[object Number]";
379
- var objectTag = "[object Object]";
380
- var regexpTag = "[object RegExp]";
381
- var setTag = "[object Set]";
382
- var stringTag = "[object String]";
383
- var symbolTag = "[object Symbol]";
384
- var weakMapTag = "[object WeakMap]";
385
- var arrayBufferTag = "[object ArrayBuffer]";
386
- var dataViewTag = "[object DataView]";
387
- var float32Tag = "[object Float32Array]";
388
- var float64Tag = "[object Float64Array]";
389
- var int8Tag = "[object Int8Array]";
390
- var int16Tag = "[object Int16Array]";
391
- var int32Tag = "[object Int32Array]";
392
- var uint8Tag = "[object Uint8Array]";
393
- var uint8ClampedTag = "[object Uint8ClampedArray]";
394
- var uint16Tag = "[object Uint16Array]";
395
- var uint32Tag = "[object Uint32Array]";
396
- /** Used to identify `toStringTag` values supported by `_.clone`. */
397
- var cloneableTags = {};
398
- cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
399
- cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
400
- /**
401
- * The base implementation of `_.clone` and `_.cloneDeep` which tracks
402
- * traversed objects.
403
- *
404
- * @private
405
- * @param {*} value The value to clone.
406
- * @param {boolean} bitmask The bitmask flags.
407
- * 1 - Deep clone
408
- * 2 - Flatten inherited properties
409
- * 4 - Clone symbols
410
- * @param {Function} [customizer] The function to customize cloning.
411
- * @param {string} [key] The key of `value`.
412
- * @param {Object} [object] The parent object of `value`.
413
- * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
414
- * @returns {*} Returns the cloned value.
415
- */
416
- function baseClone(value, bitmask, customizer, key, object, stack) {
417
- var result, isDeep = bitmask & CLONE_DEEP_FLAG$2, isFlat = bitmask & CLONE_FLAT_FLAG$1, isFull = bitmask & CLONE_SYMBOLS_FLAG$2;
418
- if (customizer) result = object ? customizer(value, key, object, stack) : customizer(value);
419
- if (result !== void 0) return result;
420
- if (!isObject(value)) return value;
421
- var isArr = isArray(value);
422
- if (isArr) {
423
- result = initCloneArray(value);
424
- if (!isDeep) return copyArray(value, result);
425
- } else {
426
- var tag = _getTag_default(value), isFunc = tag == funcTag || tag == genTag;
427
- if (isBuffer(value)) return cloneBuffer(value, isDeep);
428
- if (tag == objectTag || tag == argsTag || isFunc && !object) {
429
- result = isFlat || isFunc ? {} : initCloneObject(value);
430
- if (!isDeep) return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value));
431
- } else {
432
- if (!cloneableTags[tag]) return object ? value : {};
433
- result = initCloneByTag(value, tag, isDeep);
434
- }
435
- }
436
- stack || (stack = new Stack());
437
- var stacked = stack.get(value);
438
- if (stacked) return stacked;
439
- stack.set(value, result);
440
- if (isSet(value)) value.forEach(function(subValue) {
441
- result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
442
- });
443
- else if (isMap(value)) value.forEach(function(subValue, key) {
444
- result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
445
- });
446
- var props = isArr ? void 0 : (isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys)(value);
447
- arrayEach(props || value, function(subValue, key) {
448
- if (props) {
449
- key = subValue;
450
- subValue = value[key];
451
- }
452
- assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
453
- });
454
- return result;
455
- }
456
- //#endregion
457
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/cloneDeep.js
458
- /** Used to compose bitmasks for cloning. */
459
- var CLONE_DEEP_FLAG$1 = 1;
460
- var CLONE_SYMBOLS_FLAG$1 = 4;
461
- /**
462
- * This method is like `_.clone` except that it recursively clones `value`.
463
- *
464
- * @static
465
- * @memberOf _
466
- * @since 1.0.0
467
- * @category Lang
468
- * @param {*} value The value to recursively clone.
469
- * @returns {*} Returns the deep cloned value.
470
- * @see _.clone
471
- * @example
472
- *
473
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
474
- *
475
- * var deep = _.cloneDeep(objects);
476
- * console.log(deep[0] === objects[0]);
477
- * // => false
478
- */
479
- function cloneDeep(value) {
480
- return baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
481
- }
482
- //#endregion
483
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/last.js
484
- /**
485
- * Gets the last element of `array`.
486
- *
487
- * @static
488
- * @memberOf _
489
- * @since 0.1.0
490
- * @category Array
491
- * @param {Array} array The array to query.
492
- * @returns {*} Returns the last element of `array`.
493
- * @example
494
- *
495
- * _.last([1, 2, 3]);
496
- * // => 3
497
- */
498
- function last(array) {
499
- var length = array == null ? 0 : array.length;
500
- return length ? array[length - 1] : void 0;
501
- }
502
- //#endregion
503
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_parent.js
504
- /**
505
- * Gets the parent value at `path` of `object`.
506
- *
507
- * @private
508
- * @param {Object} object The object to query.
509
- * @param {Array} path The path to get the parent value of.
510
- * @returns {*} Returns the parent value.
511
- */
512
- function parent(object, path) {
513
- return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
514
- }
515
- //#endregion
516
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnset.js
517
- /**
518
- * The base implementation of `_.unset`.
519
- *
520
- * @private
521
- * @param {Object} object The object to modify.
522
- * @param {Array|string} path The property path to unset.
523
- * @returns {boolean} Returns `true` if the property is deleted, else `false`.
524
- */
525
- function baseUnset(object, path) {
526
- path = castPath(path, object);
527
- object = parent(object, path);
528
- return object == null || delete object[toKey(last(path))];
529
- }
530
- //#endregion
531
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_customOmitClone.js
532
- /**
533
- * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
534
- * objects.
535
- *
536
- * @private
537
- * @param {*} value The value to inspect.
538
- * @param {string} key The key of the property to inspect.
539
- * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
540
- */
541
- function customOmitClone(value) {
542
- return isPlainObject(value) ? void 0 : value;
543
- }
544
- //#endregion
545
- //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/omit.js
546
- /** Used to compose bitmasks for cloning. */
547
- var CLONE_DEEP_FLAG = 1;
548
- var CLONE_FLAT_FLAG = 2;
549
- var CLONE_SYMBOLS_FLAG = 4;
550
- /**
551
- * The opposite of `_.pick`; this method creates an object composed of the
552
- * own and inherited enumerable property paths of `object` that are not omitted.
553
- *
554
- * **Note:** This method is considerably slower than `_.pick`.
555
- *
556
- * @static
557
- * @since 0.1.0
558
- * @memberOf _
559
- * @category Object
560
- * @param {Object} object The source object.
561
- * @param {...(string|string[])} [paths] The property paths to omit.
562
- * @returns {Object} Returns the new object.
563
- * @example
564
- *
565
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
566
- *
567
- * _.omit(object, ['a', 'c']);
568
- * // => { 'b': '2' }
569
- */
570
- var omit = flatRest(function(object, paths) {
571
- var result = {};
572
- if (object == null) return result;
573
- var isDeep = false;
574
- paths = arrayMap(paths, function(path) {
575
- path = castPath(path, object);
576
- isDeep || (isDeep = path.length > 1);
577
- return path;
578
- });
579
- copyObject(object, getAllKeysIn(object), result);
580
- if (isDeep) result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
581
- var length = paths.length;
582
- while (length--) baseUnset(result, paths[length]);
583
- return result;
584
- });
585
- //#endregion
586
- //#region src/exit-parser.ts
587
- /**
588
- * Checks if a value is primitive (not an object or is an array/null)
589
- */
590
- function isValuePrimitive(value) {
591
- return value === null || value === void 0 || typeof value !== "object" || Array.isArray(value);
592
- }
593
- /**
594
- * Generates possible wraps for a primitive value in an object schema
595
- */
596
- function generatePossibleWraps(value, shape, discriminator) {
597
- const possibleWraps = [];
598
- const commonNames = [
599
- "result",
600
- "value",
601
- "data",
602
- "message",
603
- "error",
604
- "output",
605
- "response"
606
- ];
607
- if (shape && typeof shape === "object") {
608
- for (const key of Object.keys(shape)) if (key !== discriminator) {
609
- const wrap = discriminator ? {
610
- [discriminator]: shape[discriminator]._def.value,
611
- [key]: value
612
- } : { [key]: value };
613
- possibleWraps.push(wrap);
614
- }
615
- }
616
- for (const name of commonNames) if (!possibleWraps.some((w) => Object.keys(w).includes(name))) {
617
- const wrap = discriminator && (shape === null || shape === void 0 ? void 0 : shape[discriminator]) ? {
618
- [discriminator]: shape[discriminator]._def.value,
619
- [name]: value
620
- } : { [name]: value };
621
- possibleWraps.push(wrap);
622
- }
623
- return possibleWraps;
624
- }
625
- /**
626
- * Tries to wrap a primitive value in object schemas
627
- */
628
- function tryObjectWrapping(schema, candidateValue) {
629
- const possibleWraps = generatePossibleWraps(candidateValue, schema.shape);
630
- for (const wrap of possibleWraps) {
631
- const testParse = schema.safeParse(wrap);
632
- if (testParse.success) return {
633
- success: true,
634
- valueToValidate: wrap,
635
- parsed: testParse
636
- };
637
- }
638
- return {
639
- success: false,
640
- valueToValidate: candidateValue,
641
- parsed: { success: false }
642
- };
643
- }
644
- /**
645
- * Detects discriminator field from union options
646
- */
647
- function detectDiscriminator(options) {
648
- if (options.length === 0 || options[0]._def.typeName !== "ZodObject") return;
649
- const firstShape = options[0].shape;
650
- for (const key in firstShape) if (firstShape[key]._def.typeName === "ZodLiteral") {
651
- if (options.every((opt) => {
652
- var _opt$shape$key;
653
- return ((_opt$shape$key = opt.shape[key]) === null || _opt$shape$key === void 0 ? void 0 : _opt$shape$key._def.typeName) === "ZodLiteral";
654
- })) return key;
655
- }
656
- }
657
- /**
658
- * Tries to add missing discriminator to object values
659
- */
660
- function tryAddDiscriminator(schema, options, discriminator, valueToValidate) {
661
- const matchingOptions = [];
662
- for (const option of options) if (option._def.typeName === "ZodObject" && option.shape[discriminator]) {
663
- const discriminatorValue = option.shape[discriminator]._def.value;
664
- const wrappedValue = {
665
- [discriminator]: discriminatorValue,
666
- ...valueToValidate
667
- };
668
- if (schema.safeParse(wrappedValue).success) matchingOptions.push({ wrappedValue });
669
- }
670
- if (matchingOptions.length === 1) {
671
- const wrapped = matchingOptions[0].wrappedValue;
672
- return {
673
- success: true,
674
- valueToValidate: wrapped,
675
- parsed: schema.safeParse(wrapped)
676
- };
677
- }
678
- return {
679
- success: false,
680
- valueToValidate,
681
- parsed: { success: false }
682
- };
683
- }
684
- /**
685
- * Tries to wrap primitive in union options
686
- */
687
- function tryUnionPrimitiveWrapping(schema, options, discriminator, valueToValidate) {
688
- const allSuccessfulWraps = [];
689
- for (const option of options) if (option._def.typeName === "ZodObject" && option.shape[discriminator]) {
690
- const discriminatorValue = option.shape[discriminator]._def.value;
691
- const possibleWraps = generatePossibleWraps(valueToValidate, option.shape, discriminator);
692
- for (const wrap of possibleWraps) {
693
- const finalWrap = {
694
- [discriminator]: discriminatorValue,
695
- ...wrap
696
- };
697
- if (schema.safeParse(finalWrap).success) {
698
- allSuccessfulWraps.push({ wrap: finalWrap });
699
- break;
700
- }
701
- }
702
- }
703
- if (allSuccessfulWraps.length === 1) {
704
- const wrapped = allSuccessfulWraps[0].wrap;
705
- return {
706
- success: true,
707
- valueToValidate: wrapped,
708
- parsed: schema.safeParse(wrapped)
709
- };
710
- }
711
- return {
712
- success: false,
713
- valueToValidate,
714
- parsed: { success: false }
715
- };
716
- }
717
- /**
718
- * Tries smart wrapping for union schemas
719
- */
720
- function tryUnionWrapping(schema, valueToValidate) {
721
- const options = schema._def.options;
722
- let discriminator = schema._def.discriminator;
723
- if (!discriminator) discriminator = detectDiscriminator(options);
724
- if (!discriminator) return {
725
- success: false,
726
- valueToValidate,
727
- parsed: { success: false }
728
- };
729
- const isValueObject = valueToValidate !== null && typeof valueToValidate === "object" && !Array.isArray(valueToValidate);
730
- const isPrimitive = isValuePrimitive(valueToValidate);
731
- if (isValueObject && !(discriminator in valueToValidate)) {
732
- const result = tryAddDiscriminator(schema, options, discriminator, valueToValidate);
733
- if (result.success) return result;
734
- }
735
- if (isPrimitive) return tryUnionPrimitiveWrapping(schema, options, discriminator, valueToValidate);
736
- return {
737
- success: false,
738
- valueToValidate,
739
- parsed: { success: false }
740
- };
741
- }
742
- /**
743
- * Attempts various smart wrapping strategies to fit data to schema
744
- */
745
- function trySmartWrapping(schema, schemaType, valueToValidate, alternativeValue) {
746
- const valuesToTry = [valueToValidate];
747
- if (alternativeValue !== void 0 && alternativeValue !== valueToValidate) valuesToTry.push(alternativeValue);
748
- for (const candidateValue of valuesToTry) {
749
- const isPrimitive = isValuePrimitive(candidateValue);
750
- if (schemaType === "ZodObject" && isPrimitive) {
751
- const result = tryObjectWrapping(schema, candidateValue);
752
- if (result.success) return result;
753
- }
754
- }
755
- if (alternativeValue !== void 0 && alternativeValue !== valueToValidate) valueToValidate = alternativeValue;
756
- if (schemaType === "ZodDiscriminatedUnion" || schemaType === "ZodUnion") {
757
- const result = tryUnionWrapping(schema, valueToValidate);
758
- if (result.success) return result;
759
- }
760
- return {
761
- valueToValidate,
762
- parsed: { success: false }
763
- };
764
- }
765
- /**
766
- * Parses and validates a return value against a list of exits.
767
- * Attempts to intelligently fit the data to the expected schema.
768
- *
769
- * @param returnValue - The raw return value from code execution
770
- * @param exits - Available exits to match against
771
- * @returns Parsed exit result with validated data or error
772
- *
773
- * @example
774
- * ```typescript
775
- * const exits = [
776
- * new Exit({ name: 'done', schema: z.object({ result: z.string() }) })
777
- * ]
778
- *
779
- * // Returns primitive value - will be smart-wrapped
780
- * const result = parseExit({ action: 'done', data: 'hello' }, exits)
781
- * // result.success === true
782
- * // result.value === { result: 'hello' }
783
- * ```
784
- */
785
- function parseExit(returnValue, exits) {
786
- if (!returnValue) return {
787
- success: false,
788
- error: "No return value provided",
789
- returnValue
790
- };
791
- const returnAction = returnValue.action;
792
- if (!returnAction) return {
793
- success: false,
794
- error: `Code did not return an action. Valid actions are: ${exits.map((x) => x.name).join(", ")}`,
795
- returnValue
796
- };
797
- const returnExit = exits.find((x) => x.name.toLowerCase() === returnAction.toLowerCase()) ?? exits.find((x) => x.aliases.some((a) => a.toLowerCase() === returnAction.toLowerCase()));
798
- if (!returnExit) return {
799
- success: false,
800
- error: `Exit "${returnAction}" not found. Valid actions are: ${exits.map((x) => x.name).join(", ")}`,
801
- returnValue
802
- };
803
- if (!returnExit.zSchema) {
804
- const otherProps = omit(returnValue, "action");
805
- return {
806
- success: true,
807
- exit: returnExit,
808
- value: Object.keys(otherProps).length === 1 ? Object.values(otherProps)[0] : otherProps
809
- };
810
- }
811
- let valueToValidate = returnValue.value;
812
- let alternativeValue = void 0;
813
- if (valueToValidate === void 0) {
814
- const otherProps = omit(returnValue, "action");
815
- if (Object.keys(otherProps).length > 0) {
816
- valueToValidate = otherProps;
817
- if (Object.keys(otherProps).length === 1) alternativeValue = Object.values(otherProps)[0];
818
- }
819
- }
820
- const schema = returnExit.zSchema;
821
- const schemaType = schema._def.typeName;
822
- const initialParse = schema.safeParse(valueToValidate);
823
- let parsed = initialParse;
824
- if (!parsed.success && alternativeValue !== void 0 && alternativeValue !== valueToValidate) {
825
- const altParsed = schema.safeParse(alternativeValue);
826
- if (altParsed.success) {
827
- parsed = altParsed;
828
- valueToValidate = alternativeValue;
829
- }
830
- }
831
- if (!parsed.success) {
832
- const result = trySmartWrapping(schema, schemaType, valueToValidate, alternativeValue);
833
- valueToValidate = result.valueToValidate;
834
- parsed = result.parsed;
835
- }
836
- if (!parsed.success) {
837
- var _initialParse$error;
838
- const getValueTypeDescription = (val) => {
839
- if (val === null) return "null";
840
- if (val === void 0) return "undefined";
841
- if (Array.isArray(val)) return "array";
842
- return typeof val;
843
- };
844
- const generatedType = getValueTypeDescription(valueToValidate);
845
- let generatedStatement = `return { action: '${returnAction}'`;
846
- if (returnValue.value !== void 0) generatedStatement += `, value: ${generatedType}`;
847
- else {
848
- const otherProps = omit(returnValue, "action");
849
- const propKeys = Object.keys(otherProps);
850
- if (propKeys.length === 1) generatedStatement += `, ${propKeys[0]}: ${generatedType}`;
851
- else if (propKeys.length > 1) generatedStatement += `, ${propKeys.join(", ")}`;
852
- }
853
- generatedStatement += " }";
854
- const expectedStatements = [];
855
- for (const exit of exits) {
856
- let statement = `return { action: '${exit.name}'`;
857
- if (exit.zSchema) {
858
- const schema = exit.zSchema;
859
- const typeName = schema._def.typeName;
860
- if (typeName === "ZodObject") {
861
- const shape = schema.shape;
862
- const properties = Object.keys(shape).map((key) => {
863
- var _field$isOptional;
864
- const field = shape[key];
865
- const fieldType = field._def.typeName || "unknown";
866
- return `${key}${((_field$isOptional = field.isOptional) === null || _field$isOptional === void 0 ? void 0 : _field$isOptional.call(field)) || false ? "?" : ""}: ${fieldType.replace("Zod", "").toLowerCase()}`;
867
- });
868
- statement += `, value: { ${properties.join(", ")} }`;
869
- } else if (typeName === "ZodUnion" || typeName === "ZodDiscriminatedUnion") {
870
- const variants = (schema._def.options || []).map((opt) => {
871
- if (opt._def.typeName === "ZodObject") {
872
- const shape = opt.shape;
873
- return `{ ${Object.keys(shape).map((key) => {
874
- return `${key}: ${(shape[key]._def.typeName || "unknown").replace("Zod", "").toLowerCase()}`;
875
- }).join(", ")} }`;
876
- }
877
- return "unknown";
878
- });
879
- statement += `, value: ${variants.join(" | ")}`;
880
- } else {
881
- const schemaTypeName = (typeName === null || typeName === void 0 ? void 0 : typeName.replace("Zod", "").toLowerCase()) || "unknown";
882
- statement += `, value: ${schemaTypeName}`;
883
- }
884
- }
885
- statement += " }";
886
- expectedStatements.push(statement);
887
- }
888
- return {
889
- success: false,
890
- error: [
891
- `Invalid return value for exit "${returnExit.name}"`,
892
- "",
893
- "You generated:",
894
- ` ${generatedStatement}`,
895
- "",
896
- "But expected one of:",
897
- ...expectedStatements.map((s) => ` ${s}`)
898
- ].join("\n"),
899
- validationErrors: (((_initialParse$error = initialParse.error) === null || _initialParse$error === void 0 ? void 0 : _initialParse$error.issues) ?? []).map((issue) => `${issue.path.join(".") || "value"}: ${issue.message}`),
900
- returnValue
901
- };
902
- }
903
- return {
904
- success: true,
905
- exit: returnExit,
906
- value: parsed.data
907
- };
908
- }
909
- //#endregion
910
- //#region src/snapshots.ts
911
- const MAX_SNAPSHOT_SIZE_BYTES = 4e3;
912
- /**
913
- * Snapshot represents a captured execution state that can be persisted and restored later.
914
- *
915
- * Snapshots are created when a SnapshotSignal is thrown during execution, typically from
916
- * within a tool handler to pause execution for long-running operations that need to be
917
- * completed asynchronously (e.g., background jobs, external API calls, user input).
918
- *
919
- * ## Use Cases
920
- * - **Long-running operations**: Pause execution while waiting for external processes
921
- * - **User interaction**: Collect input from users before continuing execution
922
- * - **Resource management**: Defer expensive operations to background workers
923
- * - **Workflow persistence**: Save execution state across process restarts
924
- *
925
- * ## Basic Usage
926
- *
927
- * ### Creating a Snapshot
928
- * From within a tool handler, throw a SnapshotSignal to create a snapshot:
929
- * ```typescript
930
- * const tool = new Tool({
931
- * handler: async ({ input }) => {
932
- * // Start long-running operation
933
- * throw new SnapshotSignal('Waiting for external API response')
934
- * }
935
- * })
936
- * ```
937
- *
938
- * ### Handling Interrupted Execution
939
- * ```typescript
940
- * const result = await execute({ tools: [tool], ... })
941
- *
942
- * if (result.isInterrupted()) {
943
- * const snapshot = result.snapshot
944
- *
945
- * // Serialize for persistence
946
- * const serialized = snapshot.toJSON()
947
- * await database.saveSnapshot(serialized)
948
- * }
949
- * ```
950
- *
951
- * ### Resuming from Snapshot
952
- * ```typescript
953
- * // Restore from persistence
954
- * const serialized = await database.getSnapshot(id)
955
- * const snapshot = Snapshot.fromJSON(serialized)
956
- *
957
- * // Resolve with the result of the long-running operation
958
- * snapshot.resolve({ result: 'Operation completed!' })
959
- *
960
- * // Continue execution
961
- * const continuation = await execute({
962
- * snapshot,
963
- * instructions: originalInstructions,
964
- * tools: originalTools,
965
- * exits: originalExits,
966
- * client
967
- * })
968
- * ```
969
- *
970
- * ## Snapshot Lifecycle
971
- * 1. **Created**: When SnapshotSignal is thrown (status: pending)
972
- * 2. **Serialized**: Convert to JSON for persistence with toJSON()
973
- * 3. **Restored**: Recreate from JSON with fromJSON()
974
- * 4. **Resolved/Rejected**: Provide result data with resolve() or reject()
975
- * 5. **Resumed**: Continue execution with the resolved snapshot
976
- *
977
- * ## What's Captured
978
- * - **Execution stack**: Current code position and call stack
979
- * - **Variables**: All local variables and their values (up to size limit)
980
- * - **Tool context**: Information about the tool call that triggered the snapshot
981
- * - **Reason**: Human-readable description of why the snapshot was created
982
- *
983
- * @see {@link https://github.com/botpress/botpress/blob/master/packages/llmz/examples/14_worker_snapshot/index.ts} Example usage
984
- */
985
- var Snapshot = class Snapshot {
986
- id;
987
- reason;
988
- stack;
989
- toolCall;
990
- variables;
991
- #status;
992
- /**
993
- * Gets the current status of the snapshot.
994
- *
995
- * @returns The snapshot status (pending, resolved, or rejected)
996
- */
997
- get status() {
998
- return Object.freeze({ ...this.#status });
999
- }
1000
- constructor(props) {
1001
- this.id = props.id;
1002
- this.stack = props.stack;
1003
- this.reason = props.reason;
1004
- this.variables = props.variables;
1005
- this.toolCall = props.toolCall;
1006
- this.#status = props.status;
1007
- }
1008
- /**
1009
- * Creates a new Snapshot from a SnapshotSignal.
1010
- *
1011
- * This method is called internally by the LLMz execution engine when a SnapshotSignal
1012
- * is thrown during execution. It captures the current execution state including
1013
- * variables, stack trace, and tool context.
1014
- *
1015
- * @param signal The SnapshotSignal containing execution state
1016
- * @returns A new Snapshot instance in pending status
1017
- * @internal
1018
- */
1019
- static fromSignal(signal) {
1020
- return new Snapshot({
1021
- id: "snapshot_" + ulid(),
1022
- reason: signal.message,
1023
- stack: signal.truncatedCode,
1024
- variables: parseVariables(signal.variables),
1025
- toolCall: signal.toolCall,
1026
- status: { type: "pending" }
1027
- });
1028
- }
1029
- /**
1030
- * Serializes the snapshot to a JSON-compatible object for persistence.
1031
- *
1032
- * Use this method to save snapshots to databases, files, or other storage systems.
1033
- * The serialized snapshot can be restored later using fromJSON().
1034
- *
1035
- * @returns A JSON-serializable representation of the snapshot
1036
- * @example
1037
- * ```typescript
1038
- * const snapshot = result.snapshot
1039
- * const serialized = snapshot.toJSON()
1040
- * await database.save('snapshots', snapshot.id, serialized)
1041
- * ```
1042
- */
1043
- toJSON() {
1044
- return {
1045
- id: this.id,
1046
- reason: this.reason,
1047
- stack: this.stack,
1048
- variables: this.variables,
1049
- toolCall: this.toolCall,
1050
- status: this.#status
1051
- };
1052
- }
1053
- /**
1054
- * Restores a snapshot from its JSON representation.
1055
- *
1056
- * Use this method to recreate snapshots from persistent storage. The restored
1057
- * snapshot will maintain its original state and can be resolved/rejected as needed.
1058
- *
1059
- * @param json The serialized snapshot data from toJSON()
1060
- * @returns A restored Snapshot instance
1061
- * @example
1062
- * ```typescript
1063
- * const serialized = await database.get('snapshots', snapshotId)
1064
- * const snapshot = Snapshot.fromJSON(serialized)
1065
- * ```
1066
- */
1067
- static fromJSON(json) {
1068
- return new Snapshot({
1069
- id: json.id,
1070
- reason: json.reason,
1071
- stack: json.stack,
1072
- variables: json.variables,
1073
- toolCall: json.toolCall,
1074
- status: json.status
1075
- });
1076
- }
1077
- /**
1078
- * Creates a deep copy of the snapshot.
1079
- *
1080
- * @returns A new Snapshot instance with identical data
1081
- */
1082
- clone() {
1083
- return new Snapshot({
1084
- id: this.id,
1085
- reason: this.reason,
1086
- stack: this.stack,
1087
- variables: this.variables,
1088
- toolCall: this.toolCall,
1089
- status: this.#status
1090
- });
1091
- }
1092
- /**
1093
- * Resets the snapshot status back to pending.
1094
- *
1095
- * This allows a previously resolved or rejected snapshot to be resolved/rejected
1096
- * again with different data. Useful for retry scenarios.
1097
- */
1098
- reset() {
1099
- this.#status = { type: "pending" };
1100
- }
1101
- /**
1102
- * Resolves the snapshot with a successful result value.
1103
- *
1104
- * Call this method when the long-running operation that caused the snapshot
1105
- * has completed successfully. The provided value will be returned as the
1106
- * result of the original tool call when execution resumes.
1107
- *
1108
- * @param value The result value from the completed operation
1109
- * @throws Error if the snapshot is not in pending status
1110
- * @example
1111
- * ```typescript
1112
- * // After a background job completes
1113
- * const result = await backgroundJob.getResult()
1114
- * snapshot.resolve(result)
1115
- *
1116
- * // Continue execution
1117
- * const continuation = await execute({ snapshot, ... })
1118
- * ```
1119
- */
1120
- resolve(value) {
1121
- var _this$toolCall;
1122
- if (this.#status.type !== "pending") throw new Error(`Cannot resolve snapshot because it is already settled: ${this.#status.type}`);
1123
- const assignment = (_this$toolCall = this.toolCall) === null || _this$toolCall === void 0 ? void 0 : _this$toolCall.assignment;
1124
- if (assignment) try {
1125
- const assignmentValue = new Function(assignment.evalFn)(value);
1126
- this.variables = [...this.variables, ...parseVariables(assignmentValue)];
1127
- } catch {}
1128
- this.#status = {
1129
- type: "resolved",
1130
- value
1131
- };
1132
- }
1133
- /**
1134
- * Rejects the snapshot with an error.
1135
- *
1136
- * Call this method when the long-running operation that caused the snapshot
1137
- * has failed or encountered an error. The provided error will be thrown
1138
- * when execution resumes, allowing the generated code to handle it.
1139
- *
1140
- * @param error The error that occurred during the operation
1141
- * @throws Error if the snapshot is not in pending status
1142
- * @example
1143
- * ```typescript
1144
- * try {
1145
- * const result = await externalAPI.call()
1146
- * snapshot.resolve(result)
1147
- * } catch (error) {
1148
- * snapshot.reject(error)
1149
- * }
1150
- *
1151
- * // Continue execution (will throw the error)
1152
- * const continuation = await execute({ snapshot, ... })
1153
- * ```
1154
- */
1155
- reject(error) {
1156
- if (this.#status.type !== "pending") throw new Error(`Cannot reject snapshot because it is already settled: ${this.#status.type}`);
1157
- this.#status = {
1158
- type: "rejected",
1159
- error
1160
- };
1161
- }
1162
- };
1163
- function parseVariables(variableMap) {
1164
- return Object.entries(variableMap).map(([name, value]) => {
1165
- const type = extractType(value);
1166
- const bytes = JSON.stringify(value || "").length;
1167
- return bytes > MAX_SNAPSHOT_SIZE_BYTES ? {
1168
- name,
1169
- type,
1170
- bytes,
1171
- truncated: true,
1172
- preview: inspect(value, name) ?? "N/A"
1173
- } : {
1174
- name,
1175
- type,
1176
- bytes,
1177
- truncated: false,
1178
- value
1179
- };
1180
- });
1181
- }
1182
- //#endregion
1183
- //#region src/result.ts
1184
- /**
1185
- * Base class for all execution results returned by the `execute()` function.
1186
- *
1187
- * ExecutionResult provides a type-safe way to handle the different outcomes of LLMz
1188
- * agent execution. All results contain the execution context and provide methods
1189
- * to check the final status and access relevant data.
1190
- *
1191
- * ## Result Types
1192
- *
1193
- * LLMz execution can result in three different outcomes:
1194
- * - **Success**: Agent completed with an Exit (SuccessExecutionResult)
1195
- * - **Error**: Execution failed with an unrecoverable error (ErrorExecutionResult)
1196
- * - **Interrupted**: Execution was paused for snapshots or cancellation (PartialExecutionResult)
1197
- *
1198
- * ## Usage Patterns
1199
- *
1200
- * ### Basic Status Checking
1201
- * ```typescript
1202
- * const result = await execute({
1203
- * instructions: 'Calculate the sum of numbers 1 to 100',
1204
- * client,
1205
- * })
1206
- *
1207
- * if (result.isSuccess()) {
1208
- * console.log('Success:', result.output)
1209
- * } else if (result.isError()) {
1210
- * console.error('Error:', result.error)
1211
- * } else if (result.isInterrupted()) {
1212
- * console.log('Interrupted - snapshot available:', !!result.snapshot)
1213
- * }
1214
- * ```
1215
- *
1216
- * ### Type-Safe Exit Checking
1217
- * ```typescript
1218
- * const dataExit = new Exit({
1219
- * name: 'dataProcessed',
1220
- * schema: z.object({
1221
- * recordCount: z.number(),
1222
- * processingTime: z.number(),
1223
- * }),
1224
- * })
1225
- *
1226
- * const result = await execute({
1227
- * instructions: 'Process the data',
1228
- * exits: [dataExit],
1229
- * client,
1230
- * })
1231
- *
1232
- * // Type-safe exit checking with typed output access
1233
- * if (result.is(dataExit)) {
1234
- * console.log(`Processed ${result.output.recordCount} records`)
1235
- * console.log(`Processing took ${result.output.processingTime}ms`)
1236
- * }
1237
- * ```
1238
- *
1239
- * ### Accessing Execution Details
1240
- * ```typescript
1241
- * if (result.isSuccess()) {
1242
- * // Access the generated code from the final iteration
1243
- * console.log('Generated code:', result.iteration.code)
1244
- *
1245
- * // Access all iterations to see the full execution flow
1246
- * result.iterations.forEach((iteration, index) => {
1247
- * console.log(`Iteration ${index + 1}:`, iteration.status.type)
1248
- * })
1249
- *
1250
- * // Access execution context
1251
- * console.log('Original instructions:', result.context.instructions)
1252
- * }
1253
- * ```
1254
- *
1255
- * ### Snapshot Handling
1256
- * ```typescript
1257
- * if (result.isInterrupted()) {
1258
- * // Serialize snapshot for persistence
1259
- * const serialized = result.snapshot.toJSON()
1260
- * await database.saveSnapshot(serialized)
1261
- *
1262
- * // Later, resume from snapshot
1263
- * const snapshot = Snapshot.fromJSON(serialized)
1264
- * snapshot.resolve({ data: 'resolved data' })
1265
- *
1266
- * const continuation = await execute({
1267
- * snapshot,
1268
- * instructions: result.context.instructions,
1269
- * tools: result.context.tools,
1270
- * exits: result.context.exits,
1271
- * client,
1272
- * })
1273
- * }
1274
- * ```
1275
- *
1276
- * @see {@link SuccessExecutionResult} For successful execution results
1277
- * @see {@link ErrorExecutionResult} For failed execution results
1278
- * @see {@link PartialExecutionResult} For interrupted execution results
1279
- */
1280
- var ExecutionResult = class {
1281
- status;
1282
- context;
1283
- constructor(status, context) {
1284
- this.status = status;
1285
- this.context = context;
1286
- }
1287
- /**
1288
- * Type guard to check if the execution completed successfully.
1289
- *
1290
- * @returns True if the execution completed with an Exit, false otherwise
1291
- * @example
1292
- * ```typescript
1293
- * const result = await execute({ ... })
1294
- *
1295
- * if (result.isSuccess()) {
1296
- * // TypeScript knows this is SuccessExecutionResult
1297
- * console.log('Output:', result.output)
1298
- * console.log('Exit name:', result.result.exit.name)
1299
- * }
1300
- * ```
1301
- */
1302
- isSuccess() {
1303
- return this.status === "success" && this instanceof SuccessExecutionResult;
1304
- }
1305
- /**
1306
- * Type guard to check if the execution failed with an error.
1307
- *
1308
- * @returns True if the execution failed with an unrecoverable error, false otherwise
1309
- * @example
1310
- * ```typescript
1311
- * const result = await execute({ ... })
1312
- *
1313
- * if (result.isError()) {
1314
- * // TypeScript knows this is ErrorExecutionResult
1315
- * console.error('Execution failed:', result.error)
1316
- *
1317
- * // Access error details from the last iteration
1318
- * const lastIteration = result.iteration
1319
- * if (lastIteration?.status.type === 'execution_error') {
1320
- * console.error('Stack trace:', lastIteration.status.execution_error.stack)
1321
- * }
1322
- * }
1323
- * ```
1324
- */
1325
- isError() {
1326
- return this.status === "error" && this instanceof ErrorExecutionResult;
1327
- }
1328
- /**
1329
- * Type guard to check if the execution was interrupted.
1330
- * Interrupted means there's a snapshot available and the execution was paused and needs resuming.
1331
- *
1332
- * @returns True if the execution was interrupted, false otherwise
1333
- * @example
1334
- * ```typescript
1335
- * const result = await execute({ ... })
1336
- *
1337
- * if (result.isInterrupted()) {
1338
- * // TypeScript knows this is PartialExecutionResult
1339
- * console.log('Execution paused:', result.signal.message)
1340
- *
1341
- * // Access snapshot for later resumption
1342
- * const snapshot = result.snapshot
1343
- * const serialized = snapshot.toJSON()
1344
- * await storage.save('execution-state', serialized)
1345
- * }
1346
- * ```
1347
- */
1348
- isInterrupted() {
1349
- return this.status === "interrupted" && this instanceof PartialExecutionResult;
1350
- }
1351
- /**
1352
- * Type guard to check if the execution completed with a specific exit.
1353
- *
1354
- * This method provides type-safe access to the output data based on the exit's schema.
1355
- * It's the recommended way to handle different exit types in complex agents.
1356
- *
1357
- * @param exit - The Exit instance to check against
1358
- * @returns True if the execution completed with the specified exit, false otherwise
1359
- * @template T - The output type of the exit
1360
- *
1361
- * @example
1362
- * ```typescript
1363
- * // Define typed exits
1364
- * const successExit = new Exit({
1365
- * name: 'success',
1366
- * schema: z.object({
1367
- * message: z.string(),
1368
- * count: z.number(),
1369
- * }),
1370
- * })
1371
- *
1372
- * const errorExit = new Exit({
1373
- * name: 'error',
1374
- * schema: z.object({
1375
- * errorCode: z.string(),
1376
- * details: z.string(),
1377
- * }),
1378
- * })
1379
- *
1380
- * const result = await execute({
1381
- * instructions: 'Process the data',
1382
- * exits: [successExit, errorExit],
1383
- * client,
1384
- * })
1385
- *
1386
- * // Type-safe exit handling
1387
- * if (result.is(successExit)) {
1388
- * // TypeScript knows result.output has { message: string, count: number }
1389
- * console.log(`Success: ${result.output.message}`)
1390
- * console.log(`Processed ${result.output.count} items`)
1391
- * } else if (result.is(errorExit)) {
1392
- * // TypeScript knows result.output has { errorCode: string, details: string }
1393
- * console.error(`Error ${result.output.errorCode}: ${result.output.details}`)
1394
- * }
1395
- * ```
1396
- */
1397
- is(exit) {
1398
- return this.status === "success" && this instanceof SuccessExecutionResult && this.result.exit === exit;
1399
- }
1400
- /**
1401
- * Gets the output data from the last successful iteration.
1402
- *
1403
- * For successful executions, returns the data produced by the exit.
1404
- * For failed or interrupted executions, returns null.
1405
- *
1406
- * @returns The output data for successful executions, null otherwise
1407
- * @example
1408
- * ```typescript
1409
- * const result = await execute({ ... })
1410
- *
1411
- * // Generic output access
1412
- * if (result.isSuccess()) {
1413
- * console.log('Output:', result.output)
1414
- * }
1415
- *
1416
- * // Type-safe output access with specific exits
1417
- * if (result.is(myExit)) {
1418
- * // result.output is now typed based on myExit's schema
1419
- * console.log(result.output.specificField)
1420
- * }
1421
- * ```
1422
- */
1423
- get output() {
1424
- return this.isSuccess() ? this.result.result : null;
1425
- }
1426
- /**
1427
- * Gets the most recent (last) iteration from the execution.
1428
- *
1429
- * Iterations represent individual steps in the execution loop where the LLM
1430
- * generates code, executes it, and processes the results. The last iteration
1431
- * contains the final generated code and execution status.
1432
- *
1433
- * @returns The last iteration, or null if no iterations were completed
1434
- * @example
1435
- * ```typescript
1436
- * const result = await execute({ ... })
1437
- *
1438
- * const lastIteration = result.iteration
1439
- * if (lastIteration) {
1440
- * console.log('Generated code:', lastIteration.code)
1441
- * console.log('Status:', lastIteration.status.type)
1442
- * console.log('Variables:', lastIteration.variables)
1443
- * console.log('Tool calls:', lastIteration.toolCalls)
1444
- * }
1445
- * ```
1446
- */
1447
- get iteration() {
1448
- return this.context.iterations.at(-1) || null;
1449
- }
1450
- /**
1451
- * Gets all iterations from the execution.
1452
- *
1453
- * This provides access to the complete execution history, showing how the agent
1454
- * progressed through multiple iterations to reach the final result. Useful for
1455
- * debugging, logging, or understanding the agent's reasoning process.
1456
- *
1457
- * @returns Array of all iterations in execution order
1458
- * @example
1459
- * ```typescript
1460
- * const result = await execute({ ... })
1461
- *
1462
- * // Analyze the full execution flow
1463
- * result.iterations.forEach((iteration, index) => {
1464
- * console.log(`Iteration ${index + 1}:`)
1465
- * console.log(' Status:', iteration.status.type)
1466
- * console.log(' Code length:', iteration.code?.length || 0)
1467
- * console.log(' Tool calls:', iteration.toolCalls.length)
1468
- * console.log(' Variables:', Object.keys(iteration.variables).length)
1469
- * })
1470
- *
1471
- * // Find iterations with specific characteristics
1472
- * const iterationsWithErrors = result.iterations.filter(
1473
- * iter => iter.status.type === 'execution_error'
1474
- * )
1475
- *
1476
- * // Calculate total execution time
1477
- * const totalTime = result.iterations.reduce(
1478
- * (sum, iter) => sum + (iter.duration || 0), 0
1479
- * )
1480
- * ```
1481
- */
1482
- get iterations() {
1483
- return this.context.iterations ?? [];
1484
- }
1485
- /**
1486
- * Gets the total token usage of the execution, aggregated across all iterations.
1487
- *
1488
- * `input`/`output` are the provider-reported token counts of every LLM call made
1489
- * during the execution. Per-iteration detail (including the measured context size
1490
- * breakdown by prompt part) is available on each iteration's `tokens` property.
1491
- *
1492
- * @example
1493
- * ```typescript
1494
- * const result = await execute({ ... })
1495
- * console.log(`Execution used ${result.tokens.total} tokens`)
1496
- *
1497
- * for (const iteration of result.iterations) {
1498
- * console.log(iteration.id, iteration.tokens?.context)
1499
- * }
1500
- * ```
1501
- */
1502
- get tokens() {
1503
- let input = 0;
1504
- let output = 0;
1505
- for (const iteration of this.iterations) {
1506
- var _iteration$tokens, _iteration$tokens2;
1507
- input += ((_iteration$tokens = iteration.tokens) === null || _iteration$tokens === void 0 ? void 0 : _iteration$tokens.input) ?? 0;
1508
- output += ((_iteration$tokens2 = iteration.tokens) === null || _iteration$tokens2 === void 0 ? void 0 : _iteration$tokens2.output) ?? 0;
1509
- }
1510
- return {
1511
- input,
1512
- output,
1513
- total: input + output
1514
- };
1515
- }
1516
- };
1517
- /**
1518
- * Result for successful executions that completed with an Exit.
1519
- *
1520
- * SuccessExecutionResult indicates that the agent successfully completed its task
1521
- * and returned structured data through one of the provided exits. This is the
1522
- * most common positive outcome for LLMz executions.
1523
- *
1524
- * In *Worker Mode* (ie. no `chat` provided), if no exits were provided, the "DefaultExit" will be used.
1525
- * If *Chat Mode* is enabled, most likely the "ListenExit" will be used if no exits were provided.
1526
- *
1527
- * You can check for a specific exit using the `is()` method, which provides type-safe access to the output data of the exit.
1528
- * You can import "ListenExit" and "DefaultExit" from `llmz`.
1529
- *
1530
- * @template TOutput - The type of the output data based on the exit schema
1531
- *
1532
- * @example
1533
- * ```typescript
1534
- * import { execute, Exit, DefaultExit, ListenExit } from 'llmz'
1535
- *
1536
- * const exit = new Exit({
1537
- * name: 'dataProcessed',
1538
- * schema: z.object({
1539
- * recordCount: z.number(),
1540
- * summary: z.string(),
1541
- * }),
1542
- * })
1543
- *
1544
- * const result = await execute({
1545
- * instructions: 'Process the user data',
1546
- * exits: [exit],
1547
- * client,
1548
- * })
1549
- *
1550
- * if (result.isSuccess() && result.is(exit)) {
1551
- * // Access the exit information
1552
- * console.log('Exit name:', result.result.exit.name)
1553
- *
1554
- * // Access typed output data
1555
- * console.log('Records processed:', result.output.recordCount)
1556
- * console.log('Summary:', result.output.summary)
1557
- *
1558
- * // Access the final iteration (guaranteed to exist)
1559
- * console.log('Generated code:', result.iteration.code)
1560
- * }
1561
- * ```
1562
- */
1563
- var SuccessExecutionResult = class extends ExecutionResult {
1564
- result;
1565
- constructor(context, result) {
1566
- super("success", context);
1567
- this.result = result;
1568
- }
1569
- /**
1570
- * Gets the typed output data from the successful execution.
1571
- *
1572
- * This overrides the base class output property to provide proper typing
1573
- * based on the exit schema. The output is guaranteed to match the schema
1574
- * of the exit that was triggered.
1575
- *
1576
- * @returns The typed output data
1577
- */
1578
- get output() {
1579
- return this.result.result;
1580
- }
1581
- /**
1582
- * Gets the final iteration from the successful execution.
1583
- *
1584
- * For successful executions, there is always at least one iteration,
1585
- * so this method returns the guaranteed non-null final iteration.
1586
- *
1587
- * @returns The final iteration (guaranteed to exist)
1588
- */
1589
- get iteration() {
1590
- return this.context.iterations.at(-1);
1591
- }
1592
- /**
1593
- * Serializes the execution result to JSON.
1594
- *
1595
- * This method converts the execution result into a JSON format that includes
1596
- * the execution status, context, and exit information. It is used for serialization
1597
- * and transmission of the execution result.
1598
- *
1599
- * @returns The JSON representation of the execution result.
1600
- */
1601
- toJSON() {
1602
- return {
1603
- status: "success",
1604
- context: this.context.toJSON(),
1605
- result: {
1606
- exit: this.result.exit.toJSON(),
1607
- result: this.result.result
1608
- }
1609
- };
1610
- }
1611
- };
1612
- /**
1613
- * Result for executions that failed with an unrecoverable error.
1614
- *
1615
- * ErrorExecutionResult indicates that the execution encountered an error that could not be recovered from, such as:
1616
- * - Execution has been aborted by the user (eg. via the `signal` AbortSignal parameter)
1617
- * - Iterations exceeded the maximum allowed limit
1618
- *
1619
- * Upon iteration failure, the execution will continue until the maximum iteration limit is reached or an exit is triggered.
1620
- *
1621
- * @example
1622
- * ```typescript
1623
- * const result = await execute({
1624
- * instructions: 'Call a non-existent function',
1625
- * client,
1626
- * })
1627
- *
1628
- * if (result.isError()) {
1629
- * console.error('Execution failed:', result.error)
1630
- *
1631
- * // Access error details from the last iteration
1632
- * const lastIteration = result.iteration
1633
- * if (lastIteration?.status.type === 'execution_error') {
1634
- * console.error('Error type:', lastIteration.status.execution_error.type)
1635
- * console.error('Stack trace:', lastIteration.status.execution_error.stack)
1636
- * console.error('Generated code:', lastIteration.code)
1637
- * }
1638
- *
1639
- * // Access all iterations to understand the failure progression
1640
- * console.log('Total iterations before failure:', result.iterations.length)
1641
- * }
1642
- * ```
1643
- */
1644
- var ErrorExecutionResult = class extends ExecutionResult {
1645
- error;
1646
- constructor(context, error) {
1647
- super("error", context);
1648
- this.error = error;
1649
- }
1650
- /**
1651
- * Gets the output data (always null for error results).
1652
- *
1653
- * @returns Always null since error executions don't produce output
1654
- */
1655
- get output() {
1656
- return null;
1657
- }
1658
- toJSON() {
1659
- return {
1660
- status: "error",
1661
- context: this.context.toJSON(),
1662
- error: this.error
1663
- };
1664
- }
1665
- };
1666
- /**
1667
- * Result for executions that were interrupted before completion.
1668
- *
1669
- * PartialExecutionResult indicates that a snapshot was created during the execution.
1670
- * Interrupted executions can be resumed using the provided snapshot.
1671
- *
1672
- * @example
1673
- * ```typescript
1674
- * // Tool that throws SnapshotSignal for long-running operations
1675
- * const longRunningTool = new Tool({
1676
- * name: 'processLargeDataset',
1677
- * async handler({ datasetId }) {
1678
- * // Start background processing
1679
- * const jobId = await startBackgroundJob(datasetId)
1680
- *
1681
- * // Pause execution until job completes
1682
- * throw new SnapshotSignal('Processing dataset', 'Waiting for background job completion', {
1683
- * jobId,
1684
- * datasetId,
1685
- * startTime: Date.now(),
1686
- * })
1687
- * },
1688
- * })
1689
- *
1690
- * const result = await execute({
1691
- * instructions: 'Process the large dataset',
1692
- * tools: [longRunningTool],
1693
- * client,
1694
- * })
1695
- *
1696
- * if (result.isInterrupted()) {
1697
- * console.log('Execution paused:', result.signal.message)
1698
- * console.log('Reason:', result.signal.longMessage)
1699
- *
1700
- * // Serialize snapshot for later resumption
1701
- * const serialized = result.snapshot.toJSON()
1702
- * await database.saveSnapshot('job-123', serialized)
1703
- *
1704
- * // Later, when the background job completes...
1705
- * const snapshot = Snapshot.fromJSON(serialized)
1706
- * snapshot.resolve({ jobResult: 'Processing completed successfully' })
1707
- *
1708
- * const continuation = await execute({
1709
- * snapshot,
1710
- * instructions: result.context.instructions,
1711
- * tools: result.context.tools,
1712
- * exits: result.context.exits,
1713
- * client,
1714
- * })
1715
- * }
1716
- * ```
1717
- */
1718
- var PartialExecutionResult = class extends ExecutionResult {
1719
- signal;
1720
- snapshot;
1721
- constructor(context, signal, snapshot) {
1722
- super("interrupted", context);
1723
- this.signal = signal;
1724
- this.snapshot = snapshot;
1725
- }
1726
- /**
1727
- * Gets the output data (always null for interrupted results).
1728
- *
1729
- * @returns Always null since interrupted executions don't produce final output
1730
- */
1731
- get output() {
1732
- return null;
1733
- }
1734
- /**
1735
- * Serializes the execution result to JSON.
1736
- *
1737
- * @returns The JSON representation of the execution result.
1738
- */
1739
- toJSON() {
1740
- return {
1741
- status: "interrupted",
1742
- context: this.context.toJSON(),
1743
- snapshot: this.snapshot.toJSON(),
1744
- signal: {
1745
- message: this.signal.message,
1746
- truncatedCode: this.signal.truncatedCode,
1747
- variables: this.signal.variables
1748
- }
1749
- };
1750
- }
1751
- };
1752
- //#endregion
1753
- //#region src/getter.ts
1754
- const getValue = async (valueOrGetter, ctx) => {
1755
- if (typeof valueOrGetter === "function") try {
1756
- return await valueOrGetter(ctx);
1757
- } catch (e) {
1758
- throw new Error(`Error while getting value for ${valueOrGetter}: ${e}`);
1759
- }
1760
- else return valueOrGetter;
1761
- };
1762
- //#endregion
1763
- //#region src/handlers.ts
1764
- var Emitter = class {
1765
- _handlers = [];
1766
- subscribe = (fn) => {
1767
- this._handlers.push(fn);
1768
- return () => {
1769
- this._handlers = this._handlers.filter((handler) => handler !== fn);
1770
- };
1771
- };
1772
- emit(event) {
1773
- this._handlers.forEach((handler) => handler(event));
1774
- }
1775
- };
1776
- var HookedArray = class extends Array {
1777
- #listeners = new Emitter();
1778
- constructor(...items) {
1779
- super(...items);
1780
- Object.setPrototypeOf(this, new.target.prototype);
1781
- }
1782
- push(...items) {
1783
- try {
1784
- this.#listeners.emit(items);
1785
- } finally {
1786
- return super.push(...items);
1787
- }
1788
- }
1789
- onPush(fn) {
1790
- return this.#listeners.subscribe(fn);
1791
- }
1792
- };
1793
- //#endregion
1794
- //#region src/prompts/execution-history.ts
1795
- function describeOutcome(status) {
1796
- switch (status.type) {
1797
- case "thinking_requested": return status.thinking_requested.interrupted ? "a tool paused execution" : "code completed and returned control";
1798
- case "execution_error": return "code execution failed";
1799
- case "invalid_code_error": return "invalid code or protocol";
1800
- case "exit_error": return "exit validation failed";
1801
- default: return status.type;
1802
- }
1803
- }
1804
- /** Summarize observed effects, including failed calls and retracted deliveries. */
1805
- function summarizeIterations(iterations, canTalk) {
1806
- const history = [];
1807
- const attempts = /* @__PURE__ */ new Map();
1808
- const deliveredMessages = [];
1809
- for (const [index, iteration] of iterations.entries()) {
1810
- const calls = [];
1811
- const lastRestart = iteration.traces.reduce((last, trace, traceIndex) => trace.type === "llm_call_restarted" ? traceIndex : last, -1);
1812
- for (const [traceIndex, trace] of iteration.traces.entries()) {
1813
- if (trace.type === "tool_call") {
1814
- const name = trace.object ? `${trace.object}.${trace.tool_name}` : trace.tool_name;
1815
- let outcome = "failed or paused";
1816
- if (trace.success) outcome = trace.output instanceof ThinkSignal ? "paused for attention" : "succeeded";
1817
- attempts.set(name, (attempts.get(name) ?? 0) + 1);
1818
- calls.push(`${name}: ${outcome}`);
1819
- }
1820
- if (canTalk && trace.type === "yield") deliveredMessages.push({
1821
- iteration: index + 1,
1822
- content: trace.value,
1823
- ...traceIndex < lastRestart ? { retracted: true } : {}
1824
- });
1825
- }
1826
- const outcome = describeOutcome(iteration.status);
1827
- const toolSummary = calls.length ? ` Tool attempts: ${calls.join("; ")}.` : "";
1828
- history.push(`Iteration ${index + 1}: ${outcome}.${toolSummary}`);
1829
- }
1830
- return {
1831
- history,
1832
- toolAttempts: Object.fromEntries(attempts),
1833
- deliveredMessages: canTalk ? deliveredMessages : void 0
1834
- };
1835
- }
1836
- //#endregion
1837
- //#region src/transcript.ts
1838
- const MAX_MESSAGE_LENGTH = 5e3;
1839
- function getMessagePreview(message) {
1840
- if (message.role === "assistant" || message.role === "user" || message.role === "summary") return message.content;
1841
- if (message.role === "event") return inspect(message.payload, message.name, { tokens: 1e3 });
1842
- return inspect(message, void 0, { tokens: 1e3 });
1843
- }
1844
- function getMessageType(message) {
1845
- if (message.role === "assistant" || message.role === "user" || message.role === "summary") return message.role;
1846
- if (message.role === "event") return `event:${message.name}`;
1847
- return "unknown";
1848
- }
1849
- /** Whether the message is a spoken turn: explicit voice modality or an audio attachment. */
1850
- function isVoiceMessage(message) {
1851
- if (message.role === "user" && message.modality === "voice") return true;
1852
- if (message.role === "user" || message.role === "event") {
1853
- var _message$attachments;
1854
- return ((_message$attachments = message.attachments) === null || _message$attachments === void 0 ? void 0 : _message$attachments.some((attachment) => attachment.type === "audio")) ?? false;
1855
- }
1856
- return false;
1857
- }
1858
- var TranscriptArray = class extends Array {
1859
- constructor(items = []) {
1860
- items = Array.isArray(items) ? items : [];
1861
- super(...items);
1862
- items.forEach((item) => {
1863
- if (![
1864
- "user",
1865
- "assistant",
1866
- "event",
1867
- "summary"
1868
- ].includes(item.role)) throw new Error(`Invalid role "${item.role}" in transcript message`);
1869
- if ("name" in item && item.name && typeof item.name !== "string") throw new Error(`Invalid name for transcript message. Expected a string, but got type "${typeof item.name}"`);
1870
- if ("content" in item && typeof item.content !== "string") throw new Error(`Invalid content for transcript message. Expected a string, but got type "${typeof item.content}"`);
1871
- if ("modality" in item && item.modality !== void 0 && !["text", "voice"].includes(item.modality)) throw new Error(`Invalid modality "${item.modality}" in transcript message. Expected "text" or "voice"`);
1872
- });
1873
- Object.setPrototypeOf(this, new.target.prototype);
1874
- }
1875
- toString() {
1876
- if (!this.length) return "";
1877
- return this.map((item, idx) => {
1878
- var _item$attachments, _item$name;
1879
- const msgIdx = getMessageType(item) + "-" + String(idx + 1).padStart(3, "0");
1880
- let preview = getMessagePreview(item);
1881
- if (preview.length > MAX_MESSAGE_LENGTH) preview = preview.slice(0, MAX_MESSAGE_LENGTH) + "\n... (truncated)";
1882
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1883
- if ((item.role === "event" || item.role === "user") && ((_item$attachments = item.attachments) === null || _item$attachments === void 0 ? void 0 : _item$attachments.length)) for (let i = 0; i < item.attachments.length; i++) {
1884
- const attachment = item.attachments[i];
1885
- const ref = attachment.id ?? `${msgIdx}-${alphabet[i % 26]}`;
1886
- const alt = attachment.alt ? `: ${attachment.alt}` : "";
1887
- preview += attachment.type === "audio" ? `\n[Voice message ${ref}${alt}]` : `\n[Attachment ${ref}${alt}]`;
1888
- }
1889
- const tags = [];
1890
- tags.push({
1891
- key: "role",
1892
- value: item.role
1893
- });
1894
- if (isVoiceMessage(item)) tags.push({
1895
- key: "modality",
1896
- value: "voice"
1897
- });
1898
- if ("name" in item && ((_item$name = item.name) === null || _item$name === void 0 ? void 0 : _item$name.length)) tags.push({
1899
- key: "name",
1900
- value: item.name
1901
- });
1902
- return `<${msgIdx} ${tags.map(({ key, value }) => `${key}="${value}"`).join(" ")}>\n${preview.trim()}\n</${msgIdx}>`;
1903
- }).join("\n");
1904
- }
1905
- };
1906
- //#endregion
1907
- //#region src/context.ts
1908
- /**
1909
- * Built-in exit for requesting thinking time during agent execution.
1910
- *
1911
- * The ThinkExit allows agents to pause execution and reflect on the current situation,
1912
- * variables, and context before continuing. There are two ways to trigger thinking:
1913
- *
1914
- * 1. **Agent-initiated**: Agent calls `return { action: 'think' }` to pause and reflect
1915
- * 2. **Tool/Hook-initiated**: Tools or hooks throw `ThinkSignal` to force agent reflection
1916
- *
1917
- * This exit is automatically available in all LLMz executions and is commonly used for:
1918
- * - Complex decision making that requires analysis
1919
- * - Debugging and understanding current variable state
1920
- * - Planning multi-step operations
1921
- * - Tool feedback and result processing
1922
- * - Reflecting on previous iterations and results
1923
- *
1924
- * @example
1925
- * ```typescript
1926
- * // Agent retrieves web search results and decides to think about them
1927
- * const results = await searchWeb(query)
1928
- *
1929
- * // Agent decides it needs to think (look at the search results) before responding
1930
- * return { action: 'think', results }
1931
- * ```
1932
- *
1933
- * Sometimes, as the author of the tool, you may want to always force the agent to think about the results.
1934
- * In this case, you can throw a `ThinkSignal` from the tool handler to trigger thinking.
1935
- *
1936
- * @example
1937
- * ```typescript
1938
- * // Tool-initiated thinking using ThinkSignal
1939
- * import { ThinkSignal } from 'llmz'
1940
- *
1941
- * const searchTool = new Tool({
1942
- * name: 'search',
1943
- * handler: async ({ query }) => {
1944
- * const results = await performSearch(query)
1945
- *
1946
- * if (!results.length) {
1947
- * // Force agent to think about alternative approaches
1948
- * throw new ThinkSignal(
1949
- * 'No search results found',
1950
- * 'No results were found. Consider rephrasing the query or using a different approach.'
1951
- * )
1952
- * }
1953
- *
1954
- * // Provide context for agent to process results
1955
- * throw new ThinkSignal(
1956
- * 'Search completed with results',
1957
- * `Found ${results.length} results. Process them carefully and provide citations.`
1958
- * )
1959
- * }
1960
- * })
1961
- * ```
1962
- * When an iteration ends with ThinkExit, the agent will automatically loop and start a new iteration to continue processing, unless iteration limit is reached.
1963
- *
1964
- * The thinking process helps agents:
1965
- * - Avoid rushing into incorrect solutions
1966
- * - Better understand complex problems and tool results
1967
- * - Maintain variable state across iterations
1968
- * - Process feedback from tools and hooks
1969
- * - Provide more thoughtful and accurate responses
1970
- */
1971
- const ThinkExit = new Exit({
1972
- name: "think",
1973
- description: "Think about the current situation and provide a response"
1974
- });
1975
- /**
1976
- * Built-in exit for waiting for user input in chat mode.
1977
- *
1978
- * The ListenExit is automatically available when chat mode is enabled (when a Chat
1979
- * instance is provided to execute()). When an agent calls `return { action: 'listen' }`,
1980
- * the execution pauses and waits for user input before continuing the conversation.
1981
- *
1982
- * This exit is essential for interactive conversational agents and is used to:
1983
- * - Wait for user responses in chat interfaces
1984
- * - Pause execution until user provides input
1985
- * - Enable back-and-forth conversation flow
1986
- * - Allow users to guide the conversation direction
1987
- *
1988
- * The ListenExit is only available in chat mode - it will not be present in
1989
- * worker mode executions where no chat interface is provided.
1990
- *
1991
- * @example
1992
- * ```typescript
1993
- * // Agent generated code using ListenExit in chat mode
1994
- * yield <Message>What would you like me to help you with today?</Message>
1995
- * yield <Button action="postback" label="Get Weather" value="weather" />
1996
- * yield <Button action="postback" label="Set Reminder" value="reminder" />
1997
- *
1998
- * // Wait for user to respond
1999
- * return { action: 'listen' }
2000
- * ```
2001
- *
2002
- * @example
2003
- * ```typescript
2004
- * // Standard chat interaction pattern
2005
- * const calculation = 2 + 8
2006
- * yield <Message>The result of `2 + 8` is **{calculation}**.</Message>
2007
- * return { action: 'listen' }
2008
- * ```
2009
- *
2010
- * @example
2011
- * ```typescript
2012
- * // CLI chat example with ListenExit handling
2013
- * const chat = new CLIChat()
2014
- *
2015
- * while (chat.iterate()) {
2016
- * const result = await execute({
2017
- * instructions: 'Help the user with their questions',
2018
- * chat,
2019
- * client,
2020
- * })
2021
- *
2022
- * if (result.is(ListenExit)) {
2023
- * // CLIChat handles prompting user automatically
2024
- * continue
2025
- * } else {
2026
- * console.log('Conversation ended')
2027
- * break
2028
- * }
2029
- * }
2030
- * ```
2031
- *
2032
- * The ListenExit enables natural conversation flow where:
2033
- * - Agent sends messages and waits for responses
2034
- * - User provides input to guide the conversation
2035
- * - Conversation continues iteratively until completion
2036
- * - Chat interface manages the input/output cycle
2037
- */
2038
- const ListenExit = new Exit({
2039
- name: "listen",
2040
- description: "Stop talking and wait for the user to talk next."
2041
- });
2042
- /**
2043
- * Default exit used when no custom exits are provided.
2044
- *
2045
- * The DefaultExit is automatically used in worker mode when no custom exits are defined.
2046
- * It provides a standard way to complete execution with either success or failure outcomes.
2047
- * The exit uses a discriminated union schema to ensure type-safe handling of both success
2048
- * and error cases.
2049
- *
2050
- * This exit is commonly used for:
2051
- * - Simple worker mode executions without custom completion logic
2052
- * - Standardized success/failure reporting
2053
- * - Basic task completion with result or error information
2054
- * - Default fallback when no specific exit behavior is needed
2055
- *
2056
- * @example
2057
- * ```typescript
2058
- * // Agent generated code using DefaultExit for successful completion
2059
- * const data = await fetchUserData(userId)
2060
- * const processedResult = processData(data)
2061
- *
2062
- * return {
2063
- * action: 'done',
2064
- * success: true,
2065
- * result: processedResult
2066
- * }
2067
- * ```
2068
- *
2069
- * @example
2070
- * ```typescript
2071
- * // Agent generated code using DefaultExit for error cases
2072
- * try {
2073
- * const result = await riskyOperation()
2074
- * return { action: 'done', success: true, result }
2075
- * } catch (error) {
2076
- * return {
2077
- * action: 'done',
2078
- * success: false,
2079
- * error: `Operation failed: ${error.message}`
2080
- * }
2081
- * }
2082
- * ```
2083
- *
2084
- * @example
2085
- * ```typescript
2086
- * import { execute, DefaultExit } from 'llmz'
2087
- *
2088
- * // Handling DefaultExit in execution results
2089
- * const result = await execute({
2090
- * instructions: 'Process the user data and return results',
2091
- * // No custom exits provided - DefaultExit will be used
2092
- * client,
2093
- * })
2094
- *
2095
- * if (result.is(DefaultExit)) {
2096
- * if (result.output.success) {
2097
- * console.log('Success:', result.output.result)
2098
- * } else {
2099
- * console.error('Error:', result.output.error)
2100
- * }
2101
- * }
2102
- * ```
2103
- *
2104
- * @example
2105
- * ```typescript
2106
- * // Worker mode execution with automatic DefaultExit
2107
- * const result = await execute({
2108
- * instructions: 'Calculate fibonacci numbers up to 100',
2109
- * tools: [mathTools],
2110
- * client,
2111
- * // No chat provided = worker mode
2112
- * // No exits provided = DefaultExit automatically added
2113
- * })
2114
- *
2115
- * // Result will use DefaultExit for completion
2116
- * if (result.isSuccess() && result.is(DefaultExit)) {
2117
- * const { success, result: data, error } = result.output
2118
- * // Handle success/failure cases
2119
- * }
2120
- * ```
2121
- *
2122
- * The DefaultExit provides a consistent interface for:
2123
- * - Type-safe success/failure handling
2124
- * - Standardized result reporting across different executions
2125
- * - Automatic fallback behavior when no custom exits are defined
2126
- * - Clear separation between successful results and error conditions
2127
- */
2128
- const DefaultExit = new Exit({
2129
- name: "done",
2130
- description: "When the execution is sucessfully completed or when error recovery is not possible",
2131
- schema: z.discriminatedUnion("success", [z.object({
2132
- success: z.literal(true),
2133
- result: z.any().describe("The result of the execution")
2134
- }), z.object({
2135
- success: z.literal(false),
2136
- error: z.string().describe("The error message if the execution failed")
2137
- })])
2138
- });
2139
- var Iteration = class {
2140
- id;
2141
- messages;
2142
- code;
2143
- /** Messages (`■send` blocks) parsed from the assistant response, in order. */
2144
- sends;
2145
- /** The `■next` exit parsed from the assistant response, if any. */
2146
- next;
2147
- traces;
2148
- variables;
2149
- /**
2150
- * Token usage of this iteration's LLM call. The `context` breakdown is measured
2151
- * when the prompt is assembled; `input`/`output` are filled in once the LLM call
2152
- * completes, from the provider-reported usage.
2153
- */
2154
- tokens;
2155
- started_ts;
2156
- ended_ts;
2157
- status;
2158
- _mutations;
2159
- get mutations() {
2160
- return [...this._mutations.values()];
2161
- }
2162
- trackMutation(mutation) {
2163
- this._mutations.set(`${mutation.object ?? "global"}:${mutation.property}`, mutation);
2164
- }
2165
- _parameters;
2166
- get components() {
2167
- return this._parameters.components;
2168
- }
2169
- get transcript() {
2170
- return this._parameters.transcript;
2171
- }
2172
- get tools() {
2173
- return this._parameters.tools;
2174
- }
2175
- get objects() {
2176
- return this._parameters.objects;
2177
- }
2178
- get model() {
2179
- return this._parameters.model;
2180
- }
2181
- set model(value) {
2182
- this._parameters.model = value;
2183
- }
2184
- get temperature() {
2185
- return this._parameters.temperature;
2186
- }
2187
- get reasoningEffort() {
2188
- return this._parameters.reasoningEffort;
2189
- }
2190
- get exits() {
2191
- const exits = [...this._parameters.exits];
2192
- if (this.isChatEnabled) exits.push(ListenExit);
2193
- return exits;
2194
- }
2195
- get instructions() {
2196
- return this._parameters.instructions;
2197
- }
2198
- llm;
2199
- hasExited() {
2200
- return ["exit_success"].includes(this.status.type);
2201
- }
2202
- hasExitedWith(exit) {
2203
- return this.status.type === "exit_success" && this.status.exit_success.exit_name === exit.name;
2204
- }
2205
- isSuccessful() {
2206
- return [
2207
- "callback_requested",
2208
- "exit_success",
2209
- "thinking_requested"
2210
- ].includes(this.status.type);
2211
- }
2212
- isFailed() {
2213
- return [
2214
- "generation_error",
2215
- "invalid_code_error",
2216
- "execution_error",
2217
- "exit_error",
2218
- "aborted"
2219
- ].includes(this.status.type);
2220
- }
2221
- get duration() {
2222
- const ms = (this.ended_ts ?? Date.now()) - this.started_ts;
2223
- const trailing = this.ended_ts ? "" : " (still running)";
2224
- return ms.toLocaleString("en-US", {
2225
- style: "unit",
2226
- unit: "millisecond"
2227
- }) + trailing;
2228
- }
2229
- get error() {
2230
- if (this.status.type === "generation_error") return `CodeGenerationError: ${this.status.generation_error.message}`;
2231
- if (this.status.type === "invalid_code_error") return `InvalidCodeError: ${this.status.invalid_code_error.message}`;
2232
- if (this.status.type === "execution_error") return `CodeExecutionError: ${this.status.execution_error.message}`;
2233
- if (this.status.type === "exit_error") return `ExitError: ${this.status.exit_error.message}`;
2234
- if (this.status.type === "aborted") return `Aborted: ${this.status.aborted.reason}`;
2235
- return null;
2236
- }
2237
- get isChatEnabled() {
2238
- return this._parameters.components.length > 0;
2239
- }
2240
- constructor(props) {
2241
- this.id = props.id;
2242
- this.status = { type: "pending" };
2243
- this.traces = new HookedArray();
2244
- this._mutations = /* @__PURE__ */ new Map();
2245
- this.messages = props.messages;
2246
- this.variables = props.variables;
2247
- this._parameters = props.parameters;
2248
- this.started_ts = Date.now();
2249
- }
2250
- end(status) {
2251
- if (this.status.type !== "pending") throw new Error(`Iteration ${this.id} has already ended with status ${this.status.type}`);
2252
- this.ended_ts = Date.now();
2253
- this.status = status;
2254
- }
2255
- toJSON() {
2256
- return {
2257
- id: this.id,
2258
- messages: [...this.messages],
2259
- code: this.code,
2260
- model: this.model,
2261
- temperature: this.temperature,
2262
- reasoningEffort: this.reasoningEffort,
2263
- traces: [...this.traces],
2264
- variables: this.variables,
2265
- started_ts: this.started_ts,
2266
- ended_ts: this.ended_ts,
2267
- status: this.status,
2268
- mutations: [...this._mutations.values()],
2269
- llm: this.llm,
2270
- tokens: this.tokens,
2271
- transcript: [...this._parameters.transcript],
2272
- tools: this._parameters.tools.map((tool) => tool.toJSON()),
2273
- objects: this._parameters.objects.map((obj) => obj.toJSON()),
2274
- exits: this._parameters.exits.map((exit) => exit.toJSON()),
2275
- instructions: this._parameters.instructions,
2276
- duration: this.duration,
2277
- error: this.error,
2278
- isChatEnabled: this.isChatEnabled
2279
- };
2280
- }
2281
- };
2282
- var Context = class {
2283
- id;
2284
- chat;
2285
- instructions;
2286
- examples;
2287
- objects;
2288
- tools;
2289
- exits;
2290
- model;
2291
- temperature;
2292
- reasoningEffort;
2293
- version = DualModePrompt;
2294
- timeout = 6e4;
2295
- loop;
2296
- /**
2297
- * Optional cap on the model's context window. The effective limit is
2298
- * `min(maxTokens, model's max input tokens)`.
2299
- */
2300
- maxTokens;
2301
- /**
2302
- * Maximum time to wait for the first streamed token, in milliseconds,
2303
- * before the cognitive service falls back to the next model/provider.
2304
- */
2305
- maxTimeToFirstToken;
2306
- /**
2307
- * Allow Cognitive to restart a failed stream on another model. Previews remain
2308
- * live and are retracted with a restart delta before replacement output.
2309
- * Completed sends and code always wait for a valid response and successful
2310
- * transport. Streaming-only; defaults to false.
2311
- */
2312
- midStreamFallback;
2313
- /**
2314
- * STT model used by the cognitive service to transcribe audio attachments
2315
- * when the target LLM does not support audio natively. Defaults to 'fast'.
2316
- */
2317
- transcriptionModel;
2318
- metadata;
2319
- snapshot;
2320
- _lastMessageWithoutExecutionState;
2321
- iteration = 0;
2322
- iterations;
2323
- async nextIteration() {
2324
- if (this.iterations.length >= this.loop) throw new LoopExceededError();
2325
- if (this.snapshot && this.snapshot.status.type === "pending") throw new Error(`Cannot resume execution from a snapshot that is still pending: ${this.snapshot.id}. Please resolve() or reject() it first.`);
2326
- const parameters = await this._refreshIterationParameters();
2327
- const { messages, parts } = await this._getIterationMessages(parameters);
2328
- const contextTokens = this._measureContextTokens(messages, parts);
2329
- const iteration = new Iteration({
2330
- id: `${this.id}_${this.iterations.length + 1}`,
2331
- variables: this._getIterationVariables(),
2332
- parameters,
2333
- messages
2334
- });
2335
- iteration.tokens = {
2336
- input: 0,
2337
- output: 0,
2338
- total: 0,
2339
- context: contextTokens
2340
- };
2341
- this.iterations.push(iteration);
2342
- this.iteration = this.iterations.length;
2343
- this.snapshot = void 0;
2344
- return iteration;
2345
- }
2346
- _getIterationVariables() {
2347
- var _this$snapshot;
2348
- const lastIteration = this.iterations.at(-1);
2349
- const variables = {};
2350
- if ((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type) === "thinking_requested") {
2351
- const lastThinkingVariables = lastIteration.status.thinking_requested.variables;
2352
- if (isPlainObject(lastThinkingVariables)) Object.assign(variables, cloneDeep(lastThinkingVariables));
2353
- }
2354
- if (isPlainObject(lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.variables)) Object.assign(variables, cloneDeep((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.variables) ?? {}));
2355
- if (((_this$snapshot = this.snapshot) === null || _this$snapshot === void 0 ? void 0 : _this$snapshot.status.type) === "resolved") {
2356
- for (const v of this.snapshot.variables) if (!v.truncated && v.value !== void 0) variables[v.name] = v.value;
2357
- }
2358
- return variables;
2359
- }
2360
- /**
2361
- * Measures the token size of each part of the prompt (pre-truncation).
2362
- * The named parts come from the system prompt; everything else in the system
2363
- * message is `framework`. Non-system messages count towards `iterations`,
2364
- * except the very first user message of a fresh execution (task recap),
2365
- * which is prompt scaffolding.
2366
- */
2367
- _measureContextTokens(messages, parts) {
2368
- const tokenizer = getTokenizer();
2369
- const countText = (text) => (text === null || text === void 0 ? void 0 : text.length) ? tokenizer.count(stripTruncationTags(text)) : 0;
2370
- const countMessage = (message) => {
2371
- if (typeof message.content === "string") return countText(message.content);
2372
- if (Array.isArray(message.content)) return message.content.reduce((acc, part) => acc + (part.type === "text" ? countText(part.text) : 0), 0);
2373
- return 0;
2374
- };
2375
- const instructions = countText(parts.instructions);
2376
- const tools = countText(parts.tools);
2377
- const transcript = countText(parts.transcript);
2378
- const protocol = countText(parts.protocol);
2379
- const examples = countText(parts.examples);
2380
- const systemTokens = messages.filter((x) => x.role === "system").reduce((acc, x) => acc + countMessage(x), 0);
2381
- const otherTokens = messages.filter((x) => x.role !== "system").reduce((acc, x) => acc + countMessage(x), 0);
2382
- const isFirstIteration = this.iterations.length === 0 && !this.snapshot;
2383
- const framework = Math.max(0, systemTokens - (instructions + tools + transcript + protocol + examples));
2384
- const iterations = isFirstIteration ? 0 : otherTokens;
2385
- return {
2386
- total: framework + instructions + tools + transcript + protocol + examples + iterations + (isFirstIteration ? otherTokens : 0),
2387
- framework: framework + (isFirstIteration ? otherTokens : 0),
2388
- instructions,
2389
- tools,
2390
- transcript,
2391
- protocol,
2392
- examples,
2393
- iterations
2394
- };
2395
- }
2396
- async _getIterationMessages(parameters) {
2397
- var _this$snapshot2, _this$snapshot3;
2398
- const lastIteration = this.iterations.at(-1);
2399
- const promptProps = {
2400
- iteration: {
2401
- current: this.iterations.length + 1,
2402
- limit: this.loop,
2403
- resumed: !!this.snapshot,
2404
- ...summarizeIterations(this.iterations, parameters.components.length > 0)
2405
- },
2406
- globalTools: parameters.tools,
2407
- objects: parameters.objects,
2408
- instructions: parameters.instructions,
2409
- examples: parameters.examples,
2410
- transcript: parameters.transcript,
2411
- exits: parameters.components.length ? [...parameters.exits, ListenExit] : parameters.exits,
2412
- components: parameters.components
2413
- };
2414
- const { message: systemMessage, parts } = await this.version.getSystemMessage(promptProps);
2415
- const previousLastMessage = this._lastMessageWithoutExecutionState;
2416
- const withParts = (messages) => {
2417
- var _this$version$getExec, _this$version;
2418
- const last = messages.at(-1);
2419
- this._lastMessageWithoutExecutionState = last;
2420
- const state = ((_this$version$getExec = (_this$version = this.version).getExecutionState) === null || _this$version$getExec === void 0 ? void 0 : _this$version$getExec.call(_this$version, promptProps)) ?? "";
2421
- if (state) messages[messages.length - 1] = Array.isArray(last.content) ? {
2422
- ...last,
2423
- content: [...last.content, {
2424
- type: "text",
2425
- text: state.trim()
2426
- }]
2427
- } : {
2428
- ...last,
2429
- content: (last.content ?? "") + state
2430
- };
2431
- return {
2432
- messages,
2433
- parts
2434
- };
2435
- };
2436
- if (((_this$snapshot2 = this.snapshot) === null || _this$snapshot2 === void 0 ? void 0 : _this$snapshot2.status.type) === "resolved") return withParts([systemMessage, this.version.getSnapshotResolvedMessage({ snapshot: this.snapshot })]);
2437
- if (((_this$snapshot3 = this.snapshot) === null || _this$snapshot3 === void 0 ? void 0 : _this$snapshot3.status.type) === "rejected") return withParts([systemMessage, this.version.getSnapshotRejectedMessage({ snapshot: this.snapshot })]);
2438
- if (!lastIteration) return withParts([systemMessage, await this.version.getInitialUserMessage(promptProps)]);
2439
- const history = lastIteration.messages.slice();
2440
- if (previousLastMessage) history[history.length - 1] = previousLastMessage;
2441
- const lastIterationMessages = [systemMessage, ...history.filter((x) => x.role !== "system")];
2442
- if ((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type) === "thinking_requested") {
2443
- var _lastIteration$llm, _lastIteration$llm2;
2444
- return withParts([
2445
- ...lastIterationMessages,
2446
- {
2447
- role: "assistant",
2448
- content: wrapContent(((_lastIteration$llm = lastIteration.llm) === null || _lastIteration$llm === void 0 ? void 0 : _lastIteration$llm.output) ?? "", {
2449
- preserve: "top",
2450
- flex: 4,
2451
- minTokens: 25
2452
- })
2453
- },
2454
- await this.version.getThinkingMessage({
2455
- isChatEnabled: parameters.components.length > 0,
2456
- reason: lastIteration.status.thinking_requested.reason,
2457
- variables: lastIteration.status.thinking_requested.variables,
2458
- interrupted: lastIteration.status.thinking_requested.interrupted,
2459
- discardedMessages: (_lastIteration$llm2 = lastIteration.llm) === null || _lastIteration$llm2 === void 0 || (_lastIteration$llm2 = _lastIteration$llm2.diagnostics) === null || _lastIteration$llm2 === void 0 ? void 0 : _lastIteration$llm2.some((diagnostic) => diagnostic.code === "send-after-run")
2460
- })
2461
- ]);
2462
- }
2463
- if ((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type) === "exit_error") {
2464
- var _lastIteration$llm3;
2465
- return withParts([
2466
- ...lastIterationMessages,
2467
- {
2468
- role: "assistant",
2469
- content: wrapContent(((_lastIteration$llm3 = lastIteration.llm) === null || _lastIteration$llm3 === void 0 ? void 0 : _lastIteration$llm3.output) ?? "", {
2470
- preserve: "top",
2471
- flex: 4,
2472
- minTokens: 25
2473
- })
2474
- },
2475
- await this.version.getInvalidCodeMessage({
2476
- isChatEnabled: parameters.components.length > 0,
2477
- code: lastIteration.next ? `■next=${lastIteration.next.name} ${JSON.stringify(lastIteration.next.props)}` : lastIteration.code ?? "// No code generated",
2478
- message: `Invalid ■next block (${lastIteration.status.exit_error.exit}): ${lastIteration.status.exit_error.message}`,
2479
- variables: lastIteration.variables,
2480
- toolCalls: lastIteration.traces.filter((trace) => trace.type === "tool_call").map((trace) => ({
2481
- tool: trace.tool_name,
2482
- input: trace.input,
2483
- success: trace.success,
2484
- ...trace.success ? { output: trace.output } : { error: getErrorMessage(trace.error) }
2485
- }))
2486
- })
2487
- ]);
2488
- }
2489
- if ((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type) === "invalid_code_error") {
2490
- var _lastIteration$llm4;
2491
- return withParts([
2492
- ...lastIterationMessages,
2493
- {
2494
- role: "assistant",
2495
- content: wrapContent(((_lastIteration$llm4 = lastIteration.llm) === null || _lastIteration$llm4 === void 0 ? void 0 : _lastIteration$llm4.output) ?? "", {
2496
- preserve: "top",
2497
- flex: 4,
2498
- minTokens: 25
2499
- })
2500
- },
2501
- await this.version.getInvalidCodeMessage({
2502
- isChatEnabled: parameters.components.length > 0,
2503
- code: lastIteration.code ?? "// No code generated",
2504
- message: lastIteration.status.invalid_code_error.message
2505
- })
2506
- ]);
2507
- }
2508
- if ((lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type) === "execution_error") {
2509
- var _lastIteration$llm5;
2510
- return withParts([
2511
- ...lastIterationMessages,
2512
- {
2513
- role: "assistant",
2514
- content: wrapContent(((_lastIteration$llm5 = lastIteration.llm) === null || _lastIteration$llm5 === void 0 ? void 0 : _lastIteration$llm5.output) ?? "", {
2515
- preserve: "top",
2516
- flex: 4,
2517
- minTokens: 25
2518
- })
2519
- },
2520
- await this.version.getCodeExecutionErrorMessage({
2521
- isChatEnabled: parameters.components.length > 0,
2522
- variables: lastIteration.variables,
2523
- toolCalls: lastIteration.traces.filter((trace) => trace.type === "tool_call").map((trace) => ({
2524
- tool: trace.tool_name,
2525
- input: trace.input,
2526
- success: trace.success,
2527
- ...trace.success ? { output: trace.output } : { error: getErrorMessage(trace.error) }
2528
- })),
2529
- message: lastIteration.status.execution_error.message,
2530
- stacktrace: lastIteration.status.execution_error.stack
2531
- })
2532
- ]);
2533
- }
2534
- throw new Error(`Unexpected iteration status: ${lastIteration === null || lastIteration === void 0 ? void 0 : lastIteration.status.type}. This is likely a bug, please report it.`);
2535
- }
2536
- async _refreshIterationParameters() {
2537
- var _this$chat, _this$chat2;
2538
- const instructions = await getValue(this.instructions, this);
2539
- const examples = await getValue(this.examples, this);
2540
- const transcript = new TranscriptArray(await getValue(((_this$chat = this.chat) === null || _this$chat === void 0 ? void 0 : _this$chat.transcript) ?? [], this));
2541
- const tools = Tool.withUniqueNames(await getValue(this.tools, this) ?? []);
2542
- const objects = await getValue(this.objects, this) ?? [];
2543
- const exits = await getValue(this.exits, this) ?? [];
2544
- const components = await getValue(((_this$chat2 = this.chat) === null || _this$chat2 === void 0 ? void 0 : _this$chat2.components) ?? [], this);
2545
- const model = await getValue(this.model, this) ?? "best";
2546
- const temperature = await getValue(this.temperature, this);
2547
- const reasoningEffort = await getValue(this.reasoningEffort, this);
2548
- if (objects && objects.length > 100) throw new Error("Too many objects. Expected at most 100 objects.");
2549
- if (tools && tools.length > 100) throw new Error("Too many tools. Expected at most 100 tools.");
2550
- for (const component of components) assertValidComponent(component.definition);
2551
- const ReservedToolNames = [
2552
- "think",
2553
- "listen",
2554
- "return",
2555
- "exit",
2556
- "action",
2557
- "function",
2558
- "callback",
2559
- "code",
2560
- "execute",
2561
- "jsx",
2562
- "object",
2563
- "string",
2564
- "number",
2565
- "boolean",
2566
- "array"
2567
- ];
2568
- for (const tool of tools) for (let name of [...tool.aliases, tool.name]) {
2569
- name = name.toLowerCase();
2570
- if (ReservedToolNames.includes(name)) throw new Error(`Tool name "${name}" (${tool.name}) is reserved. Please choose a different name.`);
2571
- if (components.find((x) => {
2572
- var _x$definition$aliases;
2573
- return x.definition.name.toLowerCase() === name || ((_x$definition$aliases = x.definition.aliases) === null || _x$definition$aliases === void 0 ? void 0 : _x$definition$aliases.map((x) => x.toLowerCase()).includes(name));
2574
- })) throw new Error(`Tool name "${name}" (${tool.name}) is already used by a component. Please choose a different name.`);
2575
- if (exits.find((x) => x.name.toLowerCase() === name) || exits.find((x) => {
2576
- var _x$aliases;
2577
- return (_x$aliases = x.aliases) === null || _x$aliases === void 0 ? void 0 : _x$aliases.map((x) => x.toLowerCase()).includes(name);
2578
- })) throw new Error(`Tool name "${name}" (${tool.name}) is already used by an exit. Please choose a different name.`);
2579
- }
2580
- if (exits && exits.length > 100) throw new Error("Too many exits. Expected at most 100 exits.");
2581
- if (components && components.length > 100) throw new Error("Too many components. Expected at most 100 components.");
2582
- if (instructions && instructions.length > 1e6) throw new Error("Instructions are too long. Expected at most 1,000,000 characters.");
2583
- if (transcript && transcript.length > 250) throw new Error("Too many transcript messages. Expected at most 250 messages.");
2584
- if (!components.length && !exits.length) exits.push(DefaultExit);
2585
- if (typeof temperature !== "number" || isNaN(temperature) || temperature < 0 || temperature > 2) throw new Error("Invalid temperature. Expected a number between 0 and 2.");
2586
- const isValidModel = (m) => typeof m === "string" && (m === "best" || m === "fast" || m === "auto" || m.includes(":"));
2587
- if (Array.isArray(model)) {
2588
- if (model.length === 0 || !model.every(isValidModel)) throw new Error("Invalid model. Expected a non-empty array of model strings ('best'/'fast'/'auto' or 'provider:model').");
2589
- } else if (!isValidModel(model)) throw new Error("Invalid model. Expected 'best'/'fast'/'auto' or 'provider:model'.");
2590
- return {
2591
- transcript,
2592
- tools,
2593
- objects,
2594
- exits,
2595
- instructions,
2596
- examples,
2597
- components,
2598
- model,
2599
- temperature,
2600
- reasoningEffort
2601
- };
2602
- }
2603
- constructor(props) {
2604
- this.id = `llmz_${ulid()}`;
2605
- this.instructions = props.instructions;
2606
- this.examples = props.examples;
2607
- this.objects = props.objects;
2608
- this.tools = props.tools;
2609
- this.exits = props.exits;
2610
- this.chat = props.chat;
2611
- this.timeout = Math.min(999999999, Math.max(0, props.timeout ?? 6e4));
2612
- this.loop = props.loop ?? 3;
2613
- this.temperature = props.temperature ?? .7;
2614
- this.reasoningEffort = props.reasoningEffort;
2615
- this.model = props.model ?? "best";
2616
- this.iterations = [];
2617
- this.metadata = props.metadata ?? {};
2618
- this.snapshot = props.snapshot;
2619
- this.maxTokens = props.maxTokens;
2620
- this.maxTimeToFirstToken = props.maxTimeToFirstToken;
2621
- this.midStreamFallback = props.midStreamFallback;
2622
- this.transcriptionModel = props.transcriptionModel;
2623
- if (this.loop < 1 || this.loop > 100) throw new Error("Invalid loop. Expected a number between 1 and 100.");
2624
- if (this.maxTokens !== void 0 && (!Number.isFinite(this.maxTokens) || this.maxTokens < 1)) throw new Error("Invalid maxTokens. Expected a positive number.");
2625
- if (this.maxTimeToFirstToken !== void 0 && (!Number.isFinite(this.maxTimeToFirstToken) || this.maxTimeToFirstToken < 1)) throw new Error("Invalid maxTimeToFirstToken. Expected a positive number of milliseconds.");
2626
- if (this.midStreamFallback !== void 0 && typeof this.midStreamFallback !== "boolean") throw new Error("Invalid midStreamFallback. Expected a boolean.");
2627
- }
2628
- toJSON() {
2629
- var _this$snapshot4;
2630
- return {
2631
- id: this.id,
2632
- iterations: this.iterations.map((iteration) => iteration.toJSON()),
2633
- iteration: this.iteration,
2634
- timeout: this.timeout,
2635
- loop: this.loop,
2636
- metadata: this.metadata,
2637
- snapshot: (_this$snapshot4 = this.snapshot) === null || _this$snapshot4 === void 0 ? void 0 : _this$snapshot4.toJSON()
2638
- };
2639
- }
2640
- };
2641
- //#endregion
2642
- //#region src/custom-client.ts
2643
- /**
2644
- * Internal escape hatch for supplying a custom model client that bypasses Cognitive.
2645
- *
2646
- * Intended for use by the Botpress engineering team only (e.g. running benchmarks
2647
- * against arbitrary models). It is intentionally undocumented and offers no stability
2648
- * guarantees — the API may change or be removed without notice. Avoid it unless you
2649
- * fully understand the implications.
2650
- */
2651
- var _CustomModelClient = class _CustomModelClient {
2652
- ["$$COGNITIVE"] = "runtime";
2653
- static isCustomClient(obj) {
2654
- return obj instanceof _CustomModelClient || (obj === null || obj === void 0 ? void 0 : obj["$$COGNITIVE"]) === "runtime";
2655
- }
2656
- };
2657
- //#endregion
2658
- export { ThinkExit as a, ExecutionResult as c, Snapshot as d, parseExit as f, ListenExit as i, PartialExecutionResult as l, Context as n, getValue as o, DefaultExit as r, ErrorExecutionResult as s, _CustomModelClient as t, SuccessExecutionResult as u };