llmz 0.0.2 → 0.0.5

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 (87) hide show
  1. package/dist/chat.d.ts +17 -0
  2. package/dist/chunk-3U57H7GT.js +608 -0
  3. package/dist/{chunk-RB2L33ZR.js → chunk-4EWY34YA.js} +24 -24
  4. package/dist/{chunk-R2N2UUKC.cjs → chunk-4I7UPBLN.cjs} +14 -8
  5. package/dist/{chunk-YPOOKE3A.cjs → chunk-4QTK5ALH.cjs} +59 -28
  6. package/dist/{chunk-BKGPO722.cjs → chunk-5NVNEEYW.cjs} +55 -55
  7. package/dist/{chunk-DFZ6GX5C.js → chunk-5TRUJES5.js} +1 -1
  8. package/dist/{chunk-E2B5DRIC.cjs → chunk-6WT5VZBG.cjs} +362 -26
  9. package/dist/{chunk-7S3UY52U.js → chunk-7WRN4E42.js} +36 -8
  10. package/dist/{chunk-E5W3P7EO.cjs → chunk-EJRCDWBA.cjs} +64 -7
  11. package/dist/{chunk-VP6WWAE2.cjs → chunk-FIVFS4HG.cjs} +2 -2
  12. package/dist/{chunk-3T465BEW.js → chunk-HP7RKM25.js} +63 -6
  13. package/dist/{chunk-YUDUY7XW.cjs → chunk-HYVKY3W6.cjs} +23 -24
  14. package/dist/{chunk-PQN6HW7A.cjs → chunk-IKSIOIIP.cjs} +3 -3
  15. package/dist/{chunk-ZUAFUOUR.cjs → chunk-JDABP4SD.cjs} +3 -3
  16. package/dist/{chunk-RJHDQL4C.js → chunk-JKVVQN2P.js} +1 -1
  17. package/dist/{chunk-MSTBEKOQ.js → chunk-JQBT7UWN.js} +3 -3
  18. package/dist/{chunk-BOLDQGES.cjs → chunk-KMZDFWYZ.cjs} +3 -3
  19. package/dist/chunk-MU4LFVY7.cjs +608 -0
  20. package/dist/{chunk-7FIPXMZR.js → chunk-ORQP26SZ.js} +1 -1
  21. package/dist/{chunk-ENFB45AI.cjs → chunk-P7J2WCBB.cjs} +7 -7
  22. package/dist/{chunk-DILHJIMP.js → chunk-QBXIE6EY.js} +49 -18
  23. package/dist/{chunk-UVSOAH2H.js → chunk-QT4QF3YA.js} +1 -1
  24. package/dist/{chunk-6QDFMQHA.js → chunk-S6FOL2HY.js} +8 -2
  25. package/dist/{chunk-ZSRC3TN4.js → chunk-UNMKB2DA.js} +9 -10
  26. package/dist/{chunk-3CGLDS5T.cjs → chunk-UQOBUJIQ.cjs} +38 -10
  27. package/dist/{chunk-QPSUMPLP.js → chunk-WLUVY5QU.js} +345 -9
  28. package/dist/citations.d.ts +63 -0
  29. package/dist/component-R2Y74VUI.js +16 -0
  30. package/dist/component-TSNW3SC7.cjs +16 -0
  31. package/dist/component.d.ts +26 -17
  32. package/dist/component.default.d.ts +314 -8
  33. package/dist/context.d.ts +9 -6
  34. package/dist/dual-modes-UHNDHNIF.cjs +12 -0
  35. package/dist/dual-modes-ZUQKPJFH.js +12 -0
  36. package/dist/exit-KJ4COC5N.cjs +8 -0
  37. package/dist/exit-OIYZLBVJ.js +8 -0
  38. package/dist/exit.d.ts +6 -0
  39. package/dist/getter.d.ts +1 -1
  40. package/dist/index.cjs +256 -160
  41. package/dist/index.d.ts +7 -4
  42. package/dist/index.js +242 -146
  43. package/dist/{jsx-CJ2RBODH.js → jsx-AEHVFB3L.js} +2 -3
  44. package/dist/jsx-AJAXBWFE.cjs +13 -0
  45. package/dist/llmz-VDA4M42R.cjs +604 -0
  46. package/dist/llmz-YE5N54IU.js +604 -0
  47. package/dist/llmz.d.ts +8 -10
  48. package/dist/snapshots.d.ts +9 -1
  49. package/dist/tool-LY77IWV2.js +11 -0
  50. package/dist/tool-SWJYOR2Z.cjs +11 -0
  51. package/dist/tool.d.ts +34 -9
  52. package/dist/truncator-NYN7BGKJ.cjs +10 -0
  53. package/dist/truncator-WAL2GCUY.js +10 -0
  54. package/dist/types.d.ts +9 -1
  55. package/dist/typings-AIV2OASX.js +10 -0
  56. package/dist/typings-XR6CYHW4.cjs +10 -0
  57. package/dist/{utils-TS23YJPE.js → utils-L5GLCS3C.js} +2 -3
  58. package/dist/utils-QC4I2L6R.cjs +37 -0
  59. package/dist/vm-GJ5R72AP.cjs +12 -0
  60. package/dist/vm-ZUQOSRRM.js +12 -0
  61. package/dist/vm.d.ts +1 -1
  62. package/package.json +8 -6
  63. package/dist/chunk-A7BDFLAE.cjs +0 -30
  64. package/dist/chunk-C2TSWGYC.cjs +0 -91
  65. package/dist/chunk-Q4DEJGXD.js +0 -344
  66. package/dist/chunk-QZGFCB4T.cjs +0 -344
  67. package/dist/chunk-UG2GCPHF.js +0 -91
  68. package/dist/chunk-YSQDPG26.js +0 -30
  69. package/dist/component-DWBRHLEN.cjs +0 -9
  70. package/dist/component-R3ZAVXUC.js +0 -9
  71. package/dist/dual-modes-2VDEOJ5D.js +0 -13
  72. package/dist/dual-modes-3MH5N6RY.cjs +0 -13
  73. package/dist/exit-GYMXZZ4I.js +0 -9
  74. package/dist/exit-PQHMJEOG.cjs +0 -9
  75. package/dist/jsx-PPLE5YTB.cjs +0 -14
  76. package/dist/llmz-EGTGPSTX.cjs +0 -1049
  77. package/dist/llmz-WY74UVE3.js +0 -1049
  78. package/dist/tool-AY47ML65.cjs +0 -12
  79. package/dist/tool-WVIPESKN.js +0 -12
  80. package/dist/truncator-MTONQESU.js +0 -11
  81. package/dist/truncator-ZKPOW2I3.cjs +0 -11
  82. package/dist/typings-HTYLRNIC.js +0 -11
  83. package/dist/typings-QRJGGNUM.cjs +0 -11
  84. package/dist/utils-UR4IMUHC.cjs +0 -38
  85. package/dist/vm-4JFSZAMR.cjs +0 -13
  86. package/dist/vm-SMMA664M.js +0 -13
  87. package/patches/source-map-js@1.2.1.patch +0 -16
