@theokit/sdk 5.9.2 → 5.11.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 (133) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/{agent-WQ4LLTSY.cjs → agent-5DOR5T3E.cjs} +12 -10
  3. package/dist/{agent-WQ4LLTSY.cjs.map → agent-5DOR5T3E.cjs.map} +1 -1
  4. package/dist/{agent-enXXu447.d.ts → agent-CmKwSyyD.d.ts} +27 -0
  5. package/dist/{agent-GZVZXKME.js → agent-GWKRARAL.js} +11 -9
  6. package/dist/{agent-GZVZXKME.js.map → agent-GWKRARAL.js.map} +1 -1
  7. package/dist/{agent-Dh2YHSLj.d.cts → agent-XMkGzff_.d.cts} +27 -0
  8. package/dist/{chunk-PEIV7LOU.js → chunk-4PHSVR2R.js} +68 -37
  9. package/dist/chunk-4PHSVR2R.js.map +1 -0
  10. package/dist/{chunk-KXKT3HSD.cjs → chunk-5H2GJXGC.cjs} +4 -4
  11. package/dist/{chunk-KXKT3HSD.cjs.map → chunk-5H2GJXGC.cjs.map} +1 -1
  12. package/dist/{chunk-JU76WCW7.cjs → chunk-5OHB5HJF.cjs} +123 -92
  13. package/dist/chunk-5OHB5HJF.cjs.map +1 -0
  14. package/dist/{chunk-EVH3OUMY.js → chunk-74OA5DIM.js} +189 -43
  15. package/dist/chunk-74OA5DIM.js.map +1 -0
  16. package/dist/chunk-7KIN3L2S.js +103 -0
  17. package/dist/chunk-7KIN3L2S.js.map +1 -0
  18. package/dist/{chunk-EXI7EHDN.js → chunk-7Y23B7XX.js} +3 -3
  19. package/dist/{chunk-EXI7EHDN.js.map → chunk-7Y23B7XX.js.map} +1 -1
  20. package/dist/chunk-ASK2OQM5.cjs +84 -0
  21. package/dist/chunk-ASK2OQM5.cjs.map +1 -0
  22. package/dist/{chunk-QY3CIMUV.cjs → chunk-BZKF7TXX.cjs} +192 -44
  23. package/dist/chunk-BZKF7TXX.cjs.map +1 -0
  24. package/dist/{chunk-ZDF2IJKC.js → chunk-DPY2M74T.js} +3 -3
  25. package/dist/{chunk-ZDF2IJKC.js.map → chunk-DPY2M74T.js.map} +1 -1
  26. package/dist/{chunk-X7Z2FEI7.cjs → chunk-FYEHYQ7T.cjs} +8 -8
  27. package/dist/{chunk-X7Z2FEI7.cjs.map → chunk-FYEHYQ7T.cjs.map} +1 -1
  28. package/dist/{chunk-OZLQ6ZFM.js → chunk-IZDDSLL2.js} +4 -3
  29. package/dist/chunk-IZDDSLL2.js.map +1 -0
  30. package/dist/{chunk-DLUCTZ56.cjs → chunk-L3C6CCBG.cjs} +15 -15
  31. package/dist/{chunk-DLUCTZ56.cjs.map → chunk-L3C6CCBG.cjs.map} +1 -1
  32. package/dist/chunk-LZJXEPEQ.js +58 -0
  33. package/dist/chunk-LZJXEPEQ.js.map +1 -0
  34. package/dist/{chunk-FR6COQXZ.cjs → chunk-N7ZIPW2N.cjs} +3 -3
  35. package/dist/{chunk-FR6COQXZ.cjs.map → chunk-N7ZIPW2N.cjs.map} +1 -1
  36. package/dist/{chunk-RX3CFWQ2.cjs → chunk-NQVWSSX2.cjs} +6 -5
  37. package/dist/chunk-NQVWSSX2.cjs.map +1 -0
  38. package/dist/chunk-NWS2CS3Y.cjs +61 -0
  39. package/dist/chunk-NWS2CS3Y.cjs.map +1 -0
  40. package/dist/chunk-R5YPDAKD.cjs +108 -0
  41. package/dist/chunk-R5YPDAKD.cjs.map +1 -0
  42. package/dist/chunk-RGQICWFU.js +82 -0
  43. package/dist/chunk-RGQICWFU.js.map +1 -0
  44. package/dist/{chunk-N7KYUNFO.js → chunk-W2ZVTEOD.js} +3 -3
  45. package/dist/{chunk-N7KYUNFO.js.map → chunk-W2ZVTEOD.js.map} +1 -1
  46. package/dist/{chunk-47Z6LP3I.js → chunk-X3LOJJMO.js} +88 -28
  47. package/dist/chunk-X3LOJJMO.js.map +1 -0
  48. package/dist/{chunk-M2CCHC66.js → chunk-Z5BAFHPU.js} +3 -3
  49. package/dist/{chunk-M2CCHC66.js.map → chunk-Z5BAFHPU.js.map} +1 -1
  50. package/dist/{chunk-VZ2JZ2EH.cjs → chunk-ZD66GFH5.cjs} +89 -27
  51. package/dist/chunk-ZD66GFH5.cjs.map +1 -0
  52. package/dist/{compact-session-4QHBBGEY.cjs → compact-session-2AETONOS.cjs} +12 -12
  53. package/dist/{compact-session-4QHBBGEY.cjs.map → compact-session-2AETONOS.cjs.map} +1 -1
  54. package/dist/{compact-session-PVAWTKKL.js → compact-session-F2UDGZCN.js} +3 -3
  55. package/dist/{compact-session-PVAWTKKL.js.map → compact-session-F2UDGZCN.js.map} +1 -1
  56. package/dist/{cron-DTuaPMVI.d.ts → cron-BPccQCO8.d.ts} +1 -1
  57. package/dist/{cron-QTgcwcZt.d.cts → cron-Blj6wMYg.d.cts} +1 -1
  58. package/dist/cron.cjs +11 -9
  59. package/dist/cron.d.cts +2 -2
  60. package/dist/cron.d.ts +2 -2
  61. package/dist/cron.js +10 -8
  62. package/dist/eval.cjs +14 -12
  63. package/dist/eval.cjs.map +1 -1
  64. package/dist/eval.js +10 -8
  65. package/dist/eval.js.map +1 -1
  66. package/dist/fs-session-store-3VI4CPTX.js +11 -0
  67. package/dist/{fs-session-store-LCZBM3LT.js.map → fs-session-store-3VI4CPTX.js.map} +1 -1
  68. package/dist/fs-session-store-IQ6PEHYF.cjs +20 -0
  69. package/dist/{fs-session-store-SVEMRE4K.cjs.map → fs-session-store-IQ6PEHYF.cjs.map} +1 -1
  70. package/dist/{index-manager-6B2UF5S3.js → index-manager-JVYIVTZG.js} +5 -4
  71. package/dist/{index-manager-6B2UF5S3.js.map → index-manager-JVYIVTZG.js.map} +1 -1
  72. package/dist/{index-manager-M3FHJCHQ.cjs → index-manager-YGXRFJMZ.cjs} +6 -5
  73. package/dist/{index-manager-M3FHJCHQ.cjs.map → index-manager-YGXRFJMZ.cjs.map} +1 -1
  74. package/dist/index.cjs +62 -145
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.cts +12 -3
  77. package/dist/index.d.ts +12 -3
  78. package/dist/index.js +27 -115
  79. package/dist/index.js.map +1 -1
  80. package/dist/{inject-session-O24XGRR6.js → inject-session-E5UDFVLI.js} +3 -3
  81. package/dist/{inject-session-O24XGRR6.js.map → inject-session-E5UDFVLI.js.map} +1 -1
  82. package/dist/{inject-session-OMLFL2V3.cjs → inject-session-W4UKACYJ.cjs} +4 -4
  83. package/dist/{inject-session-OMLFL2V3.cjs.map → inject-session-W4UKACYJ.cjs.map} +1 -1
  84. package/dist/internal/budget/normalize-usage.d.ts +81 -0
  85. package/dist/internal/llm/anthropic-shared.d.ts +6 -0
  86. package/dist/internal/llm/openai.d.ts +3 -5
  87. package/dist/internal/llm/openrouter-system.d.ts +1 -0
  88. package/dist/internal/llm/types.d.ts +10 -5
  89. package/dist/internal/memory/dreaming/phases.d.ts +2 -0
  90. package/dist/internal/memory/dreaming/run.d.ts +5 -0
  91. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  92. package/dist/internal/memory/storage/fact-ceiling.d.cts +19 -0
  93. package/dist/internal/memory/storage/fact-ceiling.d.ts +19 -0
  94. package/dist/internal/memory/storage/index.cjs +40 -31
  95. package/dist/internal/memory/storage/index.d.cts +1 -0
  96. package/dist/internal/memory/storage/index.d.ts +1 -0
  97. package/dist/internal/memory/storage/index.js +3 -2
  98. package/dist/internal/memory/storage/markdown-store.d.cts +3 -1
  99. package/dist/internal/memory/storage/markdown-store.d.ts +3 -1
  100. package/dist/internal/memory/types.d.ts +6 -0
  101. package/dist/internal/persistence/index.cjs +7 -6
  102. package/dist/internal/persistence/index.cjs.map +1 -1
  103. package/dist/internal/persistence/index.js +2 -1
  104. package/dist/internal/persistence/index.js.map +1 -1
  105. package/dist/internal/runtime/registry/agent-registry-store.d.ts +2 -0
  106. package/dist/models.cjs +5 -50
  107. package/dist/models.cjs.map +1 -1
  108. package/dist/models.js +3 -51
  109. package/dist/models.js.map +1 -1
  110. package/dist/persistence.cjs +7 -6
  111. package/dist/persistence.cjs.map +1 -1
  112. package/dist/persistence.js +2 -1
  113. package/dist/persistence.js.map +1 -1
  114. package/dist/subagents-loader.d.cts +1 -1
  115. package/dist/subagents-loader.d.ts +1 -1
  116. package/dist/types/agent.d.ts +27 -0
  117. package/docs/error-codes.md +29 -26
  118. package/docs/harness-capability-map.md +6 -1
  119. package/package.json +1 -1
  120. package/dist/chunk-47Z6LP3I.js.map +0 -1
  121. package/dist/chunk-BKMDRBJ7.js +0 -180
  122. package/dist/chunk-BKMDRBJ7.js.map +0 -1
  123. package/dist/chunk-EVH3OUMY.js.map +0 -1
  124. package/dist/chunk-JU76WCW7.cjs.map +0 -1
  125. package/dist/chunk-OF2CLCTH.cjs +0 -186
  126. package/dist/chunk-OF2CLCTH.cjs.map +0 -1
  127. package/dist/chunk-OZLQ6ZFM.js.map +0 -1
  128. package/dist/chunk-PEIV7LOU.js.map +0 -1
  129. package/dist/chunk-QY3CIMUV.cjs.map +0 -1
  130. package/dist/chunk-RX3CFWQ2.cjs.map +0 -1
  131. package/dist/chunk-VZ2JZ2EH.cjs.map +0 -1
  132. package/dist/fs-session-store-LCZBM3LT.js +0 -10
  133. package/dist/fs-session-store-SVEMRE4K.cjs +0 -19
