llmz 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/DOCS.md +8 -4
  2. package/ERRORS.md +5 -2
  3. package/dist/{component-BpMVZYOa.cjs → component-CMFoCHyu.cjs} +3 -3
  4. package/dist/{component-C27qu6Zv.js → component-DncqP4fB.js} +3 -3
  5. package/dist/context.d.ts +1 -1
  6. package/dist/{custom-client-BDkgBR2w.js → custom-client-C-WXvLD9.js} +37 -13
  7. package/dist/{custom-client-MytucGI-.cjs → custom-client-Cgt9_0r1.cjs} +37 -13
  8. package/dist/errors/catalog.d.ts +7 -0
  9. package/dist/{errors-IhnTKUp7.cjs → errors-C6ppQUZX.cjs} +22 -0
  10. package/dist/{errors-H4JJFH3S.js → errors-Crk5P8jo.js} +17 -1
  11. package/dist/errors.d.ts +6 -0
  12. package/dist/{execute-BYI_U5sR.js → execute-CiYvPs5Q.js} +196 -78
  13. package/dist/{execute-DLas4V2n.cjs → execute-DTTfacsi.cjs} +196 -78
  14. package/dist/{exit-BUgJ5qi5.cjs → exit-BOtKWPuT.cjs} +2 -2
  15. package/dist/{exit-CPNk3vbz.js → exit-DMPwCSba.js} +2 -2
  16. package/dist/index.cjs +18 -17
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +18 -18
  19. package/dist/index.workerd.js +252 -79
  20. package/dist/inspection.d.ts +2 -0
  21. package/dist/{native-Bm6L9zOb.cjs → native-0bq5ATZM.cjs} +3 -3
  22. package/dist/{native-DvTH9vFe.js → native-n_718Z-T.js} +3 -3
  23. package/dist/{quickjs-variant-DJwYDSsb.cjs → quickjs-variant-21IO97PF.cjs} +15 -8
  24. package/dist/{quickjs-variant-DlPi9-Sx.js → quickjs-variant-CtuGagsb.js} +10 -9
  25. package/dist/runtime/chat-completion.test.d.ts +1 -0
  26. package/dist/runtime/chat-last-speaker.test.d.ts +1 -0
  27. package/dist/runtime/empty-completion.test.d.ts +1 -0
  28. package/dist/runtime/execution-report.d.ts +3 -0
  29. package/dist/runtime/forced-inspection.d.ts +13 -0
  30. package/dist/runtime/forced-inspection.test.d.ts +1 -0
  31. package/dist/runtime/javascript-api.d.ts +3 -0
  32. package/dist/runtime/think-signal.test.d.ts +1 -0
  33. package/dist/runtime/tool-wrapper.d.ts +4 -2
  34. package/dist/runtime/types.d.ts +8 -0
  35. package/dist/{schema-DBkjo0b7.cjs → schema-CXlnbb3n.cjs} +1 -1
  36. package/dist/{schema-Aer_W7Al.js → schema-GE4ISPCR.js} +1 -1
  37. package/dist/session/messages.d.ts +2 -0
  38. package/dist/session/serialization.d.ts +2 -0
  39. package/dist/session/session.d.ts +4 -0
  40. package/dist/session/speaker.test.d.ts +1 -0
  41. package/dist/{tool--gK91eez.js → tool-DstssiAs.js} +4 -4
  42. package/dist/{tool-Da_F-N-5.cjs → tool-_wK9hQOb.cjs} +4 -4
  43. package/dist/{truncate-BSoH2-nY.js → truncate-BEKbdo3t.js} +1 -1
  44. package/dist/{truncate-nV3Mxr6-.cjs → truncate-uomAMGPs.cjs} +1 -1
  45. package/dist/types.d.ts +6 -0
  46. package/dist/{typings-C1ihexWE.cjs → typings-BA_XxAcY.cjs} +1 -1
  47. package/dist/{typings-D9_aC8aq.js → typings-BEVDvtuk.js} +1 -1
  48. package/dist/vm/types.d.ts +2 -0
  49. package/dist/{vm-8jxt8PTK.js → vm-C7SfutHn.js} +28 -3
  50. package/dist/{vm-XuVPuW3Y.cjs → vm-gmekHc0i.cjs} +28 -2
  51. package/package.json +1 -1
@@ -1,13 +1,13 @@
1
1
  const require_utils = require("./utils-CTlsXvdj.cjs");
2
- const require_errors = require("./errors-IhnTKUp7.cjs");
3
- const require_component = require("./component-BpMVZYOa.cjs");
4
- const require_schema = require("./schema-DBkjo0b7.cjs");
5
- const require_truncate = require("./truncate-nV3Mxr6-.cjs");
6
- const require_quickjs_variant = require("./quickjs-variant-DJwYDSsb.cjs");
7
- const require_typings = require("./typings-C1ihexWE.cjs");
8
- const require_custom_client = require("./custom-client-MytucGI-.cjs");
9
- const require_native = require("./native-Bm6L9zOb.cjs");
10
- const require_vm = require("./vm-XuVPuW3Y.cjs");
2
+ const require_errors = require("./errors-C6ppQUZX.cjs");
3
+ const require_component = require("./component-CMFoCHyu.cjs");
4
+ const require_schema = require("./schema-CXlnbb3n.cjs");
5
+ const require_truncate = require("./truncate-uomAMGPs.cjs");
6
+ const require_quickjs_variant = require("./quickjs-variant-21IO97PF.cjs");
7
+ const require_typings = require("./typings-BA_XxAcY.cjs");
8
+ const require_custom_client = require("./custom-client-Cgt9_0r1.cjs");
9
+ const require_native = require("./native-0bq5ATZM.cjs");
10
+ const require_vm = require("./vm-gmekHc0i.cjs");
11
11
  let _bpinternal_zui = require("@bpinternal/zui");
12
12
  let ulid = require("ulid");
13
13
  let _botpress_cognitive = require("@botpress/cognitive");
