llmz 0.2.2 → 0.3.0

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 (55) hide show
  1. package/CLAUDE.md +0 -1
  2. package/dist/{chunk-2EZSVF5X.cjs → chunk-3UZKLXAD.cjs} +29 -23
  3. package/dist/{chunk-HM5H556L.js → chunk-72ZWBNZV.js} +1 -1
  4. package/dist/{chunk-D6PU5YAS.cjs → chunk-DDSJTR6Q.cjs} +8 -7
  5. package/dist/{chunk-GDWRFHM5.js → chunk-GDJTKI7J.js} +1 -1
  6. package/dist/{chunk-YX27XM67.js → chunk-GLXADNTR.js} +13 -1
  7. package/dist/{chunk-FPLSJF4S.cjs → chunk-GOWPACSK.cjs} +15 -3
  8. package/dist/{chunk-XVVYNOTX.js → chunk-HB2G32AK.js} +3 -2
  9. package/dist/{chunk-YQT5G77W.cjs → chunk-HEAQAEFZ.cjs} +2 -2
  10. package/dist/{chunk-MHVORH33.cjs → chunk-HMMM32RG.cjs} +14 -14
  11. package/dist/{chunk-5XPEVOOW.cjs → chunk-KG5E3UZZ.cjs} +20 -20
  12. package/dist/{chunk-C2KND2PS.cjs → chunk-OVRDJMZJ.cjs} +26 -34
  13. package/dist/{chunk-5ISVDYBA.js → chunk-OXEKAOVI.js} +3 -11
  14. package/dist/{chunk-S46T73HR.cjs → chunk-PZE6PIPG.cjs} +12 -11
  15. package/dist/chunk-RGUG3UMF.cjs +26 -0
  16. package/dist/{chunk-3OSQ4XL4.js → chunk-TDALRNGL.js} +4 -3
  17. package/dist/chunk-UGHFNCPD.js +26 -0
  18. package/dist/{chunk-2MSLOTFO.js → chunk-XMFQVARN.js} +5 -5
  19. package/dist/{chunk-EJIDFDQP.js → chunk-YRS7KRKP.js} +28 -22
  20. package/dist/context.d.ts +2 -2
  21. package/dist/custom-client.d.ts +4 -3
  22. package/dist/{dual-modes-J4RWHJ2O.js → dual-modes-BYABHBDI.js} +3 -3
  23. package/dist/dual-modes-HO6RRIZ5.cjs +10 -0
  24. package/dist/emscripten-module.wasm +0 -0
  25. package/dist/{execute-4IL4QPAR.cjs → execute-2H4F7GFE.cjs} +81 -69
  26. package/dist/{execute-6AYBMTRM.js → execute-DPCZ6PKH.js} +51 -39
  27. package/dist/exit-MX56VN2C.cjs +8 -0
  28. package/dist/{exit-VJATJTQI.js → exit-UQ3EUX5D.js} +2 -2
  29. package/dist/exit.d.ts +1 -1
  30. package/dist/index.cjs +67 -61
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +23 -17
  33. package/dist/index.workerd.js +17339 -0
  34. package/dist/prompts/prompt.d.ts +3 -6
  35. package/dist/quickjs-variant.d.ts +22 -0
  36. package/dist/quickjs-variant.workerd.d.ts +22 -0
  37. package/dist/result.d.ts +3 -3
  38. package/dist/runtime/types.d.ts +7 -9
  39. package/dist/{tool-I3MAWDN2.js → tool-KD7FL45V.js} +3 -3
  40. package/dist/{tool-56I7OSKU.cjs → tool-VE2YHIY2.cjs} +4 -4
  41. package/dist/{truncator-OZOBNYON.js → truncator-73RCL52Y.js} +2 -2
  42. package/dist/truncator-FZNLYSDL.cjs +12 -0
  43. package/dist/{typings-SR3EE6LR.js → typings-E2RROCLT.js} +2 -2
  44. package/dist/{typings-LVI4VGE2.cjs → typings-LQOBZXSO.cjs} +3 -3
  45. package/dist/{utils-ZEZ66X6Q.js → utils-IATCUNKF.js} +5 -1
  46. package/dist/utils-ITB4NEL7.cjs +43 -0
  47. package/dist/utils.d.ts +18 -0
  48. package/dist/vm-6D3IIIU7.cjs +12 -0
  49. package/dist/{vm-ZLWGAYYJ.js → vm-QO5FSGPN.js} +2 -1
  50. package/package.json +6 -4
  51. package/dist/dual-modes-IZQJTXR7.cjs +0 -10
  52. package/dist/exit-LUJY7JIG.cjs +0 -8
  53. package/dist/truncator-7PGEGCHV.cjs +0 -12
  54. package/dist/utils-GLZVMRWO.cjs +0 -39
  55. package/dist/vm-ZVONLAZV.cjs +0 -11
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunk2EZSVF5Xcjs = require('./chunk-2EZSVF5X.cjs');
5
+ var _chunk3UZKLXADcjs = require('./chunk-3UZKLXAD.cjs');
6
6
 