@@ -328,7 +328,10 @@ async function consumeAnthropicResponse(response) {
328
328
  toolCalls: extractAnthropicToolCalls(data),
329
329
  stopReason: mapAnthropicStopReason(data.stop_reason ?? null),
330
330
  inputTokens: data.usage?.input_tokens,
331
- outputTokens: data.usage?.output_tokens
331
+ outputTokens: data.usage?.output_tokens,
332
+ // B-412 — the counters the Bedrock and Vertex Anthropic clients used to drop.
333
+ cacheReadTokens: data.usage?.cache_read_input_tokens,
334
+ cacheWriteTokens: data.usage?.cache_creation_input_tokens
332
335
  };
333
336
  }
334
337
  async function parseHttpErrorBody(response) {
@@ -541,13 +544,9 @@ var AnthropicClient = class {
541
544
  }
542
545
  const accumulator = new AnthropicStreamAccumulator();
543
546
  for await (const record of parseSseStream(response.body, signal)) {
544
- if (record.event === "ping" || record.event === "message_start") continue;
545
- let parsed;
546
- try {
547
- parsed = JSON.parse(record.data);
548
- } catch {
549
- continue;
550
- }
547
+ if (record.event === "ping") continue;
548
+ const parsed = parseAnthropicFrame(record);
549
+ if (parsed === void 0) continue;
551
550
  const events = accumulator.consume(parsed);
552
551
  for (const event of events) yield event;
553
552
  }
@@ -559,6 +558,30 @@ var AnthropicClient = class {
559
558
  return accumulator.finish();
560
559
  }
561
560
  };