@@ -209,10 +209,7 @@ function errorPreview(value, inspector, identity) {
209
209
  //#region src/runtime/execution-diagnostics.ts
210
210
  /** XML-style boundaries keep diagnostic text separate from recovery instructions. */
211
211
  function reportSection(name, content, maxTokens = 2e3, options = {}) {
212
- const escape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
213
- const heading = options.heading ? `${escape(options.heading)}\n` : "";
214
- const body = require_quickjs_variant.limitInspectionOutput(content, maxTokens, false, options.preserve ?? "top");
215
- return `<${name}>\n${heading}${/[<&]|\]\]>/.test(body) ? `<![CDATA[\n${body.replaceAll("]]>", "]]]]><![CDATA[>")}\n]]>` : body}\n</${name}>`;
212
+ return `<${name}>\n${options.heading ? `${options.heading}\n` : ""}${require_quickjs_variant.limitInspectionOutput(content, maxTokens, false, options.preserve ?? "top")}\n</${name}>`;
216
213
  }
217
214
  /** Show the specific failure and guest source, never the host's implementation stack. */
218
215
  function renderExecutionDiagnostics(error, message, inspector, identity) {
@@ -253,11 +250,58 @@ function renderSourceTrace(stack, inspector, identity) {
253
250
  }), 1e3);
254
251
  }
255
252
  //#endregion
253
+ //#region src/runtime/forced-inspection.ts
254
+ /** Keep attribution and content together, using the same display budgets as inspect(). */
255
+ function renderForcedInspection(inspections, inspector, identity, maxTokens, policies) {
256
+ return [
257
+ "<forced_inspection>",
258
+ "Forced inspection: the tools listed below completed successfully and requested review of their results.",
259
+ "This is the equivalent of an inspect() call. Do not repeat these tool calls; use the results below and retained variables.",
260
+ "No exit was applied. Review the evidence before continuing or completing the task.",
261
+ "",
262
+ "Tools requesting inspection (lines refer to the executed JavaScript):",
263
+ ...inspections.map((entry) => {
264
+ const entryIdentity = {
265
+ ...identity,
266
+ tool: entry.tool
267
+ };
268
+ const name = inspector(entry.tool, {
269
+ purpose: "name",
270
+ maxTokens: 80,
271
+ identity: entryIdentity
272
+ });
273
+ const reason = inspector(entry.reason, {
274
+ purpose: "error",
275
+ maxTokens: 1e3,
276
+ identity: entryIdentity
277
+ });
278
+ const budget = require_quickjs_variant.resolveInspectionBudget(entry.value, {
279
+ tokens: maxTokens,
280
+ policies
281
+ });
282
+ const result = inspector(entry.value, {
283
+ purpose: "result",
284
+ maxTokens,
285
+ policies,
286
+ identity: entryIdentity
287
+ });
288
+ return [
289
+ `<tool name="${name}" line="${entry.line ?? "unknown"}">`,
290
+ `<reason>${reason}</reason>`,
291
+ reportSection("result", result, budget.tokens, { preserve: budget.preserve }),
292
+ "</tool>"
293
+ ].join("\n");
294
+ }),
295
+ "</forced_inspection>"
296
+ ].join("\n");
297
+ }
298
+ //#endregion
256
299
  //#region src/runtime/execution-report.ts
257
300
  const MAX_REPORTED_CHANGES = 40;
258
301
  const MAX_OVERRIDE_SOURCE_LENGTH = 3e3;
259
302
  /** Format one settled outcome; execution is responsible for deciding what happened. */
