llmz 0.0.11 → 0.0.13

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 (92) hide show
  1. package/dist/chat.d.ts +17 -0
  2. package/dist/chunk-276Q6EWP.cjs +224 -0
  3. package/dist/chunk-4L6D2A6O.cjs +283 -0
  4. package/dist/chunk-4MNIJGK6.js +224 -0
  5. package/dist/chunk-7WRN4E42.js +3087 -0
  6. package/dist/chunk-BEPRLBPK.cjs +3123 -0
  7. package/dist/chunk-C6WNNTEV.cjs +212 -0
  8. package/dist/chunk-D3ESDRLH.js +3123 -0
  9. package/dist/chunk-GGWM6X2K.js +184 -0
  10. package/dist/chunk-GWFYZDUR.cjs +105 -0
  11. package/dist/chunk-HJKOSEH2.cjs +722 -0
  12. package/dist/chunk-IH2WQFO5.js +283 -0
  13. package/dist/chunk-IKSIOIIP.cjs +28 -0
  14. package/dist/chunk-JAGB2AOU.js +212 -0
  15. package/dist/chunk-JDABP4SD.cjs +161 -0
  16. package/dist/chunk-JGVAZO4X.cjs +152 -0
  17. package/dist/chunk-JKVVQN2P.js +161 -0
  18. package/dist/chunk-JMSZKB4T.js +105 -0
  19. package/dist/chunk-JQBT7UWN.js +28 -0
  20. package/dist/chunk-KH6JQYQA.js +796 -0
  21. package/dist/chunk-KMZDFWYZ.cjs +33 -0
  22. package/dist/chunk-ORQP26SZ.js +33 -0
  23. package/dist/chunk-PRVFVXT4.js +722 -0
  24. package/dist/chunk-SHJDRZF5.cjs +796 -0
  25. package/dist/chunk-SNDVQU5A.js +152 -0
  26. package/dist/chunk-UQOBUJIQ.cjs +3087 -0
  27. package/dist/chunk-ZRCU35UV.cjs +184 -0
  28. package/dist/citations.d.ts +63 -0
  29. package/dist/compiler/compiler.d.ts +28 -0
  30. package/dist/compiler/index.d.ts +2 -0
  31. package/dist/compiler/plugins/async-iterator.d.ts +4 -0
  32. package/dist/compiler/plugins/braces-tsx.d.ts +3 -0
  33. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +5 -0
  34. package/dist/compiler/plugins/line-tracking.d.ts +5 -0
  35. package/dist/compiler/plugins/replace-comment.d.ts +5 -0
  36. package/dist/compiler/plugins/return-async.d.ts +4 -0
  37. package/dist/compiler/plugins/track-tool-calls.d.ts +16 -0
  38. package/dist/compiler/plugins/variable-extraction.d.ts +5 -0
  39. package/dist/component-R4WTW6DZ.cjs +18 -0
  40. package/dist/component-WFVDVSDK.js +18 -0
  41. package/dist/component.d.ts +66 -0
  42. package/dist/component.default.d.ts +316 -0
  43. package/dist/context.d.ts +176 -0
  44. package/dist/dual-modes-T53P72CH.js +12 -0
  45. package/dist/dual-modes-VLIGPIHX.cjs +12 -0
  46. package/dist/errors.d.ts +64 -0
  47. package/dist/exit-TRXEU4OU.cjs +8 -0
  48. package/dist/exit-YORW76T3.js +8 -0
  49. package/dist/exit.d.ts +26 -0
  50. package/dist/formatting.d.ts +5 -0
  51. package/dist/getter.d.ts +2 -0
  52. package/dist/handlers.d.ts +10 -0
  53. package/dist/hoist.d.ts +2 -0
  54. package/dist/index.cjs +921 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +921 -0
  57. package/dist/inspect.d.ts +6 -0
  58. package/dist/jsx-AEHVFB3L.js +13 -0
  59. package/dist/jsx-AJAXBWFE.cjs +13 -0
  60. package/dist/jsx.d.ts +11 -0
  61. package/dist/llmz-QLZBDG2Z.cjs +576 -0
  62. package/dist/llmz-ROOX7RYI.js +576 -0
  63. package/dist/llmz.d.ts +40 -0
  64. package/dist/objects.d.ts +24 -0
  65. package/dist/prompts/chat-mode/system.md.d.ts +2 -0
  66. package/dist/prompts/chat-mode/user.md.d.ts +2 -0
  67. package/dist/prompts/common.d.ts +6 -0
  68. package/dist/prompts/dual-modes.d.ts +2 -0
  69. package/dist/prompts/prompt.d.ts +55 -0
  70. package/dist/prompts/worker-mode/system.md.d.ts +2 -0
  71. package/dist/prompts/worker-mode/user.md.d.ts +2 -0
  72. package/dist/result.d.ts +33 -0
  73. package/dist/snapshots.d.ts +69 -0
  74. package/dist/stack-traces.d.ts +1 -0
  75. package/dist/tool-N6ODRRGH.js +11 -0
  76. package/dist/tool-QP4MVRWI.cjs +11 -0
  77. package/dist/tool.d.ts +56 -0
  78. package/dist/transcript.d.ts +36 -0
  79. package/dist/truncator-DUMWEGQO.cjs +10 -0
  80. package/dist/truncator-IY2MXOMC.js +10 -0
  81. package/dist/truncator.d.ts +20 -0
  82. package/dist/types.d.ts +105 -0
  83. package/dist/typings-2CPHOFDN.cjs +10 -0
  84. package/dist/typings-GDMY6VY2.js +10 -0
  85. package/dist/typings.d.ts +5 -0
  86. package/dist/utils-A7WNEFTA.cjs +39 -0
  87. package/dist/utils-N24IHDFA.js +39 -0
  88. package/dist/utils.d.ts +23 -0
  89. package/dist/vm-2DLG7V4G.cjs +12 -0
  90. package/dist/vm-FLBMZUA2.js +12 -0
  91. package/dist/vm.d.ts +3 -0
  92. package/package.json +4 -4
