llmz 0.1.5 → 0.2.1

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 (88) hide show
  1. package/README.md +185 -98
  2. package/dist/chat.d.ts +34 -0
  3. package/dist/chunk-665O7CAN.js +788 -0
  4. package/dist/chunk-DD4AZSP5.cjs +788 -0
  5. package/dist/{chunk-EFEF2AL7.js → chunk-DH35WO5G.js} +93 -556
  6. package/dist/chunk-E5NHK3FS.js +1637 -0
  7. package/dist/{chunk-WODK7Y4J.cjs → chunk-ETYFOCWC.cjs} +2 -2
  8. package/dist/{chunk-IRCB4FRM.js → chunk-GC5IQDGV.js} +1 -1
  9. package/dist/{chunk-L74UZONX.js → chunk-HM5H556L.js} +3 -1
  10. package/dist/chunk-I56MPOVG.cjs +62 -0
  11. package/dist/chunk-KWQTYXAT.js +62 -0
  12. package/dist/{chunk-C7T6OJB4.cjs → chunk-MY26EAOP.cjs} +146 -88
  13. package/dist/{chunk-JXD2KJVB.cjs → chunk-WWZ2W4WR.cjs} +103 -566
  14. package/dist/chunk-YGKQEVQQ.cjs +1637 -0
  15. package/dist/{chunk-ZPHRTTQX.cjs → chunk-YQT5G77W.cjs} +3 -1
  16. package/dist/{chunk-TIZWOIDF.js → chunk-ZWUWCRHG.js} +135 -77
  17. package/dist/compiler/compiler.d.ts +7 -2
  18. package/dist/compiler/index.d.ts +1 -1
  19. package/dist/compiler/plugins/async-wrapper.d.ts +11 -0
  20. package/dist/component-2NYFY6CW.cjs +14 -0
  21. package/dist/{component-2Z3KLWLX.js → component-ASNZHQUR.js} +3 -7
  22. package/dist/component.d.ts +3 -10
  23. package/dist/context.d.ts +88 -2
  24. package/dist/{dual-modes-HEXPFVUE.js → dual-modes-RMF7V7ZQ.js} +2 -4
  25. package/dist/dual-modes-ZZY6QPYT.cjs +10 -0
  26. package/dist/{execute-22PSGL7P.cjs → execute-2AGZ5QUN.cjs} +333 -89
  27. package/dist/{execute-ZENBZBWL.js → execute-LNUBLVMZ.js} +323 -79
  28. package/dist/formatting.d.ts +1 -2
  29. package/dist/index.cjs +511 -36
  30. package/dist/index.d.ts +8 -5
  31. package/dist/index.js +495 -20
  32. package/dist/message-stream/index.d.ts +9 -0
  33. package/dist/message-stream/instructions.d.ts +22 -0
  34. package/dist/message-stream/normalizer.d.ts +21 -0
  35. package/dist/message-stream/parser.d.ts +81 -0
  36. package/dist/message-stream/registry.d.ts +14 -0
  37. package/dist/message-stream/replayable.d.ts +27 -0
  38. package/dist/message-stream/sanitize.d.ts +10 -0
  39. package/dist/message-stream/stream.d.ts +54 -0
  40. package/dist/message-stream/types.d.ts +96 -0
  41. package/dist/message-stream/validator.d.ts +23 -0
  42. package/dist/message-stream/validator.test.d.ts +1 -0
  43. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  44. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  45. package/dist/prompts/common.d.ts +5 -5
  46. package/dist/prompts/prompt.d.ts +43 -6
  47. package/dist/prompts/protocol.d.ts +18 -0
  48. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  49. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  50. package/dist/result.d.ts +31 -0
  51. package/dist/runtime/execute.test.d.ts +1 -0
  52. package/dist/runtime/generate.d.ts +24 -1
  53. package/dist/runtime/interpret-result.d.ts +10 -0
  54. package/dist/runtime/types.d.ts +29 -4
  55. package/dist/{tool-DNHVW3KC.js → tool-HTAYKIA2.js} +2 -2
  56. package/dist/{tool-GJ6ZXWS2.cjs → tool-V55GD2FS.cjs} +3 -3
  57. package/dist/truncator-7PGEGCHV.cjs +12 -0
  58. package/dist/{truncator-3U2QUUJJ.js → truncator-OZOBNYON.js} +3 -1
  59. package/dist/truncator.d.ts +2 -0
  60. package/dist/types.d.ts +8 -1
  61. package/dist/{typings-ZTFPPA5W.cjs → typings-S6I6IPTG.cjs} +2 -2
  62. package/dist/{typings-3YV3RDMP.js → typings-SCKZCAPN.js} +1 -1
  63. package/dist/typings-formatter.d.ts +15 -0
  64. package/dist/typings-formatter.test.d.ts +1 -0
  65. package/dist/vm/drivers/quickjs.d.ts +2 -0
  66. package/dist/vm/index.d.ts +7 -0
  67. package/dist/vm/instrument.d.ts +1 -1
  68. package/dist/{vm-PYCKS77H.js → vm-44H4UKI2.js} +5 -4
  69. package/dist/{vm-VHB67FVH.cjs → vm-A3OTQVIR.cjs} +4 -3
  70. package/package.json +6 -7
  71. package/dist/chunk-2O3UTPVH.js +0 -813
  72. package/dist/chunk-3T5IU7OU.js +0 -186
  73. package/dist/chunk-7LMIOS6H.cjs +0 -287
  74. package/dist/chunk-BBX2LDZE.cjs +0 -813
  75. package/dist/chunk-CQ3UJW76.cjs +0 -186
  76. package/dist/chunk-TOGYDN6U.js +0 -287
  77. package/dist/compiler/plugins/async-iterator.d.ts +0 -6
  78. package/dist/compiler/plugins/braces-tsx.d.ts +0 -3
  79. package/dist/compiler/plugins/html-to-markdown.d.ts +0 -21
  80. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +0 -5
  81. package/dist/compiler/plugins/jsx-undefined-vars.d.ts +0 -14
  82. package/dist/component-NNHBHD72.cjs +0 -18
  83. package/dist/dual-modes-LLIWZCHC.cjs +0 -12
  84. package/dist/truncator-3ZN7W6NB.cjs +0 -10
  85. /package/dist/{compiler/plugins/html-to-markdown.test.d.ts → message-stream/instructions.test.d.ts} +0 -0
  86. /package/dist/{compiler/plugins/jsx-undefined-vars.test.d.ts → message-stream/normalizer.test.d.ts} +0 -0
  87. /package/dist/{component.test.d.ts → message-stream/parser.test.d.ts} +0 -0
  88. /package/dist/{vm/vm-jsx.test.d.ts → message-stream/stream.test.d.ts} +0 -0