7
7
 
8
8
 
@@ -11,13 +11,14 @@ var _chunk2EZSVF5Xcjs = require('./chunk-2EZSVF5X.cjs');
11
11
 
12
12
 
13
13
 
14
- var _chunk5XPEVOOWcjs = require('./chunk-5XPEVOOW.cjs');
14
+ var _chunkKG5E3UZZcjs = require('./chunk-KG5E3UZZ.cjs');
15
15
 
16
16
 
17
17
 
18
- var _chunkC2KND2PScjs = require('./chunk-C2KND2PS.cjs');
19
- require('./chunk-S46T73HR.cjs');
20
- require('./chunk-MHVORH33.cjs');
18
+ var _chunkOVRDJMZJcjs = require('./chunk-OVRDJMZJ.cjs');
19
+ require('./chunk-RGUG3UMF.cjs');
20
+ require('./chunk-PZE6PIPG.cjs');
21
+ require('./chunk-HMMM32RG.cjs');
21
22
 
22
23
 
23
24
 
@@ -31,19 +32,19 @@ var _chunkPK72FAKDcjs = require('./chunk-PK72FAKD.cjs');
31
32
 
32
33
 
33
34
  var _chunkKIN7Y247cjs = require('./chunk-KIN7Y247.cjs');
34
- require('./chunk-D6PU5YAS.cjs');
35
+ require('./chunk-DDSJTR6Q.cjs');
35
36
  require('./chunk-I56MPOVG.cjs');
36
37
 
37
38
 
38
39
  var _chunk5ZF6NTYIcjs = require('./chunk-5ZF6NTYI.cjs');
39
40
 
40
41
 
41
- var _chunkYQT5G77Wcjs = require('./chunk-YQT5G77W.cjs');
42
+ var _chunkHEAQAEFZcjs = require('./chunk-HEAQAEFZ.cjs');
42
43
 
43
44
 
44
45
 
45
46
 
46
- var _chunkFPLSJF4Scjs = require('./chunk-FPLSJF4S.cjs');
47
+ var _chunkGOWPACSKcjs = require('./chunk-GOWPACSK.cjs');
47
48
 
48
49
 
49
50
 
@@ -134,12 +135,12 @@ var generateCode = async ({
134
135
  onRunStart,
135
136
  onRunComplete
136
137
  }) => {
137
- var _a, _b, _c, _d;
138
+ var _a, _b;
138
139
  const startedAt = Date.now();
139
140
  const traces = iteration.traces;
140
141
  const modelRef = Array.isArray(iteration.model) ? iteration.model[0] : iteration.model;
141
142
  const model = await cognitive.getModelDetails(modelRef).catch((thrown) => {
142
- throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`Failed to fetch model details for model "${modelRef}": ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, thrown)}`);
143
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`Failed to fetch model details for model "${modelRef}": ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
143
144
  });
144
145
  let modelLimit = Math.max(model.input.maxTokens, 8e3);
145
146
  if (ctx.maxTokens) {
@@ -151,34 +152,32 @@ var generateCode = async ({
151
152
  }
152
153
  let messages;
153
154
  try {
154
- messages = _chunkYQT5G77Wcjs.truncateWrappedContent.call(void 0, {
155
+ messages = _chunkHEAQAEFZcjs.truncateWrappedContent.call(void 0, {
155
156
  messages: iteration.messages,
156
157
  tokenLimit: modelLimit - responseLengthBuffer,
157
158
  throwOnFailure: true
158
159
  }).filter((x) => typeof x.content !== "string" || x.content.trim().length > 0);
159
160
  } catch (thrown) {
160
161
  const cap = ctx.maxTokens ? ` (context window capped at ${modelLimit} tokens by options.maxTokens \u2014 consider raising or removing it)` : ` (model context window: ${modelLimit} tokens)`;
161
- throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`The prompt does not fit in the context window${cap}: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, thrown)}`);
162
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`The prompt does not fit in the context window${cap}: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
162
163
  }
163
164
  iteration.messages = messages;
164
165
  traces.push({
165
166
  type: "llm_call_started",
166
167
  started_at: startedAt,
167
168
  ended_at: startedAt,
168
- model: model.ref
169
+ model: model.id
169
170
  });