@@ -0,0 +1,6 @@
1
+ type PreviewOptions = {
2
+ tokens: number;
3
+ };
4
+ export declare function extractType(value: unknown, generic?: boolean): string;
5
+ export declare const inspect: (value: unknown, name?: string, options?: PreviewOptions) => string;
6
+ export {};
@@ -0,0 +1,13 @@
1
+ import {
2
+ Jsx,
3
+ createJsxComponent,
4
+ isAnyJsxComponent,
5
+ isJsxComponent
6
+ } from "./chunk-ORQP26SZ.js";
7
+ import "./chunk-7WRN4E42.js";
8
+ export {
9
+ Jsx,
10
+ createJsxComponent,
11
+ isAnyJsxComponent,
12
+ isJsxComponent
13
+ };
@@ -0,0 +1,13 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+ var _chunkKMZDFWYZcjs = require('./chunk-KMZDFWYZ.cjs');
7
+ require('./chunk-UQOBUJIQ.cjs');
8
+
9
+
10
+
11
+
12
+
13
+ exports.Jsx = _chunkKMZDFWYZcjs.Jsx; exports.createJsxComponent = _chunkKMZDFWYZcjs.createJsxComponent; exports.isAnyJsxComponent = _chunkKMZDFWYZcjs.isAnyJsxComponent; exports.isJsxComponent = _chunkKMZDFWYZcjs.isJsxComponent;
package/dist/jsx.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { z } from '@bpinternal/zui';
2
+ export type JsxComponent<TType extends string = string, TProps extends {} = {}, TChildren = any> = {
3
+ __jsx: true;
4
+ type: TType;
5
+ props: TProps;
6
+ children: Array<TChildren>;
7
+ };
8
+ export declare function isAnyJsxComponent(component: any): component is JsxComponent;
9
+ export declare function isJsxComponent<T extends JsxComponent>(type: T['type'], component: any): component is T;
10
+ export declare const createJsxComponent: (props: Omit<JsxComponent, "__jsx">) => JsxComponent;
11
+ export declare const Jsx: z.Schema<JsxComponent<string, {}, any>, import("@bpinternal/zui").ZodTypeDef, JsxComponent<string, {}, any>>;
@@ -0,0 +1,576 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+ var _chunkBEPRLBPKcjs = require('./chunk-BEPRLBPK.cjs');
4
+
5
+
6
+
7
+
8
+
9
+
10
+ var _chunkHJKOSEH2cjs = require('./chunk-HJKOSEH2.cjs');
11
+ require('./chunk-SHJDRZF5.cjs');
12
+ require('./chunk-C6WNNTEV.cjs');
13
+ require('./chunk-4L6D2A6O.cjs');
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ var _chunkJDABP4SDcjs = require('./chunk-JDABP4SD.cjs');
24
+
25
+
26
+ var _chunkIKSIOIIPcjs = require('./chunk-IKSIOIIP.cjs');
27
+ require('./chunk-GWFYZDUR.cjs');
28
+ require('./chunk-ZRCU35UV.cjs');
29
+ require('./chunk-KMZDFWYZ.cjs');
30
+
31
+
32
+ var _chunkJGVAZO4Xcjs = require('./chunk-JGVAZO4X.cjs');
33
+
34
+
35
+
36
+ var _chunk276Q6EWPcjs = require('./chunk-276Q6EWP.cjs');
37
+
38
+
39
+
40
+
41
+
42
+ var _chunkUQOBUJIQcjs = require('./chunk-UQOBUJIQ.cjs');
43
+
44
+ // src/llmz.ts
45
+ var _cognitive = require('@botpress/cognitive');
46
+ var _zui = require('@bpinternal/zui');
47
+ var _ms = require('ms'); var _ms2 = _interopRequireDefault(_ms);
48
+ var _ulid = require('ulid');
49
+ var getErrorMessage = (err) => err instanceof Error ? err.message : JSON.stringify(err);
50
+ var SLOW_TOOL_WARNING = _ms2.default.call(void 0, "15s");
51
+ var RESPONSE_LENGTH_BUFFER = {
52
+ MIN_TOKENS: 1e3,
53
+ MAX_TOKENS: 16e3,
54
+ PERCENTAGE: 0.1
55
+ };
56
+ var getModelOutputLimit = (inputLength) => _chunkUQOBUJIQcjs.clamp_default.call(void 0,
57
+ RESPONSE_LENGTH_BUFFER.PERCENTAGE * inputLength,
58
+ RESPONSE_LENGTH_BUFFER.MIN_TOKENS,
59
+ RESPONSE_LENGTH_BUFFER.MAX_TOKENS
60
+ );
61
+ var executeContext = async (props) => {
62
+ var _a, _b;
63
+ await _chunk276Q6EWPcjs.init.call(void 0, );
64
+ const result = await _executeContext(props);
65
+ try {
66
+ (_b = (_a = result.context.chat) == null ? void 0 : _a.onExecutionDone) == null ? void 0 : _b.call(_a, result);
67
+ } catch (e) {
68
+ }
69
+ return result;
70
+ };
71
+ var _executeContext = async (props) => {
72
+ var _a, _b, _c, _d;
73
+ const { signal, onIterationEnd, onTrace, onExit, onBeforeExecution } = props;
74
+ const cognitive = _cognitive.Cognitive.isCognitiveClient(props.client) ? props.client : new (0, _cognitive.Cognitive)({ client: props.client });
75
+ const cleanups = [];
76
+ const ctx = new (0, _chunkHJKOSEH2cjs.Context)({
77
+ chat: props.chat,
78
+ instructions: props.instructions,
79
+ objects: props.objects,
80
+ tools: props.tools,
81
+ loop: (_a = props.options) == null ? void 0 : _a.loop,
82
+ temperature: (_b = props.options) == null ? void 0 : _b.temperature,
83
+ model: (_c = props.options) == null ? void 0 : _c.model,
84
+ timeout: (_d = props.options) == null ? void 0 : _d.timeout,
85
+ exits: props.exits,
86
+ snapshot: props.snapshot
87
+ });
88
+ try {
89
+ while (true) {
90
+ if (ctx.iterations.length >= ctx.loop) {
91
+ return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, new (0, _chunkJDABP4SDcjs.LoopExceededError)());
92
+ }
93
+ const iteration = await ctx.nextIteration();
94
+ if (signal == null ? void 0 : signal.aborted) {
95
+ iteration.end({
96
+ type: "aborted",
97
+ aborted: {
98
+ reason: _nullishCoalesce(signal.reason, () => ( "The operation was aborted"))
99
+ }
100
+ });
101
+ return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(signal.reason, () => ( "The operation was aborted")));
102
+ }
103
+ cleanups.push(
104
+ iteration.traces.onPush((traces) => {
105
+ for (const trace of traces) {
106
+ onTrace == null ? void 0 : onTrace({ trace, iteration: ctx.iterations.length });
107
+ }
108
+ })
109
+ );
110
+ try {
111
+ await executeIteration({
112
+ iteration,
113
+ ctx,
114
+ cognitive,
115
+ abortSignal: signal,
116
+ onExit,
117
+ onBeforeExecution
118
+ });
119
+ } catch (err) {
120
+ iteration.end({
121
+ type: "execution_error",
122
+ execution_error: {
123
+ message: "An unexpected error occurred: " + getErrorMessage(err),
124
+ stack: _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce(err.stack, () => ( "No stack trace available")))
125
+ }
126
+ });
127
+ }
128
+ try {
129
+ await (onIterationEnd == null ? void 0 : onIterationEnd(iteration));
130
+ } catch (err) {
131
+ console.error(err);
132
+ }
133
+ if (iteration.status.type === "exit_success") {
134
+ const exitName = iteration.status.exit_success.exit_name;
135
+ return new (0, _chunkHJKOSEH2cjs.SuccessExecutionResult)(ctx, {
136
+ exit: iteration.exits.find((x) => x.name === exitName),
137
+ result: iteration.status.exit_success.return_value
138
+ });
139
+ }
140
+ if (iteration.status.type === "callback_requested") {
141
+ return new (0, _chunkHJKOSEH2cjs.PartialExecutionResult)(
142
+ ctx,
143
+ iteration.status.callback_requested.signal,
144
+ _chunkHJKOSEH2cjs.Snapshot.fromSignal(iteration.status.callback_requested.signal)
145
+ );
146
+ }
147
+ if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") {
148
+ continue;
149
+ }
150
+ return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( `Unknown error. Status: ${iteration.status.type}`)));
151
+ }
152
+ } catch (error) {
153
+ return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(error, () => ( "Unknown error")));
154
+ } finally {
155
+ for (const cleanup of cleanups) {
156
+ try {
157
+ cleanup();
158
+ } catch (e2) {
159
+ }
160
+ }
161
+ }
162
+ };
163
+ var executeIteration = async ({
164
+ iteration,
165
+ ctx,
166
+ cognitive,
167
+ abortSignal,
168
+ onExit,
169
+ onBeforeExecution
170
+ }) => {
171
+ var _a, _b, _c, _d, _e;
172
+ let startedAt = Date.now();
173
+ const traces = iteration.traces;
174
+ const model = await cognitive.getModelDetails(_nullishCoalesce(ctx.model, () => ( "best")));
175
+ const modelLimit = model.input.maxTokens;
176
+ const responseLengthBuffer = getModelOutputLimit(modelLimit);
177
+ const messages = _chunkJGVAZO4Xcjs.truncateWrappedContent.call(void 0, {
178
+ messages: iteration.messages,
179
+ tokenLimit: modelLimit - responseLengthBuffer,
180
+ throwOnFailure: true
181
+ }).filter(
182
+ (x) => (
183
+ // Filter out empty messages, as they are not valid inputs for the LLM
184
+ // This can happen when a message is truncated and the content is empty
185
+ typeof x.content !== "string" || x.content.trim().length > 0
186
+ )
187
+ );
188
+ traces.push({
189
+ type: "llm_call_started",
190
+ started_at: startedAt,
191
+ ended_at: startedAt,
192
+ model: model.ref
193
+ });
194
+ const output = await cognitive.generateContent({
195
+ signal: abortSignal,
196
+ systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
197
+ model: model.ref,
198
+ temperature: ctx.temperature,
199
+ responseFormat: "text",
200
+ messages: messages.filter((x) => x.role !== "system"),
201
+ stopSequences: ctx.version.getStopTokens()
202
+ });
203
+ const out = ((_c = (_b = output.output.choices) == null ? void 0 : _b[0]) == null ? void 0 : _c.type) === "text" && typeof ((_d = output.output.choices) == null ? void 0 : _d[0].content) === "string" ? output.output.choices[0].content : null;
204
+ if (!out) {
205
+ throw new Error("No output from LLM");
206
+ }
207
+ const assistantResponse = ctx.version.parseAssistantResponse(out);
208
+ iteration.code = assistantResponse.code.trim();
209
+ if (typeof onBeforeExecution === "function") {
210
+ try {
211
+ await onBeforeExecution(iteration);
212
+ } catch (err) {
213
+ if (err instanceof _chunkJDABP4SDcjs.ThinkSignal) {
214
+ return iteration.end({
215
+ type: "thinking_requested",
216
+ thinking_requested: {
217
+ variables: err.context,
218
+ reason: err.reason
219
+ }
220
+ });
221
+ }
222
+ return iteration.end({
223
+ type: "execution_error",
224
+ execution_error: {
225
+ message: `Error in onBeforeExecution hook: ${getErrorMessage(err)}`,
226
+ stack: _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce(err.stack, () => ( "No stack trace available")))
227
+ }
228
+ });
229
+ }
230
+ }
231
+ iteration.llm = {
232
+ cached: output.meta.cached || false,
233
+ ended_at: Date.now(),
234
+ started_at: startedAt,
235
+ status: "success",
236
+ tokens: output.meta.tokens.input + output.meta.tokens.output,
237
+ spend: output.meta.cost.input + output.meta.cost.output,
238
+ output: assistantResponse.raw,
239
+ model: `${output.meta.model.integration}:${output.meta.model.model}`
240
+ };
241
+ traces.push({
242
+ type: "llm_call_success",
243
+ started_at: startedAt,
244
+ ended_at: iteration.llm.ended_at,
245
+ model: model.ref,
246
+ code: iteration.code
247
+ });
248
+ const vmContext = { ..._chunk276Q6EWPcjs.stripInvalidIdentifiers.call(void 0, iteration.variables) };
249
+ for (const obj of iteration.objects) {
250
+ const internalValues = {};
251
+ const instance = {};
252
+ for (const { name, value, writable, type } of _nullishCoalesce(obj.properties, () => ( []))) {
253
+ internalValues[name] = value;
254
+ const initialValue = value;
255
+ const schema = _nullishCoalesce(type, () => ( _zui.z.any()));
256
+ Object.defineProperty(instance, name, {
257
+ enumerable: true,
258
+ configurable: true,
259
+ get() {
260
+ return internalValues[name];
261
+ },
262
+ set(value2) {
263
+ if (_chunkUQOBUJIQcjs.isEqual_default.call(void 0, value2, internalValues[name])) {
264
+ return;
265
+ }
266
+ if (!writable) {
267
+ throw new (0, _chunkJDABP4SDcjs.AssignmentError)(`Property ${obj.name}.${name} is read-only and cannot be modified`);
268
+ }
269
+ if (value2 === internalValues[name]) {
270
+ return;
271
+ }
272
+ const parsed = schema.safeParse(value2);
273
+ if (!parsed.success) {
274
+ throw new (0, _chunkJDABP4SDcjs.AssignmentError)(
275
+ `Invalid value for Object property ${obj.name}.${name}: ${getErrorMessage(parsed.error)}`
276
+ );
277
+ }
278
+ internalValues[name] = parsed.data;
279
+ traces.push({
280
+ type: "property",
281
+ started_at: Date.now(),
282
+ object: obj.name,
283
+ property: name,
284
+ value: parsed.data
285
+ });
286
+ iteration.trackMutation({ object: obj.name, property: name, before: initialValue, after: parsed.data });
287
+ }
288
+ });
289
+ }
290
+ for (const tool of _nullishCoalesce(obj.tools, () => ( []))) {
291
+ instance[tool.name] = wrapTool({ tool, traces, object: obj.name });
292
+ }
293
+ Object.preventExtensions(instance);
294
+ Object.seal(instance);
295
+ vmContext[obj.name] = instance;
296
+ }
297
+ for (const tool of iteration.tools) {
298
+ const wrapped = wrapTool({ tool, traces });
299
+ for (const key of [tool.name, ..._nullishCoalesce(tool.aliases, () => ( []))]) {
300
+ vmContext[key] = wrapped;
301
+ }
302
+ }
303
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
304
+ traces.push({
305
+ type: "abort_signal",
306
+ started_at: Date.now(),
307
+ reason: "The operation was aborted by user."
308
+ });
309
+ return iteration.end({
310
+ type: "aborted",
311
+ aborted: {
312
+ reason: _nullishCoalesce((abortSignal == null ? void 0 : abortSignal.reason), () => ( "The operation was aborted"))
313
+ }
314
+ });
315
+ }
316
+ startedAt = Date.now();
317
+ const result = await _chunkBEPRLBPKcjs.runAsyncFunction.call(void 0, vmContext, iteration.code, traces, abortSignal, ctx.timeout).catch(
318
+ (err) => {
319
+ return {
320
+ success: false,
321
+ error: err,
322
+ lines_executed: [],
323
+ traces: [],
324
+ variables: {}
325
+ };
326
+ }
327
+ );
328
+ if (result.error && result.error instanceof _chunkJDABP4SDcjs.InvalidCodeError) {
329
+ return iteration.end({
330
+ type: "invalid_code_error",
331
+ invalid_code_error: {
332
+ message: result.error.message
333
+ }
334
+ });
335
+ }
336
+ traces.push({
337
+ type: "code_execution",
338
+ lines_executed: _nullishCoalesce(result.lines_executed, () => ( 0)),
339
+ started_at: startedAt,
340
+ ended_at: Date.now()
341
+ });
342
+ if (result.error && result.error instanceof _chunkJDABP4SDcjs.CodeExecutionError) {
343
+ return iteration.end({
344
+ type: "execution_error",
345
+ execution_error: {
346
+ message: result.error.message,
347
+ stack: _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce(_nullishCoalesce(result.error.stacktrace, () => ( result.error.stack)), () => ( "No stack trace available")))
348
+ }
349
+ });
350
+ }
351
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
352
+ return iteration.end({
353
+ type: "aborted",
354
+ aborted: {
355
+ reason: _nullishCoalesce((abortSignal == null ? void 0 : abortSignal.reason), () => ( "The operation was aborted"))
356
+ }
357
+ });
358
+ }
359
+ if (!result.success) {
360
+ return iteration.end({
361
+ type: "execution_error",
362
+ execution_error: {
363
+ message: _nullishCoalesce(((_e = result == null ? void 0 : result.error) == null ? void 0 : _e.message), () => ( "Unknown error occurred")),
364
+ stack: _chunkIKSIOIIPcjs.cleanStackTrace.call(void 0, _nullishCoalesce(result.error.stack, () => ( "No stack trace available")))
365
+ }
366
+ });
367
+ }
368
+ if (result.signal instanceof _chunkJDABP4SDcjs.ThinkSignal) {
369
+ return iteration.end({
370
+ type: "thinking_requested",
371
+ thinking_requested: {
372
+ variables: result.signal.context,
373
+ reason: result.signal.reason
374
+ }
375
+ });
376
+ }
377
+ if (result.signal instanceof _chunkJDABP4SDcjs.SnapshotSignal) {
378
+ return iteration.end({
379
+ type: "callback_requested",
380
+ callback_requested: {
381
+ signal: result.signal
382
+ }
383
+ });
384
+ }
385
+ const validActions = [...iteration.exits.map((x) => x.name.toLowerCase()), "think"];
386
+ let returnValue = result.success && result.return_value ? result.return_value : null;
387
+ const returnAction = returnValue == null ? void 0 : returnValue.action;
388
+ const returnExit = _nullishCoalesce(iteration.exits.find((x) => x.name.toLowerCase() === (returnAction == null ? void 0 : returnAction.toLowerCase())), () => ( iteration.exits.find((x) => x.aliases.some((a) => a.toLowerCase() === (returnAction == null ? void 0 : returnAction.toLowerCase())))));
389
+ if (returnAction === "think") {
390
+ const variables = _chunkUQOBUJIQcjs.omit_default.call(void 0, _nullishCoalesce(returnValue, () => ( {})), "action");
391
+ if (_chunkUQOBUJIQcjs.isPlainObject_default.call(void 0, variables) && Object.keys(variables).length > 0) {
392
+ return iteration.end({
393
+ type: "thinking_requested",
394
+ thinking_requested: {
395
+ variables,
396
+ reason: "Thinking requested"
397
+ }
398
+ });
399
+ }
400
+ return iteration.end({
401
+ type: "thinking_requested",
402
+ thinking_requested: {
403
+ reason: "Thinking requested",
404
+ variables: iteration.variables
405
+ }
406
+ });
407
+ }
408
+ if (!returnAction) {
409
+ return iteration.end({
410
+ type: "exit_error",
411
+ exit_error: {
412
+ exit: "n/a",
413
+ message: `Code did not return an action. Valid actions are: ${validActions.join(", ")}`,
414
+ return_value: returnValue
415
+ }
416
+ });
417
+ }
418
+ if (!returnExit) {
419
+ return iteration.end({
420
+ type: "exit_error",
421
+ exit_error: {
422
+ exit: returnAction,
423
+ message: `Exit "${returnAction}" not found. Valid actions are: ${validActions.join(", ")}`,
424
+ return_value: returnValue
425
+ }
426
+ });
427
+ }
428
+ if (returnExit.zSchema) {
429
+ const parsed = returnExit.zSchema.safeParse(returnValue == null ? void 0 : returnValue.value);
430
+ if (!parsed.success) {
431
+ return iteration.end({
432
+ type: "exit_error",
433
+ exit_error: {
434
+ exit: returnExit.name,
435
+ message: `Invalid return value for exit ${returnExit.name}: ${getErrorMessage(parsed.error)}`,
436
+ return_value: returnValue
437
+ }
438
+ });
439
+ }
440
+ returnValue = { action: returnExit.name, value: parsed.data };
441
+ }
442
+ try {
443
+ await (onExit == null ? void 0 : onExit({
444
+ exit: returnExit,
445
+ result: returnValue == null ? void 0 : returnValue.value
446
+ }));
447
+ } catch (err) {
448
+ return iteration.end({
449
+ type: "exit_error",
450
+ exit_error: {
451
+ exit: returnExit.name,
452
+ message: `Error executing exit ${returnExit.name}: ${getErrorMessage(err)}`,
453
+ return_value: returnValue
454
+ }
455
+ });
456
+ }
457
+ return iteration.end({
458
+ type: "exit_success",
459
+ exit_success: {
460
+ exit_name: returnExit.name,
461
+ return_value: returnValue == null ? void 0 : returnValue.value
462
+ }
463
+ });
464
+ };
465
+ function wrapTool({ tool, traces, object }) {
466
+ const getToolInput = (input) => _nullishCoalesce(tool.zInput.safeParse(input).data, () => ( input));
467
+ return function(input) {
468
+ const toolCallId = `tcall_${_ulid.ulid.call(void 0, )}`;
469
+ const alertSlowTool = setTimeout(
470
+ () => traces.push({
471
+ type: "tool_slow",
472
+ tool_name: tool.name,
473
+ tool_call_id: toolCallId,
474
+ started_at: Date.now(),
475
+ input: getToolInput(input),
476
+ object,
477
+ duration: SLOW_TOOL_WARNING
478
+ }),
479
+ SLOW_TOOL_WARNING
480
+ );
481
+ const cancelSlowTool = () => clearTimeout(alertSlowTool);
482
+ const toolStart = Date.now();
483
+ let output;
484
+ let error;
485
+ let success = true;
486
+ const handleSignals = (error2) => {
487
+ if (output === error2) {
488
+ return true;
489
+ }
490
+ if (error2 instanceof _chunkJDABP4SDcjs.SnapshotSignal) {
491
+ error2.toolCall = {
492
+ name: tool.name,
493
+ inputSchema: tool.input,
494
+ outputSchema: tool.output,
495
+ input
496
+ };
497
+ error2.message = _chunkJDABP4SDcjs.Signals.serializeError(error2);
498
+ }
499
+ if (error2 instanceof _chunkJDABP4SDcjs.ThinkSignal) {
500
+ traces.push({
501
+ type: "think_signal",
502
+ started_at: Date.now(),
503
+ line: 0,
504
+ ended_at: Date.now()
505
+ });
506
+ success = true;
507
+ output = error2;
508
+ return true;
509
+ }
510
+ return false;
511
+ };
512
+ try {
513
+ const result = tool.execute(input, {
514
+ callId: toolCallId
515
+ });
516
+ if (result instanceof Promise || (result == null ? void 0 : result.then) && (result == null ? void 0 : result.catch)) {
517
+ return result.then((res) => {
518
+ output = res;
519
+ success = true;
520
+ return res;
521
+ }).catch((err) => {
522
+ if (!handleSignals(err)) {
523
+ success = false;
524
+ error = err;
525
+ }
526
+ throw err;
527
+ }).finally(() => {
528
+ cancelSlowTool();
529
+ traces.push({
530
+ type: "tool_call",
531
+ tool_call_id: toolCallId,
532
+ started_at: toolStart,
533
+ ended_at: Date.now(),
534
+ tool_name: tool.name,
535
+ object,
536
+ input: getToolInput(input),
537
+ output,
538
+ error,
539
+ success
540
+ });
541
+ });
542
+ }
543
+ success = true;
544
+ output = result;
545
+ } catch (err) {
546
+ if (!handleSignals(err)) {
547
+ success = false;
548
+ error = err;
549
+ }
550
+ }
551
+ cancelSlowTool();
552
+ traces.push({
553
+ type: "tool_call",
554
+ tool_call_id: toolCallId,
555
+ started_at: toolStart,
556
+ ended_at: Date.now(),
557
+ tool_name: tool.name,
558
+ object,
559
+ input: getToolInput(input),
560
+ output,
561
+ error,
562
+ success
563
+ });
564
+ if (!success) {
565
+ throw error;
566
+ }
567
+ if (output instanceof _chunkJDABP4SDcjs.VMSignal) {
568
+ throw output;
569
+ }
570
+ return output;
571
+ };
572
+ }
573
+
574
+
575
+
576
+ exports._executeContext = _executeContext; exports.executeContext = executeContext;