260
303
  function renderExecutionReport({ outcome, activity, memory, source, requiresExit = false, iteration, identity = { iteration }, inspector = require_quickjs_variant.createInspector(), maxTokens = require_truncate.DEFAULT_TOOL_RESULT_MAX_TOKENS, policies }) {
304
+ var _outcome$forcedInspec, _outcome$forcedInspec2;
261
305
  const detail = (value) => inspector(value, {
262
306
  purpose: "error",
263
307
  maxTokens: 1e3,
@@ -284,6 +328,13 @@ function renderExecutionReport({ outcome, activity, memory, source, requiresExit
284
328
  });
285
329
  };
286
330
  const sections = [renderStatus(outcome, memory)];
331
+ if (outcome.type === "inspect" && ((_outcome$forcedInspec = outcome.forcedInspections) === null || _outcome$forcedInspec === void 0 ? void 0 : _outcome$forcedInspec.length)) {
332
+ sections.push(renderForcedInspection(outcome.forcedInspections, inspector, identity, maxTokens, policies));
333
+ if (outcome.downstreamError) {
334
+ sections.push(...renderExecutionDiagnostics(outcome.downstreamError, require_utils.getErrorMessage(outcome.downstreamError), inspector, identity));
335
+ sections.push(reportSection("recovery", "A later operation failed. The tool results above were successfully retrieved; inspect them and repair only the failed work. Do not repeat successful calls."));
336
+ }
337
+ }
287
338
  if (outcome.type === "error") {
288
339
  sections.push(...renderExecutionDiagnostics(outcome.error, outcome.message, inspector, identity));
289
340
  sections.push(reportSection("recovery", [
@@ -316,7 +367,7 @@ function renderExecutionReport({ outcome, activity, memory, source, requiresExit
316
367
  if (memory.unavailable.length > failures.length) entries.push(`- ${memory.unavailable.length - failures.length} additional values could not be retained.`);
317
368
  sections.push(reportSection("memory_errors", `Memory errors\n${entries.join("\n")}`));
318
369
  }
319
- if (outcome.type === "inspect") {
370
+ if (outcome.type === "inspect" && ((_outcome$forcedInspec2 = outcome.forcedInspections) === null || _outcome$forcedInspec2 === void 0 ? void 0 : _outcome$forcedInspec2.length) && (!outcome.explicit || outcome.forcedInspections.some((entry) => isEqual(entry.value, outcome.value)))) {} else if (outcome.type === "inspect") {
320
371
  const heading = outcome.explicit ? "inspect() result" : "Result";
321
372
  sections.push(outcome.available ? resultSection("result", heading, outcome.value) : reportSection("result", "Unavailable; see memory errors above.", maxTokens, { heading }));
322
373
  } else if (outcome.type === "exit") sections.push(resultSection("completion", `Completion\nExit "${outcome.name}" completed.`, outcome.value === void 0 ? "" : outcome.value));
@@ -852,6 +903,7 @@ const isRecord = (value) => value !== null && typeof value === "object" && !Arra
852
903
  function createJavaScriptApi({ iteration, components, exits, deliver, signal, onError }) {
853
904
  const decisions = /* @__PURE__ */ new Map();
854
905
  const pending = /* @__PURE__ */ new Set();
906
+ const inspections = [];
855
907
  let open = true;
856
908
  let outstanding = [];
857
909
  let delivery;
@@ -988,6 +1040,10 @@ function createJavaScriptApi({ iteration, components, exits, deliver, signal, on
988
1040
  isReceipt: (value) => resolve(value) !== void 0,
989
1041
  getTerminalOutcome: () => terminalOutcome,
990
1042
  getInterruption: () => interruption,
1043
+ requestInspection: (inspection) => {
1044
+ inspections.push(inspection);
1045
+ },
1046
+ getForcedInspections: () => inspections,
991
1047
  throwIfTerminated,
992
1048
  track,
993
1049
  assertOpen,
@@ -1015,8 +1071,8 @@ const finalizeIteration = async ({ iteration, status, controller, onIterationEnd
1015
1071
  //#endregion
1016
1072
  //#region src/runtime/tool-wrapper.ts
1017
1073
  const SLOW_TOOL_WARNING = (0, ms.default)("15s");
1018
- function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation, onResult, controller }) {
1019
- return async function(input) {
1074
+ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation, onResult, controller, onThink }) {
1075
+ return async function(input, line) {
1020
1076
  controller.signal.throwIfAborted();
1021
1077
  const toolCallId = `tcall_${(0, ulid.ulid)()}`;
1022
1078
  const originalInput = input;
@@ -1035,7 +1091,7 @@ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation
1035
1091
  let output;
1036
1092
  let error;
1037
1093
  let success = true;
1038
- let signalToThrow;
1094
+ const inspections = [];
1039
1095
  const pushToolCallTrace = () => {
1040
1096
  iteration.recordTrace({
1041
1097
  type: "tool_call",
@@ -1051,32 +1107,21 @@ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation
1051
1107
  success
1052
1108
  });
1053
1109
  };
1054
- const handleSignals = async (err) => {
1055
- if (output === err) return true;
1056
- if (require_errors.ThinkSignal.is(err)) {
1057
- signalToThrow = err;
1058
- iteration.recordTrace({
1059
- type: "think_signal",
1060
- started_at: Date.now(),
1061
- line: 0,
1062
- ended_at: Date.now()
1063
- });
1064
- success = true;
1065
- output = err;
1066
- const afterRes = await callHook(() => afterHook === null || afterHook === void 0 ? void 0 : afterHook({
1067
- iteration,
1068
- tool,
1069
- input: originalInput,
1070
- output,
1071
- controller,
1072
- object,
1073
- toolCallId,
1074
- nativeCallId: iteration.nativeCallId
1075
- }));
1076
- if (typeof (afterRes === null || afterRes === void 0 ? void 0 : afterRes.output) !== "undefined") output = afterRes.output;
1077
- return true;
1078
- }
1079
- return false;
1110
+ const unwrapSignal = (value) => {
1111
+ if (!require_errors.ThinkSignal.is(value)) return value;
1112
+ const context = value.context;
1113
+ const output = require_truncate.unwrapTruncated(context);
1114
+ if (require_truncate.isTruncated(context)) onTruncation === null || onTruncation === void 0 || onTruncation(output, context.$$truncate);
1115
+ const inspection = {
1116
+ tool: object ? `${object}.${tool.name}` : tool.name,
1117
+ toolCallId,
1118
+ line,
1119
+ reason: value.reason,
1120
+ value: output,
1121
+ metadata: value.metadata
1122
+ };
1123
+ inspections.push(inspection);
1124
+ return output;
1080
1125
  };
1081
1126
  try {
1082
1127
  const beforeRes = await callHook(() => beforeHook === null || beforeHook === void 0 ? void 0 : beforeHook({
@@ -1088,18 +1133,25 @@ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation
1088
1133
  toolCallId,
1089
1134
  nativeCallId: iteration.nativeCallId
1090
1135
  }));
1136
+ if (require_errors.ThinkSignal.is(beforeRes)) throw new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1091
1137
  if (typeof (beforeRes === null || beforeRes === void 0 ? void 0 : beforeRes.input) !== "undefined") effectiveInput = beforeRes.input;
1092
1138
  controller.signal.throwIfAborted();
1093
- output = await tool.execute(effectiveInput, {
1094
- callId: toolCallId,
1095
- iterationId: iteration.id,
1096
- nativeCallId: iteration.nativeCallId,
1097
- onTruncation,
1098
- onInput: (parsed) => {
1099
- controller.signal.throwIfAborted();
1100
- if (effectiveInput === originalInput) reportedInput = parsed;
1101
- }
1102
- });
1139
+ try {
1140
+ output = await tool.execute(effectiveInput, {
1141
+ callId: toolCallId,
1142
+ iterationId: iteration.id,
1143
+ nativeCallId: iteration.nativeCallId,
1144
+ onTruncation,
1145
+ onInput: (parsed) => {
1146
+ controller.signal.throwIfAborted();
1147
+ if (effectiveInput === originalInput) reportedInput = parsed;
1148
+ }
1149
+ });
1150
+ } catch (error) {
1151
+ if (!require_errors.ThinkSignal.is(error)) throw error;
1152
+ output = error;
1153
+ }
1154
+ output = unwrapSignal(output);
1103
1155
  const afterRes = await callHook(() => afterHook === null || afterHook === void 0 ? void 0 : afterHook({
1104
1156
  iteration,
1105
1157
  tool,
@@ -1110,19 +1162,39 @@ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation
1110
1162
  toolCallId,
1111
1163
  nativeCallId: iteration.nativeCallId
1112
1164
  }));
1165
+ if (require_errors.ThinkSignal.is(afterRes) || require_errors.ThinkSignal.is(afterRes === null || afterRes === void 0 ? void 0 : afterRes.output)) throw new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1113
1166
  if (typeof (afterRes === null || afterRes === void 0 ? void 0 : afterRes.output) !== "undefined") output = afterRes.output;
1167
+ controller.signal.throwIfAborted();
1114
1168
  } catch (err) {
1115
- if (!await handleSignals(err)) {
1116
- success = false;
1117
- error = require_errors.isLLMzError(err) ? err : new require_errors.ToolExecutionError(tool.name, err);
1118
- iteration.recordError(error);
1119
- }
1169
+ success = false;
1170
+ output = void 0;
1171
+ if (require_errors.ThinkSignal.is(err)) error = new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1172
+ else error = require_errors.isLLMzError(err) ? err : new require_errors.ToolExecutionError(tool.name, err);
1173
+ iteration.recordError(error);
1120
1174
  } finally {
1121
1175
  clearTimeout(alertSlowTool);
1176
+ for (const inspection of success ? inspections : []) {
1177
+ const value = require_quickjs_variant.snapshotInspectionValue(output);
1178
+ onThink === null || onThink === void 0 || onThink({
1179
+ ...inspection,
1180
+ value
1181
+ });
1182
+ iteration.recordTrace({
1183
+ type: "think_signal",
1184
+ started_at: Date.now(),
1185
+ ended_at: Date.now(),
1186
+ line: line ?? 0,
1187
+ tool_name: tool.name,
1188
+ tool_call_id: toolCallId,
1189
+ object,
1190
+ reason: inspection.reason,
1191
+ context: value,
1192
+ metadata: inspection.metadata
1193
+ });
1194
+ }
1122
1195
  pushToolCallTrace();
1123
1196
  }
1124
1197
  if (!success) throw error;
1125
- if (signalToThrow) throw signalToThrow;
1126
1198
  onResult === null || onResult === void 0 || onResult(output);
1127
1199
  return output;
1128
1200
  };
@@ -1213,9 +1285,14 @@ const buildVMContext = ({ ctx, iteration, controller, onBeforeTool, onAfterTool,
1213
1285
  afterHook: onAfterTool,
1214
1286
  onTruncation,
1215
1287
  onResult: onToolResult,
1216
- controller
1288
+ controller,
1289
+ onThink: javascriptApi === null || javascriptApi === void 0 ? void 0 : javascriptApi.requestInspection
1217
1290
  });
1218
- instance[tool.name] = javascriptApi ? (input) => javascriptApi.track(() => wrapped(input)) : wrapped;
1291
+ instance[tool.name] = javascriptApi ? (input) => {
1292
+ var _vmContext$VM_CALL_SI;
1293
+ const line = (_vmContext$VM_CALL_SI = vmContext[require_vm.VM_CALL_SITE]) === null || _vmContext$VM_CALL_SI === void 0 ? void 0 : _vmContext$VM_CALL_SI.call(vmContext);
1294
+ return javascriptApi.track(() => wrapped(input, line));
1295
+ } : wrapped;
1219
1296
  }
1220
1297
  vmContext[obj.name] = require_vm.withMissingMember(instance, (name) => {
1221
1298
  const error = new require_errors.UnknownToolError(`${obj.name}.${name}`, (obj.tools ?? []).map((tool) => `${obj.name}.${tool.name}`));
@@ -1231,9 +1308,14 @@ const buildVMContext = ({ ctx, iteration, controller, onBeforeTool, onAfterTool,
1231
1308
  afterHook: onAfterTool,
1232
1309
  onTruncation,
1233
1310
  onResult: onToolResult,
1234
- controller
1311
+ controller,
1312
+ onThink: javascriptApi === null || javascriptApi === void 0 ? void 0 : javascriptApi.requestInspection
1235
1313
  });
1236
- const callable = javascriptApi ? (input) => javascriptApi.track(() => wrapped(input)) : wrapped;
1314
+ const callable = javascriptApi ? (input) => {
1315
+ var _vmContext$VM_CALL_SI2;
1316
+ const line = (_vmContext$VM_CALL_SI2 = vmContext[require_vm.VM_CALL_SITE]) === null || _vmContext$VM_CALL_SI2 === void 0 ? void 0 : _vmContext$VM_CALL_SI2.call(vmContext);
1317
+ return javascriptApi.track(() => wrapped(input, line));
1318
+ } : wrapped;
1237
1319
  for (const key of [tool.name, ...tool.aliases ?? []]) vmContext[key] = callable;
1238
1320
  }
1239
1321
  return vmContext;
@@ -1273,9 +1355,10 @@ async function executeContextInternal(props) {
1273
1355
  });
1274
1356
  let release;
1275
1357
  try {
1276
- var _ctx$iterations$at;
1358
+ var _props$options8, _ctx$iterations$at;
1277
1359
  if ("snapshot" in props) throw new require_errors.InvalidConfigurationError("Snapshots and external pause/resume are no longer supported. Use a session for conversation history and memory.");
1278
1360
  if ("messages" in props) throw new require_errors.InvalidConfigurationError("Append input with session.append(message) before calling execute(). execute.messages is no longer supported.");
1361
+ if (((_props$options8 = props.options) === null || _props$options8 === void 0 ? void 0 : _props$options8.requireChatResponse) !== void 0 && typeof props.options.requireChatResponse !== "boolean") throw new require_errors.InvalidConfigurationError("Invalid requireChatResponse. Expected a boolean.");
1279
1362
  release = ctx.session.acquire();
1280
1363
  prepareSession(ctx);
1281
1364
  const client = props.client ?? new _botpress_client.Client();
@@ -1458,20 +1541,21 @@ async function rejectNativeBatch({ ctx, iteration }, generated, errors) {
1458
1541
  }, generated.toolCalls.some((call) => call.name !== "run_javascript") ? new require_errors.UnknownToolError(generated.toolCalls.find((call) => call.name !== "run_javascript").name, ["run_javascript"], message) : new require_errors.NativeProtocolError(message));
1459
1542
  }
1460
1543
  async function deliverAssistantText(state, generated) {
1544
+ var _iteration$response4;
1461
1545
  const { ctx, iteration } = state;
1462
- if (!generated.output.trim() || !ctx.chat) return;
1546
+ if (!generated.output.trim() || !ctx.chat || !((_iteration$response4 = iteration.response) === null || _iteration$response4 === void 0 ? void 0 : _iteration$response4.handler)) return;
1463
1547
  const startedAt = Date.now();
1464
1548
  const message = {
1465
1549
  type: "text",
1466
1550
  text: generated.output
1467
1551
  };
1468
1552
  try {
1469
- var _iteration$response4, _iteration$response4$;
1470
- await ((_iteration$response4 = iteration.response) === null || _iteration$response4 === void 0 || (_iteration$response4$ = _iteration$response4.handler) === null || _iteration$response4$ === void 0 ? void 0 : _iteration$response4$.call(_iteration$response4, generated.output.trim(), generated.messageMetadata));
1553
+ await iteration.response.handler(generated.output.trim(), generated.messageMetadata);
1471
1554
  } catch (cause) {
1472
1555
  if (require_errors.isCriticalError(cause)) throw cause;
1473
1556
  throw new require_errors.DeliveryError(`Assistant response delivery failed: ${require_utils.getErrorMessage(cause)}`, { cause });
1474
1557
  }
1558
+ ctx.session.recordAssistantDelivery(iteration.id);
1475
1559
  iteration.recordTrace({
1476
1560
  type: "message_delivery",
1477
1561
  value: message,
@@ -1509,6 +1593,31 @@ async function settleJavaScriptCall(state, execution) {
1509
1593
  inspected: (outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect"
1510
1594
  };
1511
1595
  if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect" && result.success) result.return_value = outcome.value;
1596
+ const forcedInspections = api.getForcedInspections();
1597
+ if (forcedInspections.length && !controller.signal.aborted && !require_errors.isCriticalError(result.error)) {
1598
+ if (!result.success && result.error) {
1599
+ iteration.recordError(result.error);
1600
+ state.capture.downstreamError = result.error;
1601
+ }
1602
+ state.capture.forcedInspections = forcedInspections;
1603
+ let value = forcedInspections.length === 1 ? forcedInspections[0].value : forcedInspections.map((entry) => entry.value);
1604
+ if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect") value = outcome.value;
1605
+ state.capture.result = {
1606
+ ...result,
1607
+ success: true,
1608
+ signal: void 0,
1609
+ return_value: value
1610
+ };
1611
+ iteration.end({
1612
+ type: "thinking_requested",
1613
+ thinking_requested: {
1614
+ reason: "Tools completed successfully and requested forced inspection.",
1615
+ variables: value,
1616
+ metadata: forcedInspections.length === 1 ? forcedInspections[0].metadata : void 0
1617
+ }
1618
+ });
1619
+ return;
1620
+ }
1512
1621
  if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "exit") {
1513
1622
  await completeJavaScriptExit(state, result, outcome);
1514
1623
  return;
@@ -1568,11 +1677,11 @@ function containsDecision(value, api, seen = /* @__PURE__ */ new Set()) {
1568
1677
  return Object.values(value).some((nested) => containsDecision(nested, api, seen));
1569
1678
  }
1570
1679
  async function completeJavaScriptExit(state, result, outcome) {
1571
- const { iteration, controller, props } = state;
1680
+ const { iteration, controller } = state;
1572
1681
  state.memory = commitMemory(state, result, false);
1573
1682
  try {
1574
1683
  controller.signal.throwIfAborted();
1575
- await applyNativeExit(iteration, outcome.exit, outcome.value, controller, props.onExit);
1684
+ await applyNativeExit(state, outcome.exit, outcome.value);
1576
1685
  } catch (error) {
1577
1686
  endFailedIteration(iteration, controller, error);
1578
1687
  }
@@ -1604,6 +1713,7 @@ async function deliverJavaScriptMessages({ ctx, iteration, controller }, message
1604
1713
  });
1605
1714
  throw require_errors.isCriticalError(error) ? error : new require_errors.DeliveryError(`Delivery ${message.id} failed: ${require_utils.getErrorMessage(error)}. Its external outcome is uncertain. Later messages were skipped; earlier acknowledged messages remain delivered.`, { cause: error });
1606
1715
  }
1716
+ ctx.session.recordAssistantDelivery(iteration.id);
1607
1717
  iteration.recordTrace({
1608
1718
  type: "message_delivery",
1609
1719
  value: message.component,
@@ -1616,9 +1726,9 @@ async function deliverJavaScriptMessages({ ctx, iteration, controller }, message
1616
1726
  }
1617
1727
  }
1618
1728
  async function finishNativeResponse(state, generated) {
1619
- const { ctx, iteration, controller, props } = state;
1620
- if (!generated.toolCalls.length && generated.output.trim() && ctx.chat) {
1621
- await applyNativeExit(iteration, require_custom_client.ListenExit, {}, controller, props.onExit);
1729
+ const { ctx, iteration } = state;
1730
+ if (!generated.toolCalls.length && ctx.chat && (generated.output.trim() || generated.metadata.stopReason === "stop")) {
1731
+ await applyNativeExit(state, require_custom_client.ListenExit, {});
1622
1732
  if (!iteration.hasExited()) ctx.session.appendContext(ctx.inspector(iteration.error ?? "Completion rejected.", {
1623
1733
  purpose: "error",
1624
1734
  maxTokens: 200
@@ -1717,7 +1827,9 @@ function getExecutionOutcome(state, memory) {
1717
1827
  type: "inspect",
1718
1828
  value: (capture === null || capture === void 0 ? void 0 : capture.result.success) ? capture.result.return_value : void 0,
1719
1829
  available: memory.resultAvailable,
1720
- explicit: (capture === null || capture === void 0 ? void 0 : capture.inspected) ?? false
1830
+ explicit: (capture === null || capture === void 0 ? void 0 : capture.inspected) ?? false,
1831
+ forcedInspections: capture === null || capture === void 0 ? void 0 : capture.forcedInspections,
1832
+ downstreamError: capture === null || capture === void 0 ? void 0 : capture.downstreamError
1721
1833
  };
1722
1834
  }
1723
1835
  return {
@@ -1809,12 +1921,18 @@ function getIterationResult(state) {
1809
1921
  }
1810
1922
  if (iteration.status.type === "aborted") return new require_custom_client.ErrorExecutionResult(ctx, iteration.error);
1811
1923
  }
1812
- async function applyNativeExit(iteration, exit, value, controller, onExit) {
1924
+ async function applyNativeExit(state, exit, value) {
1925
+ const { ctx, iteration, controller, props } = state;
1813
1926
  try {
1814
- await callHook(() => onExit === null || onExit === void 0 ? void 0 : onExit({
1815
- exit,
1816
- result: value
1817
- }, controller));
1927
+ var _props$options9;
1928
+ if (ctx.chat && exit === require_custom_client.ListenExit && ((_props$options9 = props.options) === null || _props$options9 === void 0 ? void 0 : _props$options9.requireChatResponse) !== false && ctx.session.lastSpeaker !== "assistant") throw new require_errors.MissingChatResponseError("The assistant has not delivered a message since the last user message. Send a response using the inspected results before waiting for the user. Do not repeat completed tool calls.");
1929
+ await callHook(() => {
1930
+ var _props$onExit;
1931
+ return (_props$onExit = props.onExit) === null || _props$onExit === void 0 ? void 0 : _props$onExit.call(props, {
1932
+ exit,
1933
+ result: value
1934
+ }, controller);
1935
+ });
1818
1936
  controller.signal.throwIfAborted();
1819
1937
  iteration.end({
1820
1938
  type: "exit_success",
@@ -1,7 +1,7 @@
1
1
  const require_utils = require("./utils-CTlsXvdj.cjs");
2
- const require_errors = require("./errors-IhnTKUp7.cjs");
2
+ const require_errors = require("./errors-C6ppQUZX.cjs");
3
3
  const require_uniq = require("./uniq-DiXgysNV.cjs");
4
- const require_schema = require("./schema-DBkjo0b7.cjs");
4
+ const require_schema = require("./schema-CXlnbb3n.cjs");
5
5
  //#region src/exit.ts
6
6
  var exit_exports = /* @__PURE__ */ require_utils.__exportAll({ Exit: () => Exit });
7
7
  /**
@@ -1,7 +1,7 @@
1
1
  import { Y as __exportAll, c as isValidIdentifier, l as isZuiSchema, n as fromJSONSchemaCompat, s as isJsonSchema } from "./utils-BOFzb8Ok.js";
2
- import { S as InvalidExitError } from "./errors-H4JJFH3S.js";
2
+ import { S as InvalidExitError } from "./errors-Crk5P8jo.js";
3
3
  import { t as uniq } from "./uniq-DfUeSNaX.js";
4
- import { i as toModelSchema } from "./schema-Aer_W7Al.js";
4
+ import { i as toModelSchema } from "./schema-GE4ISPCR.js";
5
5
  //#region src/exit.ts
6
6
  var exit_exports = /* @__PURE__ */ __exportAll({ Exit: () => Exit });
7
7
  /**
package/dist/index.cjs CHANGED
@@ -1,16 +1,16 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_utils = require("./utils-CTlsXvdj.cjs");
3
- const require_errors = require("./errors-IhnTKUp7.cjs");
4
- const require_component = require("./component-BpMVZYOa.cjs");
5
- const require_tool = require("./tool-Da_F-N-5.cjs");
6
- const require_exit = require("./exit-BUgJ5qi5.cjs");
7
- const require_truncate = require("./truncate-nV3Mxr6-.cjs");
8
- const require_quickjs_variant = require("./quickjs-variant-DJwYDSsb.cjs");
9
- const require_typings = require("./typings-C1ihexWE.cjs");
10
- const require_custom_client = require("./custom-client-MytucGI-.cjs");
3
+ const require_errors = require("./errors-C6ppQUZX.cjs");
4
+ const require_component = require("./component-CMFoCHyu.cjs");
5
+ const require_tool = require("./tool-_wK9hQOb.cjs");
6
+ const require_exit = require("./exit-BOtKWPuT.cjs");
7
+ const require_truncate = require("./truncate-uomAMGPs.cjs");
8
+ const require_quickjs_variant = require("./quickjs-variant-21IO97PF.cjs");
9
+ const require_typings = require("./typings-BA_XxAcY.cjs");
10
+ const require_custom_client = require("./custom-client-Cgt9_0r1.cjs");
11
11
  let _bpinternal_zui = require("@bpinternal/zui");
12
12
  //#region package.json
13
- var version = "1.0.1";
13
+ var version = "1.0.2";
14
14
  //#endregion
15
15
  //#region src/objects.ts
16
16
  /**
@@ -619,7 +619,7 @@ const utils = {
619
619
  * })
620
620
  */
621
621
  const execute = async (props) => {
622
- const { executeContext } = await Promise.resolve().then(() => require("./execute-DLas4V2n.cjs"));
622
+ const { executeContext } = await Promise.resolve().then(() => require("./execute-DTTfacsi.cjs"));
623
623
  return executeContext(props);
624
624
  };
625
625
  /**
@@ -628,14 +628,14 @@ const execute = async (props) => {
628
628
  * It's recommended to call this function at the beginning of your application without awaiting it (void init())
629
629
  */
630
630
  const init = async () => {
631
- await Promise.resolve().then(() => require("./execute-DLas4V2n.cjs"));
632
- await Promise.resolve().then(() => require("./component-BpMVZYOa.cjs")).then((n) => n.component_exports);
633
- await Promise.resolve().then(() => require("./tool-Da_F-N-5.cjs")).then((n) => n.tool_exports);
634
- await Promise.resolve().then(() => require("./exit-BUgJ5qi5.cjs")).then((n) => n.exit_exports);
635
- await Promise.resolve().then(() => require("./vm-XuVPuW3Y.cjs"));
631
+ await Promise.resolve().then(() => require("./execute-DTTfacsi.cjs"));
632
+ await Promise.resolve().then(() => require("./component-CMFoCHyu.cjs")).then((n) => n.component_exports);
633
+ await Promise.resolve().then(() => require("./tool-_wK9hQOb.cjs")).then((n) => n.tool_exports);
634
+ await Promise.resolve().then(() => require("./exit-BOtKWPuT.cjs")).then((n) => n.exit_exports);
635
+ await Promise.resolve().then(() => require("./vm-gmekHc0i.cjs"));
636
636
  await Promise.resolve().then(() => require("./utils-CTlsXvdj.cjs")).then((n) => n.utils_exports);
637
- await Promise.resolve().then(() => require("./typings-C1ihexWE.cjs")).then((n) => n.typings_exports);
638
- await Promise.resolve().then(() => require("./native-Bm6L9zOb.cjs")).then((n) => n.native_exports);
637
+ await Promise.resolve().then(() => require("./typings-BA_XxAcY.cjs")).then((n) => n.typings_exports);
638
+ await Promise.resolve().then(() => require("./native-0bq5ATZM.cjs")).then((n) => n.native_exports);
639
639
  };
640
640
  //#endregion
641
641
  exports.AssignmentError = require_errors.AssignmentError;
@@ -673,6 +673,7 @@ exports.LoopExceededError = require_errors.LoopExceededError;
673
673
  exports.Memory = require_quickjs_variant.Memory;
674
674
  exports.MemoryCapacityError = require_errors.MemoryCapacityError;
675
675
  exports.MemoryValueError = require_errors.MemoryValueError;
676
+ exports.MissingChatResponseError = require_errors.MissingChatResponseError;
676
677
  exports.NativeProtocolError = require_errors.NativeProtocolError;
677
678
  exports.ObjectInstance = ObjectInstance;
678
679
  exports.ObjectPropertyError = require_errors.ObjectPropertyError;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { version } from '../package.json';
2
2
  export { ThinkSignal, type ErrorDetails } from './errors.js';
3
- export { AssignmentError, CodeExecutionError, CodeFormattingError, CognitiveError, CompactionError, ComponentInputError, DeliveryError, ExecutionAbortedError, ExitInputError, HookError, HostOperationError, InternalError, InvalidCodeError, InvalidComponentError, InvalidConfigurationError, InvalidEventError, InvalidExitError, InvalidMessageError, InvalidObjectError, InvalidSessionError, InvalidToolError, isCriticalError, isLLMzError, LLMzError, LoopExceededError, MemoryCapacityError, MemoryValueError, NativeProtocolError, ObjectPropertyError, ReservedIdentifierError, SessionStateError, TokenOverflowError, ToolExecutionError, ToolInputError, UnknownComponentError, UnknownExitError, UnknownToolError, type ErrorCode, type LLMzFailure, type ToolInputIssue, type ValidationIssue, } from './errors/catalog.js';
3
+ export { AssignmentError, CodeExecutionError, CodeFormattingError, CognitiveError, CompactionError, ComponentInputError, DeliveryError, MissingChatResponseError, ExecutionAbortedError, ExitInputError, HookError, HostOperationError, InternalError, InvalidCodeError, InvalidComponentError, InvalidConfigurationError, InvalidEventError, InvalidExitError, InvalidMessageError, InvalidObjectError, InvalidSessionError, InvalidToolError, isCriticalError, isLLMzError, LLMzError, LoopExceededError, MemoryCapacityError, MemoryValueError, NativeProtocolError, ObjectPropertyError, ReservedIdentifierError, SessionStateError, TokenOverflowError, ToolExecutionError, ToolInputError, UnknownComponentError, UnknownExitError, UnknownToolError, type ErrorCode, type LLMzFailure, type ToolInputIssue, type ValidationIssue, } from './errors/catalog.js';
4
4
  export { Exit, type ExitResult } from './exit.js';
5
5
  export { inspect, type InspectOptions } from './inspect.js';
6
6
  export { createInspector, type InspectEvent, type InspectionIdentity, type InspectionPurpose, type Inspector, type OnInspect, } from './inspection.js';
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { c as isValidIdentifier, f as toValidFunctionName, i as getMultilineComment, p as toValidObjectName, t as configureTokenizer } from "./utils-BOFzb8Ok.js";
2
- import { A as MemoryValueError, B as UnknownToolError, C as InvalidMessageError, D as LLMzError, E as InvalidToolError, F as TokenOverflowError, H as isLLMzError, I as ToolExecutionError, L as ToolInputError, M as ObjectPropertyError, N as ReservedIdentifierError, O as LoopExceededError, P as SessionStateError, R as UnknownComponentError, S as InvalidExitError, T as InvalidSessionError, V as isCriticalError, _ as InternalError, b as InvalidConfigurationError, c as CodeFormattingError, d as ComponentInputError, f as DeliveryError, g as HostOperationError, h as HookError, j as NativeProtocolError, k as MemoryCapacityError, l as CognitiveError, m as ExitInputError, n as ThinkSignal, o as AssignmentError, p as ExecutionAbortedError, s as CodeExecutionError, u as CompactionError, v as InvalidCodeError, w as InvalidObjectError, x as InvalidEventError, y as InvalidComponentError, z as UnknownExitError } from "./errors-H4JJFH3S.js";
3
- import { a as isAnyComponent, n as assertValidComponent, o as isComponent, t as Component } from "./component-C27qu6Zv.js";
4
- import { t as Tool } from "./tool--gK91eez.js";
5
- import { t as Exit } from "./exit-CPNk3vbz.js";
6
- import { r as truncate } from "./truncate-BSoH2-nY.js";
7
- import { f as createInspector, p as inspect, r as Memory, t as configureQuickJS } from "./quickjs-variant-DlPi9-Sx.js";
8
- import { i as formatTypings } from "./typings-D9_aC8aq.js";
9
- import { c as getValue, i as SuccessExecutionResult, l as Session, n as ErrorExecutionResult, o as DefaultExit, r as ExecutionResult, s as ListenExit, t as _CustomModelClient } from "./custom-client-BDkgBR2w.js";
2
+ import { A as MemoryValueError, B as UnknownExitError, C as InvalidMessageError, D as LLMzError, E as InvalidToolError, F as SessionStateError, H as isCriticalError, I as TokenOverflowError, L as ToolExecutionError, M as NativeProtocolError, N as ObjectPropertyError, O as LoopExceededError, P as ReservedIdentifierError, R as ToolInputError, S as InvalidExitError, T as InvalidSessionError, U as isLLMzError, V as UnknownToolError, _ as InternalError, b as InvalidConfigurationError, c as CodeFormattingError, d as ComponentInputError, f as DeliveryError, g as HostOperationError, h as HookError, j as MissingChatResponseError, k as MemoryCapacityError, l as CognitiveError, m as ExitInputError, n as ThinkSignal, o as AssignmentError, p as ExecutionAbortedError, s as CodeExecutionError, u as CompactionError, v as InvalidCodeError, w as InvalidObjectError, x as InvalidEventError, y as InvalidComponentError, z as UnknownComponentError } from "./errors-Crk5P8jo.js";
3
+ import { a as isAnyComponent, n as assertValidComponent, o as isComponent, t as Component } from "./component-DncqP4fB.js";
4
+ import { t as Tool } from "./tool-DstssiAs.js";
5
+ import { t as Exit } from "./exit-DMPwCSba.js";
6
+ import { r as truncate } from "./truncate-BEKbdo3t.js";
7
+ import { f as createInspector, m as inspect, r as Memory, t as configureQuickJS } from "./quickjs-variant-CtuGagsb.js";
8
+ import { i as formatTypings } from "./typings-BEVDvtuk.js";
9
+ import { c as getValue, i as SuccessExecutionResult, l as Session, n as ErrorExecutionResult, o as DefaultExit, r as ExecutionResult, s as ListenExit, t as _CustomModelClient } from "./custom-client-C-WXvLD9.js";
10
10
  import { z } from "@bpinternal/zui";
11
11
  //#region package.json
12
- var version = "1.0.1";
12
+ var version = "1.0.2";
13
13
  //#endregion
14
14
  //#region src/objects.ts
15
15
  /**
@@ -618,7 +618,7 @@ const utils = {
618
618
  * })
619
619
  */
620
620
  const execute = async (props) => {
621
- const { executeContext } = await import("./execute-BYI_U5sR.js");
621
+ const { executeContext } = await import("./execute-CiYvPs5Q.js");
622
622
  return executeContext(props);
623
623
  };
624
624
  /**
@@ -627,14 +627,14 @@ const execute = async (props) => {
627
627
  * It's recommended to call this function at the beginning of your application without awaiting it (void init())
628
628
  */
629
629
  const init = async () => {
630
- await import("./execute-BYI_U5sR.js");
631
- await import("./component-C27qu6Zv.js").then((n) => n.r);
632
- await import("./tool--gK91eez.js").then((n) => n.n);
633
- await import("./exit-CPNk3vbz.js").then((n) => n.n);
634
- await import("./vm-8jxt8PTK.js");
630
+ await import("./execute-CiYvPs5Q.js");
631
+ await import("./component-DncqP4fB.js").then((n) => n.r);
632
+ await import("./tool-DstssiAs.js").then((n) => n.n);
633
+ await import("./exit-DMPwCSba.js").then((n) => n.n);
634
+ await import("./vm-C7SfutHn.js");
635
635
  await import("./utils-BOFzb8Ok.js").then((n) => n.m);
636
- await import("./typings-D9_aC8aq.js").then((n) => n.r);
637
- await import("./native-DvTH9vFe.js").then((n) => n.n);
636
+ await import("./typings-BEVDvtuk.js").then((n) => n.r);
637
+ await import("./native-n_718Z-T.js").then((n) => n.n);
638
638
  };
639
639
  //#endregion
640
- export { AssignmentError, Chat, CitationsManager, CodeExecutionError, CodeFormattingError, CognitiveError, CompactionError, Component, ComponentInputError, DefaultComponents, DefaultExit, DeliveryError, ErrorExecutionResult, ExecutionAbortedError, ExecutionResult, Exit, ExitInputError, HookError, HostOperationError, InternalError, InvalidCodeError, InvalidComponentError, InvalidConfigurationError, InvalidEventError, InvalidExitError, InvalidMessageError, InvalidObjectError, InvalidSessionError, InvalidToolError, LLMzError, ListenExit, LoopExceededError, Memory, MemoryCapacityError, MemoryValueError, NativeProtocolError, ObjectInstance, ObjectPropertyError, ReservedIdentifierError, Session, SessionStateError, SuccessExecutionResult, ThinkSignal, TokenOverflowError, Tool, ToolExecutionError, ToolInputError, UnknownComponentError, UnknownExitError, UnknownToolError, _CustomModelClient, assertValidComponent, configureQuickJS, configureTokenizer, createInspector, execute, getValue, init, inspect, isAnyComponent, isComponent, isCriticalError, isLLMzError, truncate, utils, version };
640
+ export { AssignmentError, Chat, CitationsManager, CodeExecutionError, CodeFormattingError, CognitiveError, CompactionError, Component, ComponentInputError, DefaultComponents, DefaultExit, DeliveryError, ErrorExecutionResult, ExecutionAbortedError, ExecutionResult, Exit, ExitInputError, HookError, HostOperationError, InternalError, InvalidCodeError, InvalidComponentError, InvalidConfigurationError, InvalidEventError, InvalidExitError, InvalidMessageError, InvalidObjectError, InvalidSessionError, InvalidToolError, LLMzError, ListenExit, LoopExceededError, Memory, MemoryCapacityError, MemoryValueError, MissingChatResponseError, NativeProtocolError, ObjectInstance, ObjectPropertyError, ReservedIdentifierError, Session, SessionStateError, SuccessExecutionResult, ThinkSignal, TokenOverflowError, Tool, ToolExecutionError, ToolInputError, UnknownComponentError, UnknownExitError, UnknownToolError, _CustomModelClient, assertValidComponent, configureQuickJS, configureTokenizer, createInspector, execute, getValue, init, inspect, isAnyComponent, isComponent, isCriticalError, isLLMzError, truncate, utils, version };