170
171
  const input = {
171
- signal: controller.signal,
172
- systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
173
172
  model: iteration.model,
174
173
  temperature: iteration.temperature,
175
174
  responseFormat: "text",
176
175
  reasoningEffort: iteration.reasoningEffort,
177
- messages: messages.filter((x) => x.role !== "system"),
176
+ messages,
178
177
  stopSequences: ctx.version.getStopTokens(),
179
178
  meta: metadata ? { metadata } : void 0
180
179
  };
181
- let output;
180
+ let responseMetadata;
182
181
  let raw;
183
182
  let assistantResponse;
184
183
  let timeToFirstToken;
@@ -223,18 +222,20 @@ var generateCode = async ({
223
222
  }
224
223
  }
225
224
  };
226
- if (typeof cognitive.generateContentStream === "function") {
227
- const parser = new (0, _chunkC2KND2PScjs.StreamingMessageParser)();
225
+ if (typeof cognitive.generateTextStream === "function") {
226
+ const parser = new (0, _chunkOVRDJMZJcjs.StreamingMessageParser)();
228
227
  const fence = new LeadingFenceFilter();
229
228
  const streamController = createJoinedAbortController([controller.signal]);
230
229
  const requestedAt = Date.now();
231
- const stream = cognitive.generateContentStream({
232
- ...input,
233
- signal: streamController.signal,
234
- // Passed through to the cognitive v2 request: fall back to the next
235
- // model/provider when the first token takes too long
236
- ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
237
- });
230
+ const stream = cognitive.generateTextStream(
231
+ {
232
+ ...input,
233
+ // Passed through to the cognitive request: fall back to the next
234
+ // model/provider when the first token takes too long
235
+ ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
236
+ },
237
+ { signal: streamController.signal }
238
+ );
238
239
  const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, _nullishCoalesce(ctx.maxTimeToFirstToken, () => ( 0)));
239
240
  const nextChunk = async () => {
240
241
  let timer;
@@ -256,12 +257,14 @@ var generateCode = async ({
256
257
  try {
257
258
  chunk = await nextChunk();
258
259
  } catch (thrown) {
259
- throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, thrown)}`);
260
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
260
261
  }
261
262
  if (chunk.done) {
262
- output = chunk.value;
263
263
  break;
264
264
  }
265
+ if ((_a = chunk.value) == null ? void 0 : _a.metadata) {
266
+ responseMetadata = chunk.value.metadata;
267
+ }
265
268
  const delta = (_b = chunk.value) == null ? void 0 : _b.output;
266
269
  if (!delta) {
267
270
  continue;
@@ -271,22 +274,25 @@ var generateCode = async ({
271
274
  raw += delta;
272
275
  await dispatchSends(parser.push(fence.push(delta)));
273
276
  }
277
+ if (!responseMetadata) {
278
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)("LLM streaming completed without metadata");
279
+ }
274
280
  const remaining = fence.flush();
275
281
  if (remaining) {
276
282
  await dispatchSends(parser.push(remaining));
277
283
  }
278
284
  await dispatchSends(parser.finish());
279
- assistantResponse = _chunkC2KND2PScjs.toParsedAssistantResponse.call(void 0, parser.items, raw);
285
+ assistantResponse = _chunkOVRDJMZJcjs.toParsedAssistantResponse.call(void 0, parser.items, raw);
280
286
  } else {
281
- output = await cognitive.generateContent(input).catch((thrown) => {
282
- throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, thrown)}`);
287
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
288
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
283
289
  });
