llmz 0.6.0 → 0.6.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 (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-CFhWe_W6.js +48 -0
  3. package/dist/_baseForOwn-buOZDFbK.cjs +103 -0
  4. package/dist/_baseIteratee-CF4qP2a8.cjs +2377 -0
  5. package/dist/_baseIteratee-P_firB7b.js +2138 -0
  6. package/dist/_getPrototype-CG7Dxrrz.js +6 -0
  7. package/dist/_getPrototype-DQDlNVVM.cjs +10 -0
  8. package/dist/_overArg-C5Hy7oCi.cjs +196 -0
  9. package/dist/_overArg-CRYbj1NH.js +155 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-BwixNVH8.cjs +73 -0
  12. package/dist/component-DGG7d_Mz.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-BPmEoWKu.cjs +2618 -0
  15. package/dist/custom-client-NUoxrFQh.js +2547 -0
  16. package/dist/dual-modes-D_p-jedw.js +2750 -0
  17. package/dist/dual-modes-wAOAlaBS.cjs +2840 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-BEaq3jkV.cjs +1003 -0
  21. package/dist/execute-DYvFRs54.js +1001 -0
  22. package/dist/exit-BGi0Kk0y.cjs +428 -0
  23. package/dist/exit-CDdxDBRT.js +417 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17534 -16875
  28. package/dist/isEmpty-BhJRCqIF.js +52 -0
  29. package/dist/isEmpty-LY533Wmh.cjs +57 -0
  30. package/dist/isPlainObject-CSxXVKCk.cjs +56 -0
  31. package/dist/isPlainObject-D39AzPO2.js +51 -0
  32. package/dist/jsx-BWvT6ukg.cjs +75 -0
  33. package/dist/jsx-CIgdGGVs.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-CAo-BQHs.js +643 -0
  49. package/dist/tool-DdPZb0JW.cjs +654 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-B6aaJaN1.cjs +276 -0
  52. package/dist/truncator-DZqEqnpD.js +253 -0
  53. package/dist/typings-BwAz_TM9.cjs +784 -0
  54. package/dist/typings-CrBa7Tyy.js +743 -0
  55. package/dist/uniq-BYQ7GWwb.js +183 -0
  56. package/dist/uniq-G872RWmE.cjs +200 -0
  57. package/dist/utils-UBeAFeEI.js +950 -0
  58. package/dist/utils-ZpJm00ed.cjs +1075 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BjkJqSQH.cjs +3438 -0
  61. package/dist/vm-C5vf1LH3.js +3436 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -0,0 +1,1003 @@
1
+ const require__baseForOwn = require("./_baseForOwn-buOZDFbK.cjs");
2
+ const require_dual_modes = require("./dual-modes-wAOAlaBS.cjs");
3
+ const require_custom_client = require("./custom-client-BPmEoWKu.cjs");
4
+ const require_utils = require("./utils-ZpJm00ed.cjs");
5
+ const require_jsx = require("./jsx-BWvT6ukg.cjs");
6
+ const require_stack_traces = require("./stack-traces-ntw_qhoy.cjs");
7
+ const require_errors = require("./errors-C962uJdS.cjs");
8
+ const require_truncator = require("./truncator-B6aaJaN1.cjs");
9
+ const require_vm = require("./vm-BjkJqSQH.cjs");
10
+ let _bpinternal_zui = require("@bpinternal/zui");
11
+ let ulid = require("ulid");
12
+ let _botpress_client = require("@botpress/client");
13
+ let _botpress_cognitive = require("@botpress/cognitive");
14
+ let ms = require("ms");
15
+ ms = require__baseForOwn.__toESM(ms, 1);
16
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseClamp.js
17
+ /**
18
+ * The base implementation of `_.clamp` which doesn't coerce arguments.
19
+ *
20
+ * @private
21
+ * @param {number} number The number to clamp.
22
+ * @param {number} [lower] The lower bound.
23
+ * @param {number} upper The upper bound.
24
+ * @returns {number} Returns the clamped number.
25
+ */
26
+ function baseClamp(number, lower, upper) {
27
+ if (number === number) {
28
+ if (upper !== void 0) number = number <= upper ? number : upper;
29
+ if (lower !== void 0) number = number >= lower ? number : lower;
30
+ }
31
+ return number;
32
+ }
33
+ //#endregion
34
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/clamp.js
35
+ /**
36
+ * Clamps `number` within the inclusive `lower` and `upper` bounds.
37
+ *
38
+ * @static
39
+ * @memberOf _
40
+ * @since 4.0.0
41
+ * @category Number
42
+ * @param {number} number The number to clamp.
43
+ * @param {number} [lower] The lower bound.
44
+ * @param {number} upper The upper bound.
45
+ * @returns {number} Returns the clamped number.
46
+ * @example
47
+ *
48
+ * _.clamp(-10, -5, 5);
49
+ * // => -5
50
+ *
51
+ * _.clamp(10, -5, 5);
52
+ * // => 5
53
+ */
54
+ function clamp(number, lower, upper) {
55
+ if (upper === void 0) {
56
+ upper = lower;
57
+ lower = void 0;
58
+ }
59
+ if (upper !== void 0) {
60
+ upper = require_dual_modes.toNumber(upper);
61
+ upper = upper === upper ? upper : 0;
62
+ }
63
+ if (lower !== void 0) {
64
+ lower = require_dual_modes.toNumber(lower);
65
+ lower = lower === lower ? lower : 0;
66
+ }
67
+ return baseClamp(require_dual_modes.toNumber(number), lower, upper);
68
+ }
69
+ //#endregion
70
+ //#region src/abort-signal.ts
71
+ /**
72
+ * Creates a new AbortController that aborts when any of the provided signals abort.
73
+ * This is useful for combining multiple abort conditions (e.g., user cancellation, timeout, parent operation abort).
74
+ *
75
+ * @param signals - Array of AbortSignals to listen to. Undefined/null signals are ignored.
76
+ * @returns A new AbortController that will abort if any input signal aborts
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const userController = new AbortController()
81
+ * const timeoutController = new AbortController()
82
+ *
83
+ * // Create a joined controller that aborts if either signal aborts
84
+ * const joinedController = createJoinedAbortController([
85
+ * userController.signal,
86
+ * timeoutController.signal
87
+ * ])
88
+ *
89
+ * // Use the joined signal in operations
90
+ * await fetch('/api/data', { signal: joinedController.signal })
91
+ * ```
92
+ */
93
+ function createJoinedAbortController(signals) {
94
+ const controller = new AbortController();
95
+ const validSignals = signals.filter((signal) => signal != null);
96
+ if (validSignals.length === 0) return controller;
97
+ for (const signal of validSignals) if (signal.aborted) {
98
+ controller.abort(signal.reason);
99
+ return controller;
100
+ }
101
+ const abortListeners = [];
102
+ for (const signal of validSignals) {
103
+ const listener = () => {
104
+ controller.abort(signal.reason);
105
+ cleanup();
106
+ };
107
+ signal.addEventListener("abort", listener);
108
+ abortListeners.push(() => signal.removeEventListener("abort", listener));
109
+ }
110
+ const cleanup = () => {
111
+ abortListeners.forEach((removeListener) => removeListener());
112
+ };
113
+ controller.signal.addEventListener("abort", cleanup, { once: true });
114
+ return controller;
115
+ }
116
+ //#endregion
117
+ //#region src/runtime/generate.ts
118
+ const RESPONSE_LENGTH_BUFFER = {
119
+ MIN_TOKENS: 1e3,
120
+ MAX_TOKENS: 16e3,
121
+ PERCENTAGE: .1
122
+ };
123
+ /** Maximum time to wait between two stream chunks before considering the stream stalled. */
124
+ const STREAM_INACTIVITY_TIMEOUT = 6e4;
125
+ const getModelOutputLimit = (inputLength) => clamp(RESPONSE_LENGTH_BUFFER.PERCENTAGE * inputLength, RESPONSE_LENGTH_BUFFER.MIN_TOKENS, RESPONSE_LENGTH_BUFFER.MAX_TOKENS);
126
+ /**
127
+ * Models sometimes wrap their whole response in a code fence. The fence has to
128
+ * be removed before it reaches the incremental parser, otherwise it would be
129
+ * recovered as an unexpected-text message. Works on arbitrary chunk boundaries
130
+ * by holding content back until the first newline.
131
+ */
132
+ var LeadingFenceFilter = class {
133
+ _buffer = "";
134
+ _done = false;
135
+ push(text) {
136
+ if (this._done) return text;
137
+ this._buffer += text;
138
+ const newline = this._buffer.indexOf("\n");
139
+ if (newline === -1) return "";
140
+ this._done = true;
141
+ const firstLine = this._buffer.slice(0, newline);
142
+ const rest = this._buffer.slice(newline + 1);
143
+ this._buffer = "";
144
+ return firstLine.trim().startsWith("```") ? rest : `${firstLine}\n${rest}`;
145
+ }
146
+ flush() {
147
+ if (this._done) return "";
148
+ this._done = true;
149
+ const buffered = this._buffer;
150
+ this._buffer = "";
151
+ return buffered.trim().startsWith("```") ? "" : buffered;
152
+ }
153
+ };
154
+ const generateCode = async ({ iteration, ctx, cognitive, controller, metadata, onSend, onSendDelta, onRunStart, onRunComplete }) => {
155
+ const startedAt = Date.now();
156
+ const traces = iteration.traces;
157
+ const modelRef = Array.isArray(iteration.model) ? iteration.model[0] : iteration.model;
158
+ const model = await cognitive.getModelDetails(modelRef).catch((thrown) => {
159
+ throw new require_errors.CognitiveError(`Failed to fetch model details for model "${modelRef}": ${require_utils.getErrorMessage(thrown)}`);
160
+ });
161
+ let modelLimit = Math.max(model.input.maxTokens, 8e3);
162
+ if (ctx.maxTokens) modelLimit = Math.min(ctx.maxTokens, modelLimit);
163
+ const responseLengthBuffer = getModelOutputLimit(modelLimit);
164
+ if (iteration.tokens) iteration.tokens.limit = modelLimit;
165
+ let messages;
166
+ try {
167
+ messages = require_truncator.truncateWrappedContent({
168
+ messages: iteration.messages,
169
+ tokenLimit: modelLimit - responseLengthBuffer,
170
+ throwOnFailure: true
171
+ }).filter((x) => typeof x.content !== "string" || x.content.trim().length > 0);
172
+ } catch (thrown) {
173
+ const cap = ctx.maxTokens ? ` (context window capped at ${modelLimit} tokens by options.maxTokens — consider raising or removing it)` : ` (model context window: ${modelLimit} tokens)`;
174
+ throw new require_errors.CognitiveError(`The prompt does not fit in the context window${cap}: ${require_utils.getErrorMessage(thrown)}`);
175
+ }
176
+ iteration.messages = messages;
177
+ traces.push({
178
+ type: "llm_call_started",
179
+ started_at: startedAt,
180
+ ended_at: startedAt,
181
+ model: model.id
182
+ });
183
+ const hasAudioParts = messages.some((message) => Array.isArray(message.content) && message.content.some((part) => part.type === "audio"));
184
+ const input = {
185
+ model: iteration.model,
186
+ temperature: iteration.temperature,
187
+ responseFormat: "text",
188
+ reasoningEffort: iteration.reasoningEffort,
189
+ messages,
190
+ stopSequences: ctx.version.getStopTokens(),
191
+ meta: metadata ? { metadata } : void 0,
192
+ options: hasAudioParts ? { transcriptionModel: ctx.transcriptionModel ?? "fast" } : void 0
193
+ };
194
+ let responseMetadata;
195
+ let raw;
196
+ let assistantResponse;
197
+ /** Milliseconds between the stream request and the first/last streamed tokens. */
198
+ let timeToFirstToken;
199
+ let timeToLastToken;
200
+ const liveItems = /* @__PURE__ */ new Map();
201
+ const liveContent = /* @__PURE__ */ new Map();
202
+ let codeGenerationTraced = false;
203
+ let runCompleted = false;
204
+ const dispatchSends = async (events) => {
205
+ for (const event of events) if (event.type === "item-start") {
206
+ liveItems.set(event.item.id, event.item);
207
+ if (event.item.kind === "run" && !codeGenerationTraced) {
208
+ codeGenerationTraced = true;
209
+ traces.push({
210
+ type: "code_generation_started",
211
+ started_at: Date.now()
212
+ });
213
+ onRunStart === null || onRunStart === void 0 || onRunStart();
214
+ }
215
+ } else if (event.type === "body-delta" && onSendDelta) {
216
+ const item = liveItems.get(event.itemId);
217
+ if ((item === null || item === void 0 ? void 0 : item.kind) !== "send") continue;
218
+ const content = (liveContent.get(item.id) ?? "") + event.delta;
219
+ liveContent.set(item.id, content);
220
+ try {
221
+ await onSendDelta({
222
+ id: `${iteration.id}:${item.id}`,
223
+ component: item.name,
224
+ props: item.props,
225
+ delta: event.delta,
226
+ content
227
+ });
228
+ } catch (err) {}
229
+ } else if (event.type === "item-complete") {
230
+ if (event.item.kind === "send" && onSend) await onSend({
231
+ name: event.item.name,
232
+ props: event.item.props,
233
+ body: event.item.body
234
+ });
235
+ else if (event.item.kind === "run" && event.item.status === "complete" && !runCompleted) {
236
+ runCompleted = true;
237
+ onRunComplete === null || onRunComplete === void 0 || onRunComplete((event.item.body ?? "").trim());
238
+ }
239
+ }
240
+ };
241
+ if (typeof cognitive.generateTextStream === "function") {
242
+ const parser = new require_dual_modes.StreamingMessageParser();
243
+ const fence = new LeadingFenceFilter();
244
+ const streamController = createJoinedAbortController([controller.signal]);
245
+ const requestedAt = Date.now();
246
+ const stream = cognitive.generateTextStream({
247
+ ...input,
248
+ ...ctx.maxTimeToFirstToken ? { options: {
249
+ ...input.options,
250
+ maxTimeToFirstToken: ctx.maxTimeToFirstToken
251
+ } } : {}
252
+ }, { signal: streamController.signal });
253
+ const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, ctx.maxTimeToFirstToken ?? 0);
254
+ const nextChunk = async () => {
255
+ let timer;
256
+ const stalled = new Promise((_, reject) => {
257
+ timer = setTimeout(() => {
258
+ streamController.abort("LLM stream stalled");
259
+ reject(/* @__PURE__ */ new Error(`LLM stream stalled: no data received for ${inactivityTimeout}ms`));
260
+ }, inactivityTimeout);
261
+ });
262
+ try {
263
+ return await Promise.race([stream.next(), stalled]);
264
+ } finally {
265
+ clearTimeout(timer);
266
+ }
267
+ };
268
+ raw = "";
269
+ while (true) {
270
+ var _chunk$value, _chunk$value2;
271
+ let chunk;
272
+ try {
273
+ chunk = await nextChunk();
274
+ } catch (thrown) {
275
+ throw new require_errors.CognitiveError(`LLM generation failed: ${require_utils.getErrorMessage(thrown)}`);
276
+ }
277
+ if (chunk.done) break;
278
+ if ((_chunk$value = chunk.value) === null || _chunk$value === void 0 ? void 0 : _chunk$value.metadata) responseMetadata = chunk.value.metadata;
279
+ const delta = (_chunk$value2 = chunk.value) === null || _chunk$value2 === void 0 ? void 0 : _chunk$value2.output;
280
+ if (!delta) continue;
281
+ timeToLastToken = Date.now() - requestedAt;
282
+ timeToFirstToken ??= timeToLastToken;
283
+ raw += delta;
284
+ await dispatchSends(parser.push(fence.push(delta)));
285
+ }
286
+ if (!responseMetadata) throw new require_errors.CognitiveError("LLM streaming completed without metadata");
287
+ const remaining = fence.flush();
288
+ if (remaining) await dispatchSends(parser.push(remaining));
289
+ await dispatchSends(parser.finish());
290
+ assistantResponse = require_dual_modes.toParsedAssistantResponse(parser.items, raw);
291
+ } else {
292
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
293
+ throw new require_errors.CognitiveError(`LLM generation failed: ${require_utils.getErrorMessage(thrown)}`);
294
+ });
295
+ if (!response.output) throw new require_errors.CognitiveError("LLM did not return any text output");
296
+ responseMetadata = response.metadata;
297
+ raw = response.output;
298
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
299
+ for (const send of assistantResponse.sends) await (onSend === null || onSend === void 0 ? void 0 : onSend(send));
300
+ }
301
+ iteration.code = assistantResponse.code;
302
+ iteration.sends = assistantResponse.sends;
303
+ iteration.next = assistantResponse.next;
304
+ const usage = responseMetadata.usage;
305
+ iteration.llm = {
306
+ cached: responseMetadata.cached || false,
307
+ ended_at: Date.now(),
308
+ started_at: startedAt,
309
+ status: "success",
310
+ tokens: usage.inputTokens + usage.outputTokens,
311
+ spend: responseMetadata.cost ?? usage.inputCost + usage.outputCost,
312
+ output: assistantResponse.raw,
313
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
314
+ time_to_first_token: timeToFirstToken,
315
+ time_to_last_token: timeToLastToken,
316
+ usage: {
317
+ inputTokens: usage.inputTokens,
318
+ inputCost: usage.inputCost,
319
+ outputTokens: usage.outputTokens,
320
+ outputCost: usage.outputCost
321
+ }
322
+ };
323
+ if (iteration.tokens) {
324
+ iteration.tokens.input = usage.inputTokens;
325
+ iteration.tokens.output = usage.outputTokens;
326
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
327
+ }
328
+ traces.push({
329
+ type: "llm_call_success",
330
+ started_at: startedAt,
331
+ ended_at: iteration.llm.ended_at,
332
+ model: model.id,
333
+ code: iteration.code ?? ""
334
+ });
335
+ };
336
+ //#endregion
337
+ //#region src/runtime/interpret-result.ts
338
+ const interpretVMResult = async ({ iteration, result, controller, startedAt, onExit }) => {
339
+ if (result.error && result.error instanceof require_errors.InvalidCodeError) {
340
+ iteration.end({
341
+ type: "invalid_code_error",
342
+ invalid_code_error: { message: result.error.message }
343
+ });
344
+ return;
345
+ }
346
+ iteration.traces.push({
347
+ type: "code_execution",
348
+ lines_executed: result.lines_executed ?? 0,
349
+ started_at: startedAt,
350
+ ended_at: Date.now()
351
+ });
352
+ if (controller.signal.aborted) {
353
+ iteration.end({
354
+ type: "aborted",
355
+ aborted: { reason: controller.signal.reason ?? "The operation was aborted" }
356
+ });
357
+ return;
358
+ }
359
+ if (result.error && result.error instanceof require_errors.CodeExecutionError) {
360
+ iteration.end({
361
+ type: "execution_error",
362
+ execution_error: {
363
+ message: result.error.message,
364
+ stack: require_stack_traces.cleanStackTrace(result.error.stacktrace ?? result.error.stack ?? "No stack trace available")
365
+ }
366
+ });
367
+ return;
368
+ }
369
+ if (!result.success) {
370
+ var _result$error;
371
+ iteration.end({
372
+ type: "execution_error",
373
+ execution_error: {
374
+ message: (result === null || result === void 0 || (_result$error = result.error) === null || _result$error === void 0 ? void 0 : _result$error.message) ?? "Unknown error occurred",
375
+ stack: require_stack_traces.cleanStackTrace(result.error.stack ?? "No stack trace available")
376
+ }
377
+ });
378
+ return;
379
+ }
380
+ if (result.signal instanceof require_errors.ThinkSignal) {
381
+ iteration.end({
382
+ type: "thinking_requested",
383
+ thinking_requested: {
384
+ variables: result.signal.context,
385
+ reason: result.signal.reason,
386
+ metadata: result.signal.metadata
387
+ }
388
+ });
389
+ return;
390
+ }
391
+ if (result.signal instanceof require_errors.SnapshotSignal) {
392
+ iteration.end({
393
+ type: "callback_requested",
394
+ callback_requested: { signal: result.signal }
395
+ });
396
+ return;
397
+ }
398
+ const returnValue = result.return_value;
399
+ const codeRequestsInspection = require_vm.hasTopLevelReturn(iteration.code ?? "");
400
+ if (iteration.next && !codeRequestsInspection) {
401
+ await applyNextExit({
402
+ iteration,
403
+ controller,
404
+ onExit
405
+ });
406
+ return;
407
+ }
408
+ const localVariables = Object.fromEntries(Object.entries(result.variables ?? {}).filter(([, value]) => value !== "[[non-primitive]]"));
409
+ iteration.end({
410
+ type: "thinking_requested",
411
+ thinking_requested: {
412
+ reason: iteration.next ? `Code execution completed. The ■next=${iteration.next.name} exit was NOT applied because your code returns a value — inspect it below, then end your next response with ■next.` : "Code execution completed",
413
+ variables: returnValue !== void 0 ? returnValue : Object.keys(localVariables).length ? localVariables : iteration.variables
414
+ }
415
+ });
416
+ };
417
+ /**
418
+ * Applies the `■next=<exit>` block of the current iteration: validates the exit
419
+ * name and props against the available exits, runs the onExit hook, and ends
420
+ * the iteration with exit_success or exit_error.
421
+ */
422
+ const applyNextExit = async ({ iteration, controller, onExit }) => {
423
+ const next = iteration.next;
424
+ if (!next) throw new Error("applyNextExit called without a ■next block on the iteration");
425
+ const attempt = (props) => require_custom_client.parseExit(Object.keys(props).length ? {
426
+ action: next.name,
427
+ value: props
428
+ } : { action: next.name }, iteration.exits);
429
+ let parsedExit = attempt(next.props);
430
+ const keys = Object.keys(next.props);
431
+ if (!parsedExit.success && keys.length === 1 && [
432
+ "props",
433
+ "value",
434
+ "data"
435
+ ].includes(keys[0])) {
436
+ const inner = next.props[keys[0]];
437
+ if (inner && typeof inner === "object" && !Array.isArray(inner)) {
438
+ const unwrapped = attempt(inner);
439
+ if (unwrapped.success) parsedExit = unwrapped;
440
+ }
441
+ }
442
+ const returnValue = {
443
+ action: next.name,
444
+ value: parsedExit.success ? parsedExit.value : next.props
445
+ };
446
+ if (!parsedExit.success) {
447
+ iteration.end({
448
+ type: "exit_error",
449
+ exit_error: {
450
+ exit: next.name,
451
+ message: parsedExit.error,
452
+ return_value: returnValue
453
+ }
454
+ });
455
+ return;
456
+ }
457
+ const returnExit = parsedExit.exit;
458
+ try {
459
+ await (onExit === null || onExit === void 0 ? void 0 : onExit({
460
+ exit: returnExit,
461
+ result: parsedExit.value
462
+ }, controller));
463
+ } catch (err) {
464
+ iteration.end({
465
+ type: "exit_error",
466
+ exit_error: {
467
+ exit: returnExit.name,
468
+ message: `Error executing exit ${returnExit.name}: ${require_utils.getErrorMessage(err)}`,
469
+ return_value: returnValue
470
+ }
471
+ });
472
+ return;
473
+ }
474
+ iteration.end({
475
+ type: "exit_success",
476
+ exit_success: {
477
+ exit_name: returnExit.name,
478
+ return_value: parsedExit.value
479
+ }
480
+ });
481
+ };
482
+ //#endregion
483
+ //#region src/runtime/utils.ts
484
+ const finalizeIteration = async ({ iteration, status, controller, onIterationEnd }) => {
485
+ if (status) iteration.end(status);
486
+ if (iteration.status.type === "pending") return;
487
+ try {
488
+ await (onIterationEnd === null || onIterationEnd === void 0 ? void 0 : onIterationEnd(iteration, controller));
489
+ } catch (err) {
490
+ console.error(err);
491
+ }
492
+ };
493
+ //#endregion
494
+ //#region src/runtime/tool-wrapper.ts
495
+ const SLOW_TOOL_WARNING = (0, ms.default)("15s");
496
+ function wrapTool({ chat, tool, traces, object, iteration, beforeHook, afterHook, controller }) {
497
+ const getToolInput = (input) => tool.zInput.safeParse(input).data ?? input;
498
+ return async function(input) {
499
+ const toolCallId = `tcall_${(0, ulid.ulid)()}`;
500
+ const originalInput = input;
501
+ let effectiveInput = input;
502
+ const alertSlowTool = setTimeout(() => traces.push({
503
+ type: "tool_slow",
504
+ tool_name: tool.name,
505
+ tool_call_id: toolCallId,
506
+ started_at: Date.now(),
507
+ input: getToolInput(originalInput),
508
+ object,
509
+ duration: SLOW_TOOL_WARNING
510
+ }), SLOW_TOOL_WARNING);
511
+ const toolStart = Date.now();
512
+ let output;
513
+ let error;
514
+ let success = true;
515
+ let signalToThrow;
516
+ const pushToolCallTrace = () => {
517
+ traces.push({
518
+ type: "tool_call",
519
+ tool_call_id: toolCallId,
520
+ started_at: toolStart,
521
+ ended_at: Date.now(),
522
+ tool_name: tool.name,
523
+ object,
524
+ input: getToolInput(originalInput),
525
+ output,
526
+ error,
527
+ success
528
+ });
529
+ };
530
+ const handleSignals = async (err) => {
531
+ if (output === err) return true;
532
+ if (err instanceof require_errors.SnapshotSignal) {
533
+ err.toolCall = {
534
+ name: tool.name,
535
+ inputSchema: tool.input,
536
+ outputSchema: tool.output,
537
+ input: originalInput
538
+ };
539
+ err.message = require_errors.Signals.serializeError(err);
540
+ }
541
+ if (err instanceof require_errors.ThinkSignal) {
542
+ signalToThrow = err;
543
+ traces.push({
544
+ type: "think_signal",
545
+ started_at: Date.now(),
546
+ line: 0,
547
+ ended_at: Date.now()
548
+ });
549
+ success = true;
550
+ output = err;
551
+ const afterRes = await (afterHook === null || afterHook === void 0 ? void 0 : afterHook({
552
+ iteration,
553
+ tool,
554
+ input: originalInput,
555
+ output,
556
+ controller,
557
+ object,
558
+ toolCallId
559
+ }));
560
+ if (typeof (afterRes === null || afterRes === void 0 ? void 0 : afterRes.output) !== "undefined") output = afterRes.output;
561
+ return true;
562
+ }
563
+ return false;
564
+ };
565
+ try {
566
+ const beforeRes = await (beforeHook === null || beforeHook === void 0 ? void 0 : beforeHook({
567
+ iteration,
568
+ tool,
569
+ input: effectiveInput,
570
+ controller,
571
+ object,
572
+ toolCallId
573
+ }));
574
+ if (typeof (beforeRes === null || beforeRes === void 0 ? void 0 : beforeRes.input) !== "undefined") effectiveInput = beforeRes.input;
575
+ output = await tool.execute(effectiveInput, { callId: toolCallId }, chat);
576
+ const afterRes = await (afterHook === null || afterHook === void 0 ? void 0 : afterHook({
577
+ iteration,
578
+ tool,
579
+ input: effectiveInput,
580
+ output,
581
+ controller,
582
+ object,
583
+ toolCallId
584
+ }));
585
+ if (typeof (afterRes === null || afterRes === void 0 ? void 0 : afterRes.output) !== "undefined") output = afterRes.output;
586
+ } catch (err) {
587
+ if (!await handleSignals(err)) {
588
+ success = false;
589
+ error = err;
590
+ }
591
+ } finally {
592
+ clearTimeout(alertSlowTool);
593
+ pushToolCallTrace();
594
+ }
595
+ if (!success) throw error;
596
+ if (signalToThrow) throw signalToThrow;
597
+ return output;
598
+ };
599
+ }
600
+ //#endregion
601
+ //#region src/runtime/vm-context.ts
602
+ const buildVMContext = ({ ctx, iteration, controller, onBeforeTool, onAfterTool }) => {
603
+ const traces = iteration.traces;
604
+ const vmContext = { ...require_utils.stripInvalidIdentifiers(iteration.variables) };
605
+ for (const obj of iteration.objects) {
606
+ const internalValues = {};
607
+ const instance = {};
608
+ for (const { name, value, writable, type } of obj.properties ?? []) {
609
+ internalValues[name] = value;
610
+ const initialValue = value;
611
+ const schema = type ?? _bpinternal_zui.z.any();
612
+ Object.defineProperty(instance, name, {
613
+ enumerable: true,
614
+ configurable: true,
615
+ get() {
616
+ return internalValues[name];
617
+ },
618
+ set(value) {
619
+ if (require_dual_modes.isEqual(value, internalValues[name])) return;
620
+ if (!writable) throw new require_errors.AssignmentError(`Property ${obj.name}.${name} is read-only and cannot be modified`);
621
+ const parsed = schema.safeParse(value);
622
+ if (!parsed.success) throw new require_errors.AssignmentError(`Invalid value for Object property ${obj.name}.${name}: ${require_utils.getErrorMessage(parsed.error)}`);
623
+ internalValues[name] = parsed.data;
624
+ traces.push({
625
+ type: "property",
626
+ started_at: Date.now(),
627
+ object: obj.name,
628
+ property: name,
629
+ value: parsed.data
630
+ });
631
+ iteration.trackMutation({
632
+ object: obj.name,
633
+ property: name,
634
+ before: initialValue,
635
+ after: parsed.data
636
+ });
637
+ }
638
+ });
639
+ }
640
+ for (const tool of obj.tools ?? []) instance[tool.name] = wrapTool({
641
+ chat: ctx.chat,
642
+ tool,
643
+ traces,
644
+ object: obj.name,
645
+ iteration,
646
+ beforeHook: onBeforeTool,
647
+ afterHook: onAfterTool,
648
+ controller
649
+ });
650
+ Object.preventExtensions(instance);
651
+ Object.seal(instance);
652
+ vmContext[obj.name] = instance;
653
+ }
654
+ for (const tool of iteration.tools) {
655
+ const wrapped = wrapTool({
656
+ chat: ctx.chat,
657
+ tool,
658
+ traces,
659
+ iteration,
660
+ beforeHook: onBeforeTool,
661
+ afterHook: onAfterTool,
662
+ controller
663
+ });
664
+ for (const key of [tool.name, ...tool.aliases ?? []]) vmContext[key] = wrapped;
665
+ }
666
+ return vmContext;
667
+ };
668
+ //#endregion
669
+ //#region src/runtime/execute.ts
670
+ const executeContext = async (props) => {
671
+ await require_utils.init();
672
+ const result = await executeContextInternal(props);
673
+ try {
674
+ var _result$context$chat, _result$context$chat$;
675
+ (_result$context$chat = result.context.chat) === null || _result$context$chat === void 0 || (_result$context$chat$ = _result$context$chat.onExecutionDone) === null || _result$context$chat$ === void 0 || _result$context$chat$.call(_result$context$chat, result);
676
+ } catch (err) {}
677
+ return result;
678
+ };
679
+ const executeContextInternal = async (props) => {
680
+ var _props$options, _props$options2, _props$options3, _props$options4, _props$options5;
681
+ const controller = createJoinedAbortController([props.signal]);
682
+ const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
683
+ const client = props.client ?? new _botpress_client.Client();
684
+ const cognitive = _botpress_cognitive.Cognitive.isCognitiveClient(client) || require_custom_client._CustomModelClient.isCustomClient(client) ? client : new _botpress_cognitive.Cognitive({ client });
685
+ const ctx = new require_custom_client.Context({
686
+ chat: props.chat,
687
+ instructions: props.instructions,
688
+ objects: props.objects,
689
+ tools: props.tools,
690
+ loop: (_props$options = props.options) === null || _props$options === void 0 ? void 0 : _props$options.loop,
691
+ timeout: (_props$options2 = props.options) === null || _props$options2 === void 0 ? void 0 : _props$options2.timeout,
692
+ maxTokens: (_props$options3 = props.options) === null || _props$options3 === void 0 ? void 0 : _props$options3.maxTokens,
693
+ maxTimeToFirstToken: (_props$options4 = props.options) === null || _props$options4 === void 0 ? void 0 : _props$options4.maxTimeToFirstToken,
694
+ transcriptionModel: (_props$options5 = props.options) === null || _props$options5 === void 0 ? void 0 : _props$options5.transcriptionModel,
695
+ exits: props.exits,
696
+ snapshot: props.snapshot,
697
+ model: props.model,
698
+ temperature: props.temperature,
699
+ reasoningEffort: props.reasoningEffort
700
+ });
701
+ try {
702
+ while (true) {
703
+ if (ctx.iterations.length >= ctx.loop) return new require_custom_client.ErrorExecutionResult(ctx, new require_errors.LoopExceededError());
704
+ const iteration = await ctx.nextIteration();
705
+ const unsubscribeTrace = iteration.traces.onPush((traces) => {
706
+ for (const trace of traces) onTrace === null || onTrace === void 0 || onTrace({
707
+ trace,
708
+ iteration: ctx.iterations.length,
709
+ controller
710
+ });
711
+ });
712
+ try {
713
+ if ((await executeIterationStartHook({
714
+ ctx,
715
+ iteration,
716
+ controller,
717
+ onIterationStart,
718
+ onIterationEnd
719
+ })).type === "continue") continue;
720
+ if (controller.signal.aborted) {
721
+ await finalizeIteration({
722
+ iteration,
723
+ controller,
724
+ onIterationEnd,
725
+ status: {
726
+ type: "aborted",
727
+ aborted: { reason: controller.signal.reason ?? "The operation was aborted" }
728
+ }
729
+ });
730
+ return new require_custom_client.ErrorExecutionResult(ctx, controller.signal.reason ?? "The operation was aborted");
731
+ }
732
+ const iterationResult = await executeIterationWithErrorHandling({
733
+ iteration,
734
+ ctx,
735
+ cognitive,
736
+ controller,
737
+ onExit,
738
+ onBeforeExecution,
739
+ onAfterTool,
740
+ onBeforeTool,
741
+ onIterationEnd,
742
+ metadata: props.metadata
743
+ });
744
+ if (iterationResult.type === "return") return iterationResult.result;
745
+ const selectedResult = transformIterationResult({
746
+ ctx,
747
+ iteration
748
+ });
749
+ if (selectedResult.type === "continue") continue;
750
+ return selectedResult.result;
751
+ } finally {
752
+ try {
753
+ unsubscribeTrace();
754
+ } catch (err) {}
755
+ }
756
+ }
757
+ } catch (error) {
758
+ return new require_custom_client.ErrorExecutionResult(ctx, error ?? "Unknown error");
759
+ }
760
+ };
761
+ const executeIterationStartHook = async ({ ctx, iteration, controller, onIterationStart, onIterationEnd }) => {
762
+ try {
763
+ const hookRes = await (onIterationStart === null || onIterationStart === void 0 ? void 0 : onIterationStart(iteration, controller, ctx));
764
+ if (hookRes) Object.assign(iteration, hookRes);
765
+ return { type: "proceed" };
766
+ } catch (err) {
767
+ await finalizeIteration({
768
+ iteration,
769
+ controller,
770
+ onIterationEnd,
771
+ status: err instanceof require_errors.ThinkSignal ? {
772
+ type: "thinking_requested",
773
+ thinking_requested: {
774
+ variables: err.context,
775
+ reason: err.reason
776
+ }
777
+ } : {
778
+ type: "execution_error",
779
+ execution_error: {
780
+ message: `Error in onIterationStart hook: ${require_utils.getErrorMessage(err)}`,
781
+ stack: require_stack_traces.cleanStackTrace(err instanceof Error ? err.stack ?? "No stack trace available" : "No stack trace available")
782
+ }
783
+ }
784
+ });
785
+ return { type: "continue" };
786
+ }
787
+ };
788
+ const executeIterationWithErrorHandling = async ({ iteration, ctx, cognitive, controller, onExit, onBeforeExecution, onAfterTool, onBeforeTool, onIterationEnd, metadata }) => {
789
+ try {
790
+ await executeIteration({
791
+ iteration,
792
+ ctx,
793
+ cognitive,
794
+ controller,
795
+ onExit,
796
+ onBeforeExecution,
797
+ onAfterTool,
798
+ onBeforeTool,
799
+ metadata
800
+ });
801
+ await finalizeIteration({
802
+ iteration,
803
+ controller,
804
+ onIterationEnd
805
+ });
806
+ return { type: "proceed" };
807
+ } catch (err) {
808
+ if (!(err instanceof require_errors.CognitiveError)) {
809
+ await finalizeIteration({
810
+ iteration,
811
+ controller,
812
+ onIterationEnd,
813
+ status: iteration.status.type === "pending" ? {
814
+ type: "execution_error",
815
+ execution_error: {
816
+ message: "An unexpected error occurred: " + require_utils.getErrorMessage(err),
817
+ stack: require_stack_traces.cleanStackTrace(err instanceof Error ? err.stack ?? "No stack trace available" : "No stack trace available")
818
+ }
819
+ } : void 0
820
+ });
821
+ return { type: "proceed" };
822
+ }
823
+ if (!controller.signal.aborted) return {
824
+ type: "return",
825
+ result: new require_custom_client.ErrorExecutionResult(ctx, err)
826
+ };
827
+ await finalizeIteration({
828
+ iteration,
829
+ controller,
830
+ onIterationEnd,
831
+ status: iteration.status.type === "pending" ? {
832
+ type: "aborted",
833
+ aborted: { reason: controller.signal.reason ?? "The operation was aborted" }
834
+ } : void 0
835
+ });
836
+ return {
837
+ type: "return",
838
+ result: new require_custom_client.ErrorExecutionResult(ctx, controller.signal.reason ?? "The operation was aborted")
839
+ };
840
+ }
841
+ };
842
+ const transformIterationResult = ({ ctx, iteration }) => {
843
+ if (iteration.status.type === "exit_success") {
844
+ const exitName = iteration.status.exit_success.exit_name;
845
+ return {
846
+ type: "return",
847
+ result: new require_custom_client.SuccessExecutionResult(ctx, {
848
+ exit: iteration.exits.find((x) => x.name === exitName),
849
+ result: iteration.status.exit_success.return_value
850
+ })
851
+ };
852
+ }
853
+ if (iteration.status.type === "callback_requested") return {
854
+ type: "return",
855
+ result: new require_custom_client.PartialExecutionResult(ctx, iteration.status.callback_requested.signal, require_custom_client.Snapshot.fromSignal(iteration.status.callback_requested.signal))
856
+ };
857
+ if (iteration.status.type === "aborted") return {
858
+ type: "return",
859
+ result: new require_custom_client.ErrorExecutionResult(ctx, iteration.error ?? "The operation was aborted")
860
+ };
861
+ if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") return { type: "continue" };
862
+ return {
863
+ type: "return",
864
+ result: new require_custom_client.ErrorExecutionResult(ctx, iteration.error ?? `Unknown error. Status: ${iteration.status.type}`)
865
+ };
866
+ };
867
+ const executeIteration = async ({ iteration, ctx, cognitive, controller, onExit, onBeforeExecution, onBeforeTool, onAfterTool, metadata }) => {
868
+ var _ctx$chat;
869
+ const runCode = (code) => {
870
+ const vmContext = buildVMContext({
871
+ ctx,
872
+ iteration,
873
+ controller,
874
+ onBeforeTool,
875
+ onAfterTool
876
+ });
877
+ return require_vm.runAsyncFunction(vmContext, code, iteration.traces, controller.signal, ctx.timeout).catch((err) => {
878
+ return {
879
+ success: false,
880
+ error: err instanceof Error ? err : new Error(require_utils.getErrorMessage(err)),
881
+ lines_executed: [],
882
+ traces: [],
883
+ variables: {}
884
+ };
885
+ });
886
+ };
887
+ const canExecuteEarly = typeof onBeforeExecution !== "function";
888
+ let earlyExecution;
889
+ await generateCode({
890
+ iteration,
891
+ ctx,
892
+ cognitive,
893
+ controller,
894
+ metadata,
895
+ onRunStart: () => require_vm.warmupVM(),
896
+ onRunComplete: canExecuteEarly ? (code) => {
897
+ if (!code.length || controller.signal.aborted || earlyExecution) return;
898
+ iteration.code = code;
899
+ earlyExecution = {
900
+ code,
901
+ started_at: Date.now(),
902
+ promise: runCode(code)
903
+ };
904
+ } : void 0,
905
+ onSend: async (send) => {
906
+ if (!ctx.chat) return;
907
+ const sendStartedAt = Date.now();
908
+ const component = require_jsx.createJsxComponent({
909
+ type: send.name,
910
+ props: send.props,
911
+ children: send.body ? [send.body] : []
912
+ });
913
+ try {
914
+ await ctx.chat.handler(component);
915
+ } catch (err) {
916
+ throw new Error(`Error while sending message (■send=${send.name}): ${require_utils.getErrorMessage(err)}`);
917
+ }
918
+ iteration.traces.push({
919
+ type: "yield",
920
+ value: component,
921
+ started_at: sendStartedAt,
922
+ ended_at: Date.now()
923
+ });
924
+ },
925
+ onSendDelta: ((_ctx$chat = ctx.chat) === null || _ctx$chat === void 0 ? void 0 : _ctx$chat.onMessageDelta) ? (delta) => ctx.chat.onMessageDelta(delta) : void 0
926
+ });
927
+ if (earlyExecution) iteration.code = earlyExecution.code;
928
+ if (typeof onBeforeExecution === "function") try {
929
+ const hookRes = await onBeforeExecution(iteration, controller);
930
+ if (typeof (hookRes === null || hookRes === void 0 ? void 0 : hookRes.code) === "string" && hookRes.code.trim().length > 0) iteration.code = hookRes.code.trim();
931
+ } catch (err) {
932
+ if (err instanceof require_errors.ThinkSignal) {
933
+ iteration.end({
934
+ type: "thinking_requested",
935
+ thinking_requested: {
936
+ variables: err.context,
937
+ reason: err.reason
938
+ }
939
+ });
940
+ return;
941
+ }
942
+ iteration.end({
943
+ type: "execution_error",
944
+ execution_error: {
945
+ message: `Error in onBeforeExecution hook: ${require_utils.getErrorMessage(err)}`,
946
+ stack: require_stack_traces.cleanStackTrace(err instanceof Error ? err.stack ?? "No stack trace available" : "No stack trace available")
947
+ }
948
+ });
949
+ return;
950
+ }
951
+ const traces = iteration.traces;
952
+ if (controller.signal.aborted) {
953
+ traces.push({
954
+ type: "abort_signal",
955
+ started_at: Date.now(),
956
+ reason: "The operation was aborted by user."
957
+ });
958
+ iteration.end({
959
+ type: "aborted",
960
+ aborted: { reason: controller.signal.reason ?? "The operation was aborted" }
961
+ });
962
+ return;
963
+ }
964
+ if (!iteration.code) {
965
+ var _iteration$sends;
966
+ if (iteration.next) {
967
+ await applyNextExit({
968
+ iteration,
969
+ controller,
970
+ onExit
971
+ });
972
+ return;
973
+ }
974
+ if (ctx.chat && ((_iteration$sends = iteration.sends) === null || _iteration$sends === void 0 ? void 0 : _iteration$sends.length)) {
975
+ iteration.next = {
976
+ name: "listen",
977
+ props: {}
978
+ };
979
+ await applyNextExit({
980
+ iteration,
981
+ controller,
982
+ onExit
983
+ });
984
+ return;
985
+ }
986
+ iteration.end({
987
+ type: "invalid_code_error",
988
+ invalid_code_error: { message: "The response did not include a ■run block or a ■next exit. Reply using ■ blocks and end your response with ■run or ■next=<exit>." }
989
+ });
990
+ return;
991
+ }
992
+ const startedAt = (earlyExecution === null || earlyExecution === void 0 ? void 0 : earlyExecution.started_at) ?? Date.now();
993
+ const result = earlyExecution ? await earlyExecution.promise : await runCode(iteration.code ?? "");
994
+ await interpretVMResult({
995
+ iteration,
996
+ result,
997
+ controller,
998
+ startedAt,
999
+ onExit
1000
+ });
1001
+ };
1002
+ //#endregion
1003
+ exports.executeContext = executeContext;