llmz 0.1.5 → 0.2.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 (75) hide show
  1. package/README.md +185 -98
  2. package/dist/chat.d.ts +34 -0
  3. package/dist/{chunk-TIZWOIDF.js → chunk-33AB6SVX.js} +134 -76
  4. package/dist/{chunk-EFEF2AL7.js → chunk-DH35WO5G.js} +93 -556
  5. package/dist/chunk-E5NHK3FS.js +1637 -0
  6. package/dist/{chunk-L74UZONX.js → chunk-HM5H556L.js} +3 -1
  7. package/dist/chunk-I56MPOVG.cjs +62 -0
  8. package/dist/{chunk-C7T6OJB4.cjs → chunk-IKLFMVSW.cjs} +144 -86
  9. package/dist/chunk-KWQTYXAT.js +62 -0
  10. package/dist/{chunk-JXD2KJVB.cjs → chunk-WWZ2W4WR.cjs} +103 -566
  11. package/dist/chunk-YGKQEVQQ.cjs +1637 -0
  12. package/dist/{chunk-ZPHRTTQX.cjs → chunk-YQT5G77W.cjs} +3 -1
  13. package/dist/compiler/compiler.d.ts +7 -2
  14. package/dist/compiler/index.d.ts +1 -1
  15. package/dist/compiler/plugins/async-wrapper.d.ts +11 -0
  16. package/dist/component-2NYFY6CW.cjs +14 -0
  17. package/dist/{component-2Z3KLWLX.js → component-ASNZHQUR.js} +3 -7
  18. package/dist/component.d.ts +3 -10
  19. package/dist/context.d.ts +88 -2
  20. package/dist/{dual-modes-HEXPFVUE.js → dual-modes-RMF7V7ZQ.js} +2 -4
  21. package/dist/dual-modes-ZZY6QPYT.cjs +10 -0
  22. package/dist/{execute-22PSGL7P.cjs → execute-BXPFSEVX.cjs} +331 -87
  23. package/dist/{execute-ZENBZBWL.js → execute-HIRXXR6X.js} +321 -77
  24. package/dist/index.cjs +502 -27
  25. package/dist/index.d.ts +8 -5
  26. package/dist/index.js +491 -16
  27. package/dist/message-stream/index.d.ts +9 -0
  28. package/dist/message-stream/instructions.d.ts +22 -0
  29. package/dist/message-stream/normalizer.d.ts +21 -0
  30. package/dist/message-stream/parser.d.ts +81 -0
  31. package/dist/message-stream/registry.d.ts +14 -0
  32. package/dist/message-stream/replayable.d.ts +27 -0
  33. package/dist/message-stream/sanitize.d.ts +10 -0
  34. package/dist/message-stream/stream.d.ts +54 -0
  35. package/dist/message-stream/types.d.ts +96 -0
  36. package/dist/message-stream/validator.d.ts +23 -0
  37. package/dist/message-stream/validator.test.d.ts +1 -0
  38. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  39. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  40. package/dist/prompts/common.d.ts +5 -5
  41. package/dist/prompts/prompt.d.ts +43 -6
  42. package/dist/prompts/protocol.d.ts +18 -0
  43. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  44. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  45. package/dist/result.d.ts +31 -0
  46. package/dist/runtime/execute.test.d.ts +1 -0
  47. package/dist/runtime/generate.d.ts +24 -1
  48. package/dist/runtime/interpret-result.d.ts +10 -0
  49. package/dist/runtime/types.d.ts +29 -4
  50. package/dist/truncator-7PGEGCHV.cjs +12 -0
  51. package/dist/{truncator-3U2QUUJJ.js → truncator-OZOBNYON.js} +3 -1
  52. package/dist/truncator.d.ts +2 -0
  53. package/dist/types.d.ts +8 -1
  54. package/dist/vm/drivers/quickjs.d.ts +2 -0
  55. package/dist/vm/index.d.ts +7 -0
  56. package/dist/vm/instrument.d.ts +1 -1
  57. package/dist/{vm-PYCKS77H.js → vm-44H4UKI2.js} +5 -4
  58. package/dist/{vm-VHB67FVH.cjs → vm-A3OTQVIR.cjs} +4 -3
  59. package/package.json +5 -5
  60. package/dist/chunk-2O3UTPVH.js +0 -813
  61. package/dist/chunk-3T5IU7OU.js +0 -186
  62. package/dist/chunk-BBX2LDZE.cjs +0 -813
  63. package/dist/chunk-CQ3UJW76.cjs +0 -186
  64. package/dist/compiler/plugins/async-iterator.d.ts +0 -6
  65. package/dist/compiler/plugins/braces-tsx.d.ts +0 -3
  66. package/dist/compiler/plugins/html-to-markdown.d.ts +0 -21
  67. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +0 -5
  68. package/dist/compiler/plugins/jsx-undefined-vars.d.ts +0 -14
  69. package/dist/component-NNHBHD72.cjs +0 -18
  70. package/dist/dual-modes-LLIWZCHC.cjs +0 -12
  71. package/dist/truncator-3ZN7W6NB.cjs +0 -10
  72. /package/dist/{compiler/plugins/html-to-markdown.test.d.ts → message-stream/instructions.test.d.ts} +0 -0
  73. /package/dist/{compiler/plugins/jsx-undefined-vars.test.d.ts → message-stream/normalizer.test.d.ts} +0 -0
  74. /package/dist/{component.test.d.ts → message-stream/parser.test.d.ts} +0 -0
  75. /package/dist/{vm/vm-jsx.test.d.ts → message-stream/stream.test.d.ts} +0 -0
@@ -2,7 +2,7 @@ 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
8
  } from "./chunk-IRCB4FRM.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;