@@ -0,0 +1,604 @@
1
+ import {
2
+ runAsyncFunction
3
+ } from "./chunk-4EWY34YA.js";
4
+ import {
5
+ Context,
6
+ Snapshot
7
+ } from "./chunk-3U57H7GT.js";
8
+ import "./chunk-WLUVY5QU.js";
9
+ import "./chunk-QBXIE6EY.js";
10
+ import "./chunk-UNMKB2DA.js";
11
+ import {
12
+ AssignmentError,
13
+ CodeExecutionError,
14
+ InvalidCodeError,
15
+ Signals,
16
+ SnapshotSignal,
17
+ ThinkSignal,
18
+ VMSignal
19
+ } from "./chunk-JKVVQN2P.js";
20
+ import {
21
+ cleanStackTrace
22
+ } from "./chunk-JQBT7UWN.js";
23
+ import "./chunk-S6FOL2HY.js";
24
+ import "./chunk-HP7RKM25.js";
25
+ import "./chunk-ORQP26SZ.js";
26
+ import {
27
+ truncateWrappedContent
28
+ } from "./chunk-QT4QF3YA.js";
29
+ import {
30
+ init,
31
+ stripInvalidIdentifiers
32
+ } from "./chunk-5TRUJES5.js";
33
+ import {
34
+ clamp_default,
35
+ isEqual_default,
36
+ isPlainObject_default,
37
+ omit_default
38
+ } from "./chunk-7WRN4E42.js";
39
+
40
+ // src/llmz.ts
41
+ import { Cognitive } from "@botpress/cognitive";
42
+ import { z } from "@bpinternal/zui";
43
+ import ms from "ms";
44
+ import { ulid } from "ulid";
45
+ var getErrorMessage = (err) => err instanceof Error ? err.message : JSON.stringify(err);
46
+ var SLOW_TOOL_WARNING = ms("15s");
47
+ var RESPONSE_LENGTH_BUFFER = {
48
+ MIN_TOKENS: 1e3,
49
+ MAX_TOKENS: 16e3,
50
+ PERCENTAGE: 0.1
51
+ };
52
+ var getModelOutputLimit = (inputLength) => clamp_default(
53
+ RESPONSE_LENGTH_BUFFER.PERCENTAGE * inputLength,
54
+ RESPONSE_LENGTH_BUFFER.MIN_TOKENS,
55
+ RESPONSE_LENGTH_BUFFER.MAX_TOKENS
56
+ );
57
+ var executeContext = async (props) => {
58
+ var _a, _b;
59
+ await init();
60
+ const result = await _executeContext(props);
61
+ try {
62
+ (_b = (_a = result.context.chat) == null ? void 0 : _a.onExecutionDone) == null ? void 0 : _b.call(_a, result);
63
+ } catch {
64
+ }
65
+ return result;
66
+ };
67
+ var _executeContext = async (props) => {
68
+ var _a, _b, _c, _d;
69
+ const { signal, onIterationEnd, onTrace, onExit, onBeforeExecution } = props;
70
+ const cognitive = props.client instanceof Cognitive ? props.client : new Cognitive({ client: props.client });
71
+ const cleanups = [];
72
+ const ctx = new Context({
73
+ chat: props.chat,
74
+ instructions: props.instructions,
75
+ objects: props.objects,
76
+ tools: props.tools,
77
+ loop: (_a = props.options) == null ? void 0 : _a.loop,
78
+ temperature: (_b = props.options) == null ? void 0 : _b.temperature,
79
+ model: (_c = props.options) == null ? void 0 : _c.model,
80
+ timeout: (_d = props.options) == null ? void 0 : _d.timeout,
81
+ exits: props.exits,
82
+ snapshot: props.snapshot
83
+ });
84
+ try {
85
+ while (true) {
86
+ if (ctx.iterations.length >= ctx.loop) {
87
+ return {
88
+ status: "error",
89
+ context: ctx,
90
+ error: `Loop limit exceeded. Maximum allowed loops: ${ctx.loop}`,
91
+ iterations: ctx.iterations
92
+ };
93
+ }
94
+ const iteration = await ctx.nextIteration();
95
+ if (signal == null ? void 0 : signal.aborted) {
96
+ iteration.end({
97
+ type: "aborted",
98
+ aborted: {
99
+ reason: signal.reason ?? "The operation was aborted"
100
+ }
101
+ });
102
+ return {
103
+ status: "error",
104
+ error: signal.reason ?? "The operation was aborted",
105
+ context: ctx,
106
+ iterations: ctx.iterations
107
+ };
108
+ }
109
+ cleanups.push(
110
+ iteration.traces.onPush((traces) => {
111
+ for (const trace of traces) {
112
+ onTrace == null ? void 0 : onTrace({ trace, iteration: ctx.iterations.length });
113
+ }
114
+ })
115
+ );
116
+ try {
117
+ await executeIteration({
118
+ iteration,
119
+ ctx,
120
+ cognitive,
121
+ abortSignal: signal,
122
+ onExit,
123
+ onBeforeExecution
124
+ });
125
+ } catch (err) {
126
+ iteration.end({
127
+ type: "execution_error",
128
+ execution_error: {
129
+ message: "An unexpected error occurred: " + getErrorMessage(err),
130
+ stack: cleanStackTrace(err.stack ?? "No stack trace available")
131
+ }
132
+ });
133
+ }
134
+ try {
135
+ await (onIterationEnd == null ? void 0 : onIterationEnd(iteration));
136
+ } catch (err) {
137
+ console.error(err);
138
+ }
139
+ if (iteration.status.type === "exit_success") {
140
+ const exitName = iteration.status.exit_success.exit_name;
141
+ return {
142
+ status: "success",
143
+ context: ctx,
144
+ iterations: ctx.iterations,
145
+ result: {
146
+ exit: iteration.exits.find((x) => x.name === exitName),
147
+ result: iteration.status.exit_success.return_value
148
+ }
149
+ };
150
+ }
151
+ if (iteration.status.type === "callback_requested") {
152
+ return {
153
+ status: "interrupted",
154
+ context: ctx,
155
+ iterations: ctx.iterations,
156
+ signal: iteration.status.callback_requested.signal,
157
+ snapshot: Snapshot.fromSignal(iteration.status.callback_requested.signal)
158
+ };
159
+ }
160
+ if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") {
161
+ continue;
162
+ }
163
+ return {
164
+ context: ctx,
165
+ error: iteration.error ?? `Unknown error. Status: ${iteration.status.type}`,
166
+ status: "error",
167
+ iterations: ctx.iterations
168
+ };
169
+ }
170
+ } catch (error) {
171
+ return {
172
+ status: "error",
173
+ iterations: ctx.iterations,
174
+ context: ctx,
175
+ error: error instanceof Error ? error.message : (error == null ? void 0 : error.toString()) ?? "Unknown error"
176
+ };
177
+ } finally {
178
+ for (const cleanup of cleanups) {
179
+ try {
180
+ cleanup();
181
+ } catch {
182
+ }
183
+ }
184
+ }
185
+ };
186
+ var executeIteration = async ({
187
+ iteration,
188
+ ctx,
189
+ cognitive,
190
+ abortSignal,
191
+ onExit,
192
+ onBeforeExecution
193
+ }) => {
194
+ var _a, _b, _c, _d, _e;
195
+ let startedAt = Date.now();
196
+ const traces = iteration.traces;
197
+ const modelLimit = 128e3;
198
+ const responseLengthBuffer = getModelOutputLimit(modelLimit);
199
+ const messages = truncateWrappedContent({
200
+ messages: iteration.messages,
201
+ tokenLimit: modelLimit - responseLengthBuffer,
202
+ throwOnFailure: false
203
+ }).filter(
204
+ (x) => (
205
+ // Filter out empty messages, as they are not valid inputs for the LLM
206
+ // This can happen when a message is truncated and the content is empty
207
+ x.content.trim().length > 0
208
+ )
209
+ );
210
+ traces.push({
211
+ type: "llm_call_started",
212
+ started_at: startedAt,
213
+ ended_at: startedAt,
214
+ model: ctx.model ?? ""
215
+ });
216
+ const output = await cognitive.generateContent({
217
+ signal: abortSignal,
218
+ systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
219
+ model: ctx.model,
220
+ temperature: ctx.temperature,
221
+ responseFormat: "text",
222
+ messages: messages.filter((x) => x.role === "user" || x.role === "assistant").map(
223
+ (x) => ({
224
+ role: x.role === "user" ? "user" : "assistant",
225
+ type: "text",
226
+ content: x.content
227
+ })
228
+ ),
229
+ stopSequences: ctx.version.getStopTokens()
230
+ });
231
+ 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;
232
+ if (!out) {
233
+ throw new Error("No output from LLM");
234
+ }
235
+ const assistantResponse = ctx.version.parseAssistantResponse(out);
236
+ iteration.code = assistantResponse.code.trim();
237
+ if (typeof onBeforeExecution === "function") {
238
+ try {
239
+ await onBeforeExecution(iteration);
240
+ } catch (err) {
241
+ if (err instanceof ThinkSignal) {
242
+ return iteration.end({
243
+ type: "thinking_requested",
244
+ thinking_requested: {
245
+ variables: err.context,
246
+ reason: err.reason
247
+ }
248
+ });
249
+ }
250
+ return iteration.end({
251
+ type: "execution_error",
252
+ execution_error: {
253
+ message: `Error in onBeforeExecution hook: ${getErrorMessage(err)}`,
254
+ stack: cleanStackTrace(err.stack ?? "No stack trace available")
255
+ }
256
+ });
257
+ }
258
+ }
259
+ iteration.llm = {
260
+ cached: output.meta.cached || false,
261
+ ended_at: Date.now(),
262
+ started_at: startedAt,
263
+ status: "success",
264
+ tokens: output.meta.tokens.input + output.meta.tokens.output,
265
+ spend: output.meta.cost.input + output.meta.cost.output,
266
+ output: assistantResponse.raw,
267
+ model: `${output.meta.model.integration}:${output.meta.model.model}`
268
+ };
269
+ traces.push({
270
+ type: "llm_call_success",
271
+ started_at: startedAt,
272
+ ended_at: iteration.llm.ended_at,
273
+ model: ctx.model ?? "",
274
+ code: iteration.code
275
+ });
276
+ const vmContext = { ...stripInvalidIdentifiers(iteration.variables) };
277
+ for (const obj of iteration.objects) {
278
+ const internalValues = {};
279
+ const instance = {};
280
+ for (const { name, value, writable, type } of obj.properties ?? []) {
281
+ internalValues[name] = value;
282
+ const initialValue = value;
283
+ const schema = type ?? z.any();
284
+ Object.defineProperty(instance, name, {
285
+ enumerable: true,
286
+ configurable: true,
287
+ get() {
288
+ return internalValues[name];
289
+ },
290
+ set(value2) {
291
+ if (isEqual_default(value2, internalValues[name])) {
292
+ return;
293
+ }
294
+ if (!writable) {
295
+ throw new AssignmentError(`Property ${obj.name}.${name} is read-only and cannot be modified`);
296
+ }
297
+ if (value2 === internalValues[name]) {
298
+ return;
299
+ }
300
+ const parsed = schema.safeParse(value2);
301
+ if (!parsed.success) {
302
+ throw new AssignmentError(
303
+ `Invalid value for Object property ${obj.name}.${name}: ${getErrorMessage(parsed.error)}`
304
+ );
305
+ }
306
+ internalValues[name] = parsed.data;
307
+ traces.push({
308
+ type: "property",
309
+ started_at: Date.now(),
310
+ object: obj.name,
311
+ property: name,
312
+ value: parsed.data
313
+ });
314
+ iteration.trackMutation({ object: obj.name, property: name, before: initialValue, after: parsed.data });
315
+ }
316
+ });
317
+ }
318
+ for (const tool of obj.tools ?? []) {
319
+ instance[tool.name] = wrapTool({ tool, traces, object: obj.name });
320
+ }
321
+ Object.preventExtensions(instance);
322
+ Object.seal(instance);
323
+ vmContext[obj.name] = instance;
324
+ }
325
+ for (const tool of iteration.tools) {
326
+ const wrapped = wrapTool({ tool, traces });
327
+ for (const key of [tool.name, ...tool.aliases ?? []]) {
328
+ vmContext[key] = wrapped;
329
+ }
330
+ }
331
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
332
+ traces.push({
333
+ type: "abort_signal",
334
+ started_at: Date.now(),
335
+ reason: "The operation was aborted by user."
336
+ });
337
+ return iteration.end({
338
+ type: "aborted",
339
+ aborted: {
340
+ reason: (abortSignal == null ? void 0 : abortSignal.reason) ?? "The operation was aborted"
341
+ }
342
+ });
343
+ }
344
+ startedAt = Date.now();
345
+ const result = await runAsyncFunction(vmContext, iteration.code, traces, abortSignal, ctx.timeout).catch(
346
+ (err) => {
347
+ return {
348
+ success: false,
349
+ error: err,
350
+ lines_executed: [],
351
+ traces: [],
352
+ variables: {}
353
+ };
354
+ }
355
+ );
356
+ if (result.error && result.error instanceof InvalidCodeError) {
357
+ return iteration.end({
358
+ type: "invalid_code_error",
359
+ invalid_code_error: {
360
+ message: result.error.message
361
+ }
362
+ });
363
+ }
364
+ traces.push({
365
+ type: "code_execution",
366
+ lines_executed: result.lines_executed ?? 0,
367
+ started_at: startedAt,
368
+ ended_at: Date.now()
369
+ });
370
+ if (result.error && result.error instanceof CodeExecutionError) {
371
+ return iteration.end({
372
+ type: "execution_error",
373
+ execution_error: {
374
+ message: result.error.message,
375
+ stack: cleanStackTrace(result.error.stacktrace ?? result.error.stack ?? "No stack trace available")
376
+ }
377
+ });
378
+ }
379
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
380
+ return iteration.end({
381
+ type: "aborted",
382
+ aborted: {
383
+ reason: (abortSignal == null ? void 0 : abortSignal.reason) ?? "The operation was aborted"
384
+ }
385
+ });
386
+ }
387
+ if (!result.success) {
388
+ return iteration.end({
389
+ type: "execution_error",
390
+ execution_error: {
391
+ message: ((_e = result == null ? void 0 : result.error) == null ? void 0 : _e.message) ?? "Unknown error occurred",
392
+ stack: cleanStackTrace(result.error.stack ?? "No stack trace available")
393
+ }
394
+ });
395
+ }
396
+ if (result.signal instanceof ThinkSignal) {
397
+ return iteration.end({
398
+ type: "thinking_requested",
399
+ thinking_requested: {
400
+ variables: result.signal.context,
401
+ reason: result.signal.reason
402
+ }
403
+ });
404
+ }
405
+ if (result.signal instanceof SnapshotSignal) {
406
+ return iteration.end({
407
+ type: "callback_requested",
408
+ callback_requested: {
409
+ signal: result.signal
410
+ }
411
+ });
412
+ }
413
+ const validActions = [...iteration.exits.map((x) => x.name.toLowerCase()), "think"];
414
+ let returnValue = result.success && result.return_value ? result.return_value : null;
415
+ const returnAction = returnValue == null ? void 0 : returnValue.action;
416
+ const returnExit = 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())));
417
+ if (returnAction === "think") {
418
+ const variables = omit_default(returnValue ?? {}, "action");
419
+ if (isPlainObject_default(variables) && Object.keys(variables).length > 0) {
420
+ return iteration.end({
421
+ type: "thinking_requested",
422
+ thinking_requested: {
423
+ variables,
424
+ reason: "Thinking requested"
425
+ }
426
+ });
427
+ }
428
+ return iteration.end({
429
+ type: "thinking_requested",
430
+ thinking_requested: {
431
+ reason: "Thinking requested",
432
+ variables: iteration.variables
433
+ }
434
+ });
435
+ }
436
+ if (!returnAction) {
437
+ return iteration.end({
438
+ type: "exit_error",
439
+ exit_error: {
440
+ exit: "n/a",
441
+ message: `Code did not return an action. Valid actions are: ${validActions.join(", ")}`,
442
+ return_value: returnValue
443
+ }
444
+ });
445
+ }
446
+ if (!returnExit) {
447
+ return iteration.end({
448
+ type: "exit_error",
449
+ exit_error: {
450
+ exit: returnAction,
451
+ message: `Exit "${returnAction}" not found. Valid actions are: ${validActions.join(", ")}`,
452
+ return_value: returnValue
453
+ }
454
+ });
455
+ }
456
+ if (returnExit.zSchema) {
457
+ const parsed = returnExit.zSchema.safeParse(returnValue == null ? void 0 : returnValue.value);
458
+ if (!parsed.success) {
459
+ return iteration.end({
460
+ type: "exit_error",
461
+ exit_error: {
462
+ exit: returnExit.name,
463
+ message: `Invalid return value for exit ${returnExit.name}: ${getErrorMessage(parsed.error)}`,
464
+ return_value: returnValue
465
+ }
466
+ });
467
+ }
468
+ returnValue = { action: returnExit.name, value: parsed.data };
469
+ }
470
+ try {
471
+ await (onExit == null ? void 0 : onExit({
472
+ exit: returnExit,
473
+ result: returnValue == null ? void 0 : returnValue.value
474
+ }));
475
+ } catch (err) {
476
+ return iteration.end({
477
+ type: "exit_error",
478
+ exit_error: {
479
+ exit: returnExit.name,
480
+ message: `Error executing exit ${returnExit.name}: ${getErrorMessage(err)}`,
481
+ return_value: returnValue
482
+ }
483
+ });
484
+ }
485
+ return iteration.end({
486
+ type: "exit_success",
487
+ exit_success: {
488
+ exit_name: returnExit.name,
489
+ return_value: returnValue == null ? void 0 : returnValue.value
490
+ }
491
+ });
492
+ };
493
+ function wrapTool({ tool, traces, object }) {
494
+ const getToolInput = (input) => tool.zInput.safeParse(input).data ?? input;
495
+ return function(input) {
496
+ const toolCallId = `tcall_${ulid()}`;
497
+ const alertSlowTool = setTimeout(
498
+ () => traces.push({
499
+ type: "tool_slow",
500
+ tool_name: tool.name,
501
+ tool_call_id: toolCallId,
502
+ started_at: Date.now(),
503
+ input: getToolInput(input),
504
+ object,
505
+ duration: SLOW_TOOL_WARNING
506
+ }),
507
+ SLOW_TOOL_WARNING
508
+ );
509
+ const cancelSlowTool = () => clearTimeout(alertSlowTool);
510
+ const toolStart = Date.now();
511
+ let output;
512
+ let error;
513
+ let success = true;
514
+ const handleSignals = (error2) => {
515
+ if (output === error2) {
516
+ return true;
517
+ }
518
+ if (error2 instanceof SnapshotSignal) {
519
+ error2.toolCall = {
520
+ name: tool.name,
521
+ inputSchema: tool.input,
522
+ outputSchema: tool.output,
523
+ input
524
+ };
525
+ error2.message = Signals.serializeError(error2);
526
+ }
527
+ if (error2 instanceof ThinkSignal) {
528
+ traces.push({
529
+ type: "think_signal",
530
+ started_at: Date.now(),
531
+ line: 0,
532
+ ended_at: Date.now()
533
+ });
534
+ success = true;
535
+ output = error2;
536
+ return true;
537
+ }
538
+ return false;
539
+ };
540
+ try {
541
+ const result = tool.execute(input, {
542
+ callId: toolCallId
543
+ });
544
+ if (result instanceof Promise || (result == null ? void 0 : result.then) && (result == null ? void 0 : result.catch)) {
545
+ return result.then((res) => {
546
+ output = res;
547
+ success = true;
548
+ return res;
549
+ }).catch((err) => {
550
+ if (!handleSignals(err)) {
551
+ success = false;
552
+ error = err;
553
+ }
554
+ throw err;
555
+ }).finally(() => {
556
+ cancelSlowTool();
557
+ traces.push({
558
+ type: "tool_call",
559
+ tool_call_id: toolCallId,
560
+ started_at: toolStart,
561
+ ended_at: Date.now(),
562
+ tool_name: tool.name,
563
+ object,
564
+ input: getToolInput(input),
565
+ output,
566
+ error,
567
+ success
568
+ });
569
+ });
570
+ }
571
+ success = true;
572
+ output = result;
573
+ } catch (err) {
574
+ if (!handleSignals(err)) {
575
+ success = false;
576
+ error = err;
577
+ }
578
+ }
579
+ cancelSlowTool();
580
+ traces.push({
581
+ type: "tool_call",
582
+ tool_call_id: toolCallId,
583
+ started_at: toolStart,
584
+ ended_at: Date.now(),
585
+ tool_name: tool.name,
586
+ object,
587
+ input: getToolInput(input),
588
+ output,
589
+ error,
590
+ success
591
+ });
592
+ if (!success) {
593
+ throw error;
594
+ }
595
+ if (output instanceof VMSignal) {
596
+ throw output;
597
+ }
598
+ return output;
599
+ };
600
+ }
601
+ export {
602
+ _executeContext,
603
+ executeContext
604
+ };
package/dist/llmz.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import { Cognitive, type BotpressClientLike } from '@botpress/cognitive';
2
- import { Component } from './component.js';
2
+ import { Chat } from './chat.js';
3
3
  import { Context, Iteration } from './context.js';