284
- const out = typeof ((_d = (_c = output.output.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.content) === "string" ? output.output.choices[0].content : null;
285
- if (!out) {
290
+ if (!response.output) {
286
291
  throw new (0, _chunkPK72FAKDcjs.CognitiveError)("LLM did not return any text output");
287
292
  }
288
- raw = out;
289
- assistantResponse = ctx.version.parseAssistantResponse(out);
293
+ responseMetadata = response.metadata;
294
+ raw = response.output;
295
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
290
296
  for (const send of assistantResponse.sends) {
291
297
  await (onSend == null ? void 0 : onSend(send));
292
298
  }
@@ -294,29 +300,35 @@ var generateCode = async ({
294
300
  iteration.code = assistantResponse.code;
295
301
  iteration.sends = assistantResponse.sends;
296
302
  iteration.next = assistantResponse.next;
303
+ const usage = responseMetadata.usage;
297
304
  iteration.llm = {
298
- cached: output.meta.cached || false,
305
+ cached: responseMetadata.cached || false,
299
306
  ended_at: Date.now(),
300
307
  started_at: startedAt,
301
308
  status: "success",
302
- tokens: output.meta.tokens.input + output.meta.tokens.output,
303
- spend: output.meta.cost.input + output.meta.cost.output,
309
+ tokens: usage.inputTokens + usage.outputTokens,
310
+ spend: _nullishCoalesce(responseMetadata.cost, () => ( usage.inputCost + usage.outputCost)),
304
311
  output: assistantResponse.raw,
305
- model: `${output.meta.model.integration}:${output.meta.model.model}`,
312
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
306
313
  time_to_first_token: timeToFirstToken,
307
314
  time_to_last_token: timeToLastToken,
308
- usage: output.output.usage
315
+ usage: {
316
+ inputTokens: usage.inputTokens,
317
+ inputCost: usage.inputCost,
318
+ outputTokens: usage.outputTokens,
319
+ outputCost: usage.outputCost
320
+ }
309
321
  };
310
322
  if (iteration.tokens) {
311
- iteration.tokens.input = output.meta.tokens.input;
312
- iteration.tokens.output = output.meta.tokens.output;
313
- iteration.tokens.total = output.meta.tokens.input + output.meta.tokens.output;
323
+ iteration.tokens.input = usage.inputTokens;
324
+ iteration.tokens.output = usage.outputTokens;
325
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
314
326
  }
315
327
  traces.push({
316
328
  type: "llm_call_success",
317
329
  started_at: startedAt,
318
330
  ended_at: iteration.llm.ended_at,
319
- model: model.ref,
331
+ model: model.id,
320
332
  code: _nullishCoalesce(iteration.code, () => ( ""))
321
333
  });
322
334
  };
@@ -395,7 +407,7 @@ var interpretVMResult = async ({
395
407
  return;
396
408
  }
397
409
  const returnValue = result.return_value;
398
- const codeRequestsInspection = _chunk2EZSVF5Xcjs.hasTopLevelReturn.call(void 0, _nullishCoalesce(iteration.code, () => ( "")));
410
+ const codeRequestsInspection = _chunk3UZKLXADcjs.hasTopLevelReturn.call(void 0, _nullishCoalesce(iteration.code, () => ( "")));
399
411
  if (iteration.next && !codeRequestsInspection) {
400
412
  await applyNextExit({ iteration, controller, onExit });
401
413
  return;
@@ -420,7 +432,7 @@ var applyNextExit = async ({
420
432
  if (!next) {
421
433
  throw new Error("applyNextExit called without a \u25A0next block on the iteration");
422
434
  }
423
- const attempt = (props) => _chunk5XPEVOOWcjs.parseExit.call(void 0, Object.keys(props).length ? { action: next.name, value: props } : { action: next.name }, iteration.exits);
435
+ const attempt = (props) => _chunkKG5E3UZZcjs.parseExit.call(void 0, Object.keys(props).length ? { action: next.name, value: props } : { action: next.name }, iteration.exits);
424
436
  let parsedExit = attempt(next.props);
425
437
  const keys = Object.keys(next.props);
426
438
  if (!parsedExit.success && keys.length === 1 && ["props", "value", "data"].includes(keys[0])) {
@@ -458,7 +470,7 @@ var applyNextExit = async ({
458
470
  type: "exit_error",
459
471
  exit_error: {
460
472
  exit: returnExit.name,
461
- message: `Error executing exit ${returnExit.name}: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err)}`,
473
+ message: `Error executing exit ${returnExit.name}: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, err)}`,
462
474
  return_value: returnValue
463
475
  }
464
476
  });
@@ -639,7 +651,7 @@ var buildVMContext = ({
639
651
  onAfterTool
640
652
  }) => {
641
653
  const traces = iteration.traces;
642
- const vmContext = { ..._chunkFPLSJF4Scjs.stripInvalidIdentifiers.call(void 0, iteration.variables) };
654
+ const vmContext = { ..._chunkGOWPACSKcjs.stripInvalidIdentifiers.call(void 0, iteration.variables) };
643
655
  for (const obj of iteration.objects) {
644
656
  const internalValues = {};
645
657
  const instance = {};
@@ -663,7 +675,7 @@ var buildVMContext = ({
663
675
  const parsed = schema.safeParse(value2);
664
676
  if (!parsed.success) {
665
677
  throw new (0, _chunkPK72FAKDcjs.AssignmentError)(
666
- `Invalid value for Object property ${obj.name}.${name}: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, parsed.error)}`
678
+ `Invalid value for Object property ${obj.name}.${name}: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, parsed.error)}`
667
679
  );
668
680
  }
669
681
  internalValues[name] = parsed.data;
@@ -714,7 +726,7 @@ var buildVMContext = ({
714
726
  // src/runtime/execute.ts
715
727
  var executeContext = async (props) => {
716
728
  var _a, _b;
717
- await _chunkFPLSJF4Scjs.init.call(void 0, );
729
+ await _chunkGOWPACSKcjs.init.call(void 0, );
718
730
  const result = await executeContextInternal(props);
719
731
  try {
720
732
  (_b = (_a = result.context.chat) == null ? void 0 : _a.onExecutionDone) == null ? void 0 : _b.call(_a, result);
@@ -727,8 +739,8 @@ var executeContextInternal = async (props) => {
727
739
  const controller = createJoinedAbortController([props.signal]);
728
740
  const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
729
741
  const client = _nullishCoalesce(props.client, () => ( new (0, _client.Client)()));
730
- const cognitive = _cognitive.Cognitive.isCognitiveClient(client) || _chunk5XPEVOOWcjs._CustomModelClient.isCustomClient(client) ? client : _cognitive.CognitiveBeta.isBetaClient(client) ? _cognitive.cognitiveFromBeta.call(void 0, client) : new (0, _cognitive.Cognitive)({ client, __experimental_beta: true });
731
- const ctx = new (0, _chunk5XPEVOOWcjs.Context)({
742
+ const cognitive = _cognitive.Cognitive.isCognitiveClient(client) || _chunkKG5E3UZZcjs._CustomModelClient.isCustomClient(client) ? client : new (0, _cognitive.Cognitive)({ client });
743
+ const ctx = new (0, _chunkKG5E3UZZcjs.Context)({
732
744
  chat: props.chat,
733
745
  instructions: props.instructions,
734
746
  objects: props.objects,
@@ -746,7 +758,7 @@ var executeContextInternal = async (props) => {
746
758
  try {
747
759
  while (true) {
748
760
  if (ctx.iterations.length >= ctx.loop) {
749
- return new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, new (0, _chunkPK72FAKDcjs.LoopExceededError)());
761
+ return new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, new (0, _chunkPK72FAKDcjs.LoopExceededError)());
750
762
  }
751
763
  const iteration = await ctx.nextIteration();
752
764
  const unsubscribeTrace = iteration.traces.onPush((traces) => {
@@ -777,7 +789,7 @@ var executeContextInternal = async (props) => {
777
789
  }
778
790
  }
779
791
  });
780
- return new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted")));
792
+ return new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted")));
781
793
  }
782
794
  const iterationResult = await executeIterationWithErrorHandling({
783
795
  iteration,
@@ -807,7 +819,7 @@ var executeContextInternal = async (props) => {
807
819
  }
808
820
  }
809
821
  } catch (error) {
810
- return new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(error, () => ( "Unknown error")));
822
+ return new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(error, () => ( "Unknown error")));
811
823
  }
812
824
  };
813
825
  var executeIterationStartHook = async ({
@@ -837,7 +849,7 @@ var executeIterationStartHook = async ({
837
849
  } : {
838
850
  type: "execution_error",
839
851
  execution_error: {
840
- message: `Error in onIterationStart hook: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err)}`,
852
+ message: `Error in onIterationStart hook: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, err)}`,
841
853
  stack: _chunkKIN7Y247cjs.cleanStackTrace.call(void 0,
842
854
  err instanceof Error ? _nullishCoalesce(err.stack, () => ( "No stack trace available")) : "No stack trace available"
843
855
  )
@@ -882,7 +894,7 @@ var executeIterationWithErrorHandling = async ({
882
894
  status: iteration.status.type === "pending" ? {
883
895
  type: "execution_error",
884
896
  execution_error: {
885
- message: "An unexpected error occurred: " + _chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err),
897
+ message: "An unexpected error occurred: " + _chunkGOWPACSKcjs.getErrorMessage.call(void 0, err),
886
898
  stack: _chunkKIN7Y247cjs.cleanStackTrace.call(void 0,
887
899
  err instanceof Error ? _nullishCoalesce(err.stack, () => ( "No stack trace available")) : "No stack trace available"
888
900
  )
@@ -894,7 +906,7 @@ var executeIterationWithErrorHandling = async ({
894
906
  if (!controller.signal.aborted) {
895
907
  return {
896
908
  type: "return",
897
- result: new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, err)
909
+ result: new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, err)
898
910
  };
899
911
  }
900
912
  await finalizeIteration({
@@ -910,7 +922,7 @@ var executeIterationWithErrorHandling = async ({
910
922
  });
911
923
  return {
912
924
  type: "return",
913
- result: new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted")))
925
+ result: new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted")))
914
926
  };
915
927
  }
916
928
  };
@@ -922,7 +934,7 @@ var transformIterationResult = ({
922
934
  const exitName = iteration.status.exit_success.exit_name;
923
935
  return {
924
936
  type: "return",
925
- result: new (0, _chunk5XPEVOOWcjs.SuccessExecutionResult)(ctx, {
937
+ result: new (0, _chunkKG5E3UZZcjs.SuccessExecutionResult)(ctx, {
926
938
  exit: iteration.exits.find((x) => x.name === exitName),
927
939
  result: iteration.status.exit_success.return_value
928
940
  })
@@ -931,17 +943,17 @@ var transformIterationResult = ({
931
943
  if (iteration.status.type === "callback_requested") {
932
944
  return {
933
945
  type: "return",
934
- result: new (0, _chunk5XPEVOOWcjs.PartialExecutionResult)(
946
+ result: new (0, _chunkKG5E3UZZcjs.PartialExecutionResult)(
935
947
  ctx,
936
948
  iteration.status.callback_requested.signal,
937
- _chunk5XPEVOOWcjs.Snapshot.fromSignal(iteration.status.callback_requested.signal)
949
+ _chunkKG5E3UZZcjs.Snapshot.fromSignal(iteration.status.callback_requested.signal)
938
950
  )
939
951
  };
940
952
  }
941
953
  if (iteration.status.type === "aborted") {
942
954
  return {
943
955
  type: "return",
944
- result: new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( "The operation was aborted")))
956
+ result: new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( "The operation was aborted")))
945
957
  };
946
958
  }
947
959
  if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") {
@@ -949,7 +961,7 @@ var transformIterationResult = ({
949
961
  }
950
962
  return {
951
963
  type: "return",
952
- result: new (0, _chunk5XPEVOOWcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( `Unknown error. Status: ${iteration.status.type}`)))
964
+ result: new (0, _chunkKG5E3UZZcjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( `Unknown error. Status: ${iteration.status.type}`)))
953
965
  };
954
966
  };
955
967
  var executeIteration = async ({
@@ -966,10 +978,10 @@ var executeIteration = async ({
966
978
  var _a, _b;
967
979
  const runCode = (code) => {
968
980
  const vmContext = buildVMContext({ ctx, iteration, controller, onBeforeTool, onAfterTool });
969
- return _chunk2EZSVF5Xcjs.runAsyncFunction.call(void 0, vmContext, code, iteration.traces, controller.signal, ctx.timeout).catch((err) => {
981
+ return _chunk3UZKLXADcjs.runAsyncFunction.call(void 0, vmContext, code, iteration.traces, controller.signal, ctx.timeout).catch((err) => {
970
982
  return {
971
983
  success: false,
972
- error: err instanceof Error ? err : new Error(_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err)),
984
+ error: err instanceof Error ? err : new Error(_chunkGOWPACSKcjs.getErrorMessage.call(void 0, err)),
973
985
  lines_executed: [],
974
986
  traces: [],
975
987
  variables: {}
@@ -985,7 +997,7 @@ var executeIteration = async ({
985
997
  controller,
986
998
  metadata,
987
999
  // Pre-warm the VM while the model is still writing the ■run block
988
- onRunStart: () => _chunk2EZSVF5Xcjs.warmupVM.call(void 0, ),
1000
+ onRunStart: () => _chunk3UZKLXADcjs.warmupVM.call(void 0, ),
989
1001
  onRunComplete: canExecuteEarly ? (code) => {
990
1002
  if (!code.length || controller.signal.aborted || earlyExecution) {
991
1003
  return;
@@ -1006,7 +1018,7 @@ var executeIteration = async ({
1006
1018
  try {
1007
1019
  await ctx.chat.handler(component);
1008
1020
  } catch (err) {
1009
- throw new Error(`Error while sending message (\u25A0send=${send.name}): ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err)}`);
1021
+ throw new Error(`Error while sending message (\u25A0send=${send.name}): ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, err)}`);
1010
1022
  }
1011
1023
  iteration.traces.push({ type: "yield", value: component, started_at: sendStartedAt, ended_at: Date.now() });
1012
1024
  },
@@ -1035,7 +1047,7 @@ var executeIteration = async ({
1035
1047
  iteration.end({
1036
1048
  type: "execution_error",
1037
1049
  execution_error: {
1038
- message: `Error in onBeforeExecution hook: ${_chunkFPLSJF4Scjs.getErrorMessage.call(void 0, err)}`,
1050
+ message: `Error in onBeforeExecution hook: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, err)}`,
1039
1051
  stack: _chunkKIN7Y247cjs.cleanStackTrace.call(void 0,
1040
1052
  err instanceof Error ? _nullishCoalesce(err.stack, () => ( "No stack trace available")) : "No stack trace available"
1041
1053
  )
@@ -2,7 +2,7 @@ import {
2
2
  hasTopLevelReturn,
3
3
  runAsyncFunction,
4
4
  warmupVM
5
- } from "./chunk-EJIDFDQP.js";
5
+ } from "./chunk-YRS7KRKP.js";
6
6
  import {
7
7
  Context,
8
8
  ErrorExecutionResult,
@@ -11,13 +11,14 @@ import {
11
11
  SuccessExecutionResult,
12
12
  _CustomModelClient,
13
13
  parseExit
14
- } from "./chunk-2MSLOTFO.js";
14
+ } from "./chunk-XMFQVARN.js";
15
15
  import {
16
16
  StreamingMessageParser,
17
17
  toParsedAssistantResponse
18
- } from "./chunk-5ISVDYBA.js";
19
- import "./chunk-3OSQ4XL4.js";
20
- import "./chunk-GDWRFHM5.js";
18
+ } from "./chunk-OXEKAOVI.js";
19
+ import "./chunk-UGHFNCPD.js";
20
+ import "./chunk-TDALRNGL.js";
21
+ import "./chunk-GDJTKI7J.js";
21
22
  import {
22
23
  AssignmentError,
23
24
  CodeExecutionError,
@@ -31,19 +32,19 @@ import {
31
32
  import {
32
33
  cleanStackTrace
33
34
  } from "./chunk-YEAWWJSJ.js";
34
- import "./chunk-XVVYNOTX.js";
35
+ import "./chunk-HB2G32AK.js";
35
36
  import "./chunk-KWQTYXAT.js";
36
37
  import {
37
38
  createJsxComponent
38
39
  } from "./chunk-XTEHT2TK.js";
39
40
  import {
40
41
  truncateWrappedContent
41
- } from "./chunk-HM5H556L.js";
42
+ } from "./chunk-72ZWBNZV.js";
42
43
  import {
43
44
  getErrorMessage,
44
45
  init,
45
46
  stripInvalidIdentifiers
46
- } from "./chunk-YX27XM67.js";
47
+ } from "./chunk-GLXADNTR.js";
47
48
  import {
48
49
  clamp_default,
49
50
  isEqual_default
@@ -51,7 +52,7 @@ import {
51
52
 
52
53
  // src/runtime/execute.ts
53
54
  import { Client } from "@botpress/client";
54
- import { Cognitive, CognitiveBeta, cognitiveFromBeta } from "@botpress/cognitive";
55
+ import { Cognitive } from "@botpress/cognitive";
55
56
 
56
57
  // src/abort-signal.ts
57
58
  function createJoinedAbortController(signals) {
@@ -134,7 +135,7 @@ var generateCode = async ({
134
135
  onRunStart,
135
136
  onRunComplete
136
137
  }) => {
137
- var _a, _b, _c, _d;
138
+ var _a, _b;
138
139
  const startedAt = Date.now();
139
140
  const traces = iteration.traces;
140
141
  const modelRef = Array.isArray(iteration.model) ? iteration.model[0] : iteration.model;
@@ -165,20 +166,18 @@ var generateCode = async ({
165
166
  type: "llm_call_started",
166
167
  started_at: startedAt,
167
168
  ended_at: startedAt,
168
- model: model.ref
169
+ model: model.id
169
170
  });
170
171
  const input = {
171
- signal: controller.signal,
172
- systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
173
172
  model: iteration.model,
174
173
  temperature: iteration.temperature,
175
174
  responseFormat: "text",
176
175
  reasoningEffort: iteration.reasoningEffort,
177
- messages: messages.filter((x) => x.role !== "system"),
176
+ messages,
178
177
  stopSequences: ctx.version.getStopTokens(),
179
178
  meta: metadata ? { metadata } : void 0
180
179
  };
181
- let output;
180
+ let responseMetadata;
182
181
  let raw;
183
182
  let assistantResponse;
184
183
  let timeToFirstToken;
@@ -223,18 +222,20 @@ var generateCode = async ({
223
222
  }
224
223
  }
225
224
  };
226
- if (typeof cognitive.generateContentStream === "function") {
225
+ if (typeof cognitive.generateTextStream === "function") {
227
226
  const parser = new StreamingMessageParser();
228
227
  const fence = new LeadingFenceFilter();
229
228
  const streamController = createJoinedAbortController([controller.signal]);
230
229
  const requestedAt = Date.now();
231
- const stream = cognitive.generateContentStream({
232
- ...input,
233
- signal: streamController.signal,
234
- // Passed through to the cognitive v2 request: fall back to the next
235
- // model/provider when the first token takes too long
236
- ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
237
- });
230
+ const stream = cognitive.generateTextStream(
231
+ {
232
+ ...input,
233
+ // Passed through to the cognitive request: fall back to the next
234
+ // model/provider when the first token takes too long
235
+ ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
236
+ },
237
+ { signal: streamController.signal }
238
+ );
238
239
  const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, ctx.maxTimeToFirstToken ?? 0);
239
240
  const nextChunk = async () => {
240
241
  let timer;
@@ -259,9 +260,11 @@ var generateCode = async ({
259
260
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
260
261
  }
261
262
  if (chunk.done) {
262
- output = chunk.value;
263
263
  break;
264
264
  }
265
+ if ((_a = chunk.value) == null ? void 0 : _a.metadata) {
266
+ responseMetadata = chunk.value.metadata;
267
+ }
265
268
  const delta = (_b = chunk.value) == null ? void 0 : _b.output;
266
269
  if (!delta) {
267
270
  continue;
@@ -271,6 +274,9 @@ var generateCode = async ({
271
274
  raw += delta;
272
275
  await dispatchSends(parser.push(fence.push(delta)));
273
276
  }
277
+ if (!responseMetadata) {
278
+ throw new CognitiveError("LLM streaming completed without metadata");
279
+ }
274
280
  const remaining = fence.flush();
275
281
  if (remaining) {
276
282
  await dispatchSends(parser.push(remaining));
@@ -278,15 +284,15 @@ var generateCode = async ({
278
284
  await dispatchSends(parser.finish());
279
285
  assistantResponse = toParsedAssistantResponse(parser.items, raw);
280
286
  } else {
281
- output = await cognitive.generateContent(input).catch((thrown) => {
287
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
282
288
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
283
289
  });
284
- const out = typeof ((_d = (_c = output.output.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.content) === "string" ? output.output.choices[0].content : null;
285
- if (!out) {
290
+ if (!response.output) {
286
291
  throw new CognitiveError("LLM did not return any text output");
287
292
  }
288
- raw = out;
289
- assistantResponse = ctx.version.parseAssistantResponse(out);
293
+ responseMetadata = response.metadata;
294
+ raw = response.output;
295
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
290
296
  for (const send of assistantResponse.sends) {
291
297
  await (onSend == null ? void 0 : onSend(send));
292
298
  }
@@ -294,29 +300,35 @@ var generateCode = async ({
294
300
  iteration.code = assistantResponse.code;
295
301
  iteration.sends = assistantResponse.sends;
296
302
  iteration.next = assistantResponse.next;
303
+ const usage = responseMetadata.usage;
297
304
  iteration.llm = {
298
- cached: output.meta.cached || false,
305
+ cached: responseMetadata.cached || false,
299
306
  ended_at: Date.now(),
300
307
  started_at: startedAt,
301
308
  status: "success",
302
- tokens: output.meta.tokens.input + output.meta.tokens.output,
303
- spend: output.meta.cost.input + output.meta.cost.output,
309
+ tokens: usage.inputTokens + usage.outputTokens,
310
+ spend: responseMetadata.cost ?? usage.inputCost + usage.outputCost,
304
311
  output: assistantResponse.raw,
305
- model: `${output.meta.model.integration}:${output.meta.model.model}`,
312
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
306
313
  time_to_first_token: timeToFirstToken,
307
314
  time_to_last_token: timeToLastToken,
308
- usage: output.output.usage
315
+ usage: {
316
+ inputTokens: usage.inputTokens,
317
+ inputCost: usage.inputCost,
318
+ outputTokens: usage.outputTokens,
319
+ outputCost: usage.outputCost
320
+ }
309
321
  };
310
322
  if (iteration.tokens) {
311
- iteration.tokens.input = output.meta.tokens.input;
312
- iteration.tokens.output = output.meta.tokens.output;
313
- iteration.tokens.total = output.meta.tokens.input + output.meta.tokens.output;
323
+ iteration.tokens.input = usage.inputTokens;
324
+ iteration.tokens.output = usage.outputTokens;
325
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
314
326
  }
315
327
  traces.push({
316
328
  type: "llm_call_success",
317
329
  started_at: startedAt,
318
330
  ended_at: iteration.llm.ended_at,
319
- model: model.ref,
331
+ model: model.id,
320
332
  code: iteration.code ?? ""
321
333
  });
322
334
  };
@@ -727,7 +739,7 @@ var executeContextInternal = async (props) => {
727
739
  const controller = createJoinedAbortController([props.signal]);
728
740
  const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
729
741
  const client = props.client ?? new Client();
730
- const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : CognitiveBeta.isBetaClient(client) ? cognitiveFromBeta(client) : new Cognitive({ client, __experimental_beta: true });
742
+ const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : new Cognitive({ client });
731
743
  const ctx = new Context({
732
744
  chat: props.chat,
733
745
  instructions: props.instructions,
@@ -0,0 +1,8 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkDDSJTR6Qcjs = require('./chunk-DDSJTR6Q.cjs');
4
+ require('./chunk-GOWPACSK.cjs');
5
+ require('./chunk-HC2QZTVT.cjs');
6
+
7
+
8
+ exports.Exit = _chunkDDSJTR6Qcjs.Exit;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  Exit
3
- } from "./chunk-XVVYNOTX.js";
4
- import "./chunk-YX27XM67.js";
3
+ } from "./chunk-HB2G32AK.js";
4
+ import "./chunk-GLXADNTR.js";
5
5
  import "./chunk-34GJUS6U.js";
6
6
  export {
7
7
  Exit