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,249 +0,0 @@
1
- import { ToolCall, SnapshotSignal } from './errors.js';
2
- import { Serializable } from './types.js';
3
- type Variable = {
4
- name: string;
5
- type: string;
6
- bytes: number;
7
- preview?: string;
8
- value?: unknown;
9
- truncated: boolean;
10
- } & ({
11
- truncated: true;
12
- preview: string;
13
- } | {
14
- truncated: false;
15
- value: unknown;
16
- });
17
- export type SnapshotStatus = SnapshotStatuses.Pending | SnapshotStatuses.Resolved | SnapshotStatuses.Rejected;
18
- export declare namespace SnapshotStatuses {
19
- type Pending = {
20
- type: 'pending';
21
- };
22
- type Resolved = {
23
- type: 'resolved';
24
- value: unknown;
25
- };
26
- type Rejected = {
27
- type: 'rejected';
28
- error: unknown;
29
- };
30
- }
31
- export declare namespace Snapshot {
32
- type JSON = {
33
- id: string;
34
- reason?: string;
35
- stack: string;
36
- variables: Variable[];
37
- toolCall?: ToolCall;
38
- status: SnapshotStatus;
39
- };
40
- }
41
- /**
42
- * Snapshot represents a captured execution state that can be persisted and restored later.
43
- *
44
- * Snapshots are created when a SnapshotSignal is thrown during execution, typically from
45
- * within a tool handler to pause execution for long-running operations that need to be
46
- * completed asynchronously (e.g., background jobs, external API calls, user input).
47
- *
48
- * ## Use Cases
49
- * - **Long-running operations**: Pause execution while waiting for external processes
50
- * - **User interaction**: Collect input from users before continuing execution
51
- * - **Resource management**: Defer expensive operations to background workers
52
- * - **Workflow persistence**: Save execution state across process restarts
53
- *
54
- * ## Basic Usage
55
- *
56
- * ### Creating a Snapshot
57
- * From within a tool handler, throw a SnapshotSignal to create a snapshot:
58
- * ```typescript
59
- * const tool = new Tool({
60
- * handler: async ({ input }) => {
61
- * // Start long-running operation
62
- * throw new SnapshotSignal('Waiting for external API response')
63
- * }
64
- * })
65
- * ```
66
- *
67
- * ### Handling Interrupted Execution
68
- * ```typescript
69
- * const result = await execute({ tools: [tool], ... })
70
- *
71
- * if (result.isInterrupted()) {
72
- * const snapshot = result.snapshot
73
- *
74
- * // Serialize for persistence
75
- * const serialized = snapshot.toJSON()
76
- * await database.saveSnapshot(serialized)
77
- * }
78
- * ```
79
- *
80
- * ### Resuming from Snapshot
81
- * ```typescript
82
- * // Restore from persistence
83
- * const serialized = await database.getSnapshot(id)
84
- * const snapshot = Snapshot.fromJSON(serialized)
85
- *
86
- * // Resolve with the result of the long-running operation
87
- * snapshot.resolve({ result: 'Operation completed!' })
88
- *
89
- * // Continue execution
90
- * const continuation = await execute({
91
- * snapshot,
92
- * instructions: originalInstructions,
93
- * tools: originalTools,
94
- * exits: originalExits,
95
- * client
96
- * })
97
- * ```
98
- *
99
- * ## Snapshot Lifecycle
100
- * 1. **Created**: When SnapshotSignal is thrown (status: pending)
101
- * 2. **Serialized**: Convert to JSON for persistence with toJSON()
102
- * 3. **Restored**: Recreate from JSON with fromJSON()
103
- * 4. **Resolved/Rejected**: Provide result data with resolve() or reject()
104
- * 5. **Resumed**: Continue execution with the resolved snapshot
105
- *
106
- * ## What's Captured
107
- * - **Execution stack**: Current code position and call stack
108
- * - **Variables**: All local variables and their values (up to size limit)
109
- * - **Tool context**: Information about the tool call that triggered the snapshot
110
- * - **Reason**: Human-readable description of why the snapshot was created
111
- *
112
- * @see {@link https://github.com/botpress/botpress/blob/master/packages/llmz/examples/14_worker_snapshot/index.ts} Example usage
113
- */
114
- export declare class Snapshot implements Serializable<Snapshot.JSON> {
115
- #private;
116
- readonly id: string;
117
- readonly reason?: string;
118
- readonly stack: string;
119
- readonly toolCall?: ToolCall;
120
- variables: Variable[];
121
- /**
122
- * Gets the current status of the snapshot.
123
- *
124
- * @returns The snapshot status (pending, resolved, or rejected)
125
- */
126
- get status(): Readonly<{
127
- type: 'pending';
128
- } | {
129
- type: 'rejected';
130
- error: unknown;
131
- } | {
132
- type: 'resolved';
133
- value: unknown;
134
- }>;
135
- private constructor();
136
- /**
137
- * Creates a new Snapshot from a SnapshotSignal.
138
- *
139
- * This method is called internally by the LLMz execution engine when a SnapshotSignal
140
- * is thrown during execution. It captures the current execution state including
141
- * variables, stack trace, and tool context.
142
- *
143
- * @param signal The SnapshotSignal containing execution state
144
- * @returns A new Snapshot instance in pending status
145
- * @internal
146
- */
147
- static fromSignal(signal: SnapshotSignal): Snapshot;
148
- /**
149
- * Serializes the snapshot to a JSON-compatible object for persistence.
150
- *
151
- * Use this method to save snapshots to databases, files, or other storage systems.
152
- * The serialized snapshot can be restored later using fromJSON().
153
- *
154
- * @returns A JSON-serializable representation of the snapshot
155
- * @example
156
- * ```typescript
157
- * const snapshot = result.snapshot
158
- * const serialized = snapshot.toJSON()
159
- * await database.save('snapshots', snapshot.id, serialized)
160
- * ```
161
- */
162
- toJSON(): {
163
- id: string;
164
- reason: string | undefined;
165
- stack: string;
166
- variables: Variable[];
167
- toolCall: ToolCall | undefined;
168
- status: SnapshotStatus;
169
- };
170
- /**
171
- * Restores a snapshot from its JSON representation.
172
- *
173
- * Use this method to recreate snapshots from persistent storage. The restored
174
- * snapshot will maintain its original state and can be resolved/rejected as needed.
175
- *
176
- * @param json The serialized snapshot data from toJSON()
177
- * @returns A restored Snapshot instance
178
- * @example
179
- * ```typescript
180
- * const serialized = await database.get('snapshots', snapshotId)
181
- * const snapshot = Snapshot.fromJSON(serialized)
182
- * ```
183
- */
184
- static fromJSON(json: {
185
- id: string;
186
- reason?: string;
187
- stack: string;
188
- variables: Variable[];
189
- toolCall?: ToolCall;
190
- status: SnapshotStatus;
191
- }): Snapshot;
192
- /**
193
- * Creates a deep copy of the snapshot.
194
- *
195
- * @returns A new Snapshot instance with identical data
196
- */
197
- clone(): Snapshot;
198
- /**
199
- * Resets the snapshot status back to pending.
200
- *
201
- * This allows a previously resolved or rejected snapshot to be resolved/rejected
202
- * again with different data. Useful for retry scenarios.
203
- */
204
- reset(): void;
205
- /**
206
- * Resolves the snapshot with a successful result value.
207
- *
208
- * Call this method when the long-running operation that caused the snapshot
209
- * has completed successfully. The provided value will be returned as the
210
- * result of the original tool call when execution resumes.
211
- *
212
- * @param value The result value from the completed operation
213
- * @throws Error if the snapshot is not in pending status
214
- * @example
215
- * ```typescript
216
- * // After a background job completes
217
- * const result = await backgroundJob.getResult()
218
- * snapshot.resolve(result)
219
- *
220
- * // Continue execution
221
- * const continuation = await execute({ snapshot, ... })
222
- * ```
223
- */
224
- resolve(value: any): void;
225
- /**
226
- * Rejects the snapshot with an error.
227
- *
228
- * Call this method when the long-running operation that caused the snapshot
229
- * has failed or encountered an error. The provided error will be thrown
230
- * when execution resumes, allowing the generated code to handle it.
231
- *
232
- * @param error The error that occurred during the operation
233
- * @throws Error if the snapshot is not in pending status
234
- * @example
235
- * ```typescript
236
- * try {
237
- * const result = await externalAPI.call()
238
- * snapshot.resolve(result)
239
- * } catch (error) {
240
- * snapshot.reject(error)
241
- * }
242
- *
243
- * // Continue execution (will throw the error)
244
- * const continuation = await execute({ snapshot, ... })
245
- * ```
246
- */
247
- reject(error: any): void;
248
- }
249
- export {};
@@ -1,21 +0,0 @@
1
- //#region src/stack-traces.ts
2
- const isInternalLine = (line) => {
3
- return line.includes("/llmz/") || line.includes("\\llmz\\src\\") || line.includes("node_modules");
4
- };
5
- function cleanStackTrace(stack, cleanInternal = true) {
6
- let lines = stack.split("\n");
7
- const until = lines.findIndex((line) => isInternalLine(line));
8
- if (cleanInternal && until >= 0) lines = lines.slice(0, until);
9
- else lines = lines.map((line) => {
10
- let llmzIndex = line.indexOf("/llmz/");
11
- if (llmzIndex === -1) llmzIndex = line.indexOf("\\llmz\\");
12
- if (llmzIndex === -1) return line;
13
- let lastSpaceIndex = line.lastIndexOf(" ", llmzIndex);
14
- if (lastSpaceIndex === -1) lastSpaceIndex = 0;
15
- const maybeParen = line[lastSpaceIndex + 1] === "(" ? "(" : "";
16
- return line.slice(0, lastSpaceIndex + 1) + maybeParen + line.slice(llmzIndex);
17
- });
18
- return lines.join("\n");
19
- }
20
- //#endregion
21
- export { cleanStackTrace as t };
@@ -1,26 +0,0 @@
1
- //#region src/stack-traces.ts
2
- const isInternalLine = (line) => {
3
- return line.includes("/llmz/") || line.includes("\\llmz\\src\\") || line.includes("node_modules");
4
- };
5
- function cleanStackTrace(stack, cleanInternal = true) {
6
- let lines = stack.split("\n");
7
- const until = lines.findIndex((line) => isInternalLine(line));
8
- if (cleanInternal && until >= 0) lines = lines.slice(0, until);
9
- else lines = lines.map((line) => {
10
- let llmzIndex = line.indexOf("/llmz/");
11
- if (llmzIndex === -1) llmzIndex = line.indexOf("\\llmz\\");
12
- if (llmzIndex === -1) return line;
13
- let lastSpaceIndex = line.lastIndexOf(" ", llmzIndex);
14
- if (lastSpaceIndex === -1) lastSpaceIndex = 0;
15
- const maybeParen = line[lastSpaceIndex + 1] === "(" ? "(" : "";
16
- return line.slice(0, lastSpaceIndex + 1) + maybeParen + line.slice(llmzIndex);
17
- });
18
- return lines.join("\n");
19
- }
20
- //#endregion
21
- Object.defineProperty(exports, "cleanStackTrace", {
22
- enumerable: true,
23
- get: function() {
24
- return cleanStackTrace;
25
- }
26
- });
@@ -1,276 +0,0 @@
1
- const require_compiler = require("./compiler-C-OI9sim.cjs");
2
- const require_utils = require("./utils-3ESwP3yg.cjs");
3
- //#region src/truncator.ts
4
- var truncator_exports = /* @__PURE__ */ require_compiler.__exportAll({
5
- stripTruncationTags: () => stripTruncationTags,
6
- truncateWrappedContent: () => truncateWrappedContent,
7
- wrapContent: () => wrapContent
8
- });
9
- const DEFAULT_REMOVE_CHUNK = 250;
10
- const WRAP_OPEN_TAG_1 = "【TRUNCATE";
11
- const WRAP_OPEN_TAG_2 = "】";
12
- const WRAP_CLOSE_TAG = "【/TRUNCATE】";
13
- const REGEXP = `(${WRAP_OPEN_TAG_1}(?:\\s+[\\w:]+)*\\s*${WRAP_OPEN_TAG_2})([\\s\\S]*?)(${WRAP_CLOSE_TAG})`;
14
- const DEFAULT_TRUNCATE_OPTIONS = {
15
- preserve: "top",
16
- flex: 1,
17
- minTokens: 0
18
- };
19
- /**
20
- * Wraps content with truncation tags to mark it as truncatable when using `truncateWrappedContent`.
21
- *
22
- * This function encases the provided content within special truncation tags that contain metadata
23
- * about how the content should be truncated. The wrapped content becomes eligible for intelligent
24
- * truncation while preserving non-wrapped content intact.
25
- *
26
- * @param content - The string content to wrap with truncation tags
27
- * @param options - Optional truncation configuration
28
- * @param options.preserve - Which part of the content to preserve when truncating:
29
- * - 'top': Keep the beginning, remove from the end (default)
30
- * - 'bottom': Keep the end, remove from the beginning
31
- * - 'both': Keep both ends, remove from the middle
32
- * @param options.flex - Priority factor for truncation (default: 1). Higher values make this
33
- * content more likely to be truncated. A flex of 2 means this content can shrink twice as
34
- * much as content with flex of 1.
35
- * @param options.minTokens - Minimum number of tokens to preserve (default: 0). Content will
36
- * never be truncated below this threshold.
37
- *
38
- * @returns The content wrapped with truncation tags and embedded metadata
39
- *
40
- * @example
41
- * ```typescript
42
- * // Basic usage - content will be truncated from the end if needed
43
- * const wrapped = wrapContent("This is some long content that might need truncation")
44
- *
45
- * // Preserve the end of the content
46
- * const bottomPreserved = wrapContent("Error log: ... important error details", {
47
- * preserve: 'bottom'
48
- * })
49
- *
50
- * // High priority for truncation with minimum preservation
51
- * const flexible = wrapContent("Optional context information", {
52
- * flex: 3,
53
- * minTokens: 50
54
- * })
55
- * ```
56
- */
57
- function wrapContent(content, options) {
58
- const preserve = (options === null || options === void 0 ? void 0 : options.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
59
- const flex = (options === null || options === void 0 ? void 0 : options.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
60
- const minTokens = (options === null || options === void 0 ? void 0 : options.minTokens) ?? DEFAULT_TRUNCATE_OPTIONS.minTokens;
61
- return `${WRAP_OPEN_TAG_1} preserve:${preserve} flex:${flex} min:${minTokens} ${WRAP_OPEN_TAG_2}${content}${WRAP_CLOSE_TAG}`;
62
- }
63
- /**
64
- * Intelligently truncates message content to fit within a token limit while preserving important parts.
65
- *
66
- * This function processes an array of messages and reduces their total token count to fit within the
67
- * specified limit. It only truncates content that has been wrapped with `wrapContent()`, leaving
68
- * unwrapped content completely intact. The truncation algorithm prioritizes content based on flex
69
- * values and respects preservation preferences and minimum token requirements.
70
- *
71
- * ## How it works:
72
- * 1. **Parsing**: Scans each message for wrapped content sections and unwrapped sections
73
- * 2. **Token counting**: Calculates tokens for each section using the configured tokenizer
74
- * 3. **Prioritization**: Identifies the largest truncatable sections based on flex values
75
- * 4. **Intelligent truncation**: Removes content according to preservation preferences
76
- * 5. **Reconstruction**: Rebuilds messages with truncated content and removes wrapper tags
77
- *
78
- * ## Truncation strategy:
79
- * - **Priority**: Higher flex values = higher truncation priority
80
- * - **Minimum tokens**: Content is never truncated below its `minTokens` threshold
81
- * - **Preservation modes**:
82
- * - `'top'`: Removes from the end, keeps the beginning
83
- * - `'bottom'`: Removes from the beginning, keeps the end
84
- * - `'both'`: Removes from the middle, keeps both ends
85
- *
86
- * @template T - Type extending MessageLike (must have a content property)
87
- * @param options - Configuration object
88
- * @param options.messages - Array of messages to truncate
89
- * @param options.tokenLimit - Maximum total tokens allowed across all messages
90
- * @param options.throwOnFailure - Whether to throw an error if truncation fails (default: true).
91
- * If false, returns the best effort result even if over the token limit.
92
- *
93
- * @returns Array of messages with content truncated to fit the token limit
94
- *
95
- * @throws Error if unable to truncate enough content to meet the token limit (when throwOnFailure is true)
96
- *
97
- * @example
98
- * ```typescript
99
- * const messages = [
100
- * {
101
- * role: 'system',
102
- * content: 'You are a helpful assistant. ' + wrapContent('Here is some background info...', { flex: 2 })
103
- * },
104
- * {
105
- * role: 'user',
106
- * content: 'Please help me with: ' + wrapContent('detailed context and examples', { preserve: 'both' })
107
- * }
108
- * ]
109
- *
110
- * // Truncate to fit within 1000 tokens
111
- * const truncated = truncateWrappedContent({
112
- * messages,
113
- * tokenLimit: 1000,
114
- * throwOnFailure: false
115
- * })
116
- *
117
- * // The system message background info will be truncated first (higher flex),
118
- * // and user context will be truncated from the middle if needed (preserve: 'both')
119
- * ```
120
- */
121
- function truncateWrappedContent({ messages, tokenLimit, throwOnFailure = true }) {
122
- const tokenizer = require_utils.getTokenizer();
123
- /**
124
- * Before { content: 'content', tokens: 10, truncatable: false }
125
- * <WRAPPER>content</WRAPPER> { content: 'content', tokens: 10, truncatable: true }
126
- * After { content: 'content', tokens: 10, truncatable: false }
127
- */
128
- const parts = [];
129
- for (const msg of messages) {
130
- const current = [];
131
- const content = typeof msg.content === "string" ? msg.content : "";
132
- let match;
133
- const parser = new _MessageContentParser();
134
- while ((match = parser.parse(content)) !== null) {
135
- const { attributes, nonTruncatableContent, wrappedContent } = match;
136
- if (nonTruncatableContent) current.push({
137
- content: nonTruncatableContent,
138
- tokens: tokenizer.count(nonTruncatableContent),
139
- truncatable: false
140
- });
141
- current.push({
142
- content: wrappedContent,
143
- tokens: tokenizer.count(wrappedContent),
144
- truncatable: true,
145
- attributes: {
146
- preserve: attributes.preserve,
147
- flex: Number(attributes.flex) || DEFAULT_TRUNCATE_OPTIONS.flex,
148
- minTokens: Number(attributes.min) || DEFAULT_TRUNCATE_OPTIONS.minTokens
149
- }
150
- });
151
- }
152
- const remainingContent = parser.getRemainingContent(content);
153
- if (remainingContent) current.push({
154
- content: remainingContent,
155
- tokens: tokenizer.count(remainingContent),
156
- truncatable: false
157
- });
158
- parts.push(current);
159
- }
160
- let currentCount = _countTotalTokens(parts);
161
- while (currentCount > tokenLimit) {
162
- var _biggest$attributes, _biggest$attributes3;
163
- const { biggest, secondBiggest } = _getTwoBiggestTruncables(parts);
164
- if (!biggest || !biggest.truncatable || biggest.tokens <= 0) {
165
- if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
166
- else break;
167
- }
168
- const delta = Math.max(biggest.tokens - ((secondBiggest === null || secondBiggest === void 0 ? void 0 : secondBiggest.tokens) ?? 0), DEFAULT_REMOVE_CHUNK);
169
- const room = Math.min(delta, biggest.tokens);
170
- let toRemove = Math.min(room, currentCount - tokenLimit);
171
- if (toRemove <= 0) {
172
- if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
173
- else break;
174
- }
175
- if (biggest.tokens - toRemove < (((_biggest$attributes = biggest.attributes) === null || _biggest$attributes === void 0 ? void 0 : _biggest$attributes.minTokens) ?? 0)) {
176
- var _biggest$attributes2;
177
- toRemove = biggest.tokens - (((_biggest$attributes2 = biggest.attributes) === null || _biggest$attributes2 === void 0 ? void 0 : _biggest$attributes2.minTokens) ?? 0);
178
- }
179
- const preserve = ((_biggest$attributes3 = biggest.attributes) === null || _biggest$attributes3 === void 0 ? void 0 : _biggest$attributes3.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
180
- const split = tokenizer.splitAndSlice(biggest.content);
181
- if (preserve === "bottom") biggest.content = split.slice(toRemove).join("");
182
- else if (preserve === "top") biggest.content = split.slice(0, -toRemove).join("");
183
- else {
184
- const anchor = Math.ceil(split.length / 2);
185
- const radius = Math.ceil(toRemove / 2);
186
- const left = anchor - radius;
187
- const right = anchor + radius;
188
- biggest.content = split.slice(0, left).join("") + split.slice(right).join("");
189
- }
190
- biggest.tokens -= toRemove;
191
- currentCount -= toRemove;
192
- }
193
- return messages.map((msg, i) => {
194
- const p = parts[i];
195
- return {
196
- ...msg,
197
- content: typeof msg.content === "string" ? _renderRemainingWrappers(p.map((part) => part.content).join("")) : msg.content
198
- };
199
- });
200
- }
201
- var _MessageContentParser = class {
202
- _regex;
203
- _lastIndex = 0;
204
- constructor() {
205
- this._regex = _createRegex();
206
- }
207
- parse(content) {
208
- const match = this._regex.exec(content);
209
- if (!match) return null;
210
- const attributes = match[1].split(/\s+/).slice(1).filter((x) => x !== WRAP_OPEN_TAG_2).map((x) => x.split(":")).reduce((acc, [key, value]) => ({
211
- ...acc,
212
- [key]: value
213
- }), {});
214
- let nonTruncatableContent = void 0;
215
- if (match.index > this._lastIndex) nonTruncatableContent = content.slice(this._lastIndex, match.index);
216
- const wrappedContent = match[2];
217
- this._lastIndex = this._regex.lastIndex;
218
- return {
219
- attributes,
220
- nonTruncatableContent,
221
- wrappedContent
222
- };
223
- }
224
- getRemainingContent(content) {
225
- if (this._lastIndex < content.length) return content.slice(this._lastIndex);
226
- return null;
227
- }
228
- };
229
- const _createRegex = () => new RegExp(REGEXP, "g");
230
- const _renderRemainingWrappers = (content) => content.replace(_createRegex(), "$2");
231
- /** Removes truncation wrapper tags from content, leaving the wrapped content intact. */
232
- const stripTruncationTags = (content) => _renderRemainingWrappers(content);
233
- const _countTotalTokens = (parts) => parts.reduce((acc, x) => acc + x.reduce((acc, y) => acc + y.tokens, 0), 0);
234
- const _getTwoBiggestTruncables = (parts) => {
235
- let biggest = null;
236
- let secondBiggest = null;
237
- for (const part of parts.flat()) if (part.truncatable) {
238
- var _part$attributes, _part$attributes2;
239
- if (part.tokens <= (((_part$attributes = part.attributes) === null || _part$attributes === void 0 ? void 0 : _part$attributes.minTokens) ?? 0)) continue;
240
- const flex = ((_part$attributes2 = part.attributes) === null || _part$attributes2 === void 0 ? void 0 : _part$attributes2.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
241
- const tokens = part.tokens * flex;
242
- if (!biggest || tokens > biggest.tokens) {
243
- secondBiggest = biggest;
244
- biggest = part;
245
- } else if (!secondBiggest || tokens > secondBiggest.tokens) secondBiggest = part;
246
- }
247
- return {
248
- biggest,
249
- secondBiggest
250
- };
251
- };
252
- //#endregion
253
- Object.defineProperty(exports, "stripTruncationTags", {
254
- enumerable: true,
255
- get: function() {
256
- return stripTruncationTags;
257
- }
258
- });
259
- Object.defineProperty(exports, "truncateWrappedContent", {
260
- enumerable: true,
261
- get: function() {
262
- return truncateWrappedContent;
263
- }
264
- });
265
- Object.defineProperty(exports, "truncator_exports", {
266
- enumerable: true,
267
- get: function() {
268
- return truncator_exports;
269
- }
270
- });
271
- Object.defineProperty(exports, "wrapContent", {
272
- enumerable: true,
273
- get: function() {
274
- return wrapContent;
275
- }
276
- });