4
- import { Exit } from './exit.js';
4
+ import { Exit, ExitResult } from './exit.js';
5
5
  import { ValueOrGetter } from './getter.js';
6
6
  import { type ObjectInstance } from './objects.js';
7
7
  import { Snapshot } from './snapshots.js';
8
8
  import { type Tool } from './tool.js';
9
- import { TranscriptMessage } from './transcript.js';
10
9
  import { ExecutionResult, Trace } from './types.js';
11
10
  export type ExecutionHooks = {
12
11
  /**
@@ -19,23 +18,22 @@ export type ExecutionHooks = {
19
18
  trace: Trace;
20
19
  iteration: number;
21
20
  }) => void;
22
- onExit?: (exit: Exit, value: unknown) => Promise<void> | void;
21
+ onExit?: <T = unknown>(result: ExitResult<T>) => Promise<void> | void;
22
+ onBeforeExecution?: (iteration: Iteration) => Promise<void> | void;
23
23
  };
24
- type Options = Partial<Pick<Context, 'loop' | 'temperature' | 'model'>>;
24
+ type Options = Partial<Pick<Context, 'loop' | 'temperature' | 'model' | 'timeout'>>;
25
25
  export type ExecutionProps = {
26
+ chat?: Chat;
26
27
  instructions?: ValueOrGetter<string, Context>;
27
- components?: ValueOrGetter<Component[], Context>;
28
28
  objects?: ValueOrGetter<ObjectInstance[], Context>;
29
29
  tools?: ValueOrGetter<Tool[], Context>;
30
30
  exits?: ValueOrGetter<Exit[], Context>;
31
- transcript?: ValueOrGetter<TranscriptMessage[], Context>;
32
31
  options?: Options;
33
32
  /** An instance of a Botpress Client, or an instance of Cognitive Client (@botpress/cognitive) */
34
33
  client: Cognitive | BotpressClientLike;
35
34
  signal?: AbortSignal;
36
35
  snapshot?: Snapshot;
37
36
  } & ExecutionHooks;