561
+ var CONTENT_FRAMES = /* @__PURE__ */ new Set([
562
+ "content_block_start",
563
+ "content_block_delta",
564
+ "message_delta"
565
+ ]);
566
+ function parseAnthropicFrame(record) {
567
+ try {
568
+ return JSON.parse(record.data);
569
+ } catch (parseErr) {
570
+ const event = record.event;
571
+ const size = `${record.data.length} chars`;
572
+ if (CONTENT_FRAMES.has(event)) {
573
+ throw new chunkUNFBHV46_cjs.NetworkError(
574
+ `Anthropic SSE ${event} frame (${size}) is not valid JSON; the turn would lose content`,
575
+ { code: "stream_malformed_frame", cause: parseErr }
576
+ );
577
+ }
578
+ chunk6LHQPOMI_cjs.diag(
579
+ `[theokit-sdk] skipped an Anthropic SSE ${event} frame (${size}) that is not valid JSON
580
+ `
581
+ );
582
+ return void 0;
583
+ }
584
+ }
562
585
  var AnthropicStreamAccumulator = class {
563
586
  text = "";
564
587
  stopReason = "end_turn";
@@ -593,6 +616,11 @@ var AnthropicStreamAccumulator = class {
593
616
  if (event.type === "message_delta") {
594
617
  this.handleMessageDelta(event);
595
618
  }
619
+ if (event.type === "message_start") {
620
+ const usage = event.message?.usage;
621
+ if (typeof usage?.input_tokens === "number") this.inputTokens = usage.input_tokens;
622
+ this.readCacheCounters(usage);
623
+ }
596
624
  return [];
597
625
  }
598
626
  handleToolStart(start) {
@@ -645,14 +673,26 @@ var AnthropicStreamAccumulator = class {
645
673
  this.sawStopReason = true;
646
674
  }
647
675
  this.stopReason = mapAnthropicStopReason(md.delta.stop_reason);
648
- if (md.usage?.input_tokens !== void 0) this.inputTokens = md.usage.input_tokens;
649
- if (md.usage?.output_tokens !== void 0) this.outputTokens = md.usage.output_tokens;
650
- if (md.usage?.cache_creation_input_tokens !== void 0 && md.usage.cache_creation_input_tokens > 0) {
651
- this.cacheWriteTokens = md.usage.cache_creation_input_tokens;
652
- }
653
- if (md.usage?.cache_read_input_tokens !== void 0 && md.usage.cache_read_input_tokens > 0) {
654
- this.cacheReadTokens = md.usage.cache_read_input_tokens;
676
+ const input = md.usage?.input_tokens;
677
+ if (typeof input === "number" && (input > 0 || this.inputTokens === void 0)) {
678
+ this.inputTokens = input;
655
679
  }
680
+ if (md.usage?.output_tokens !== void 0) this.outputTokens = md.usage.output_tokens;
681
+ this.readCacheCounters(md.usage);
682
+ }
683
+ /**
684
+ * T3.8 / B-412 / B-475 — the cache counters, from `message_start` and then `message_delta`. A
685
+ * value above 0 replaces the earlier one. A zero, a null or an absent field leaves it in place,
686
+ * so a `message_delta` that zero-fills its usage does not erase what `message_start` reported;
687
+ * a counter no event reports above 0 stays unreported (usage-accumulator strips zero entries).
688
+ * The `typeof` check is there because the wire is JSON: a null arrives although the type
689
+ * declares none.
690
+ */
691
+ readCacheCounters(usage) {
692
+ const write = usage?.cache_creation_input_tokens;
693
+ if (typeof write === "number" && write > 0) this.cacheWriteTokens = write;
694
+ const read = usage?.cache_read_input_tokens;
695
+ if (typeof read === "number" && read > 0) this.cacheReadTokens = read;
656
696
  }
657
697
  /** M2 #61 — whether the terminal `message_delta` (stop_reason) was seen. */
658
698
  get finishReasonSeen() {
@@ -748,7 +788,7 @@ async function resolveBedrockToken(region) {
748
788
  return cachedToken.value;
749
789
  }
750
790
  try {
751
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-QY3CIMUV.cjs', document.baseURI).href)));
791
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-BZKF7TXX.cjs', document.baseURI).href)));
752
792
  const gen = r("@aws/bedrock-token-generator");
753
793
  if (typeof gen.getToken !== "function") return void 0;
754
794
  const providers = r("@aws-sdk/credential-providers");
@@ -1231,6 +1271,117 @@ function toOllamaTools(tools) {
1231
1271
  }));
1232
1272
  }
1233
1273
 
1274
+ // src/internal/budget/normalize-usage.ts
1275
+ function int(v) {
1276
+ if (typeof v === "number") return Number.isFinite(v) ? Math.max(0, Math.trunc(v)) : 0;
1277
+ if (typeof v === "string") {
1278
+ const n = Number.parseInt(v, 10);
1279
+ return Number.isFinite(n) ? Math.max(0, n) : 0;
1280
+ }
1281
+ return 0;
1282
+ }
1283
+ function buildTotal(buckets) {
1284
+ return buckets.inputTokens + buckets.outputTokens + buckets.cacheReadTokens + buckets.cacheWriteTokens;
1285
+ }
1286
+ function omitUndefined(usage) {
1287
+ return {
1288
+ inputTokens: usage.inputTokens,
1289
+ outputTokens: usage.outputTokens,
1290
+ ...usage.cacheReadTokens > 0 ? { cacheReadTokens: usage.cacheReadTokens } : {},
1291
+ ...usage.cacheWriteTokens > 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {},
1292
+ ...usage.reasoningTokens > 0 ? { reasoningTokens: usage.reasoningTokens } : {},
1293
+ totalTokens: usage.totalTokens
1294
+ };
1295
+ }
1296
+ function inferApiMode(provider) {
1297
+ const p = provider.toLowerCase();
1298
+ if (p === "anthropic" || p === "claude" || p === "bedrock_anthropic") {
1299
+ return "anthropic_messages";
1300
+ }
1301
+ if (p === "openai-codex" || p === "codex") return "openai_responses";
1302
+ return "openai_chat_completions";
1303
+ }
1304
+ function normalizeUsage(rawUsage, opts) {
1305
+ if (rawUsage === null || rawUsage === void 0) {
1306
+ return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
1307
+ }
1308
+ if (typeof rawUsage !== "object") {
1309
+ return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
1310
+ }
1311
+ const raw = rawUsage;
1312
+ const mode = opts.apiMode ?? inferApiMode(opts.provider);
1313
+ if (mode === "anthropic_messages") return normalizeAnthropic(raw);
1314
+ if (mode === "openai_responses") return normalizeOpenAIResponses(raw);
1315
+ return normalizeOpenAIChat(raw);
1316
+ }
1317
+ function normalizeAnthropic(raw) {
1318
+ const inputTokens = int(raw.input_tokens);
1319
+ const outputTokens = int(raw.output_tokens);
1320
+ const cacheReadTokens = int(raw.cache_read_input_tokens);
1321
+ const cacheWriteTokens = int(raw.cache_creation_input_tokens);
1322
+ const usage = {
1323
+ inputTokens,
1324
+ outputTokens,
1325
+ cacheReadTokens,
1326
+ cacheWriteTokens,
1327
+ reasoningTokens: 0,
1328
+ totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens })
1329
+ };
1330
+ return omitUndefined(usage);
1331
+ }
1332
+ function normalizeOpenAIResponses(raw) {
1333
+ const inputTotal = int(raw.input_tokens);
1334
+ const outputTokens = int(raw.output_tokens);
1335
+ const inputDetails = raw.input_tokens_details ?? {};
1336
+ const outputDetails = raw.output_tokens_details ?? {};
1337
+ const cacheReadTokens = int(inputDetails.cached_tokens);
1338
+ const cacheWriteTokens = int(inputDetails.cache_creation_tokens);
1339
+ const reasoningTokens = int(outputDetails.reasoning_tokens);
1340
+ const inputTokens = Math.max(0, inputTotal - cacheReadTokens - cacheWriteTokens);
1341
+ const usage = {
1342
+ inputTokens,
1343
+ outputTokens,
1344
+ cacheReadTokens,
1345
+ cacheWriteTokens,
1346
+ reasoningTokens,
1347
+ totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens })
1348
+ };
1349
+ return omitUndefined(usage);
1350
+ }
1351
+ function sent(v) {
1352
+ return v !== void 0 && v !== null;
1353
+ }
1354
+ function splitChatCompletionsPrompt(raw) {
1355
+ const details = raw.prompt_tokens_details ?? {};
1356
+ const bucket = (nested, topLevel) => sent(nested) || sent(topLevel) ? int(nested) || int(topLevel) : void 0;
1357
+ const cacheReadTokens = bucket(details.cached_tokens, raw.cache_read_input_tokens);
1358
+ const cacheWriteTokens = bucket(details.cache_write_tokens, raw.cache_creation_input_tokens);
1359
+ const cached = (cacheReadTokens ?? 0) + (cacheWriteTokens ?? 0);
1360
+ return {
1361
+ ...sent(raw.prompt_tokens) ? { inputTokens: Math.max(0, int(raw.prompt_tokens) - cached) } : {},
1362
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
1363
+ ...cacheWriteTokens !== void 0 ? { cacheWriteTokens } : {}
1364
+ };
1365
+ }
1366
+ function normalizeOpenAIChat(raw) {
1367
+ const outputTokens = int(raw.completion_tokens);
1368
+ const completionDetails = raw.completion_tokens_details ?? {};
1369
+ const split = splitChatCompletionsPrompt(raw);
1370
+ const inputTokens = split.inputTokens ?? 0;
1371
+ const cacheReadTokens = split.cacheReadTokens ?? 0;
1372
+ const cacheWriteTokens = split.cacheWriteTokens ?? 0;
1373
+ const reasoningTokens = int(completionDetails.reasoning_tokens);
1374
+ const usage = {
1375
+ inputTokens,
1376
+ outputTokens,
1377
+ cacheReadTokens,
1378
+ cacheWriteTokens,
1379
+ reasoningTokens,
1380
+ totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens })
1381
+ };
1382
+ return omitUndefined(usage);
1383
+ }
1384
+
1234
1385
  // src/internal/base-url.ts