@@ -142,6 +142,7 @@ var _MessageContentParser = (_class = class {
142
142
  }, _class);
143
143
  var _createRegex = () => new RegExp(REGEXP, "g");
144
144
  var _renderRemainingWrappers = (content) => content.replace(_createRegex(), "$2");
145
+ var stripTruncationTags = (content) => _renderRemainingWrappers(content);
145
146
  var _countTotalTokens = (parts) => parts.reduce((acc, x) => acc + x.reduce((acc2, y) => acc2 + y.tokens, 0), 0);
146
147
  var _getTwoBiggestTruncables = (parts) => {
147
148
  var _a, _b;
@@ -168,4 +169,5 @@ var _getTwoBiggestTruncables = (parts) => {
168
169
 
169
170
 
170
171
 
171
- exports.wrapContent = wrapContent; exports.truncateWrappedContent = truncateWrappedContent;
172
+
173
+ exports.wrapContent = wrapContent; exports.truncateWrappedContent = truncateWrappedContent; exports.stripTruncationTags = stripTruncationTags;
@@ -2,10 +2,10 @@ import {
2
2
  DualModePrompt,
3
3
  extractType,
4
4
  inspect
5
- } from "./chunk-2O3UTPVH.js";
5
+ } from "./chunk-E5NHK3FS.js";
6
6
  import {
7
7
  Tool
8
- } from "./chunk-IRCB4FRM.js";
8
+ } from "./chunk-GC5IQDGV.js";
9
9
  import {
10
10
  LoopExceededError
11
11
  } from "./chunk-WSVDMGMR.js";
@@ -14,10 +14,14 @@ import {
14
14
  } from "./chunk-XVVYNOTX.js";