38
- export declare const llmz: {
39
- executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
40
- };
37
+ export declare const executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
38
+ export declare const _executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
41
39
  export {};
@@ -51,8 +51,16 @@ export declare class Snapshot {
51
51
  stack: string;
52
52
  variables: Variable[];
53
53
  toolCall: ToolCall | undefined;
54
+ status: SnapshotStatus;
54
55
  };
55
- static fromJSON(json: Snapshot): Snapshot;
56
+ static fromJSON(json: {
57
+ id: string;
58
+ reason?: string;
59
+ stack: string;
60
+ variables: Variable[];
61
+ toolCall?: ToolCall;
62
+ status: SnapshotStatus;
63
+ }): Snapshot;
56
64
  clone(): Snapshot;
57
65
  reset(): void;
58
66
  resolve(value: any): void;
@@ -0,0 +1,11 @@
1
+ import {
2
+ Tool
3
+ } from "./chunk-QBXIE6EY.js";
4
+ import "./chunk-UNMKB2DA.js";
5
+ import "./chunk-JKVVQN2P.js";
6
+ import "./chunk-JQBT7UWN.js";
7
+ import "./chunk-5TRUJES5.js";
8
+ import "./chunk-7WRN4E42.js";
9
+ export {
10
+ Tool
11
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunk4QTK5ALHcjs = require('./chunk-4QTK5ALH.cjs');
4
+ require('./chunk-HYVKY3W6.cjs');
5
+ require('./chunk-JDABP4SD.cjs');
6
+ require('./chunk-IKSIOIIP.cjs');
7
+ require('./chunk-P7J2WCBB.cjs');
8
+ require('./chunk-UQOBUJIQ.cjs');
9
+
10
+
11
+ exports.Tool = _chunk4QTK5ALHcjs.Tool;