1235
1386
  function getConfiguredBaseUrl() {
1236
1387
  const value = process.env.THEOKIT_API_BASE_URL;
@@ -1507,6 +1658,16 @@ function assistantMessage(message) {
1507
1658
  return result;
1508
1659
  }
1509
1660
 
1661
+ // src/internal/llm/openrouter-system.ts
1662
+ function encodeOpenRouterSystemContent(system) {
1663
+ if (!Array.isArray(system) || !system.some((block) => block.cacheable === true)) {
1664
+ return void 0;
1665
+ }
1666
+ return system.map(
1667
+ (block) => block.cacheable === true ? { type: "text", text: block.text, cache_control: { type: "ephemeral" } } : { type: "text", text: block.text }
1668
+ );
1669
+ }
1670
+
1510
1671
  // src/internal/llm/openai.ts
1511
1672
  function deriveChatPath(baseUrl) {
1512
1673
  try {
@@ -1649,11 +1810,8 @@ var OpenAIStreamAccumulator = class {
1649
1810
  allowedToolNames;
1650
1811
  text = "";
1651
1812
  stopReason = "end_turn";
1652
- inputTokens;
1653
- outputTokens;
1654
- cacheReadTokens;
1655
- cacheWriteTokens;
1656
- reasoningTokens;
1813
+ /** The stream's `usage` object, a later chunk replacing an earlier one per top-level field. */
1814
+ usage = {};
1657
1815
  toolCalls = /* @__PURE__ */ new Map();
1658
1816
  /** R7: present only when recovery is enabled AND the request declares tools — holds suspected
1659
1817
  * leaked-dialect content back from the `text_delta` stream. `undefined` ⇒ stream immediately. */
@@ -1687,18 +1845,7 @@ var OpenAIStreamAccumulator = class {
1687
1845
  return { type: "reasoning_delta", text: reasoning };
1688
1846
  }
1689
1847
  applyUsage(usage) {
1690
- if (usage?.prompt_tokens !== void 0) this.inputTokens = usage.prompt_tokens;
1691
- if (usage?.completion_tokens !== void 0) this.outputTokens = usage.completion_tokens;
1692
- const cachedDetail = usage?.prompt_tokens_details?.cached_tokens;
1693
- if (cachedDetail !== void 0) this.cacheReadTokens = cachedDetail;
1694
- const reasoningDetail = usage?.completion_tokens_details?.reasoning_tokens;
1695
- if (reasoningDetail !== void 0) this.reasoningTokens = reasoningDetail;
1696
- if (usage?.cache_read_input_tokens !== void 0) {
1697
- this.cacheReadTokens = usage.cache_read_input_tokens;
1698
- }
1699
- if (usage?.cache_creation_input_tokens !== void 0) {
1700
- this.cacheWriteTokens = usage.cache_creation_input_tokens;
1701
- }
1848
+ if (usage !== void 0) this.usage = { ...this.usage, ...usage };
1702
1849
  }
1703
1850
  applyContentDelta(content) {
1704
1851
  if (typeof content !== "string" || content.length === 0) return void 0;
@@ -1769,11 +1916,10 @@ var OpenAIStreamAccumulator = class {
1769
1916
  stopReason,
1770
1917
  text,
1771
1918
  toolCalls,
1772
- inputTokens: this.inputTokens,
1773
- outputTokens: this.outputTokens,
1774
- cacheReadTokens: this.cacheReadTokens,
1775
- cacheWriteTokens: this.cacheWriteTokens,
1776
- reasoningTokens: this.reasoningTokens
1919
+ // D376: the prompt split (cache buckets out of inputTokens) has one owner, normalize-usage.ts.
1920
+ ...splitChatCompletionsPrompt(this.usage),
1921
+ outputTokens: this.usage.completion_tokens,
1922
+ reasoningTokens: this.usage.completion_tokens_details?.reasoning_tokens
1777
1923
  });
1778
1924
  }
1779
1925
  };
@@ -1794,10 +1940,10 @@ function applyToolsRequest(body, request) {
1794
1940
  }
1795
1941
  function buildOpenAIBody(request, providerName) {
1796
1942
  const messages = [];
1943
+ const systemParts = providerName === "openrouter" ? encodeOpenRouterSystemContent(request.system) : void 0;
1797
1944
  const systemText = openAISystemText(request.system);
1798
- if (systemText.length > 0) {
1799
- messages.push({ role: "system", content: systemText });
1800
- }
1945
+ if (systemParts !== void 0) messages.push({ role: "system", content: systemParts });
1946
+ else if (systemText.length > 0) messages.push({ role: "system", content: systemText });
1801
1947
  for (const message of request.messages) {
1802
1948
  for (const out of toOpenAIMessages(message)) messages.push(out);
1803
1949
  }
@@ -2516,7 +2662,7 @@ async function resolveVertexAccessToken() {
2516
2662
  async function getAuthClientOrThrow() {
2517
2663
  let mod;
2518
2664
  try {
2519
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-QY3CIMUV.cjs', document.baseURI).href)));
2665
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-BZKF7TXX.cjs', document.baseURI).href)));
2520
2666
  mod = r("google-auth-library");
2521
2667
  } catch (err) {
2522
2668
  const isModuleMissing = err instanceof Error && (err.message.includes("Cannot find module") || err.code === "MODULE_NOT_FOUND");
@@ -3305,11 +3451,13 @@ exports.compactSessionTranscript = compactSessionTranscript;
3305
3451
  exports.discoverProviderPlugins = discoverProviderPlugins;
3306
3452
  exports.getConfiguredBaseUrl = getConfiguredBaseUrl;
3307
3453
  exports.httpRequest = httpRequest;
3454
+ exports.inferApiMode = inferApiMode;
3308
3455
  exports.isCompactSummary = isCompactSummary;
3309
3456
  exports.isFixtureApiKey = isFixtureApiKey;
3310
3457
  exports.mapOllamaHttpError = mapOllamaHttpError;
3311
3458
  exports.mapOllamaTransportError = mapOllamaTransportError;
3312
3459
  exports.mergeExplicitApiKey = mergeExplicitApiKey;
3460
+ exports.normalizeUsage = normalizeUsage;
3313
3461
  exports.parseSseStream = parseSseStream;
3314
3462
  exports.presentProviderCredentialEnvVars = presentProviderCredentialEnvVars;
3315
3463
  exports.readErrorResponseBody = readErrorResponseBody;
@@ -3323,5 +3471,5 @@ exports.shouldUseFixtureMode = shouldUseFixtureMode;
3323
3471
  exports.shouldUseRealLocalRuntime = shouldUseRealLocalRuntime;
3324
3472
  exports.tryFirstEvent = tryFirstEvent;
3325
3473
  exports.validateApiKeyShape = validateApiKeyShape;
3326
- //# sourceMappingURL=chunk-QY3CIMUV.cjs.map
3327
- //# sourceMappingURL=chunk-QY3CIMUV.cjs.map
3474
+ //# sourceMappingURL=chunk-BZKF7TXX.cjs.map
3475
+ //# sourceMappingURL=chunk-BZKF7TXX.cjs.map