15
15
  import {
16
16
  assertValidComponent
17
- } from "./chunk-3T5IU7OU.js";
17
+ } from "./chunk-KWQTYXAT.js";
18
18
  import {
19
+ stripTruncationTags,
19
20
  wrapContent
20
- } from "./chunk-L74UZONX.js";
21
+ } from "./chunk-HM5H556L.js";
22
+ import {
23
+ getTokenizer
24
+ } from "./chunk-YX27XM67.js";
21
25
  import {
22
26
  cloneDeep_default,
23
27
  isPlainObject_default,
@@ -777,6 +781,33 @@ var ExecutionResult = class {
777
781
  get iterations() {
778
782
  return this.context.iterations ?? [];
779
783
  }
784
+ /**
785
+ * Gets the total token usage of the execution, aggregated across all iterations.
786
+ *
787
+ * `input`/`output` are the provider-reported token counts of every LLM call made
788
+ * during the execution. Per-iteration detail (including the measured context size
789
+ * breakdown by prompt part) is available on each iteration's `tokens` property.
790
+ *
791
+ * @example
792
+ * ```typescript
793
+ * const result = await execute({ ... })
794
+ * console.log(`Execution used ${result.tokens.total} tokens`)
795
+ *
796
+ * for (const iteration of result.iterations) {
797
+ * console.log(iteration.id, iteration.tokens?.context)
798
+ * }
799
+ * ```
800
+ */
801
+ get tokens() {
802
+ var _a, _b;
803
+ let input = 0;
804
+ let output = 0;
805
+ for (const iteration of this.iterations) {
806
+ input += ((_a = iteration.tokens) == null ? void 0 : _a.input) ?? 0;
807
+ output += ((_b = iteration.tokens) == null ? void 0 : _b.output) ?? 0;
808
+ }
809
+ return { input, output, total: input + output };
810
+ }
780
811
  };
781
812
  var SuccessExecutionResult = class extends ExecutionResult {
782
813
  result;
@@ -959,8 +990,18 @@ var Iteration = class {
959
990
  id;
960
991
  messages;
961
992
  code;
993
+ /** Messages (`■send` blocks) parsed from the assistant response, in order. */
994
+ sends;
995
+ /** The `■next` exit parsed from the assistant response, if any. */
996
+ next;
962
997
  traces;
963
998
  variables;
999
+ /**
1000
+ * Token usage of this iteration's LLM call. The `context` breakdown is measured
1001
+ * when the prompt is assembled; `input`/`output` are filled in once the LLM call
1002
+ * completes, from the provider-reported usage.
1003
+ */
1004
+ tokens;
964
1005
  started_ts;
965
1006
  ended_ts;
966
1007
  status;
@@ -994,7 +1035,7 @@ var Iteration = class {
994
1035
  return this._parameters.reasoningEffort;
995
1036
  }
996
1037
  get exits() {
997
- const exits = [...this._parameters.exits, ThinkExit];
1038
+ const exits = [...this._parameters.exits];
998
1039
  if (this.isChatEnabled) {
999
1040
  exits.push(ListenExit);
1000
1041
  }
@@ -1048,7 +1089,7 @@ var Iteration = class {
1048
1089
  return null;
1049
1090
  }
1050
1091
  get isChatEnabled() {
1051
- return this._parameters.tools.find((x) => x.name.toLowerCase() === "message") !== void 0;
1092
+ return this._parameters.components.length > 0;
1052
1093
  }
1053
1094
  constructor(props) {
1054
1095
  this.id = props.id;
@@ -1082,6 +1123,7 @@ var Iteration = class {
1082
1123
  status: this.status,
1083
1124
  mutations: [...this._mutations.values()],
1084
1125
  llm: this.llm,
1126
+ tokens: this.tokens,
1085
1127
  transcript: [...this._parameters.transcript],
1086
1128
  tools: this._parameters.tools.map((tool) => tool.toJSON()),
1087
1129
  objects: this._parameters.objects.map((obj) => obj.toJSON()),
@@ -1107,6 +1149,16 @@ var Context = class {
1107
1149
  timeout = 6e4;
1108
1150
  // Default timeout of 60 seconds
1109
1151
  loop;
1152
+ /**
1153
+ * Optional cap on the model's context window. The effective limit is
1154
+ * `min(maxTokens, model's max input tokens)`.
1155
+ */
1156
+ maxTokens;
1157
+ /**
1158
+ * Maximum time to wait for the first streamed token, in milliseconds,
1159
+ * before the cognitive service falls back to the next model/provider.
1160
+ */
1161
+ maxTimeToFirstToken;
1110
1162
  metadata;
1111
1163
  snapshot;
1112
1164
  iteration = 0;
@@ -1121,13 +1173,15 @@ var Context = class {
1121
1173
  );
1122
1174
  }
1123
1175
  const parameters = await this._refreshIterationParameters();
1124
- const messages = await this._getIterationMessages(parameters);
1176
+ const { messages, parts } = await this._getIterationMessages(parameters);
1177
+ const contextTokens = this._measureContextTokens(messages, parts);
1125
1178
  const iteration = new Iteration({
1126
1179
  id: `${this.id}_${this.iterations.length + 1}`,
1127
1180
  variables: this._getIterationVariables(),
1128
1181
  parameters,
1129
1182
  messages
1130
1183
  });
1184
+ iteration.tokens = { input: 0, output: 0, total: 0, context: contextTokens };
1131
1185
  this.iterations.push(iteration);
1132
1186
  this.iteration = this.iterations.length;
1133
1187
  this.snapshot = void 0;
@@ -1155,72 +1209,80 @@ var Context = class {
1155
1209
  }
1156
1210
  return variables;
1157
1211
  }
1212
+ /**
1213
+ * Measures the token size of each part of the prompt (pre-truncation).
1214
+ * The named parts come from the system prompt; everything else in the system
1215
+ * message is `framework`. Non-system messages count towards `iterations`,
1216
+ * except the very first user message of a fresh execution (task recap),
1217
+ * which is prompt scaffolding.
1218
+ */
1219
+ _measureContextTokens(messages, parts) {
1220
+ const tokenizer = getTokenizer();
1221
+ const countText = (text) => (text == null ? void 0 : text.length) ? tokenizer.count(stripTruncationTags(text)) : 0;
1222
+ const countMessage = (message) => {
1223
+ if (typeof message.content === "string") {
1224
+ return countText(message.content);
1225
+ }
1226
+ if (Array.isArray(message.content)) {
1227
+ return message.content.reduce((acc, part) => acc + (part.type === "text" ? countText(part.text) : 0), 0);
1228
+ }
1229
+ return 0;
1230
+ };
1231
+ const instructions = countText(parts.instructions);
1232
+ const tools = countText(parts.tools);
1233
+ const transcript = countText(parts.transcript);
1234
+ const protocol = countText(parts.protocol);
1235
+ const systemTokens = messages.filter((x) => x.role === "system").reduce((acc, x) => acc + countMessage(x), 0);
1236
+ const otherTokens = messages.filter((x) => x.role !== "system").reduce((acc, x) => acc + countMessage(x), 0);
1237
+ const isFirstIteration = this.iterations.length === 0 && !this.snapshot;
1238
+ const framework = Math.max(0, systemTokens - (instructions + tools + transcript + protocol));
1239
+ const iterations = isFirstIteration ? 0 : otherTokens;
1240
+ return {
1241
+ total: framework + instructions + tools + transcript + protocol + iterations + (isFirstIteration ? otherTokens : 0),
1242
+ framework: framework + (isFirstIteration ? otherTokens : 0),
1243
+ instructions,
1244
+ tools,
1245
+ transcript,
1246
+ protocol,
1247
+ iterations
1248
+ };
1249
+ }
1158
1250
  async _getIterationMessages(parameters) {
1159
1251
  var _a, _b, _c, _d, _e, _f;
1160
1252
  const lastIteration = this.iterations.at(-1);
1253
+ const promptProps = {
1254
+ globalTools: parameters.tools,
1255
+ objects: parameters.objects,
1256
+ instructions: parameters.instructions,
1257
+ transcript: parameters.transcript,
1258
+ // ListenExit is protocol-level in chat mode: it must be documented alongside user-defined exits
1259
+ exits: parameters.components.length ? [...parameters.exits, ListenExit] : parameters.exits,
1260
+ components: parameters.components
1261
+ };
1262
+ const { message: systemMessage, parts } = await this.version.getSystemMessage(promptProps);
1263
+ const withParts = (messages) => ({ messages, parts });
1161
1264
  if (((_a = this.snapshot) == null ? void 0 : _a.status.type) === "resolved") {
1162
- return [
1163
- await this.version.getSystemMessage({
1164
- globalTools: parameters.tools,
1165
- objects: parameters.objects,
1166
- instructions: parameters.instructions,
1167
- transcript: parameters.transcript,
1168
- exits: parameters.exits,
1169
- components: parameters.components
1170
- }),
1265
+ return withParts([
1266
+ systemMessage,
1171
1267
  this.version.getSnapshotResolvedMessage({
1172
1268
  snapshot: this.snapshot
1173
1269
  })
1174
- ];
1270
+ ]);
1175
1271
  }
1176
1272
  if (((_b = this.snapshot) == null ? void 0 : _b.status.type) === "rejected") {
1177
- return [
1178
- await this.version.getSystemMessage({
1179
- globalTools: parameters.tools,
1180
- objects: parameters.objects,
1181
- instructions: parameters.instructions,
1182
- transcript: parameters.transcript,
1183
- exits: parameters.exits,
1184
- components: parameters.components
1185
- }),
1273
+ return withParts([
1274
+ systemMessage,
1186
1275
  this.version.getSnapshotRejectedMessage({
1187
1276
  snapshot: this.snapshot
1188
1277
  })
1189
- ];
1278
+ ]);
1190
1279
  }
1191
1280
  if (!lastIteration) {
1192
- return [
1193
- await this.version.getSystemMessage({
1194
- globalTools: parameters.tools,
1195
- objects: parameters.objects,
1196
- instructions: parameters.instructions,
1197
- transcript: parameters.transcript,
1198
- exits: parameters.exits,
1199
- components: parameters.components
1200
- }),
1201
- await this.version.getInitialUserMessage({
1202
- globalTools: parameters.tools,
1203
- objects: parameters.objects,
1204
- instructions: parameters.instructions,
1205
- transcript: parameters.transcript,
1206
- exits: parameters.exits,
1207
- components: parameters.components
1208
- })
1209
- ];
1281
+ return withParts([systemMessage, await this.version.getInitialUserMessage(promptProps)]);
1210
1282
  }
1211
- const lastIterationMessages = [
1212
- await this.version.getSystemMessage({
1213
- globalTools: parameters.tools,
1214
- objects: parameters.objects,
1215
- instructions: parameters.instructions,
1216
- transcript: parameters.transcript,
1217
- exits: parameters.exits,
1218
- components: parameters.components
1219
- }),
1220
- ...lastIteration.messages.filter((x) => x.role !== "system")
1221
- ];
1283
+ const lastIterationMessages = [systemMessage, ...lastIteration.messages.filter((x) => x.role !== "system")];
1222
1284
  if ((lastIteration == null ? void 0 : lastIteration.status.type) === "thinking_requested") {
1223
- return [
1285
+ return withParts([
1224
1286
  ...lastIterationMessages,
1225
1287
  {
1226
1288
  role: "assistant",
@@ -1230,10 +1292,10 @@ var Context = class {
1230
1292
  reason: lastIteration.status.thinking_requested.reason,
1231
1293
  variables: lastIteration.status.thinking_requested.variables
1232
1294
  })
1233
- ];
1295
+ ]);
1234
1296
  }
1235
1297
  if ((lastIteration == null ? void 0 : lastIteration.status.type) === "exit_error") {
1236
- return [
1298
+ return withParts([
1237
1299
  ...lastIterationMessages,
1238
1300
  {
1239
1301
  role: "assistant",
@@ -1243,10 +1305,10 @@ var Context = class {
1243
1305
  code: lastIteration.code ?? "// No code generated",
1244
1306
  message: `Invalid return statement (action: ${lastIteration.status.exit_error.exit}): ${lastIteration.status.exit_error.message}`
1245
1307
  })
1246
- ];
1308
+ ]);
1247
1309
  }
1248
1310
  if ((lastIteration == null ? void 0 : lastIteration.status.type) === "invalid_code_error") {
1249
- return [
1311
+ return withParts([
1250
1312
  ...lastIterationMessages,
1251
1313
  {
1252
1314
  role: "assistant",
@@ -1256,10 +1318,10 @@ var Context = class {
1256
1318
  code: lastIteration.code ?? "// No code generated",
1257
1319
  message: lastIteration.status.invalid_code_error.message
1258
1320
  })
1259
- ];
1321
+ ]);
1260
1322
  }
1261
1323
  if ((lastIteration == null ? void 0 : lastIteration.status.type) === "execution_error") {
1262
- return [
1324
+ return withParts([
1263
1325
  ...lastIterationMessages,
1264
1326
  {
1265
1327
  role: "assistant",
@@ -1269,7 +1331,7 @@ var Context = class {
1269
1331
  message: lastIteration.status.execution_error.message,
1270
1332
  stacktrace: lastIteration.status.execution_error.stack
1271
1333
  })
1272
- ];
1334
+ ]);
1273
1335
  }
1274
1336
  throw new Error(
1275
1337
  `Unexpected iteration status: ${lastIteration == null ? void 0 : lastIteration.status.type}. This is likely a bug, please report it.`
@@ -1312,18 +1374,6 @@ var Context = class {
1312
1374
  "boolean",
1313
1375
  "array"
1314
1376
  ];
1315
- const MessageTool = this.chat && components.length ? new Tool({
1316
- name: "Message",
1317
- description: "Send a message to the user",
1318
- aliases: Array.from(
1319
- /* @__PURE__ */ new Set(["message", ...components.flatMap((x) => [x.definition.name, ...x.definition.aliases ?? []])])
1320
- ),
1321
- handler: async (message) => {
1322
- var _a2, _b2;
1323
- return await ((_b2 = (_a2 = this.chat) == null ? void 0 : _a2.handler) == null ? void 0 : _b2.call(_a2, message));
1324
- }
1325
- }) : null;
1326
- const allTools = MessageTool ? [MessageTool, ...tools] : tools;
1327
1377
  for (const tool of tools) {
1328
1378
  for (let name of [...tool.aliases, tool.name]) {
1329
1379
  name = name.toLowerCase();
@@ -1380,7 +1430,7 @@ var Context = class {
1380
1430
  }
1381
1431
  return {
1382
1432
  transcript,
1383
- tools: allTools,
1433
+ tools,
1384
1434
  objects,
1385
1435
  exits,
1386
1436
  instructions,
@@ -1405,9 +1455,17 @@ var Context = class {
1405
1455
  this.iterations = [];
1406
1456
  this.metadata = props.metadata ?? {};
1407
1457
  this.snapshot = props.snapshot;
1458
+ this.maxTokens = props.maxTokens;
1459
+ this.maxTimeToFirstToken = props.maxTimeToFirstToken;
1408
1460
  if (this.loop < 1 || this.loop > 100) {
1409
1461
  throw new Error("Invalid loop. Expected a number between 1 and 100.");
1410
1462
  }
1463
+ if (this.maxTokens !== void 0 && (!Number.isFinite(this.maxTokens) || this.maxTokens < 1)) {
1464
+ throw new Error("Invalid maxTokens. Expected a positive number.");
1465
+ }
1466
+ if (this.maxTimeToFirstToken !== void 0 && (!Number.isFinite(this.maxTimeToFirstToken) || this.maxTimeToFirstToken < 1)) {
1467
+ throw new Error("Invalid maxTimeToFirstToken. Expected a positive number of milliseconds.");
1468
+ }
1411
1469
  }
1412
1470
  toJSON() {
1413
1471
  var _a;
@@ -2,8 +2,6 @@ import { type TransformOptions } from '@babel/core';
2
2
  import { ToolCallEntry } from './plugins/track-tool-calls.js';
3
3
  export declare const DEFAULT_TRANSFORM_OPTIONS: TransformOptions;
4
4
  export declare const Identifiers: {
5
- JSXFnIdentifier: string;
6
- AsyncIterYieldFnIdentifier: string;
7
5
  ConsoleObjIdentifier: string;
8
6
  LineTrackingFnIdentifier: string;
9
7
  VariableTrackingFnIdentifier: string;
@@ -12,6 +10,13 @@ export declare const Identifiers: {
12
10
  CommentFnIdentifier: string;
13
11
  };
14
12
  export type CompiledCode = ReturnType<typeof compile>;
13
+ /**
14
+ * Whether the code contains a top-level `return` statement (one that would
15
+ * return from the generated code itself, not from a nested function). Unlike a
16
+ * regex, this ignores `return` inside comments, strings and nested functions.
17
+ * Falls back to a word-boundary match if the code cannot be parsed.
18
+ */
19
+ export declare function hasTopLevelReturn(code: string): boolean;
15
20
  export declare function compile(code: string): {
16
21
  code: string;
17
22
  codeWithMarkers: string;
@@ -1,2 +1,2 @@
1
- export { Identifiers, compile } from './compiler.js';
1
+ export { Identifiers, compile, hasTopLevelReturn } from './compiler.js';
2
2
  export type { CompiledCode } from './compiler.js';
@@ -0,0 +1,11 @@
1
+ export declare const USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
2
+ export declare const USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
3
+ /**
4
+ * Wraps user code in an async function so top-level `await` and `return` parse,
5
+ * and so plugins can target the `__fn__` declaration. The wrapper is removed
6
+ * after transformation — drivers re-wrap the bare statements themselves.
7
+ */
8
+ export declare const AsyncWrapper: {
9
+ preProcessing: (code: string) => string;
10
+ postProcessing: (code: string) => string;
11
+ };
@@ -0,0 +1,14 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+ var _chunkI56MPOVGcjs = require('./chunk-I56MPOVG.cjs');
7
+ require('./chunk-5ZF6NTYI.cjs');
8
+ require('./chunk-HC2QZTVT.cjs');
9
+
10
+
11
+
12
+
13
+
14
+ exports.Component = _chunkI56MPOVGcjs.Component; exports.assertValidComponent = _chunkI56MPOVGcjs.assertValidComponent; exports.isAnyComponent = _chunkI56MPOVGcjs.isAnyComponent; exports.isComponent = _chunkI56MPOVGcjs.isComponent;
@@ -1,18 +1,14 @@
1
1
  import {
2
2
  Component,
3
3
  assertValidComponent,
4
- getComponentReference,
5
4
  isAnyComponent,
6
- isComponent,
7
- renderToTsx
8
- } from "./chunk-3T5IU7OU.js";
5
+ isComponent
6
+ } from "./chunk-KWQTYXAT.js";
9
7
  import "./chunk-XTEHT2TK.js";
10
8
  import "./chunk-34GJUS6U.js";
11
9
  export {
12
10
  Component,
13
11
  assertValidComponent,
14
- getComponentReference,
15
12
  isAnyComponent,
16
- isComponent,
17
- renderToTsx
13
+ isComponent
18
14
  };
@@ -10,13 +10,12 @@ export type ComponentChild = {
10
10
  component: ComponentDefinition;
11
11
  };
12
12
  export declare function assertValidComponent(component: ComponentDefinition): asserts component is ComponentDefinition;
13
- export declare function getComponentReference(component: ComponentDefinition): string;
14
13
  export type DefaultComponentDefinition<T extends z.ZodObject<any> = z.ZodObject<any>> = {
15
14
  type: 'default';
16
15
  name: string;
17
16
  aliases: string[];
18
17
  description: string;
19
- examples: ExampleUsage[];
18
+ examples?: ExampleUsage[];
20
19
  default: {
21
20
  props: T;
22
21
  children: Array<ComponentChild>;
@@ -27,7 +26,7 @@ export type LeafComponentDefinition<T extends z.ZodObject<any> = z.ZodObject<any
27
26
  name: string;
28
27
  description: string;
29
28
  aliases?: string[];
30
- examples: ExampleUsage[];
29
+ examples?: ExampleUsage[];
31
30
  leaf: {
32
31
  props: T;
33
32
  };
@@ -37,7 +36,7 @@ export type ContainerComponentDefinition<T extends z.ZodObject<any> = z.ZodObjec
37
36
  name: string;
38
37
  description: string;
39
38
  aliases?: string[];
40
- examples: ExampleUsage[];
39
+ examples?: ExampleUsage[];
41
40
  container: {
42
41
  props: T;
43
42
  children: Array<ComponentChild>;
@@ -54,10 +53,4 @@ export declare class Component<T extends ComponentDefinition = ComponentDefiniti
54
53
  }
55
54
  export declare function isComponent<T extends ComponentDefinition>(rendered: RenderedComponent<any>, component: Component<T>): rendered is RenderedComponent<ExtractComponentProps<T>>;
56
55
  export declare function isAnyComponent(message: unknown): message is RenderedComponent;
57
- /**
58
- * Converts a RenderedComponent back to TSX code
59
- * @param component The rendered component to convert
60
- * @returns A string containing the TSX representation of the component
61
- */
62
- export declare function renderToTsx(component: RenderedComponent): string;
63
56
  export {};
package/dist/context.d.ts CHANGED
@@ -7,11 +7,49 @@ import { Exit } from './exit.js';
7
7
  import { ValueOrGetter } from './getter.js';
8
8
  import { HookedArray } from './handlers.js';
9
9
  import { ObjectInstance } from './objects.js';
10
- import { LLMzPrompts, Prompt } from './prompts/prompt.js';
10
+ import { LLMzPrompts, ParsedNext, ParsedSend, Prompt } from './prompts/prompt.js';
11
11
  import { Snapshot } from './snapshots.js';
12
12
  import { Tool } from './tool.js';
13
13
  import { Transcript, TranscriptArray } from './transcript.js';
14
14
  import { ObjectMutation, Serializable, Trace } from './types.js';
15
+ /**
16
+ * Tokenizer-measured size of each part of the prompt, before truncation.
17
+ * Useful to understand what is eating up the context window.
18
+ */
19
+ export type ContextTokens = {
20
+ /** Total measured size of the prompt (sum of all the parts below). */
21
+ total: number;
22
+ /** Static prompt scaffolding: response format, VM rules, security guidelines, recap. */
23
+ framework: number;
24
+ /** The identity / instructions section. */
25
+ instructions: number;
26
+ /** tools.d.ts — tools, objects and variable typings. */
27
+ tools: number;
28
+ /** The conversation transcript. */
29
+ transcript: number;
30
+ /** The ■ protocol reference documenting components and exits. */
31
+ protocol: number;
32
+ /** Messages carried over from previous iterations (assistant responses, execution results, errors). */
33
+ iterations: number;
34
+ };
35
+ /** Token usage of a single iteration's LLM call. */
36
+ export type TokenUsage = {
37
+ /** Input tokens consumed, as reported by the LLM provider. Zero until the call completes. */
38
+ input: number;
39
+ /** Output tokens produced, as reported by the LLM provider. Zero until the call completes. */
40
+ output: number;
41
+ /** Total tokens (input + output). */
42
+ total: number;
43
+ /**
44
+ * The effective context window limit of this call, in tokens:
45
+ * `min(options.maxTokens, model's max input tokens)`. Use it to compute the
46
+ * percentage of context used (e.g. `context.total / limit`).
47
+ * Undefined until the LLM call starts.
48
+ */
49
+ limit?: number;
50
+ /** Measured context size by part of the prompt (pre-truncation). */
51
+ context: ContextTokens;
52
+ };
15
53
  export type IterationParameters = {
16
54
  transcript: TranscriptArray;
17
55
  tools: Tool[];
@@ -51,7 +89,8 @@ export declare namespace IterationStatuses {
51
89
  type: 'thinking_requested';
52
90
  thinking_requested: {
53
91
  reason?: string;
54
- variables: Record<string, unknown>;
92
+ /** The value returned by the executed code (or the context provided by a ThinkSignal). */
93
+ variables: unknown;
55
94
  metadata?: Record<string, unknown>;
56
95
  };
57
96
  };
@@ -327,7 +366,10 @@ export declare namespace Iteration {
327
366
  spend: number;
328
367
  output: string;
329
368
  model: string;
369
+ time_to_first_token?: number;
370
+ time_to_last_token?: number;
330
371
  };
372
+ tokens?: TokenUsage;
331
373
  transcript: Transcript.Message[];
332
374
  tools: Tool.JSON[];
333
375
  objects: ObjectInstance.JSON[];
@@ -342,8 +384,18 @@ export declare class Iteration implements Serializable<Iteration.JSON> {
342
384
  id: string;
343
385
  messages: LLMzPrompts.Message[];
344
386
  code?: string;
387
+ /** Messages (`■send` blocks) parsed from the assistant response, in order. */
388
+ sends?: ParsedSend[];
389
+ /** The `■next` exit parsed from the assistant response, if any. */
390
+ next?: ParsedNext;
345
391
  traces: HookedArray<Trace>;
346
392
  variables: Record<string, any>;
393
+ /**
394
+ * Token usage of this iteration's LLM call. The `context` breakdown is measured
395
+ * when the prompt is assembled; `input`/`output` are filled in once the LLM call
396
+ * completes, from the provider-reported usage.
397
+ */
398
+ tokens?: TokenUsage;
347
399
  started_ts: number;
348
400
  ended_ts?: number;
349
401
  status: IterationStatus;
@@ -369,6 +421,10 @@ export declare class Iteration implements Serializable<Iteration.JSON> {
369
421
  spend: number;
370
422
  output: string;
371
423
  model: string;
424
+ /** Milliseconds between the LLM call start and the first streamed token. Only set on streaming clients. */
425
+ time_to_first_token?: number;
426
+ /** Milliseconds between the LLM call start and the last streamed token. Only set on streaming clients. */
427
+ time_to_last_token?: number;
372
428
  usage: {
373
429
  inputCost: number;
374
430
  outputCost: number;
@@ -420,6 +476,10 @@ export declare class Iteration implements Serializable<Iteration.JSON> {
420
476
  spend: number;
421
477
  output: string;
422
478
  model: string;
479
+ /** Milliseconds between the LLM call start and the first streamed token. Only set on streaming clients. */
480
+ time_to_first_token?: number;
481
+ /** Milliseconds between the LLM call start and the last streamed token. Only set on streaming clients. */
482
+ time_to_last_token?: number;
423
483
  usage: {
424
484
  inputCost: number;
425
485
  outputCost: number;
@@ -427,6 +487,7 @@ export declare class Iteration implements Serializable<Iteration.JSON> {
427
487
  outputTokens: number;
428
488
  };
429
489
  } | undefined;
490
+ tokens: TokenUsage | undefined;
430
491
  transcript: Transcript.Message[];
431
492
  tools: {
432
493
  name: string;
@@ -493,12 +554,30 @@ export declare class Context implements Serializable<Context.JSON> {
493
554
  version: Prompt;
494
555
  timeout: number;
495
556
  loop: number;
557
+ /**
558
+ * Optional cap on the model's context window. The effective limit is
559
+ * `min(maxTokens, model's max input tokens)`.
560
+ */
561
+ maxTokens?: number;
562
+ /**
563
+ * Maximum time to wait for the first streamed token, in milliseconds,
564
+ * before the cognitive service falls back to the next model/provider.
565
+ */
566
+ maxTimeToFirstToken?: number;
496
567
  metadata: Record<string, any>;
497
568
  snapshot?: Snapshot;
498
569
  iteration: number;
499
570
  iterations: Iteration[];
500
571
  nextIteration(): Promise<Iteration>;
501
572
  private _getIterationVariables;
573
+ /**
574
+ * Measures the token size of each part of the prompt (pre-truncation).
575
+ * The named parts come from the system prompt; everything else in the system
576
+ * message is `framework`. Non-system messages count towards `iterations`,
577
+ * except the very first user message of a fresh execution (task recap),
578
+ * which is prompt scaffolding.
579
+ */
580
+ private _measureContextTokens;
502
581
  private _getIterationMessages;
503
582
  private _refreshIterationParameters;
504
583
  constructor(props: {
@@ -514,6 +593,8 @@ export declare class Context implements Serializable<Context.JSON> {
514
593
  metadata?: Record<string, any>;
515
594
  snapshot?: Snapshot;
516
595
  timeout?: number;
596
+ maxTokens?: number;
597
+ maxTimeToFirstToken?: number;
517
598
  });
518
599
  toJSON(): {
519
600
  id: string;
@@ -539,6 +620,10 @@ export declare class Context implements Serializable<Context.JSON> {
539
620
  spend: number;
540
621
  output: string;
541
622
  model: string;
623
+ /** Milliseconds between the LLM call start and the first streamed token. Only set on streaming clients. */
624
+ time_to_first_token?: number;
625
+ /** Milliseconds between the LLM call start and the last streamed token. Only set on streaming clients. */
626
+ time_to_last_token?: number;
542
627
  usage: {
543
628
  inputCost: number;
544
629
  outputCost: number;
@@ -546,6 +631,7 @@ export declare class Context implements Serializable<Context.JSON> {
546
631
  outputTokens: number;
547
632
  };
548
633
  } | undefined;
634
+ tokens: TokenUsage | undefined;
549
635
  transcript: Transcript.Message[];
550
636
  tools: {
551
637
  name: string;