@liberseek/boft-cli-linux-x64 0.7.9 → 0.8.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 (56) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.txt +9 -1
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +322 -67
  5. package/app/console-web.js +9202 -5218
  6. package/app/desktop-controller.mjs +259 -42
  7. package/app/host-runtime.mjs +6250 -1689
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +283 -42
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +35676 -24151
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +5972 -5356
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +17386 -0
  16. package/app/plugins/cursor-cli/manifest.json +18 -1
  17. package/app/plugins/cursor-cli/plugin.mjs +358 -77
  18. package/app/plugins/deepseek-harness/assets/icon.svg +1 -0
  19. package/app/plugins/deepseek-harness/manifest.json +35 -2
  20. package/app/plugins/deepseek-harness/plugin.mjs +823 -242
  21. package/app/plugins/enabled.json +2 -1
  22. package/app/plugins/grok/manifest.json +21 -1
  23. package/app/plugins/grok/plugin.mjs +933 -268
  24. package/app/plugins/hermes/assets/icon.png +0 -0
  25. package/app/plugins/hermes/manifest.json +30 -2
  26. package/app/plugins/hermes/plugin.mjs +469 -73
  27. package/app/plugins/kimi-code/assets/icon.svg +5 -0
  28. package/app/plugins/kimi-code/manifest.json +25 -2
  29. package/app/plugins/kimi-code/plugin.mjs +562 -36
  30. package/app/plugins/kiro-cli/assets/kiro-agent.svg +11 -0
  31. package/app/plugins/kiro-cli/manifest.json +18 -1
  32. package/app/plugins/kiro-cli/plugin.mjs +291 -22
  33. package/app/plugins/muse/manifest.json +18 -1
  34. package/app/plugins/muse/plugin.mjs +258 -17
  35. package/app/plugins/omp/manifest.json +21 -1
  36. package/app/plugins/omp/plugin.mjs +2763 -1958
  37. package/app/plugins/opencode/manifest.json +18 -1
  38. package/app/plugins/opencode/plugin.mjs +724 -147
  39. package/app/plugins/pi/manifest.json +32 -0
  40. package/app/plugins/pi/plugin.mjs +2908 -2312
  41. package/app/plugins/qoder/manifest.json +18 -1
  42. package/app/plugins/qoder/plugin.mjs +635 -81
  43. package/app/plugins/qoder-cn/manifest.json +18 -1
  44. package/app/plugins/qoder-cn/plugin.mjs +635 -81
  45. package/app/plugins/workbuddy/manifest.json +18 -0
  46. package/app/plugins/workbuddy/plugin.mjs +6362 -5748
  47. package/app/plugins/zcode/manifest.json +19 -1
  48. package/app/plugins/zcode/plugin.mjs +1117 -278
  49. package/app/renderer-extension.js +14675 -10087
  50. package/bin/boft +0 -0
  51. package/libexec/boft-shim +0 -0
  52. package/libexec/boft-updater +0 -0
  53. package/licenses/Cordis-LICENSE.txt +21 -0
  54. package/licenses/Cosmokit-LICENSE.txt +21 -0
  55. package/package.json +4 -4
  56. package/app/plugins/kiro-cli/assets/icon.svg +0 -5
@@ -372,20 +372,208 @@ function createHarnessInstaller(environment, source) {
372
372
  };
373
373
  }
374
374
 
375
+ // dist/usage-statistics.js
376
+ import os2 from "node:os";
377
+ import path5 from "node:path";
378
+ import { readFile } from "node:fs/promises";
379
+
380
+ // ../../harness-adapter/dist/usage-statistics.js
381
+ import { createReadStream } from "node:fs";
382
+ import { lstat, opendir } from "node:fs/promises";
383
+ import path4 from "node:path";
384
+ import { createInterface } from "node:readline";
385
+ var MAX_SESSION_ID_LENGTH = 512;
386
+ var MAX_CWD_LENGTH = 4096;
387
+ var MAX_SESSION_TITLE_LENGTH = 200;
388
+ function usageSessionTitle(value) {
389
+ if (typeof value !== "string")
390
+ return void 0;
391
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
392
+ if (!normalized)
393
+ return void 0;
394
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
395
+ return normalized;
396
+ const characters = [...normalized];
397
+ if (characters.length <= MAX_SESSION_TITLE_LENGTH)
398
+ return normalized;
399
+ return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
400
+ }
401
+ function sessionIdOk(value) {
402
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
403
+ }
404
+ function cwdOk(value) {
405
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
406
+ }
407
+ function withUsageSession(entry, session) {
408
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
409
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
410
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
411
+ if (sessionId === void 0 && cwd === void 0)
412
+ return entry;
413
+ return {
414
+ ...entry,
415
+ ...sessionId !== void 0 ? { sessionId } : {},
416
+ ...cwd !== void 0 ? { cwd } : {},
417
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
418
+ };
419
+ }
420
+ async function jsonlUsageSources(root, maxDepth, signal) {
421
+ const sources = [];
422
+ const visit = async (directory, depth) => {
423
+ signal.throwIfAborted();
424
+ const entries = await opendir(directory).catch((error53) => {
425
+ if (error53.code === "ENOENT")
426
+ return null;
427
+ throw error53;
428
+ });
429
+ if (!entries)
430
+ return;
431
+ for await (const entry of entries) {
432
+ signal.throwIfAborted();
433
+ const file2 = path4.join(directory, entry.name);
434
+ if (entry.isDirectory()) {
435
+ if (depth < maxDepth)
436
+ await visit(file2, depth + 1);
437
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
438
+ const info = await lstat(file2).catch(() => null);
439
+ if (info?.isFile() && info.size > 0) {
440
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
441
+ }
442
+ }
443
+ }
444
+ };
445
+ await visit(root, 0);
446
+ return sources;
447
+ }
448
+ async function* jsonlRecords(file2, marker, signal) {
449
+ const lines = createInterface({
450
+ input: createReadStream(file2, { encoding: "utf8", signal }),
451
+ crlfDelay: Infinity
452
+ });
453
+ for await (const line of lines) {
454
+ if (!line.includes(marker))
455
+ continue;
456
+ let value;
457
+ try {
458
+ value = JSON.parse(line);
459
+ } catch {
460
+ continue;
461
+ }
462
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
463
+ yield value;
464
+ }
465
+ }
466
+ }
467
+ function nativeTimeMs(value) {
468
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
469
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
470
+ }
471
+
472
+ // dist/usage-statistics.js
473
+ function isRecord(value) {
474
+ return typeof value === "object" && value !== null && !Array.isArray(value);
475
+ }
476
+ var USD_TICKS = 1e10;
477
+ function count(value) {
478
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
479
+ }
480
+ function grokHome(environment) {
481
+ return environment.GROK_HOME || path5.join(environment.HOME || os2.homedir(), ".grok");
482
+ }
483
+ async function grokSummary(directory) {
484
+ try {
485
+ const summary = JSON.parse(await readFile(path5.join(directory, "summary.json"), "utf8"));
486
+ if (!isRecord(summary))
487
+ return { forkedAt: null };
488
+ const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
489
+ return {
490
+ forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
491
+ ...title ? { title } : {}
492
+ };
493
+ } catch {
494
+ return { forkedAt: null };
495
+ }
496
+ }
497
+ function grokSession(file2) {
498
+ const directory = path5.dirname(file2);
499
+ let cwd;
500
+ try {
501
+ cwd = decodeURIComponent(path5.basename(path5.dirname(directory)));
502
+ } catch {
503
+ cwd = void 0;
504
+ }
505
+ return { sessionId: path5.basename(directory), cwd };
506
+ }
507
+ async function readGrokUsage(file2, signal) {
508
+ const summary = await grokSummary(path5.dirname(file2));
509
+ const forkedAt = summary.forkedAt;
510
+ let title = summary.title;
511
+ const session = grokSession(file2);
512
+ const entries = [];
513
+ for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
514
+ const params = isRecord(line.params) ? line.params : {};
515
+ const update = isRecord(params.update) ? params.update : {};
516
+ if (!title && update.sessionUpdate === "user_message_chunk") {
517
+ title = usageSessionTitle(isRecord(update.content) ? update.content.text : void 0);
518
+ continue;
519
+ }
520
+ const usage = isRecord(update.usage) ? update.usage : {};
521
+ if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
522
+ continue;
523
+ const meta3 = isRecord(params._meta) ? params._meta : {};
524
+ const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
525
+ if (at === null || forkedAt !== null && at <= forkedAt)
526
+ continue;
527
+ for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
528
+ if (!isRecord(value))
529
+ continue;
530
+ const input = count(value.inputTokens);
531
+ const output = count(value.outputTokens);
532
+ const cached2 = count(value.cachedReadTokens);
533
+ const written = count(value.cacheCreationTokens ?? 0);
534
+ const reasoning = count(value.reasoningTokens);
535
+ const ticks = count(value.costUsdTicks);
536
+ if (input === null || output === null || value.totalTokens !== input + output)
537
+ continue;
538
+ const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
539
+ entries.push(withUsageSession({
540
+ id: `${update.prompt_id}:${model2}`,
541
+ occurredAtMs: at,
542
+ model: model2,
543
+ inputTokens: input,
544
+ ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
545
+ outputTokens: output,
546
+ ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
547
+ // A turn Grok marks incomplete has no cost of its own; it counts as free rather
548
+ // than as a model without a price.
549
+ ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
550
+ }, { ...session, ...title ? { title } : {} }));
551
+ }
552
+ }
553
+ return entries;
554
+ }
555
+ function createGrokUsageStatistics(environment) {
556
+ return Object.freeze({
557
+ // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
558
+ listSources: async (signal) => (await jsonlUsageSources(path5.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path5.basename(source.id) === "updates.jsonl"),
559
+ readSource: (id, signal) => readGrokUsage(id, signal)
560
+ });
561
+ }
562
+
375
563
  // dist/grok-adapter.js
376
564
  import { randomUUID } from "node:crypto";
377
565
 
378
566
  // dist/grok-credential-export.js
379
567
  import { createHash } from "node:crypto";
380
- import { readFile } from "node:fs/promises";
381
- import os2 from "node:os";
382
- import path4 from "node:path";
568
+ import { readFile as readFile2 } from "node:fs/promises";
569
+ import os3 from "node:os";
570
+ import path6 from "node:path";
383
571
  async function readGrokCredentials(environment) {
384
572
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
385
573
  return [];
386
574
  try {
387
- const home = environment.GROK_HOME ?? path4.join(environment.HOME ?? os2.homedir(), ".grok");
388
- const auth = JSON.parse(await readFile(path4.join(home, "auth.json"), "utf8"));
575
+ const home = environment.GROK_HOME ?? path6.join(environment.HOME ?? os3.homedir(), ".grok");
576
+ const auth = JSON.parse(await readFile2(path6.join(home, "auth.json"), "utf8"));
389
577
  const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
390
578
  const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
391
579
  if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
@@ -412,7 +600,7 @@ async function readGrokCredentials(environment) {
412
600
  }
413
601
 
414
602
  // dist/grok-adapter.js
415
- import path13 from "node:path";
603
+ import path15 from "node:path";
416
604
 
417
605
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
418
606
  var AGENT_METHODS = {
@@ -1232,10 +1420,10 @@ function mergeDefs(...defs) {
1232
1420
  function cloneDef(schema) {
1233
1421
  return mergeDefs(schema._zod.def);
1234
1422
  }
1235
- function getElementAtPath(obj, path14) {
1236
- if (!path14)
1423
+ function getElementAtPath(obj, path16) {
1424
+ if (!path16)
1237
1425
  return obj;
1238
- return path14.reduce((acc, key) => acc?.[key], obj);
1426
+ return path16.reduce((acc, key) => acc?.[key], obj);
1239
1427
  }
1240
1428
  function promiseAllObject(promisesObj) {
1241
1429
  const keys = Object.keys(promisesObj);
@@ -1644,11 +1832,11 @@ function explicitlyAborted(x, startIndex = 0) {
1644
1832
  }
1645
1833
  return false;
1646
1834
  }
1647
- function prefixIssues(path14, issues) {
1835
+ function prefixIssues(path16, issues) {
1648
1836
  return issues.map((iss) => {
1649
1837
  var _a3;
1650
1838
  (_a3 = iss).path ?? (_a3.path = []);
1651
- iss.path.unshift(path14);
1839
+ iss.path.unshift(path16);
1652
1840
  return iss;
1653
1841
  });
1654
1842
  }
@@ -1795,16 +1983,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1795
1983
  }
1796
1984
  function formatError(error53, mapper = (issue2) => issue2.message) {
1797
1985
  const fieldErrors = { _errors: [] };
1798
- const processError = (error54, path14 = []) => {
1986
+ const processError = (error54, path16 = []) => {
1799
1987
  for (const issue2 of error54.issues) {
1800
1988
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1801
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1989
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1802
1990
  } else if (issue2.code === "invalid_key") {
1803
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1991
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1804
1992
  } else if (issue2.code === "invalid_element") {
1805
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1993
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1806
1994
  } else {
1807
- const fullpath = [...path14, ...issue2.path];
1995
+ const fullpath = [...path16, ...issue2.path];
1808
1996
  if (fullpath.length === 0) {
1809
1997
  fieldErrors._errors.push(mapper(issue2));
1810
1998
  } else {
@@ -1831,17 +2019,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1831
2019
  }
1832
2020
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1833
2021
  const result = { errors: [] };
1834
- const processError = (error54, path14 = []) => {
2022
+ const processError = (error54, path16 = []) => {
1835
2023
  var _a3, _b;
1836
2024
  for (const issue2 of error54.issues) {
1837
2025
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1838
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
2026
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1839
2027
  } else if (issue2.code === "invalid_key") {
1840
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
2028
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1841
2029
  } else if (issue2.code === "invalid_element") {
1842
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
2030
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1843
2031
  } else {
1844
- const fullpath = [...path14, ...issue2.path];
2032
+ const fullpath = [...path16, ...issue2.path];
1845
2033
  if (fullpath.length === 0) {
1846
2034
  result.errors.push(mapper(issue2));
1847
2035
  continue;
@@ -1873,8 +2061,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1873
2061
  }
1874
2062
  function toDotPath(_path) {
1875
2063
  const segs = [];
1876
- const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1877
- for (const seg of path14) {
2064
+ const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2065
+ for (const seg of path16) {
1878
2066
  if (typeof seg === "number")
1879
2067
  segs.push(`[${seg}]`);
1880
2068
  else if (typeof seg === "symbol")
@@ -5102,8 +5290,8 @@ function az_default() {
5102
5290
  }
5103
5291
 
5104
5292
  // ../../../node_modules/zod/v4/locales/be.js
5105
- function getBelarusianPlural(count, one, few, many) {
5106
- const absCount = Math.abs(count);
5293
+ function getBelarusianPlural(count3, one, few, many) {
5294
+ const absCount = Math.abs(count3);
5107
5295
  const lastDigit = absCount % 10;
5108
5296
  const lastTwoDigits = absCount % 100;
5109
5297
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -7181,8 +7369,8 @@ function hu_default() {
7181
7369
  }
7182
7370
 
7183
7371
  // ../../../node_modules/zod/v4/locales/hy.js
7184
- function getArmenianPlural(count, one, many) {
7185
- return Math.abs(count) === 1 ? one : many;
7372
+ function getArmenianPlural(count3, one, many) {
7373
+ return Math.abs(count3) === 1 ? one : many;
7186
7374
  }
7187
7375
  function withDefiniteArticle(word) {
7188
7376
  if (!word)
@@ -9310,8 +9498,8 @@ function ro_default() {
9310
9498
  }
9311
9499
 
9312
9500
  // ../../../node_modules/zod/v4/locales/ru.js
9313
- function getRussianPlural(count, one, few, many) {
9314
- const absCount = Math.abs(count);
9501
+ function getRussianPlural(count3, one, few, many) {
9502
+ const absCount = Math.abs(count3);
9315
9503
  const lastDigit = absCount % 10;
9316
9504
  const lastTwoDigits = absCount % 100;
9317
9505
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14566,13 +14754,13 @@ function resolveRef(ref, ctx) {
14566
14754
  if (!ref.startsWith("#")) {
14567
14755
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14568
14756
  }
14569
- const path14 = ref.slice(1).split("/").filter(Boolean);
14570
- if (path14.length === 0) {
14757
+ const path16 = ref.slice(1).split("/").filter(Boolean);
14758
+ if (path16.length === 0) {
14571
14759
  return ctx.rootSchema;
14572
14760
  }
14573
14761
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14574
- if (path14[0] === defsKey) {
14575
- const key = path14[1];
14762
+ if (path16[0] === defsKey) {
14763
+ const key = path16[1];
14576
14764
  if (!key || !ctx.defs[key]) {
14577
14765
  throw new Error(`Reference not found: ${ref}`);
14578
14766
  }
@@ -16663,17 +16851,17 @@ function isResponseMessage(value) {
16663
16851
  function isNotificationMessage(value) {
16664
16852
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
16665
16853
  }
16666
- function isRecord(value) {
16854
+ function isRecord2(value) {
16667
16855
  return typeof value === "object" && value !== null;
16668
16856
  }
16669
16857
  function isJsonRpcEnvelope(value) {
16670
- return isRecord(value) && value["jsonrpc"] === "2.0";
16858
+ return isRecord2(value) && value["jsonrpc"] === "2.0";
16671
16859
  }
16672
16860
  function isJsonRpcId(value) {
16673
16861
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
16674
16862
  }
16675
16863
  function isResponseShapedMessage(value) {
16676
- return isRecord(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
16864
+ return isRecord2(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
16677
16865
  }
16678
16866
  function isResponseBatch(batch) {
16679
16867
  let hasValidCall = false;
@@ -16683,7 +16871,7 @@ function isResponseBatch(batch) {
16683
16871
  for (const entry of batch) {
16684
16872
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
16685
16873
  hasValidResponse ||= isResponseMessage(entry);
16686
- if (!isRecord(entry)) {
16874
+ if (!isRecord2(entry)) {
16687
16875
  continue;
16688
16876
  }
16689
16877
  hasCallShape ||= "method" in entry;
@@ -16698,13 +16886,13 @@ function isResponseBatch(batch) {
16698
16886
  return hasResponseShape && !hasCallShape;
16699
16887
  }
16700
16888
  function cancelRequestId(params) {
16701
- if (!isRecord(params) || !isJsonRpcId(params["requestId"])) {
16889
+ if (!isRecord2(params) || !isJsonRpcId(params["requestId"])) {
16702
16890
  return void 0;
16703
16891
  }
16704
16892
  return params["requestId"];
16705
16893
  }
16706
16894
  function isErrorResponse(value) {
16707
- return isRecord(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
16895
+ return isRecord2(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
16708
16896
  }
16709
16897
  var Handled = {
16710
16898
  /**
@@ -17195,7 +17383,7 @@ var Connection = class {
17195
17383
  this.receiveBatch(message);
17196
17384
  return;
17197
17385
  }
17198
- if (!isRecord(message)) {
17386
+ if (!isRecord2(message)) {
17199
17387
  console.error("Invalid message", { message });
17200
17388
  return;
17201
17389
  }
@@ -17212,9 +17400,9 @@ var Connection = class {
17212
17400
  return;
17213
17401
  }
17214
17402
  const responseBatch = isResponseBatch(batch);
17215
- const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
17403
+ const responseCount = responseBatch ? 0 : batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 0 : 1), 0);
17216
17404
  let remaining = responseCount;
17217
- let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
17405
+ let remainingNotifications = batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 1 : 0), 0);
17218
17406
  let responseSent = false;
17219
17407
  const responses = [];
17220
17408
  const sendResponsesIfReady = async () => {
@@ -17258,7 +17446,7 @@ var Connection = class {
17258
17446
  if (this.abortController.signal.aborted) {
17259
17447
  return Promise.resolve();
17260
17448
  }
17261
- if (!isRecord(message)) {
17449
+ if (!isRecord2(message)) {
17262
17450
  console.error("Invalid message", { message });
17263
17451
  return Promise.resolve();
17264
17452
  }
@@ -17628,7 +17816,7 @@ function ndJsonStream(output, input) {
17628
17816
  if (trimmedLine) {
17629
17817
  try {
17630
17818
  const message = JSON.parse(trimmedLine);
17631
- if (isRecord(message) || Array.isArray(message)) {
17819
+ if (isRecord2(message) || Array.isArray(message)) {
17632
17820
  controller.enqueue(message);
17633
17821
  } else {
17634
17822
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
@@ -19089,6 +19277,15 @@ var ClientSideConnection = class {
19089
19277
  }
19090
19278
  };
19091
19279
 
19280
+ // ../../shared-contracts/dist/delegation-read.js
19281
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
19282
+ var delegationReadParamsSchema = external_exports.strictObject({
19283
+ threadId: external_exports.string().min(1).max(1024),
19284
+ view: external_exports.enum(["result", "messages"]),
19285
+ cursor: external_exports.string().min(1).max(8192).optional(),
19286
+ limit: external_exports.number().int().min(1).max(100).optional()
19287
+ });
19288
+
19092
19289
  // ../../shared-contracts/dist/credential-imports.js
19093
19290
  var credentialSourceSchema = external_exports.object({
19094
19291
  id: external_exports.string().min(1).max(256),
@@ -19159,6 +19356,160 @@ var harnessDisplaySetSchema = external_exports.strictObject({
19159
19356
  initializeOnly: external_exports.boolean().optional()
19160
19357
  });
19161
19358
 
19359
+ // ../../shared-contracts/dist/model-price-overrides.js
19360
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
19361
+ var modelPriceOverrideSchema = external_exports.strictObject({
19362
+ input: usdPerMillionTokens,
19363
+ output: usdPerMillionTokens,
19364
+ cacheRead: usdPerMillionTokens.optional(),
19365
+ cacheWrite: usdPerMillionTokens.optional(),
19366
+ cacheWrite1h: usdPerMillionTokens.optional()
19367
+ });
19368
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
19369
+ var modelPriceOverridesSchema = external_exports.strictObject({
19370
+ /** Absolute path of the Host's `pricing.json`. */
19371
+ path: external_exports.string(),
19372
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
19373
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
19374
+ error: external_exports.string().nullable()
19375
+ });
19376
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
19377
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
19378
+ key: modelPriceKeySchema,
19379
+ price: modelPriceOverrideSchema.nullable(),
19380
+ previousKey: modelPriceKeySchema.optional()
19381
+ });
19382
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
19383
+ model: modelPriceKeySchema
19384
+ });
19385
+ var modelPriceSuggestionSchema = external_exports.strictObject({
19386
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
19387
+ official: external_exports.boolean().optional(),
19388
+ canonicalModelId: external_exports.string().min(1).optional(),
19389
+ provider: external_exports.string().min(1).max(512),
19390
+ model: external_exports.string().min(1).max(512),
19391
+ price: modelPriceOverrideSchema
19392
+ });
19393
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
19394
+ price: modelPriceOverrideSchema.nullable(),
19395
+ /** Local catalog suggestions only; never used automatically for pricing. */
19396
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
19397
+ });
19398
+
19399
+ // ../../shared-contracts/dist/usage-statistics.js
19400
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
19401
+ var count2 = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
19402
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
19403
+ var harness = external_exports.string().min(1).max(128);
19404
+ var model = external_exports.string().min(1).max(512);
19405
+ var project = external_exports.string().min(1).max(4096);
19406
+ var usageStatisticsParamsSchema = external_exports.strictObject({
19407
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
19408
+ harness: harness.optional(),
19409
+ model: model.nullable().optional(),
19410
+ project: project.nullable().optional(),
19411
+ /** One local date inside the range. */
19412
+ date: localDate.optional()
19413
+ });
19414
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
19415
+ requests: count2,
19416
+ inputTokens: count2,
19417
+ cachedInputTokens: count2,
19418
+ cacheWriteInputTokens: count2,
19419
+ cacheKnownInputTokens: count2,
19420
+ outputTokens: count2,
19421
+ reasoningOutputTokens: count2,
19422
+ /** USD at the public price, summed over the priced requests only. */
19423
+ costUsd: external_exports.number().finite().min(0),
19424
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
19425
+ unpricedRequests: count2,
19426
+ /**
19427
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
19428
+ * cost, and not as unpriced.
19429
+ */
19430
+ unmeteredRequests: count2
19431
+ });
19432
+ var totals = usageStatisticsTotalsSchema.shape;
19433
+ var usageStatisticsSessionSchema = external_exports.strictObject({
19434
+ harness,
19435
+ sessionId: external_exports.string().min(1).max(512),
19436
+ project: project.nullable(),
19437
+ /** Persisted Desktop title for a mapped Session, otherwise its native name; may be absent. */
19438
+ title: external_exports.string().min(1).max(200).optional(),
19439
+ /** Models the session used, most requests first. */
19440
+ models: external_exports.array(model).max(16),
19441
+ firstAtMs: count2,
19442
+ lastAtMs: count2,
19443
+ ...totals
19444
+ });
19445
+ var usageStatisticsResultSchema = external_exports.strictObject({
19446
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
19447
+ /** First local date of the range; null for all time. */
19448
+ from: localDate.nullable(),
19449
+ to: localDate,
19450
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
19451
+ filters: external_exports.strictObject({
19452
+ harness: harness.nullable(),
19453
+ model: model.nullable(),
19454
+ unknownModel: external_exports.boolean(),
19455
+ project: project.nullable(),
19456
+ unknownProject: external_exports.boolean(),
19457
+ date: localDate.nullable()
19458
+ }),
19459
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
19460
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count2, read: count2 }),
19461
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
19462
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
19463
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
19464
+ options: external_exports.strictObject({
19465
+ harnesses: external_exports.array(harness).max(256),
19466
+ models: external_exports.array(model.nullable()).max(4096),
19467
+ projects: external_exports.array(project.nullable()).max(4096)
19468
+ }),
19469
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
19470
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
19471
+ */
19472
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
19473
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
19474
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
19475
+ */
19476
+ credits: external_exports.array(external_exports.strictObject({
19477
+ harness,
19478
+ model: model.nullable(),
19479
+ credits: external_exports.number().finite().min(0),
19480
+ reportedRequests: count2,
19481
+ requests: count2
19482
+ })).max(4096).optional(),
19483
+ /** All filters applied. */
19484
+ totals: usageStatisticsTotalsSchema,
19485
+ /** Each date and Harness of the range: every filter except the day. */
19486
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
19487
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
19488
+ hourly: external_exports.array(external_exports.strictObject({
19489
+ weekday: external_exports.number().int().min(0).max(6),
19490
+ hour: external_exports.number().int().min(0).max(23),
19491
+ ...totals
19492
+ })).max(168),
19493
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
19494
+ byModel: external_exports.array(external_exports.strictObject({
19495
+ model: model.nullable(),
19496
+ ...totals,
19497
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
19498
+ harnessPricedRequests: count2
19499
+ })).max(4096),
19500
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
19501
+ /**
19502
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
19503
+ * requests without a native session are not listed here but count everywhere else.
19504
+ */
19505
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100),
19506
+ /**
19507
+ * The sessions last active in the range, newest first, all filters applied. Optional for older
19508
+ * Hosts; missing is treated as no list rather than no sessions.
19509
+ */
19510
+ recentSessions: external_exports.array(usageStatisticsSessionSchema).max(100).optional()
19511
+ });
19512
+
19162
19513
  // ../../shared-contracts/dist/ids.js
19163
19514
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
19164
19515
  message: "Identifier must not be empty or whitespace"
@@ -19180,13 +19531,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
19180
19531
  var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
19181
19532
  var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
19182
19533
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
19534
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
19535
+ var harnessInstallationGuideSchema = external_exports.object({
19536
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
19537
+ before: localizedTextSchema.optional(),
19538
+ after: localizedTextSchema.optional(),
19539
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
19540
+ }).strict();
19183
19541
  var pluginPresentationShape = {
19184
19542
  id: harnessPluginIdSchema,
19185
19543
  name: external_exports.string().trim().min(1).max(128),
19186
19544
  version: external_exports.string().min(1).max(128),
19545
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
19546
+ kind: external_exports.literal("usage").optional(),
19547
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
19548
+ iconStyle: external_exports.object({
19549
+ vector: external_exports.object({
19550
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
19551
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
19552
+ paths: external_exports.array(external_exports.object({
19553
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
19554
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
19555
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
19556
+ }).strict()).min(1).max(32)
19557
+ }).strict().optional(),
19558
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
19559
+ borderRadius: external_exports.number().min(0).max(50).optional(),
19560
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
19561
+ }).strict().optional(),
19562
+ installation: harnessInstallationGuideSchema.optional(),
19563
+ notice: localizedTextSchema.optional(),
19187
19564
  /** The factory accepts a persisted local entrypoint through its construction context. */
19188
19565
  launchCommand: external_exports.literal(true).optional(),
19189
19566
  links: external_exports.object({
19567
+ website: documentationUrlSchema.optional(),
19190
19568
  documentation: documentationUrlSchema.optional(),
19191
19569
  installation: documentationUrlSchema.optional()
19192
19570
  }).strict().optional()
@@ -19263,6 +19641,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
19263
19641
  "codexhost/account/list",
19264
19642
  "codexhost/account/refresh",
19265
19643
  "codexhost/account/usage/inspect",
19644
+ "codexhost/usage/model-prices/get",
19645
+ "codexhost/usage/model-prices/set",
19646
+ "codexhost/usage/model-prices/default",
19647
+ "codexhost/usage/statistics/get",
19266
19648
  "codexhost/update/check",
19267
19649
  "codexhost/update/start",
19268
19650
  "codexhost/update/status"
@@ -19327,6 +19709,7 @@ var threadUsageSnapshotSchema = external_exports.object({
19327
19709
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
19328
19710
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
19329
19711
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
19712
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
19330
19713
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
19331
19714
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
19332
19715
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -19338,7 +19721,11 @@ var threadUsageSnapshotSchema = external_exports.object({
19338
19721
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
19339
19722
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
19340
19723
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
19341
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
19724
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
19725
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
19726
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
19727
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
19728
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
19342
19729
  }).strict().superRefine((usage, context) => {
19343
19730
  if (Object.keys(usage).length === 0) {
19344
19731
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -19359,6 +19746,20 @@ var threadUsageSnapshotSchema = external_exports.object({
19359
19746
  path: ["contextWindowTokens"]
19360
19747
  });
19361
19748
  }
19749
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
19750
+ context.addIssue({
19751
+ code: "custom",
19752
+ message: "Thread Usage costSource must be provided with totalCostUsd",
19753
+ path: ["costSource"]
19754
+ });
19755
+ }
19756
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
19757
+ context.addIssue({
19758
+ code: "custom",
19759
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
19760
+ path: ["unpricedModels"]
19761
+ });
19762
+ }
19362
19763
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
19363
19764
  context.addIssue({
19364
19765
  code: "custom",
@@ -19628,27 +20029,27 @@ var harnessModelCatalogSchema = external_exports.object({
19628
20029
  }).strict().superRefine((catalog, context) => {
19629
20030
  const refs = /* @__PURE__ */ new Set();
19630
20031
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
19631
- for (const [index, model] of catalog.models.entries()) {
19632
- if (refs.has(model.ref.id)) {
20032
+ for (const [index, model2] of catalog.models.entries()) {
20033
+ if (refs.has(model2.ref.id)) {
19633
20034
  context.addIssue({
19634
20035
  code: "custom",
19635
20036
  message: "Model Catalog refs must be unique",
19636
20037
  path: ["models", index, "ref", "id"]
19637
20038
  });
19638
20039
  }
19639
- refs.add(model.ref.id);
19640
- if (model.fastModel) {
19641
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
20040
+ refs.add(model2.ref.id);
20041
+ if (model2.fastModel) {
20042
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
19642
20043
  context.addIssue({
19643
20044
  code: "custom",
19644
20045
  message: "Fast Model refs must be distinct and unique",
19645
20046
  path: ["models", index, "fastModel"]
19646
20047
  });
19647
20048
  }
19648
- refs.add(model.fastModel.id);
20049
+ refs.add(model2.fastModel.id);
19649
20050
  }
19650
20051
  const supportedThinkingIds = /* @__PURE__ */ new Set();
19651
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
20052
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
19652
20053
  if (supportedThinkingIds.has(optionId)) {
19653
20054
  context.addIssue({
19654
20055
  code: "custom",
@@ -20242,6 +20643,11 @@ var codexSshDraftSchema = external_exports.strictObject({
20242
20643
  });
20243
20644
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
20244
20645
  external_exports.strictObject({ action: external_exports.literal("list") }),
20646
+ external_exports.strictObject({
20647
+ action: external_exports.literal("read-thread"),
20648
+ hostId: hostId.refine((id) => id !== "local"),
20649
+ input: delegationReadParamsSchema
20650
+ }),
20245
20651
  external_exports.strictObject({
20246
20652
  action: external_exports.literal("save"),
20247
20653
  draft: codexSshDraftSchema,
@@ -20373,7 +20779,6 @@ var tokenFields = [
20373
20779
  "cachedInputTokens",
20374
20780
  "cacheWriteInputTokens",
20375
20781
  "outputTokens",
20376
- "outputTokensPerSecond",
20377
20782
  "reasoningOutputTokens",
20378
20783
  "totalTokens",
20379
20784
  "contextWindowTokens",
@@ -20381,10 +20786,12 @@ var tokenFields = [
20381
20786
  ];
20382
20787
  var safeIntegerFields = [
20383
20788
  "planFiveHourResetsAtUnix",
20384
- "planSevenDayResetsAtUnix"
20789
+ "planSevenDayResetsAtUnix",
20790
+ "timeToFirstOutputMs"
20385
20791
  ];
20386
20792
  var percentFields = [
20387
20793
  "cacheHitRatePercent",
20794
+ "sessionCacheHitRatePercent",
20388
20795
  "planFiveHourUsedPercent",
20389
20796
  "planSevenDayUsedPercent"
20390
20797
  ];
@@ -20392,15 +20799,20 @@ var usageFields = /* @__PURE__ */ new Set([
20392
20799
  ...tokenFields,
20393
20800
  ...safeIntegerFields,
20394
20801
  ...percentFields,
20802
+ "sessionCacheUsage",
20395
20803
  "totalCostUsd",
20396
20804
  "totalCredits",
20397
- "contextUsagePercent"
20805
+ "contextUsagePercent",
20806
+ "outputTokensPerSecond",
20807
+ "apiOutputTokensPerSecond",
20808
+ "costSource",
20809
+ "unpricedModels"
20398
20810
  ]);
20399
- function isRecord2(value) {
20811
+ function isRecord3(value) {
20400
20812
  return typeof value === "object" && value !== null && !Array.isArray(value);
20401
20813
  }
20402
20814
  function parseHostUsage(value) {
20403
- if (!isRecord2(value))
20815
+ if (!isRecord3(value))
20404
20816
  throw new Error("Harness Usage must be an object");
20405
20817
  const keys = Object.keys(value);
20406
20818
  if (keys.length === 0)
@@ -20410,7 +20822,11 @@ function parseHostUsage(value) {
20410
20822
  throw new Error(`Harness Usage contains unknown field '${key}'`);
20411
20823
  }
20412
20824
  }
20413
- for (const field of ["totalCredits", "contextUsagePercent"]) {
20825
+ for (const field of [
20826
+ "totalCredits",
20827
+ "contextUsagePercent",
20828
+ "apiOutputTokensPerSecond"
20829
+ ]) {
20414
20830
  const candidate = value[field];
20415
20831
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
20416
20832
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -20446,6 +20862,12 @@ function parseHostUsage(value) {
20446
20862
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
20447
20863
  }
20448
20864
  }
20865
+ if (value.sessionCacheUsage !== void 0) {
20866
+ const totals2 = value.sessionCacheUsage;
20867
+ if (!isRecord3(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
20868
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
20869
+ }
20870
+ }
20449
20871
  const hasContextUsed = value.contextUsedTokens !== void 0;
20450
20872
  const hasContextWindow = value.contextWindowTokens !== void 0;
20451
20873
  if (hasContextUsed !== hasContextWindow) {
@@ -20460,8 +20882,43 @@ function parseHostUsage(value) {
20460
20882
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
20461
20883
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
20462
20884
  }
20885
+ if (value.costSource !== void 0) {
20886
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
20887
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
20888
+ }
20889
+ if (value.totalCostUsd === void 0) {
20890
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
20891
+ }
20892
+ }
20893
+ if (value.unpricedModels !== void 0) {
20894
+ const models = value.unpricedModels;
20895
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
20896
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
20897
+ }
20898
+ if (value.costSource !== "publicPrice") {
20899
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
20900
+ }
20901
+ return { ...value, unpricedModels: [...models] };
20902
+ }
20463
20903
  return { ...value };
20464
20904
  }
20905
+ var requestTokenFields = [
20906
+ "inputTokens",
20907
+ "cachedInputTokens",
20908
+ "cacheWriteInputTokens",
20909
+ "cacheWrite1hInputTokens",
20910
+ "outputTokens",
20911
+ "reasoningOutputTokens",
20912
+ "startedAtMs",
20913
+ "completedAtMs"
20914
+ ];
20915
+ var requestFields = /* @__PURE__ */ new Set([
20916
+ ...requestTokenFields,
20917
+ "requestId",
20918
+ "historical",
20919
+ "model",
20920
+ "provider"
20921
+ ]);
20465
20922
 
20466
20923
  // ../../harness-adapter/dist/live-command-catalog.js
20467
20924
  var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
@@ -20583,21 +21040,21 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
20583
21040
 
20584
21041
  // dist/acp-transport.js
20585
21042
  import { spawn, spawnSync } from "node:child_process";
20586
- import { readdir, readFile as readFile2 } from "node:fs/promises";
20587
- import os4 from "node:os";
20588
- import path10 from "node:path";
21043
+ import { readdir, readFile as readFile3 } from "node:fs/promises";
21044
+ import os5 from "node:os";
21045
+ import path12 from "node:path";
20589
21046
  import { Readable, Writable } from "node:stream";
20590
21047
 
20591
21048
  // dist/grok-slash-commands.js
20592
21049
  var GROK_LIVE_COMMAND_ID_PREFIX = "grok.slash.";
20593
- function isRecord3(value) {
21050
+ function isRecord4(value) {
20594
21051
  return typeof value === "object" && value !== null && !Array.isArray(value);
20595
21052
  }
20596
21053
  function parseGrokAvailableCommands(value) {
20597
21054
  if (!Array.isArray(value))
20598
21055
  return [];
20599
21056
  return value.flatMap((entry) => {
20600
- if (!isRecord3(entry))
21057
+ if (!isRecord4(entry))
20601
21058
  return [];
20602
21059
  const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
20603
21060
  if (!name)
@@ -20606,14 +21063,14 @@ function parseGrokAvailableCommands(value) {
20606
21063
  {
20607
21064
  name,
20608
21065
  description: typeof entry.description === "string" ? entry.description : "",
20609
- meta: isRecord3(entry._meta) ? entry._meta : null
21066
+ meta: isRecord4(entry._meta) ? entry._meta : null
20610
21067
  }
20611
21068
  ];
20612
21069
  });
20613
21070
  }
20614
21071
  function isGrokSkill(command) {
20615
- const path14 = command.meta?.path;
20616
- return typeof path14 === "string" && /(^|[\\/])SKILL\.md$/u.test(path14) || typeof command.meta?.qualifiedName === "string";
21072
+ const path16 = command.meta?.path;
21073
+ return typeof path16 === "string" && /(^|[\\/])SKILL\.md$/u.test(path16) || typeof command.meta?.qualifiedName === "string";
20617
21074
  }
20618
21075
  function grokLiveCommands(native) {
20619
21076
  return native.map((command) => ({
@@ -20624,7 +21081,7 @@ function grokLiveCommands(native) {
20624
21081
  }
20625
21082
 
20626
21083
  // dist/command.js
20627
- import path5 from "node:path";
21084
+ import path7 from "node:path";
20628
21085
  var GrokExecutableError = class extends Error {
20629
21086
  code = "GROK_NOT_FOUND";
20630
21087
  };
@@ -20653,7 +21110,7 @@ function resolveGrokExecutable(input = {}) {
20653
21110
  });
20654
21111
  if (!resolution)
20655
21112
  throw new GrokExecutableError("Grok CLI is not installed");
20656
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
21113
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
20657
21114
  }
20658
21115
  function grokInvocation(command, platform = process.platform, modelId) {
20659
21116
  const arguments_ = ["agent", "--no-leader"];
@@ -20666,11 +21123,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
20666
21123
 
20667
21124
  // dist/grok-fork.js
20668
21125
  import { isDeepStrictEqual } from "node:util";
20669
- import path8 from "node:path";
21126
+ import path10 from "node:path";
20670
21127
 
20671
21128
  // dist/grok-file-change.js
20672
21129
  import { Buffer as Buffer2 } from "node:buffer";
20673
- import path6 from "node:path";
21130
+ import path8 from "node:path";
20674
21131
 
20675
21132
  // ../../../node_modules/diff/libesm/diff/base.js
20676
21133
  var Diff = class {
@@ -20772,16 +21229,16 @@ var Diff = class {
20772
21229
  }
20773
21230
  }
20774
21231
  }
20775
- addToPath(path14, added, removed, oldPosInc, options) {
20776
- const last = path14.lastComponent;
21232
+ addToPath(path16, added, removed, oldPosInc, options) {
21233
+ const last = path16.lastComponent;
20777
21234
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20778
21235
  return {
20779
- oldPos: path14.oldPos + oldPosInc,
21236
+ oldPos: path16.oldPos + oldPosInc,
20780
21237
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20781
21238
  };
20782
21239
  } else {
20783
21240
  return {
20784
- oldPos: path14.oldPos + oldPosInc,
21241
+ oldPos: path16.oldPos + oldPosInc,
20785
21242
  lastComponent: { count: 1, added, removed, previousComponent: last }
20786
21243
  };
20787
21244
  }
@@ -21090,17 +21547,17 @@ function splitLines(text) {
21090
21547
  // dist/grok-file-change.js
21091
21548
  var DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT = 4 * 1024 * 1024;
21092
21549
  var MAX_GROK_FILE_CHANGES_PER_TOOL = 32;
21093
- function isRecord4(value) {
21550
+ function isRecord5(value) {
21094
21551
  return typeof value === "object" && value !== null && !Array.isArray(value);
21095
21552
  }
21096
21553
  function validAbsolutePath(value) {
21097
- return typeof value === "string" && path6.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21554
+ return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21098
21555
  }
21099
21556
  function displayPath(nativePath, cwd) {
21100
- const resolvedCwd = path6.resolve(cwd);
21101
- const resolvedPath = path6.resolve(nativePath);
21102
- const relative = path6.relative(resolvedCwd, resolvedPath);
21103
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path6.sep}`);
21557
+ const resolvedCwd = path8.resolve(cwd);
21558
+ const resolvedPath = path8.resolve(nativePath);
21559
+ const relative = path8.relative(resolvedCwd, resolvedPath);
21560
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
21104
21561
  const selected = inside ? relative : resolvedPath;
21105
21562
  const normalized = selected.replaceAll("\\", "/");
21106
21563
  if (normalized.length === 0 || normalized === ".")
@@ -21141,7 +21598,7 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21141
21598
  return null;
21142
21599
  const candidates = [];
21143
21600
  for (const entry of content) {
21144
- if (isRecord4(entry) && entry.type === "diff")
21601
+ if (isRecord5(entry) && entry.type === "diff")
21145
21602
  candidates.push(entry);
21146
21603
  }
21147
21604
  if (candidates.length === 0 || candidates.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
@@ -21162,8 +21619,8 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21162
21619
 
21163
21620
  // dist/local-media-markdown.js
21164
21621
  import { existsSync, statSync } from "node:fs";
21165
- import os3 from "node:os";
21166
- import path7 from "node:path";
21622
+ import os4 from "node:os";
21623
+ import path9 from "node:path";
21167
21624
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21168
21625
  ".aac",
21169
21626
  ".gif",
@@ -21182,14 +21639,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21182
21639
  ".webp"
21183
21640
  ]);
21184
21641
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21185
- const roots = [path7.resolve(cwd)];
21642
+ const roots = [path9.resolve(cwd)];
21186
21643
  if (sessionDirectory) {
21187
- const session = path7.resolve(sessionDirectory);
21188
- roots.push(session, path7.join(session, "videos"), path7.join(session, "images"));
21644
+ const session = path9.resolve(sessionDirectory);
21645
+ roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
21189
21646
  }
21190
- const home = process.env.HOME ?? process.env.USERPROFILE ?? os3.homedir();
21647
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
21191
21648
  if (home)
21192
- roots.push(path7.join(home, "Downloads"));
21649
+ roots.push(path9.join(home, "Downloads"));
21193
21650
  return roots;
21194
21651
  }
21195
21652
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -21290,7 +21747,7 @@ function parseInlineCode(text, start) {
21290
21747
  return { closed: false, content: text.slice(start + 1), end: text.length };
21291
21748
  }
21292
21749
  function mediaMarkdownImage(absolutePath) {
21293
- const name = path7.basename(absolutePath).replaceAll("]", "\\]");
21750
+ const name = path9.basename(absolutePath).replaceAll("]", "\\]");
21294
21751
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21295
21752
  }
21296
21753
  function parseMarkdownImage(text, start) {
@@ -21415,11 +21872,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21415
21872
  if (!hasMediaExtension(stripped))
21416
21873
  return null;
21417
21874
  if (isAbsoluteMediaPath(stripped)) {
21418
- const absolute = path7.resolve(stripped);
21875
+ const absolute = path9.resolve(stripped);
21419
21876
  return exists(absolute) ? absolute : null;
21420
21877
  }
21421
21878
  for (const root of roots) {
21422
- const absolute = path7.resolve(root, stripped);
21879
+ const absolute = path9.resolve(root, stripped);
21423
21880
  if (exists(absolute))
21424
21881
  return absolute;
21425
21882
  }
@@ -21441,11 +21898,11 @@ function stripFileUrl(value) {
21441
21898
  }
21442
21899
  }
21443
21900
  function isAbsoluteMediaPath(value) {
21444
- return path7.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21901
+ return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21445
21902
  }
21446
21903
  function hasMediaExtension(value) {
21447
21904
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21448
- return MEDIA_EXTENSIONS.has(path7.extname(pathname).toLowerCase());
21905
+ return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
21449
21906
  }
21450
21907
  function mediaFileExists(absolutePath) {
21451
21908
  try {
@@ -21458,14 +21915,14 @@ function mediaFileExists(absolutePath) {
21458
21915
  // dist/grok-tool-output.js
21459
21916
  var DEFAULT_GROK_TOOL_OUTPUT_LIMIT = 64e3;
21460
21917
  var EXECUTE_TOOL_NAMES = /* @__PURE__ */ new Set(["bash", "run_terminal_command", "shell", "cursor_shell"]);
21461
- function isRecord5(value) {
21918
+ function isRecord6(value) {
21462
21919
  return typeof value === "object" && value !== null && !Array.isArray(value);
21463
21920
  }
21464
21921
  function stringField(value, key) {
21465
- return isRecord5(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21922
+ return isRecord6(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21466
21923
  }
21467
21924
  function numberField(value, key) {
21468
- if (!isRecord5(value))
21925
+ if (!isRecord6(value))
21469
21926
  return void 0;
21470
21927
  const field = value[key];
21471
21928
  if (field === null)
@@ -21488,7 +21945,7 @@ function firstReadableText(...candidates) {
21488
21945
  for (const candidate of candidates) {
21489
21946
  if (typeof candidate === "string" && candidate.length > 0)
21490
21947
  return candidate;
21491
- if (isRecord5(candidate)) {
21948
+ if (isRecord6(candidate)) {
21492
21949
  const nested = stringField(candidate, "content") ?? stringField(candidate, "text") ?? stringField(candidate, "tool_result") ?? stringField(candidate, "raw_output");
21493
21950
  if (nested)
21494
21951
  return nested;
@@ -21511,7 +21968,7 @@ function grokToolArguments(rawInput) {
21511
21968
  if (!parsed.success)
21512
21969
  return {};
21513
21970
  const argumentsValue = parsed.data;
21514
- if (!isRecord5(argumentsValue) || stringField(argumentsValue, "path"))
21971
+ if (!isRecord6(argumentsValue) || stringField(argumentsValue, "path"))
21515
21972
  return argumentsValue;
21516
21973
  const targetFile = stringField(argumentsValue, "target_file");
21517
21974
  return targetFile ? { ...argumentsValue, path: targetFile } : argumentsValue;
@@ -21524,7 +21981,7 @@ function grokCommand(name, kind, rawInput) {
21524
21981
  return command;
21525
21982
  if (name && EXECUTE_TOOL_NAMES.has(name))
21526
21983
  return command;
21527
- return isRecord5(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21984
+ return isRecord6(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21528
21985
  }
21529
21986
  function grokCommandCwd(rawInput, fallback) {
21530
21987
  return stringField(rawInput, "cwd") ?? fallback;
@@ -21551,11 +22008,11 @@ function acpContentText(content) {
21551
22008
  if (!Array.isArray(content))
21552
22009
  return "";
21553
22010
  return content.flatMap((entry) => {
21554
- if (!isRecord5(entry))
22011
+ if (!isRecord6(entry))
21555
22012
  return [];
21556
22013
  if (entry.type === "text" && typeof entry.text === "string")
21557
22014
  return [entry.text];
21558
- if (entry.type !== "content" || !isRecord5(entry.content))
22015
+ if (entry.type !== "content" || !isRecord6(entry.content))
21559
22016
  return [];
21560
22017
  return entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : [];
21561
22018
  }).join("\n");
@@ -21566,10 +22023,10 @@ function acpContentImages(content, remainingBytes) {
21566
22023
  const images = [];
21567
22024
  let remaining = remainingBytes;
21568
22025
  for (const entry of content) {
21569
- if (!isRecord5(entry))
22026
+ if (!isRecord6(entry))
21570
22027
  continue;
21571
22028
  const image = entry.type === "image" ? entry : entry.type === "content" ? entry.content : null;
21572
- if (!isRecord5(image) || image.type !== "image")
22029
+ if (!isRecord6(image) || image.type !== "image")
21573
22030
  continue;
21574
22031
  const mimeType = stringField(image, "mimeType") ?? stringField(image, "mime_type");
21575
22032
  const data = stringField(image, "data");
@@ -21592,14 +22049,14 @@ function bashOutput(rawOutput) {
21592
22049
  function rawOutputProjection(rawOutput) {
21593
22050
  if (typeof rawOutput === "string")
21594
22051
  return rawOutput.length > 0 ? { text: rawOutput } : {};
21595
- if (!isRecord5(rawOutput))
22052
+ if (!isRecord6(rawOutput))
21596
22053
  return {};
21597
22054
  if (rawOutput.type === "Bash" || rawOutput.variant === "Bash" || numberField(rawOutput, "exit_code") !== void 0 || numberField(rawOutput, "exitCode") !== void 0) {
21598
22055
  const bash = bashOutput(rawOutput);
21599
22056
  if (bash.text !== void 0 || bash.exitCode !== void 0)
21600
22057
  return bash;
21601
22058
  }
21602
- const text = firstReadableText(rawOutput.content, rawOutput.text, rawOutput.tool_result, rawOutput.raw_output, isRecord5(rawOutput.FileContent) ? rawOutput.FileContent : void 0, isRecord5(rawOutput.Content) ? rawOutput.Content : void 0);
22059
+ const text = firstReadableText(rawOutput.content, rawOutput.text, rawOutput.tool_result, rawOutput.raw_output, isRecord6(rawOutput.FileContent) ? rawOutput.FileContent : void 0, isRecord6(rawOutput.Content) ? rawOutput.Content : void 0);
21603
22060
  if (text)
21604
22061
  return { text };
21605
22062
  if (typeof rawOutput.match_count === "number" && Number.isFinite(rawOutput.match_count)) {
@@ -21663,11 +22120,11 @@ var WAIT_TOOL_NAMES = /* @__PURE__ */ new Set([
21663
22120
  var KILL_TOOL_NAMES = /* @__PURE__ */ new Set(["kill_command_or_subagent", "kill_task"]);
21664
22121
  var DESCRIPTION_LIMIT = 500;
21665
22122
  var SUMMARY_LIMIT = 2e3;
21666
- function isRecord6(value) {
22123
+ function isRecord7(value) {
21667
22124
  return typeof value === "object" && value !== null && !Array.isArray(value);
21668
22125
  }
21669
22126
  function idField(value, key) {
21670
- if (!isRecord6(value))
22127
+ if (!isRecord7(value))
21671
22128
  return void 0;
21672
22129
  const field = value[key];
21673
22130
  if (typeof field === "string") {
@@ -21679,7 +22136,7 @@ function idField(value, key) {
21679
22136
  return void 0;
21680
22137
  }
21681
22138
  function stringField2(value, key) {
21682
- if (!isRecord6(value) || typeof value[key] !== "string")
22139
+ if (!isRecord7(value) || typeof value[key] !== "string")
21683
22140
  return void 0;
21684
22141
  const trimmed = value[key].trim();
21685
22142
  return trimmed.length > 0 ? trimmed : void 0;
@@ -21702,7 +22159,7 @@ function collectIds(value) {
21702
22159
  };
21703
22160
  push(idField(value, "task_id"));
21704
22161
  push(idField(value, "subagent_id"));
21705
- if (isRecord6(value)) {
22162
+ if (isRecord7(value)) {
21706
22163
  const list = value.task_ids ?? value.subagent_ids;
21707
22164
  if (Array.isArray(list)) {
21708
22165
  for (const entry of list)
@@ -21721,7 +22178,7 @@ function grokSubagentOperation(name, title, rawInput) {
21721
22178
  return "send";
21722
22179
  if (SPAWN_TOOL_NAMES.has(id))
21723
22180
  return "spawn";
21724
- if (isRecord6(rawInput) && rawInput.variant === "Task")
22181
+ if (isRecord7(rawInput) && rawInput.variant === "Task")
21725
22182
  return "spawn";
21726
22183
  return null;
21727
22184
  }
@@ -21744,7 +22201,7 @@ function grokSubagentRole(rawInput) {
21744
22201
  return bounded(stringField2(rawInput, "subagent_type") ?? stringField2(rawInput, "agent_type") ?? stringField2(rawInput, "type"), DESCRIPTION_LIMIT);
21745
22202
  }
21746
22203
  function grokSubagentBackground(rawInput) {
21747
- if (!isRecord6(rawInput))
22204
+ if (!isRecord7(rawInput))
21748
22205
  return true;
21749
22206
  if (rawInput.background === false || rawInput.run_in_background === false)
21750
22207
  return false;
@@ -21782,7 +22239,7 @@ function grokSubagentResultSummary(...candidates) {
21782
22239
  return void 0;
21783
22240
  }
21784
22241
  function grokSubagentEventFromUpdate(update) {
21785
- if (!isRecord6(update) || typeof update.sessionUpdate !== "string")
22242
+ if (!isRecord7(update) || typeof update.sessionUpdate !== "string")
21786
22243
  return null;
21787
22244
  const nativeSubagentId = idField(update, "subagent_id") ?? idField(update, "child_session_id");
21788
22245
  if (!nativeSubagentId)
@@ -21790,13 +22247,13 @@ function grokSubagentEventFromUpdate(update) {
21790
22247
  if (update.sessionUpdate === "subagent_spawned") {
21791
22248
  const description = bounded(stringField2(update, "description"), DESCRIPTION_LIMIT);
21792
22249
  const role = bounded(stringField2(update, "subagent_type") ?? stringField2(update, "role"), DESCRIPTION_LIMIT);
21793
- const model = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
22250
+ const model2 = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
21794
22251
  return {
21795
22252
  type: "subagent.spawned",
21796
22253
  nativeSubagentId,
21797
22254
  ...description ? { description } : {},
21798
22255
  ...role ? { role } : {},
21799
- ...model ? { model } : {}
22256
+ ...model2 ? { model: model2 } : {}
21800
22257
  };
21801
22258
  }
21802
22259
  if (update.sessionUpdate === "subagent_finished") {
@@ -21843,14 +22300,14 @@ function grokSubagentWaitSettlements(input) {
21843
22300
  return ids.map((id) => ({ id, status: overall }));
21844
22301
  }
21845
22302
  function taskOutputResults(rawOutput) {
21846
- if (!isRecord6(rawOutput))
22303
+ if (!isRecord7(rawOutput))
21847
22304
  return [];
21848
22305
  if (Array.isArray(rawOutput.results)) {
21849
- return rawOutput.results.filter(isRecord6);
22306
+ return rawOutput.results.filter(isRecord7);
21850
22307
  }
21851
22308
  const nested = firstRecord(rawOutput.MultiResult, rawOutput.multiResult, rawOutput.multi_result);
21852
22309
  if (nested && Array.isArray(nested.results)) {
21853
- return nested.results.filter(isRecord6);
22310
+ return nested.results.filter(isRecord7);
21854
22311
  }
21855
22312
  const single = firstRecord(rawOutput.Result, rawOutput.result);
21856
22313
  if (single)
@@ -21861,7 +22318,7 @@ function taskOutputResults(rawOutput) {
21861
22318
  }
21862
22319
  function firstRecord(...values) {
21863
22320
  for (const value of values) {
21864
- if (isRecord6(value))
22321
+ if (isRecord7(value))
21865
22322
  return value;
21866
22323
  }
21867
22324
  return void 0;
@@ -21884,7 +22341,7 @@ function taskOutputTextSettlements(rawOutput, content, ids) {
21884
22341
  return settled;
21885
22342
  }
21886
22343
  function taskOutputStatus(rawOutput, content) {
21887
- if (isRecord6(rawOutput) && typeof rawOutput.status === "string")
22344
+ if (isRecord7(rawOutput) && typeof rawOutput.status === "string")
21888
22345
  return rawOutput.status;
21889
22346
  const text = extractText(content) ?? extractText(rawOutput);
21890
22347
  if (!text)
@@ -21943,7 +22400,7 @@ function extractText(value, depth = 0) {
21943
22400
  const joined = parts.join("\n").trim();
21944
22401
  return joined.length > 0 ? joined : void 0;
21945
22402
  }
21946
- if (!isRecord6(value))
22403
+ if (!isRecord7(value))
21947
22404
  return void 0;
21948
22405
  if (typeof value.text === "string" && value.text.trim().length > 0)
21949
22406
  return value.text.trim();
@@ -22302,7 +22759,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22302
22759
  rememberSubagentAlias(event.callId, nativeSubagentId);
22303
22760
  const prompt = grokSubagentPrompt(event.rawInput);
22304
22761
  const role = grokSubagentRole(event.rawInput);
22305
- const model = grokSubagentModel(event.rawInput);
22762
+ const model2 = grokSubagentModel(event.rawInput);
22306
22763
  subagents.set(event.callId, {
22307
22764
  type: "subagentDelegation",
22308
22765
  itemId: stableId("subagent", turnIndex, ++messageIndex),
@@ -22314,7 +22771,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22314
22771
  ...nativeSubagentId ? { nativeSubagentId } : {},
22315
22772
  description: grokSubagentDescription(event.rawInput, event.title),
22316
22773
  ...role ? { role } : {},
22317
- ...model ? { model } : {},
22774
+ ...model2 ? { model: model2 } : {},
22318
22775
  background: grokSubagentBackground(event.rawInput),
22319
22776
  status: "running"
22320
22777
  }
@@ -22413,11 +22870,11 @@ var GROK_SESSION_DELETE_METHOD = "_x.ai/session/delete";
22413
22870
  function error51(code, message, retryable = false) {
22414
22871
  return { code, message, retryable };
22415
22872
  }
22416
- function isRecord7(value) {
22873
+ function isRecord8(value) {
22417
22874
  return typeof value === "object" && value !== null && !Array.isArray(value);
22418
22875
  }
22419
22876
  function isGrokMethodNotFound(error53) {
22420
- if (isRecord7(error53) && error53.code === -32601)
22877
+ if (isRecord8(error53) && error53.code === -32601)
22421
22878
  return true;
22422
22879
  const message = error53 instanceof Error ? error53.message : String(error53);
22423
22880
  return /method not found/iu.test(message);
@@ -22435,10 +22892,10 @@ function buildGrokForkParams(input) {
22435
22892
  };
22436
22893
  }
22437
22894
  function parseGrokForkResponse(value) {
22438
- if (!isRecord7(value) || value.error !== void 0)
22895
+ if (!isRecord8(value) || value.error !== void 0)
22439
22896
  return null;
22440
- const payload = typeof value.newSessionId !== "string" && isRecord7(value.result) ? value.result : value;
22441
- if (!isRecord7(payload) || payload.error !== void 0)
22897
+ const payload = typeof value.newSessionId !== "string" && isRecord8(value.result) ? value.result : value;
22898
+ if (!isRecord8(payload) || payload.error !== void 0)
22442
22899
  return null;
22443
22900
  if (typeof payload.newSessionId !== "string" || payload.newSessionId.length === 0)
22444
22901
  return null;
@@ -22454,11 +22911,11 @@ function parseGrokForkResponse(value) {
22454
22911
  }
22455
22912
  function projectRelativePath(value, cwds) {
22456
22913
  const normalized = value.replaceAll("\\", "/");
22457
- if (!path8.isAbsolute(value))
22914
+ if (!path10.isAbsolute(value))
22458
22915
  return normalized;
22459
22916
  for (const cwd of cwds) {
22460
- const relative = path8.relative(path8.resolve(cwd), path8.resolve(value));
22461
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`)) {
22917
+ const relative = path10.relative(path10.resolve(cwd), path10.resolve(value));
22918
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`)) {
22462
22919
  return relative.replaceAll("\\", "/");
22463
22920
  }
22464
22921
  }
@@ -22523,8 +22980,8 @@ async function forkGrokSession(input) {
22523
22980
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
22524
22981
  };
22525
22982
  }
22526
- const sourceCwd = path8.resolve(located.cwd);
22527
- const targetCwd = path8.resolve(input.cwd);
22983
+ const sourceCwd = path10.resolve(located.cwd);
22984
+ const targetCwd = path10.resolve(input.cwd);
22528
22985
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
22529
22986
  if (!source.ok)
22530
22987
  return source;
@@ -22599,9 +23056,10 @@ async function forkGrokSession(input) {
22599
23056
  // dist/grok-compaction.js
22600
23057
  var GROK_SESSION_UPDATE_EXTENSION_METHODS = [
22601
23058
  "_x.ai/session/update",
22602
- "x.ai/session_notification"
23059
+ "x.ai/session_notification",
23060
+ "_x.ai/session_notification"
22603
23061
  ];
22604
- function isRecord8(value) {
23062
+ function isRecord9(value) {
22605
23063
  return typeof value === "object" && value !== null && !Array.isArray(value);
22606
23064
  }
22607
23065
  function optionalNonNegativeInt(value) {
@@ -22622,7 +23080,7 @@ function isGrokExtensionSessionUpdateMethod(method) {
22622
23080
  return GROK_SESSION_UPDATE_EXTENSION_METHODS.includes(method);
22623
23081
  }
22624
23082
  function grokCompactionEventFromUpdate(update) {
22625
- if (!isRecord8(update) || typeof update.sessionUpdate !== "string")
23083
+ if (!isRecord9(update) || typeof update.sessionUpdate !== "string")
22626
23084
  return null;
22627
23085
  const tokensUsed = optionalNonNegativeInt(firstPresent(update, ["tokensUsed", "tokens_used"]));
22628
23086
  const contextWindowTokens = optionalNonNegativeInt(firstPresent(update, ["contextWindowTokens", "contextWindow", "context_window"]));
@@ -22661,7 +23119,7 @@ function grokCompactionEventFromUpdate(update) {
22661
23119
  // dist/grok-manual-compaction.js
22662
23120
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
22663
23121
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
22664
- function isRecord9(value) {
23122
+ function isRecord10(value) {
22665
23123
  return typeof value === "object" && value !== null && !Array.isArray(value);
22666
23124
  }
22667
23125
  function optionalNonNegativeInt2(value) {
@@ -22673,7 +23131,7 @@ function optionalErrorMessage2(value) {
22673
23131
  function parseGrokCompactResult(value, cancelled = false) {
22674
23132
  if (cancelled)
22675
23133
  return { outcome: "cancelled" };
22676
- if (!isRecord9(value))
23134
+ if (!isRecord10(value))
22677
23135
  return { outcome: "succeeded" };
22678
23136
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
22679
23137
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -22706,12 +23164,12 @@ function parseGrokCompactResult(value, cancelled = false) {
22706
23164
  }
22707
23165
 
22708
23166
  // dist/grok-rewind.js
22709
- import path9 from "node:path";
23167
+ import path11 from "node:path";
22710
23168
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
22711
23169
  function error52(code, message, retryable = false) {
22712
23170
  return { code, message, retryable };
22713
23171
  }
22714
- function isRecord10(value) {
23172
+ function isRecord11(value) {
22715
23173
  return typeof value === "object" && value !== null && !Array.isArray(value);
22716
23174
  }
22717
23175
  function buildGrokRewindParams(input) {
@@ -22723,10 +23181,10 @@ function buildGrokRewindParams(input) {
22723
23181
  };
22724
23182
  }
22725
23183
  function parseGrokRewindResponse(value) {
22726
- if (!isRecord10(value))
23184
+ if (!isRecord11(value))
22727
23185
  return null;
22728
- const payload = typeof value.success !== "boolean" && isRecord10(value.result) ? value.result : value;
22729
- if (!isRecord10(payload) || typeof payload.success !== "boolean")
23186
+ const payload = typeof value.success !== "boolean" && isRecord11(value.result) ? value.result : value;
23187
+ if (!isRecord11(payload) || typeof payload.success !== "boolean")
22730
23188
  return null;
22731
23189
  return rewindPayload(payload);
22732
23190
  }
@@ -22779,8 +23237,8 @@ async function rewindGrokLastTurn(input) {
22779
23237
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
22780
23238
  };
22781
23239
  }
22782
- const sourceCwd = path9.resolve(located.cwd);
22783
- const targetCwd = path9.resolve(input.cwd);
23240
+ const sourceCwd = path11.resolve(located.cwd);
23241
+ const targetCwd = path11.resolve(input.cwd);
22784
23242
  if (sourceCwd !== targetCwd) {
22785
23243
  return {
22786
23244
  ok: false,
@@ -22842,7 +23300,7 @@ var GROK_PLAN_STAY_VALUE = "stay";
22842
23300
  var GROK_PLAN_STAY_LABEL = "Stay in plan mode";
22843
23301
  var GROK_PLAN_OUTCOME_APPROVED = "approved";
22844
23302
  var GROK_PLAN_OUTCOME_CANCELLED = "cancelled";
22845
- function isRecord11(value) {
23303
+ function isRecord12(value) {
22846
23304
  return typeof value === "object" && value !== null && !Array.isArray(value);
22847
23305
  }
22848
23306
  function stringField3(value, ...keys) {
@@ -22854,9 +23312,9 @@ function stringField3(value, ...keys) {
22854
23312
  return void 0;
22855
23313
  }
22856
23314
  function parseGrokExitPlanModeParams(params) {
22857
- if (!isRecord11(params))
23315
+ if (!isRecord12(params))
22858
23316
  return null;
22859
- const nested = isRecord11(params.input) ? params.input : params;
23317
+ const nested = isRecord12(params.input) ? params.input : params;
22860
23318
  const plan = stringField3(nested, "planContent", "plan_content", "plan") ?? stringField3(params, "planContent", "plan_content", "plan") ?? null;
22861
23319
  const planFilePath = stringField3(nested, "planFilePath", "plan_file_path") ?? stringField3(params, "planFilePath", "plan_file_path");
22862
23320
  const sessionId = stringField3(params, "sessionId", "session_id");
@@ -22928,7 +23386,7 @@ var GROK_ACP_CLIENT_CAPABILITIES = {
22928
23386
  "x.ai/exit_plan_mode": true
22929
23387
  }
22930
23388
  };
22931
- function isRecord12(value) {
23389
+ function isRecord13(value) {
22932
23390
  return typeof value === "object" && value !== null && !Array.isArray(value);
22933
23391
  }
22934
23392
  function stringField4(value, ...keys) {
@@ -22957,15 +23415,15 @@ function isGrokExitPlanModeMethod(method) {
22957
23415
  function questionsPayload(params) {
22958
23416
  if (Array.isArray(params.questions))
22959
23417
  return params.questions;
22960
- if (isRecord12(params.input) && Array.isArray(params.input.questions))
23418
+ if (isRecord13(params.input) && Array.isArray(params.input.questions))
22961
23419
  return params.input.questions;
22962
- if (isRecord12(params.askUserQuestion) && Array.isArray(params.askUserQuestion.questions)) {
23420
+ if (isRecord13(params.askUserQuestion) && Array.isArray(params.askUserQuestion.questions)) {
22963
23421
  return params.askUserQuestion.questions;
22964
23422
  }
22965
23423
  return void 0;
22966
23424
  }
22967
23425
  function parseOption(value, labels) {
22968
- if (!isRecord12(value))
23426
+ if (!isRecord13(value))
22969
23427
  return null;
22970
23428
  const label = stringField4(value, "label");
22971
23429
  if (!label || labels.has(label))
@@ -22980,7 +23438,7 @@ function parseOption(value, labels) {
22980
23438
  };
22981
23439
  }
22982
23440
  function parseQuestion(value, questions) {
22983
- if (!isRecord12(value))
23441
+ if (!isRecord13(value))
22984
23442
  return null;
22985
23443
  const question = stringField4(value, "question");
22986
23444
  if (!question || questions.has(question))
@@ -23005,7 +23463,7 @@ function parseQuestion(value, questions) {
23005
23463
  };
23006
23464
  }
23007
23465
  function parseGrokAskUserQuestionParams(params) {
23008
- if (!isRecord12(params))
23466
+ if (!isRecord13(params))
23009
23467
  return null;
23010
23468
  const rawQuestions = questionsPayload(params);
23011
23469
  if (!Array.isArray(rawQuestions) || rawQuestions.length === 0)
@@ -23120,16 +23578,16 @@ var GrokTransportError = class extends Error {
23120
23578
  this.name = "GrokTransportError";
23121
23579
  }
23122
23580
  };
23123
- function isRecord13(value) {
23581
+ function isRecord14(value) {
23124
23582
  return typeof value === "object" && value !== null && !Array.isArray(value);
23125
23583
  }
23126
23584
  function acpToolName(update, metadata) {
23127
- if (!isRecord13(update))
23585
+ if (!isRecord14(update))
23128
23586
  return void 0;
23129
23587
  if (typeof update.name === "string" && update.name.length > 0)
23130
23588
  return update.name;
23131
- const meta3 = isRecord13(update._meta) ? update._meta : metadata;
23132
- const tool = meta3 && isRecord13(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23589
+ const meta3 = isRecord14(update._meta) ? update._meta : metadata;
23590
+ const tool = meta3 && isRecord14(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23133
23591
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
23134
23592
  }
23135
23593
  function errorText(error53) {
@@ -23185,12 +23643,27 @@ function signalProcessTree(child, signal) {
23185
23643
  try {
23186
23644
  process.kill(-child.pid, signal);
23187
23645
  } catch (error53) {
23188
- if (!isRecord13(error53) || error53.code !== "ESRCH")
23646
+ if (!isRecord14(error53) || error53.code !== "ESRCH")
23189
23647
  throw error53;
23190
23648
  }
23191
23649
  }
23192
23650
  function transportEvent(update, metadata) {
23193
23651
  const extension = update;
23652
+ if (extension.sessionUpdate === "response_completed") {
23653
+ return {
23654
+ type: "response.completed",
23655
+ ...extension.usage !== void 0 ? { usage: extension.usage } : {},
23656
+ ...typeof extension.message_id === "string" && extension.message_id ? { messageId: extension.message_id } : {},
23657
+ ...metadata ? { metadata } : {}
23658
+ };
23659
+ }
23660
+ if (extension.sessionUpdate === "tool_call_delta_chunk" && typeof extension.arguments_delta === "string") {
23661
+ return {
23662
+ type: "tool.input.delta",
23663
+ text: extension.arguments_delta,
23664
+ ...metadata ? { metadata } : {}
23665
+ };
23666
+ }
23194
23667
  if (extension.sessionUpdate === "turn_completed" && typeof extension.prompt_id === "string" && extension.prompt_id.length > 0 && typeof extension.stop_reason === "string") {
23195
23668
  return {
23196
23669
  type: "turn.completed",
@@ -23260,34 +23733,34 @@ function transportEvent(update, metadata) {
23260
23733
  }
23261
23734
  function grokHomeDir(options) {
23262
23735
  const environment = { ...process.env, ...options.environment };
23263
- const home = environment.HOME ?? environment.USERPROFILE ?? os4.homedir();
23264
- return environment.GROK_HOME ?? path10.join(home, ".grok");
23736
+ const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23737
+ return environment.GROK_HOME ?? path12.join(home, ".grok");
23265
23738
  }
23266
23739
  function grokNativeSessionDirectory(options, sessionId) {
23267
- return path10.join(grokHomeDir(options), "sessions", encodeURIComponent(path10.resolve(options.cwd)), sessionId);
23740
+ return path12.join(grokHomeDir(options), "sessions", encodeURIComponent(path12.resolve(options.cwd)), sessionId);
23268
23741
  }
23269
23742
  function nativeSessionFile(options, sessionId, fileName) {
23270
- return path10.join(grokNativeSessionDirectory(options, sessionId), fileName);
23743
+ return path12.join(grokNativeSessionDirectory(options, sessionId), fileName);
23271
23744
  }
23272
23745
  function nativeHistoryPath(options, sessionId) {
23273
23746
  return nativeSessionFile(options, sessionId, "updates.jsonl");
23274
23747
  }
23275
23748
  async function readNativeSignals(options, sessionId) {
23276
23749
  try {
23277
- return JSON.parse(await readFile2(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23750
+ return JSON.parse(await readFile3(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23278
23751
  } catch {
23279
23752
  return void 0;
23280
23753
  }
23281
23754
  }
23282
23755
  function isMissingFile(error53) {
23283
- return isRecord13(error53) && error53.code === "ENOENT";
23756
+ return isRecord14(error53) && error53.code === "ENOENT";
23284
23757
  }
23285
23758
  async function locateGrokNativeSession(options, sessionId) {
23286
23759
  if (sessionId.length === 0)
23287
23760
  return null;
23288
23761
  let entries;
23289
23762
  try {
23290
- entries = await readdir(path10.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23763
+ entries = await readdir(path12.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23291
23764
  } catch (error53) {
23292
23765
  if (isMissingFile(error53))
23293
23766
  return null;
@@ -23301,9 +23774,9 @@ async function locateGrokNativeSession(options, sessionId) {
23301
23774
  continue;
23302
23775
  let summaryRaw;
23303
23776
  try {
23304
- summaryRaw = await readFile2(path10.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23777
+ summaryRaw = await readFile3(path12.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23305
23778
  } catch (error53) {
23306
- if (isMissingFile(error53) || isRecord13(error53) && error53.code === "ENOTDIR")
23779
+ if (isMissingFile(error53) || isRecord14(error53) && error53.code === "ENOTDIR")
23307
23780
  continue;
23308
23781
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
23309
23782
  cause: error53
@@ -23315,11 +23788,11 @@ async function locateGrokNativeSession(options, sessionId) {
23315
23788
  } catch {
23316
23789
  continue;
23317
23790
  }
23318
- if (!isRecord13(parsed))
23791
+ if (!isRecord14(parsed))
23319
23792
  continue;
23320
23793
  const info = parsed.info;
23321
- const cwd = isRecord13(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path10.resolve(info.cwd) : path10.resolve(decodeURIComponent(entry.name));
23322
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path10.resolve(parsed.source_workspace_dir) : void 0;
23794
+ const cwd = isRecord14(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path12.resolve(info.cwd) : path12.resolve(decodeURIComponent(entry.name));
23795
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path12.resolve(parsed.source_workspace_dir) : void 0;
23323
23796
  matches.push({
23324
23797
  cwd,
23325
23798
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23329,7 +23802,7 @@ async function locateGrokNativeSession(options, sessionId) {
23329
23802
  }
23330
23803
  async function readGrokNativeHistory(options, sessionId) {
23331
23804
  try {
23332
- return parseNativeHistory(await readFile2(nativeHistoryPath({ ...options, cwd: path10.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23805
+ return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path12.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23333
23806
  } catch (error53) {
23334
23807
  if (isMissingFile(error53))
23335
23808
  return [];
@@ -23351,12 +23824,12 @@ function parseNativeHistory(contents, sessionId) {
23351
23824
  } catch {
23352
23825
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23353
23826
  }
23354
- if (!isRecord13(record2) || !isRecord13(record2.params))
23827
+ if (!isRecord14(record2) || !isRecord14(record2.params))
23355
23828
  continue;
23356
23829
  const params = record2.params;
23357
- if (params.sessionId !== sessionId || !isRecord13(params.update))
23830
+ if (params.sessionId !== sessionId || !isRecord14(params.update))
23358
23831
  continue;
23359
- const metadata = isRecord13(params._meta) ? params._meta : void 0;
23832
+ const metadata = isRecord14(params._meta) ? params._meta : void 0;
23360
23833
  const event = transportEvent(params.update, metadata);
23361
23834
  if (event)
23362
23835
  events.push(metadata ? { ...event, metadata } : event);
@@ -23413,6 +23886,13 @@ var GrokAcpTransport = class {
23413
23886
  async getHistory() {
23414
23887
  return this.readHistory(this.sessionId);
23415
23888
  }
23889
+ /** Native cumulative usage since this process attached, not persisted Session totals. */
23890
+ async getUsage() {
23891
+ if (!this.#connection)
23892
+ throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
23893
+ const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
23894
+ return isRecord14(result) ? result.usage : void 0;
23895
+ }
23416
23896
  async readHistory(sessionId, cwd = this.#options.cwd) {
23417
23897
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
23418
23898
  }
@@ -23616,6 +24096,7 @@ var GrokAcpTransport = class {
23616
24096
  prompt: [{ type: "text", text }]
23617
24097
  });
23618
24098
  } finally {
24099
+ await yieldToEventLoop();
23619
24100
  if (this.#activePrompt === active)
23620
24101
  this.#activePrompt = null;
23621
24102
  }
@@ -23654,16 +24135,17 @@ var GrokAcpTransport = class {
23654
24135
  this.#activeCompact = null;
23655
24136
  }
23656
24137
  }
23657
- async setModel(modelId, reasoningEffort) {
24138
+ async setModel(modelId, reasoningEffort, contextWindowTokens) {
23658
24139
  const connection = this.#connection;
23659
24140
  if (!connection || !this.#sessionId)
23660
24141
  throw new Error("Grok ACP Session is unavailable");
23661
24142
  const response = await connection.request("session/set_model", {
23662
24143
  sessionId: this.#sessionId,
23663
24144
  modelId,
23664
- ...reasoningEffort ? { reasoningEffort } : {}
24145
+ ...reasoningEffort ? { reasoningEffort } : {},
24146
+ ...contextWindowTokens !== void 0 ? { _meta: { contextWindow: contextWindowTokens } } : {}
23665
24147
  });
23666
- if (!isRecord13(response) || !isRecord13(response._meta) || !isRecord13(response._meta.model)) {
24148
+ if (!isRecord14(response) || !isRecord14(response._meta) || !isRecord14(response._meta.model)) {
23667
24149
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
23668
24150
  }
23669
24151
  const selected = response._meta.model.Ok;
@@ -23715,7 +24197,7 @@ var GrokAcpTransport = class {
23715
24197
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
23716
24198
  return;
23717
24199
  }
23718
- const metadata = isRecord13(notification._meta) ? notification._meta : void 0;
24200
+ const metadata = isRecord14(notification._meta) ? notification._meta : void 0;
23719
24201
  const event = transportEvent(notification.update, metadata);
23720
24202
  if (!event)
23721
24203
  return;
@@ -23730,7 +24212,7 @@ var GrokAcpTransport = class {
23730
24212
  #handleExtensionNotification(method, params) {
23731
24213
  if (!isGrokExtensionSessionUpdateMethod(method))
23732
24214
  return;
23733
- if (typeof params.sessionId !== "string" || !isRecord13(params.update))
24215
+ if (typeof params.sessionId !== "string" || !isRecord14(params.update))
23734
24216
  return;
23735
24217
  this.#handleUpdate(params);
23736
24218
  }
@@ -23758,13 +24240,13 @@ var GrokAcpTransport = class {
23758
24240
  };
23759
24241
 
23760
24242
  // dist/session-import.js
23761
- import { createReadStream } from "node:fs";
23762
- import { opendir, readFile as readFile3, stat } from "node:fs/promises";
23763
- import path11 from "node:path";
23764
- import { createInterface } from "node:readline";
24243
+ import { createReadStream as createReadStream2 } from "node:fs";
24244
+ import { opendir as opendir2, readFile as readFile4, stat } from "node:fs/promises";
24245
+ import path13 from "node:path";
24246
+ import { createInterface as createInterface2 } from "node:readline";
23765
24247
 
23766
24248
  // ../../harness-adapter/dist/session-import.js
23767
- import { lstat } from "node:fs/promises";
24249
+ import { lstat as lstat2 } from "node:fs/promises";
23768
24250
  var SessionImportChangedError = class extends Error {
23769
24251
  constructor(message = "Native Session changed during discovery; refresh and retry") {
23770
24252
  super(message);
@@ -23783,7 +24265,7 @@ function isStorageAccessError(error53) {
23783
24265
  }
23784
24266
  async function optionalLstat(file2) {
23785
24267
  try {
23786
- return await lstat(file2);
24268
+ return await lstat2(file2);
23787
24269
  } catch (error53) {
23788
24270
  if (isMissingFileError(error53))
23789
24271
  return null;
@@ -23881,11 +24363,11 @@ var SessionImportScope = class {
23881
24363
  // dist/session-import.js
23882
24364
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
23883
24365
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
23884
- function isRecord14(value) {
24366
+ function isRecord15(value) {
23885
24367
  return typeof value === "object" && value !== null && !Array.isArray(value);
23886
24368
  }
23887
24369
  async function readJson(file2, signal) {
23888
- return JSON.parse(await readFile3(file2, { encoding: "utf8", signal }));
24370
+ return JSON.parse(await readFile4(file2, { encoding: "utf8", signal }));
23889
24371
  }
23890
24372
  function processAlive(pid) {
23891
24373
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -23894,12 +24376,12 @@ function processAlive(pid) {
23894
24376
  process.kill(pid, 0);
23895
24377
  return true;
23896
24378
  } catch (error53) {
23897
- return isRecord14(error53) && error53.code === "EPERM";
24379
+ return isRecord15(error53) && error53.code === "EPERM";
23898
24380
  }
23899
24381
  }
23900
24382
  async function firstUserText(file2, signal) {
23901
- const stream = createReadStream(file2, { encoding: "utf8", signal });
23902
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
24383
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
24384
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
23903
24385
  try {
23904
24386
  for await (const line of lines) {
23905
24387
  signal.throwIfAborted();
@@ -23911,10 +24393,10 @@ async function firstUserText(file2, signal) {
23911
24393
  } catch {
23912
24394
  continue;
23913
24395
  }
23914
- const update = isRecord14(entry) && isRecord14(entry.params) ? entry.params.update : null;
23915
- if (!isRecord14(update) || update.sessionUpdate !== "user_message_chunk")
24396
+ const update = isRecord15(entry) && isRecord15(entry.params) ? entry.params.update : null;
24397
+ if (!isRecord15(update) || update.sessionUpdate !== "user_message_chunk")
23916
24398
  continue;
23917
- const text = isRecord14(update.content) ? update.content.text : null;
24399
+ const text = isRecord15(update.content) ? update.content.text : null;
23918
24400
  return typeof text === "string" ? text : "";
23919
24401
  }
23920
24402
  return null;
@@ -23981,7 +24463,7 @@ var GrokSessionImport = class {
23981
24463
  const active = /* @__PURE__ */ new Set();
23982
24464
  let entries;
23983
24465
  try {
23984
- entries = await readJson(path11.join(this.#home(), "active_sessions.json"), signal);
24466
+ entries = await readJson(path13.join(this.#home(), "active_sessions.json"), signal);
23985
24467
  } catch (error53) {
23986
24468
  signal.throwIfAborted();
23987
24469
  if (isStorageAccessError(error53))
@@ -23991,26 +24473,26 @@ var GrokSessionImport = class {
23991
24473
  if (!Array.isArray(entries))
23992
24474
  return active;
23993
24475
  for (const entry of entries) {
23994
- if (isRecord14(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24476
+ if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
23995
24477
  active.add(entry.session_id);
23996
24478
  }
23997
24479
  return active;
23998
24480
  }
23999
24481
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
24000
24482
  async #sessionDirectories(signal) {
24001
- const root = path11.join(this.#home(), "sessions");
24483
+ const root = path13.join(this.#home(), "sessions");
24002
24484
  const found = /* @__PURE__ */ new Map();
24003
24485
  const info = await optionalLstat(root);
24004
24486
  if (!info)
24005
24487
  return found;
24006
24488
  if (!info.isDirectory())
24007
24489
  throw new Error("Grok Session store is not a directory");
24008
- for await (const workspace of await opendir(root)) {
24490
+ for await (const workspace of await opendir2(root)) {
24009
24491
  signal.throwIfAborted();
24010
24492
  if (!workspace.isDirectory())
24011
24493
  continue;
24012
- const workspaceDirectory = path11.join(root, workspace.name);
24013
- const sessions = await opendir(workspaceDirectory).catch((error53) => {
24494
+ const workspaceDirectory = path13.join(root, workspace.name);
24495
+ const sessions = await opendir2(workspaceDirectory).catch((error53) => {
24014
24496
  if (isMissingFileError(error53))
24015
24497
  return null;
24016
24498
  throw error53;
@@ -24022,7 +24504,7 @@ var GrokSessionImport = class {
24022
24504
  if (!session.isDirectory())
24023
24505
  continue;
24024
24506
  const directories = found.get(session.name) ?? [];
24025
- directories.push(path11.join(workspaceDirectory, session.name));
24507
+ directories.push(path13.join(workspaceDirectory, session.name));
24026
24508
  found.set(session.name, directories);
24027
24509
  }
24028
24510
  }
@@ -24030,25 +24512,25 @@ var GrokSessionImport = class {
24030
24512
  }
24031
24513
  async #candidate(sessionDirectory, active, signal) {
24032
24514
  signal.throwIfAborted();
24033
- const nativeSessionId = path11.basename(sessionDirectory);
24515
+ const nativeSessionId = path13.basename(sessionDirectory);
24034
24516
  const files = [
24035
- path11.join(sessionDirectory, "summary.json"),
24036
- path11.join(sessionDirectory, "updates.jsonl")
24517
+ path13.join(sessionDirectory, "summary.json"),
24518
+ path13.join(sessionDirectory, "updates.jsonl")
24037
24519
  ];
24038
24520
  return readStableFiles(files, async ([summaryInfo, updates]) => {
24039
24521
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24040
24522
  return null;
24041
24523
  try {
24042
24524
  const summary = await readJson(files[0], signal);
24043
- if (!isRecord14(summary) || !isRecord14(summary.info) || summary.info.id !== nativeSessionId)
24525
+ if (!isRecord15(summary) || !isRecord15(summary.info) || summary.info.id !== nativeSessionId)
24044
24526
  return null;
24045
24527
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24046
24528
  return null;
24047
24529
  const nativeCwd = summary.info.cwd;
24048
- if (typeof nativeCwd !== "string" || !path11.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24530
+ if (typeof nativeCwd !== "string" || !path13.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24049
24531
  return null;
24050
- const cwd = path11.resolve(nativeCwd);
24051
- if (encodeURIComponent(cwd) !== path11.basename(path11.dirname(sessionDirectory)))
24532
+ const cwd = path13.resolve(nativeCwd);
24533
+ if (encodeURIComponent(cwd) !== path13.basename(path13.dirname(sessionDirectory)))
24052
24534
  return null;
24053
24535
  if (!(await stat(cwd)).isDirectory())
24054
24536
  return null;
@@ -24267,7 +24749,7 @@ var GrokSubagentLifecycle = class {
24267
24749
  };
24268
24750
 
24269
24751
  // dist/grok-models.js
24270
- function isRecord15(value) {
24752
+ function isRecord16(value) {
24271
24753
  return typeof value === "object" && value !== null && !Array.isArray(value);
24272
24754
  }
24273
24755
  function nonBlank(value) {
@@ -24279,7 +24761,7 @@ function thinkingOptions(value) {
24279
24761
  const seen = /* @__PURE__ */ new Set();
24280
24762
  const options = [];
24281
24763
  for (const candidate of value) {
24282
- if (!isRecord15(candidate) || !nonBlank(candidate.label))
24764
+ if (!isRecord16(candidate) || !nonBlank(candidate.label))
24283
24765
  continue;
24284
24766
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
24285
24767
  if (!id.success || seen.has(id.data))
@@ -24290,7 +24772,7 @@ function thinkingOptions(value) {
24290
24772
  return options;
24291
24773
  }
24292
24774
  function parseGrokModelState(value) {
24293
- if (!isRecord15(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24775
+ if (!isRecord16(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24294
24776
  return null;
24295
24777
  }
24296
24778
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -24298,16 +24780,20 @@ function parseGrokModelState(value) {
24298
24780
  return null;
24299
24781
  const allThinking = /* @__PURE__ */ new Map();
24300
24782
  const contextWindowTokensByModel = /* @__PURE__ */ new Map();
24783
+ const defaultContextWindowTokensByModel = /* @__PURE__ */ new Map();
24301
24784
  const models = [];
24302
24785
  let currentThinkingOptionId;
24303
24786
  for (const candidate of value.availableModels) {
24304
- if (!isRecord15(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24787
+ if (!isRecord16(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24305
24788
  continue;
24306
24789
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
24307
24790
  if (!ref.success)
24308
24791
  continue;
24309
- const metadata = isRecord15(candidate._meta) ? candidate._meta : {};
24792
+ const metadata = isRecord16(candidate._meta) ? candidate._meta : {};
24310
24793
  const options2 = thinkingOptions(metadata.reasoningEfforts);
24794
+ if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
24795
+ defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
24796
+ }
24311
24797
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
24312
24798
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
24313
24799
  }
@@ -24331,6 +24817,7 @@ function parseGrokModelState(value) {
24331
24817
  return {
24332
24818
  currentModel: currentModel.data,
24333
24819
  contextWindowTokensByModel,
24820
+ defaultContextWindowTokensByModel,
24334
24821
  ...currentThinkingOptionId ? { currentThinkingOptionId } : {},
24335
24822
  catalog: {
24336
24823
  models,
@@ -24341,13 +24828,13 @@ function parseGrokModelState(value) {
24341
24828
  };
24342
24829
  }
24343
24830
  function modelStateFromInitialize(response) {
24344
- return parseGrokModelState(isRecord15(response._meta) ? response._meta.modelState : void 0);
24831
+ return parseGrokModelState(isRecord16(response._meta) ? response._meta.modelState : void 0);
24345
24832
  }
24346
24833
  function modelStateFromSessionResponse(response) {
24347
- return parseGrokModelState(isRecord15(response) ? response.models : void 0);
24834
+ return parseGrokModelState(isRecord16(response) ? response.models : void 0);
24348
24835
  }
24349
- function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24350
- const selectedModel = model;
24836
+ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24837
+ const selectedModel = model2;
24351
24838
  const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === selectedModel.id);
24352
24839
  const availableThinkingOptions = catalogModel?.supportedThinkingOptionIds?.flatMap((id) => {
24353
24840
  const option = modelState.catalog.thinkingOptions.find((candidate) => candidate.id === id);
@@ -24363,12 +24850,12 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
24363
24850
  }
24364
24851
 
24365
24852
  // dist/grok-credits.js
24366
- import { readFile as readFile4 } from "node:fs/promises";
24367
- import os5 from "node:os";
24368
- import path12 from "node:path";
24853
+ import { readFile as readFile5 } from "node:fs/promises";
24854
+ import os6 from "node:os";
24855
+ import path14 from "node:path";
24369
24856
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
24370
24857
  var REQUEST_TIMEOUT_MS = 15e3;
24371
- function isRecord16(value) {
24858
+ function isRecord17(value) {
24372
24859
  return typeof value === "object" && value !== null && !Array.isArray(value);
24373
24860
  }
24374
24861
  function finitePercent(value) {
@@ -24377,15 +24864,15 @@ function finitePercent(value) {
24377
24864
  return Math.min(100, Math.max(0, value));
24378
24865
  }
24379
24866
  function nonNegativeCentValue(value) {
24380
- if (!isRecord16(value))
24867
+ if (!isRecord17(value))
24381
24868
  return void 0;
24382
24869
  const amount = value.val === void 0 ? 0 : value.val;
24383
24870
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
24384
24871
  return void 0;
24385
24872
  return amount;
24386
24873
  }
24387
- function grokHome(environment) {
24388
- return environment.GROK_HOME ?? path12.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
24874
+ function grokHome2(environment) {
24875
+ return environment.GROK_HOME ?? path14.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
24389
24876
  }
24390
24877
  function periodTypeFrom(value) {
24391
24878
  if (typeof value !== "string")
@@ -24401,7 +24888,7 @@ function productUsageFrom(value) {
24401
24888
  if (!Array.isArray(value))
24402
24889
  return void 0;
24403
24890
  const products = value.flatMap((entry) => {
24404
- if (!isRecord16(entry) || typeof entry.product !== "string")
24891
+ if (!isRecord17(entry) || typeof entry.product !== "string")
24405
24892
  return [];
24406
24893
  const usagePercent = finitePercent(entry.usagePercent);
24407
24894
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -24409,10 +24896,10 @@ function productUsageFrom(value) {
24409
24896
  return products.length > 0 ? products : void 0;
24410
24897
  }
24411
24898
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24412
- if (!isRecord16(value) || !isRecord16(value.config))
24899
+ if (!isRecord17(value) || !isRecord17(value.config))
24413
24900
  return null;
24414
24901
  const config2 = value.config;
24415
- const period = isRecord16(config2.currentPeriod) ? config2.currentPeriod : void 0;
24902
+ const period = isRecord17(config2.currentPeriod) ? config2.currentPeriod : void 0;
24416
24903
  const periodType = periodTypeFrom(period?.type);
24417
24904
  const resetsAt = (typeof period?.end === "string" && period.end.length > 0 ? period.end : void 0) ?? (typeof config2.billingPeriodEnd === "string" && config2.billingPeriodEnd.length > 0 ? config2.billingPeriodEnd : void 0);
24418
24905
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24439,11 +24926,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24439
24926
  };
24440
24927
  }
24441
24928
  function selectAccessToken(auth, now) {
24442
- if (!isRecord16(auth))
24929
+ if (!isRecord17(auth))
24443
24930
  return null;
24444
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord16(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
24931
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord17(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
24445
24932
  for (const [, value] of entries) {
24446
- if (!isRecord16(value) || typeof value.key !== "string")
24933
+ if (!isRecord17(value) || typeof value.key !== "string")
24447
24934
  continue;
24448
24935
  if (typeof value.expires_at === "string") {
24449
24936
  const expiresAt = Date.parse(value.expires_at);
@@ -24464,8 +24951,8 @@ async function fetchGrokAccount(input = {}) {
24464
24951
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24465
24952
  return null;
24466
24953
  const now = input.now ?? /* @__PURE__ */ new Date();
24467
- const authPath = path12.join(grokHome(environment), "auth.json");
24468
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile4(authPath, "utf8");
24954
+ const authPath = path14.join(grokHome2(environment), "auth.json");
24955
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile5(authPath, "utf8");
24469
24956
  const token = selectAccessToken(JSON.parse(raw), now);
24470
24957
  if (!token)
24471
24958
  return null;
@@ -24515,7 +25002,7 @@ async function fetchGrokCredits(input = {}) {
24515
25002
 
24516
25003
  // dist/grok-usage.js
24517
25004
  var USD_TICKS_PER_DOLLAR = 1e10;
24518
- function isRecord17(value) {
25005
+ function isRecord18(value) {
24519
25006
  return typeof value === "object" && value !== null && !Array.isArray(value);
24520
25007
  }
24521
25008
  function optionalToken(value) {
@@ -24532,7 +25019,7 @@ function combineUsage(base, next) {
24532
25019
  return base === null ? next : parseHostUsage({ ...base, ...next });
24533
25020
  }
24534
25021
  function usageFromNative(value) {
24535
- if (!isRecord17(value))
25022
+ if (!isRecord18(value))
24536
25023
  return null;
24537
25024
  const nativeInputTokens = optionalToken(value.inputTokens);
24538
25025
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24557,11 +25044,111 @@ function usageFromNative(value) {
24557
25044
  return null;
24558
25045
  }
24559
25046
  }
24560
- function usageFromPrompt(response) {
24561
- return response.usage ? usageFromNative(response.usage) : null;
25047
+ function usageFromResponse(value) {
25048
+ if (!isRecord18(value))
25049
+ return null;
25050
+ const buckets = [
25051
+ value.input_tokens,
25052
+ value.cache_read_input_tokens,
25053
+ value.cache_creation_input_tokens
25054
+ ];
25055
+ const inputTokens = buckets.every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0) ? buckets.reduce((sum, n) => sum + n, 0) : void 0;
25056
+ const outputTokens = optionalToken(value.output_tokens);
25057
+ return usageFromNative({
25058
+ inputTokens,
25059
+ outputTokens,
25060
+ cachedReadTokens: value.cache_read_input_tokens,
25061
+ cacheCreationTokens: value.cache_creation_input_tokens,
25062
+ reasoningTokens: value.reasoning_tokens,
25063
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
25064
+ });
24562
25065
  }
25066
+ var GrokTurnUsage = class {
25067
+ #totals = {};
25068
+ #seen = /* @__PURE__ */ new Set();
25069
+ #cacheComplete;
25070
+ #compacting = false;
25071
+ #startedAtMs;
25072
+ #streamKey;
25073
+ #outputTokens = 0;
25074
+ #durationMs = 0;
25075
+ #latestCacheHit;
25076
+ #sessionInputTokens = 0;
25077
+ constructor(base, emptySession = false) {
25078
+ for (const field of summedUsageFields) {
25079
+ const value = base?.[field];
25080
+ if (value !== void 0)
25081
+ this.#totals[field] = value;
25082
+ }
25083
+ this.#cacheComplete = base?.sessionCacheUsage !== void 0 || emptySession;
25084
+ this.#sessionInputTokens = base?.sessionCacheUsage?.inputTokens ?? 0;
25085
+ }
25086
+ observe(event) {
25087
+ if (event.type === "compaction.started" || event.type === "compaction.completed") {
25088
+ this.#startedAtMs = void 0;
25089
+ this.#streamKey = void 0;
25090
+ this.#compacting = event.type === "compaction.started";
25091
+ }
25092
+ if (this.#compacting)
25093
+ return null;
25094
+ if (event.type === "subagent.spawned")
25095
+ this.#cacheComplete = false;
25096
+ if (event.type === "agent.text" || event.type === "agent.thought" || event.type === "tool.input.delta") {
25097
+ if (!event.text)
25098
+ return null;
25099
+ const key = event.metadata?.streamStartMs;
25100
+ if (key !== void 0 && this.#streamKey !== void 0 && key !== this.#streamKey)
25101
+ this.#startedAtMs = void 0;
25102
+ if (key !== void 0)
25103
+ this.#streamKey = key;
25104
+ this.#startedAtMs ??= Date.now();
25105
+ }
25106
+ if (event.type !== "response.completed")
25107
+ return null;
25108
+ if (event.messageId) {
25109
+ if (this.#seen.has(event.messageId))
25110
+ return null;
25111
+ this.#seen.add(event.messageId);
25112
+ }
25113
+ const duration3 = this.#startedAtMs === void 0 ? 0 : Date.now() - this.#startedAtMs;
25114
+ this.#startedAtMs = void 0;
25115
+ this.#streamKey = void 0;
25116
+ const usage = usageFromResponse(event.usage);
25117
+ this.#latestCacheHit = usage?.cacheHitRatePercent;
25118
+ if (usage?.inputTokens === void 0 || usage.cachedInputTokens === void 0)
25119
+ this.#cacheComplete = false;
25120
+ if (usage) {
25121
+ this.#sessionInputTokens += (usage.inputTokens ?? 0) + (usage.cachedInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0);
25122
+ for (const field of summedUsageFields) {
25123
+ const value = usage[field];
25124
+ if (value !== void 0)
25125
+ this.#totals[field] = (this.#totals[field] ?? 0) + value;
25126
+ }
25127
+ if (duration3 > 0 && usage.outputTokens !== void 0) {
25128
+ this.#outputTokens += usage.outputTokens;
25129
+ this.#durationMs += duration3;
25130
+ }
25131
+ }
25132
+ return this.snapshot();
25133
+ }
25134
+ metrics() {
25135
+ return {
25136
+ ...this.#durationMs > 0 ? { outputTokensPerSecond: this.#outputTokens * 1e3 / this.#durationMs } : {},
25137
+ ...this.#latestCacheHit !== void 0 ? { cacheHitRatePercent: this.#latestCacheHit } : {}
25138
+ };
25139
+ }
25140
+ snapshot() {
25141
+ const inputTokens = this.#totals.inputTokens;
25142
+ const cachedInputTokens = this.#totals.cachedInputTokens;
25143
+ return {
25144
+ ...this.#totals,
25145
+ ...this.metrics(),
25146
+ ...this.#cacheComplete && inputTokens !== void 0 && cachedInputTokens !== void 0 ? { sessionCacheUsage: { inputTokens: this.#sessionInputTokens, cachedInputTokens } } : {}
25147
+ };
25148
+ }
25149
+ };
24563
25150
  function usageFromSignals(value) {
24564
- if (!isRecord17(value))
25151
+ if (!isRecord18(value))
24565
25152
  return null;
24566
25153
  try {
24567
25154
  return parseHostUsage({
@@ -24581,13 +25168,23 @@ var summedUsageFields = [
24581
25168
  "totalTokens"
24582
25169
  ];
24583
25170
  function nativeCostTicks(value) {
24584
- if (!isRecord17(value))
25171
+ if (!isRecord18(value))
24585
25172
  return void 0;
24586
25173
  const ticks = value.costUsdTicks;
24587
25174
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
24588
25175
  return void 0;
24589
25176
  return ticks;
24590
25177
  }
25178
+ function sessionCostFromNative(value, initialCostUsd) {
25179
+ if (!isRecord18(value))
25180
+ return void 0;
25181
+ if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
25182
+ return void 0;
25183
+ if (value.usageIsIncomplete !== void 0 && value.usageIsIncomplete !== false)
25184
+ return void 0;
25185
+ const ticks = nativeCostTicks(value);
25186
+ return ticks === void 0 ? void 0 : optionalCostUsd(Math.round(initialCostUsd * USD_TICKS_PER_DOLLAR) + ticks);
25187
+ }
24591
25188
  function historyTurnKey(event, index) {
24592
25189
  const key = event.nativeTurnKey;
24593
25190
  if (typeof key === "string" && key.startsWith("task-completed-"))
@@ -24596,7 +25193,6 @@ function historyTurnKey(event, index) {
24596
25193
  }
24597
25194
  function sessionUsageFromHistory(events) {
24598
25195
  const latestByKey = /* @__PURE__ */ new Map();
24599
- let lastCacheHitRatePercent;
24600
25196
  let index = 0;
24601
25197
  for (const event of events) {
24602
25198
  if (event?.type !== "turn.completed")
@@ -24605,27 +25201,29 @@ function sessionUsageFromHistory(events) {
24605
25201
  index += 1;
24606
25202
  if (key === null)
24607
25203
  continue;
24608
- const usage = usageFromNative(event.usage);
24609
- if (!usage)
25204
+ if (event.usage === void 0 && latestByKey.has(key))
24610
25205
  continue;
25206
+ const usage = usageFromNative(event.usage);
24611
25207
  const ticks2 = nativeCostTicks(event.usage);
24612
- latestByKey.set(key, ticks2 === void 0 ? { usage } : { usage, ticks: ticks2 });
24613
- if (usage.cacheHitRatePercent !== void 0) {
24614
- lastCacheHitRatePercent = usage.cacheHitRatePercent;
24615
- }
25208
+ const complete = isRecord18(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && typeof event.usage.inputTokens === "number" && usage.cachedInputTokens + (usage.cacheWriteInputTokens ?? 0) <= event.usage.inputTokens;
25209
+ latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
24616
25210
  }
24617
25211
  if (latestByKey.size === 0)
24618
25212
  return null;
24619
- const totals = {};
25213
+ const totals2 = {};
25214
+ let sessionInputTokens = 0;
24620
25215
  let ticks = 0;
24621
25216
  let hasTicks = false;
24622
25217
  for (const entry of latestByKey.values()) {
25218
+ if (!entry.usage)
25219
+ continue;
24623
25220
  for (const field of summedUsageFields) {
24624
25221
  const value = entry.usage[field];
24625
25222
  if (value === void 0)
24626
25223
  continue;
24627
- totals[field] = (totals[field] ?? 0) + value;
25224
+ totals2[field] = (totals2[field] ?? 0) + value;
24628
25225
  }
25226
+ sessionInputTokens += (entry.usage.inputTokens ?? 0) + (entry.usage.cachedInputTokens ?? 0) + (entry.usage.cacheWriteInputTokens ?? 0);
24629
25227
  if (entry.ticks === void 0)
24630
25228
  continue;
24631
25229
  ticks += entry.ticks;
@@ -24634,9 +25232,14 @@ function sessionUsageFromHistory(events) {
24634
25232
  const totalCostUsd = hasTicks ? optionalCostUsd(ticks) : void 0;
24635
25233
  try {
24636
25234
  return parseHostUsage({
24637
- ...totals,
25235
+ ...totals2,
24638
25236
  ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
24639
- ...lastCacheHitRatePercent !== void 0 ? { cacheHitRatePercent: lastCacheHitRatePercent } : {}
25237
+ ...[...latestByKey.values()].every((entry) => entry.complete) && totals2.inputTokens !== void 0 && totals2.cachedInputTokens !== void 0 ? {
25238
+ sessionCacheUsage: {
25239
+ inputTokens: sessionInputTokens,
25240
+ cachedInputTokens: totals2.cachedInputTokens
25241
+ }
25242
+ } : {}
24640
25243
  });
24641
25244
  } catch {
24642
25245
  return null;
@@ -24658,7 +25261,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
24658
25261
  function usageFromUpdate(update, metadata, contextWindowTokens) {
24659
25262
  try {
24660
25263
  if (update?.sessionUpdate === "usage_update") {
24661
- const cost = isRecord17(update.cost) ? update.cost : null;
25264
+ const cost = isRecord18(update.cost) ? update.cost : null;
24662
25265
  return parseHostUsage({
24663
25266
  contextUsedTokens: update.used,
24664
25267
  contextWindowTokens: update.size,
@@ -24790,6 +25393,8 @@ var GrokHarnessSession = class {
24790
25393
  #phase = "open";
24791
25394
  #state;
24792
25395
  #usage = null;
25396
+ #initialCostUsd;
25397
+ #costRequest = 0;
24793
25398
  constructor(cwd, transport, opened, modelState, onClosed, options) {
24794
25399
  this.#cwd = cwd;
24795
25400
  this.#sessionDirectory = options.sessionDirectory;
@@ -24803,6 +25408,7 @@ var GrokHarnessSession = class {
24803
25408
  this.#toolOutputLimit = options.toolOutputLimit;
24804
25409
  this.initialUsage = options.initialUsage ?? null;
24805
25410
  this.#usage = this.initialUsage;
25411
+ this.#initialCostUsd = this.initialUsage?.totalCostUsd ?? 0;
24806
25412
  this.capabilities = capabilitiesForModels(modelState);
24807
25413
  this.commands = {
24808
25414
  list: async () => ({ ok: true, value: this.#liveCommandCatalog() }),
@@ -24891,6 +25497,7 @@ var GrokHarnessSession = class {
24891
25497
  });
24892
25498
  const active = {
24893
25499
  command,
25500
+ usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
24894
25501
  agent: null,
24895
25502
  agentMessageId: null,
24896
25503
  rawAgentText: "",
@@ -25068,9 +25675,9 @@ var GrokHarnessSession = class {
25068
25675
  }
25069
25676
  async #selectThinking(command) {
25070
25677
  const parsed = harnessThinkingOptionIdSchema.safeParse(command.thinkingOptionId);
25071
- const model = this.#state.effectiveModel;
25072
- const available = this.#modelState.catalog.models.find(({ ref }) => ref.id === model?.id);
25073
- if (!parsed.success || !model || !available?.supportedThinkingOptionIds?.includes(parsed.data)) {
25678
+ const model2 = this.#state.effectiveModel;
25679
+ const available = this.#modelState.catalog.models.find(({ ref }) => ref.id === model2?.id);
25680
+ if (!parsed.success || !model2 || !available?.supportedThinkingOptionIds?.includes(parsed.data)) {
25074
25681
  return {
25075
25682
  ok: false,
25076
25683
  error: {
@@ -25080,9 +25687,9 @@ var GrokHarnessSession = class {
25080
25687
  }
25081
25688
  };
25082
25689
  }
25083
- return this.#configure(model, parsed.data);
25690
+ return this.#configure(model2, parsed.data);
25084
25691
  }
25085
- async #configure(model, thinkingOptionId) {
25692
+ async #configure(model2, thinkingOptionId) {
25086
25693
  if (this.#configuring) {
25087
25694
  return {
25088
25695
  ok: false,
@@ -25095,9 +25702,20 @@ var GrokHarnessSession = class {
25095
25702
  }
25096
25703
  this.#configuring = true;
25097
25704
  try {
25098
- await this.#transport.setModel(model.id, thinkingOptionId);
25099
- this.#state = stateForGrokModel(this.#modelState, { nativeRef: nativeRef(this.#transport.sessionId) }, model, thinkingOptionId, this.#state.effectivePermissionModeId);
25705
+ const contextWindow = this.#modelState.defaultContextWindowTokensByModel.get(model2.id);
25706
+ await this.#transport.setModel(model2.id, thinkingOptionId, contextWindow);
25707
+ if (contextWindow !== void 0) {
25708
+ this.#modelState.contextWindowTokensByModel = new Map([
25709
+ ...this.#modelState.contextWindowTokensByModel,
25710
+ [model2.id, contextWindow]
25711
+ ]);
25712
+ }
25713
+ this.#state = stateForGrokModel(this.#modelState, { nativeRef: nativeRef(this.#transport.sessionId) }, model2, thinkingOptionId, this.#state.effectivePermissionModeId);
25100
25714
  this.#event({ type: "session.state.changed", state: this.#state });
25715
+ const selectedWindow = this.#modelState.contextWindowTokensByModel.get(model2.id);
25716
+ if (selectedWindow !== void 0 && this.#usage?.contextUsedTokens !== void 0) {
25717
+ this.#publishUsage({ contextWindowTokens: selectedWindow });
25718
+ }
25101
25719
  return { ok: true, value: { completed: true } };
25102
25720
  } catch (error53) {
25103
25721
  return { ok: false, error: normalizeError(error53, "nativeFailure") };
@@ -25310,6 +25928,11 @@ var GrokHarnessSession = class {
25310
25928
  #handleEvent(active, event) {
25311
25929
  if (this.#active !== active || this.#phase !== "open")
25312
25930
  return;
25931
+ const requestUsage = active.usage?.observe(event);
25932
+ if (requestUsage) {
25933
+ this.#publishUsage(requestUsage, active.command.turnId, true);
25934
+ void this.#refreshCost(active);
25935
+ }
25313
25936
  const contextUsage = usageFromUpdate(event.type === "usage" ? event.update : void 0, event.metadata, this.#state.effectiveModel ? this.#modelState.contextWindowTokensByModel.get(this.#state.effectiveModel.id) : void 0);
25314
25937
  if (contextUsage)
25315
25938
  this.#publishUsage(contextUsage, active.command.turnId);
@@ -25333,6 +25956,17 @@ var GrokHarnessSession = class {
25333
25956
  } else if (event.type === "usage" || event.type === "turn.completed")
25334
25957
  return;
25335
25958
  }
25959
+ async #refreshCost(active) {
25960
+ const request = ++this.#costRequest;
25961
+ try {
25962
+ const totalCostUsd = sessionCostFromNative(await this.#transport.getUsage(), this.#initialCostUsd);
25963
+ if (this.#active !== active || this.#phase !== "open" || request !== this.#costRequest)
25964
+ return;
25965
+ if (totalCostUsd !== void 0)
25966
+ this.#publishUsage({ totalCostUsd }, active.command.turnId);
25967
+ } catch {
25968
+ }
25969
+ }
25336
25970
  #startCompaction(active, event) {
25337
25971
  if (active.compactionItem)
25338
25972
  return;
@@ -25445,14 +26079,14 @@ var GrokHarnessSession = class {
25445
26079
  const prompt = grokSubagentPrompt(event.rawInput);
25446
26080
  const role = grokSubagentRole(event.rawInput);
25447
26081
  const nativeSubagentId = grokNativeSubagentId(event.rawInput);
25448
- const model = grokSubagentModel(event.rawInput);
26082
+ const model2 = grokSubagentModel(event.rawInput);
25449
26083
  active.subagents.start(active.command.turnId, {
25450
26084
  callId: event.callId,
25451
26085
  operation,
25452
26086
  description: grokSubagentDescription(event.rawInput, event.title),
25453
26087
  ...prompt ? { prompt } : {},
25454
26088
  ...role ? { role } : {},
25455
- ...model ? { model } : {},
26089
+ ...model2 ? { model: model2 } : {},
25456
26090
  background: grokSubagentBackground(event.rawInput),
25457
26091
  ...nativeSubagentId ? { nativeSubagentId } : {}
25458
26092
  });
@@ -25674,7 +26308,17 @@ var GrokHarnessSession = class {
25674
26308
  checkpoint = created[0]?.checkpoint;
25675
26309
  } catch {
25676
26310
  }
25677
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, sessionUsageFromHistory(history) ?? (response ? usageFromPrompt(response) : null), nativeTurnRef);
26311
+ const promptUsage = response?.usage ?? response?._meta?.usage;
26312
+ if (nativeTurnRef && promptUsage !== void 0 && !history.some((event) => event.type === "turn.completed" && event.nativeTurnKey === nativeTurnRef.nativeTurnKey && event.usage !== void 0)) {
26313
+ history.push({
26314
+ type: "turn.completed",
26315
+ nativeTurnKey: nativeTurnRef.nativeTurnKey,
26316
+ stopReason: response?.stopReason ?? "end_turn",
26317
+ usage: promptUsage
26318
+ });
26319
+ }
26320
+ const usage = sessionUsageFromHistory(history) ?? usageFromNative(promptUsage);
26321
+ this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
25678
26322
  void this.#refreshCredits().catch(() => void 0);
25679
26323
  }
25680
26324
  #finish(active, outcome, usage = null, nativeTurnRef) {
@@ -25693,8 +26337,8 @@ var GrokHarnessSession = class {
25693
26337
  active.tools.clear();
25694
26338
  this.#closePendingInteractions(active, "cancelled");
25695
26339
  this.#active = null;
25696
- if (usage)
25697
- this.#publishUsage(usage, active.command.turnId);
26340
+ if (usage || this.#usage)
26341
+ this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
25698
26342
  this.#event({
25699
26343
  type: "turn.completed",
25700
26344
  turnId: active.command.turnId,
@@ -25703,8 +26347,14 @@ var GrokHarnessSession = class {
25703
26347
  });
25704
26348
  active.resolveCompletion();
25705
26349
  }
25706
- #publishUsage(usage, observedForTurnId) {
25707
- const merged = combineUsage(this.#usage, usage);
26350
+ #publishUsage(usage, observedForTurnId, replaceMetrics = false) {
26351
+ const base = this.#usage ? { ...this.#usage } : null;
26352
+ if (base && replaceMetrics) {
26353
+ delete base.outputTokensPerSecond;
26354
+ delete base.cacheHitRatePercent;
26355
+ delete base.sessionCacheUsage;
26356
+ }
26357
+ const merged = combineUsage(base, usage);
25708
26358
  if (merged === null || JSON.stringify(merged) === JSON.stringify(this.#usage))
25709
26359
  return;
25710
26360
  this.#usage = merged;
@@ -25766,6 +26416,7 @@ var GrokAdapter = class {
25766
26416
  liveCommandCatalog = true;
25767
26417
  harnessId = grokHarnessId;
25768
26418
  sessionImport;
26419
+ usageStatistics;
25769
26420
  subagents = {
25770
26421
  readSnapshot: async (input) => {
25771
26422
  if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
@@ -25815,6 +26466,7 @@ var GrokAdapter = class {
25815
26466
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
25816
26467
  this.#environment = options.environment;
25817
26468
  this.sessionImport = new GrokSessionImport(options.environment);
26469
+ this.usageStatistics = createGrokUsageStatistics(options.environment ?? process.env);
25818
26470
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
25819
26471
  this.#dependencies = dependencies ?? {
25820
26472
  randomUUID,
@@ -25863,7 +26515,7 @@ var GrokAdapter = class {
25863
26515
  async inspect(input = {}) {
25864
26516
  if (this.#closePromise)
25865
26517
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
25866
- const cwd = path13.resolve(input.cwd ?? process.cwd());
26518
+ const cwd = path15.resolve(input.cwd ?? process.cwd());
25867
26519
  if (!input.refresh) {
25868
26520
  const cached2 = this.#inspectionCache.get(cwd);
25869
26521
  if (cached2)
@@ -25925,7 +26577,7 @@ var GrokAdapter = class {
25925
26577
  }
25926
26578
  };
25927
26579
  }
25928
- const cwd = path13.resolve(input.cwd);
26580
+ const cwd = path15.resolve(input.cwd);
25929
26581
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
25930
26582
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
25931
26583
  return {
@@ -26029,6 +26681,8 @@ var GrokAdapter = class {
26029
26681
  const modelState = modelStateFromSessionResponse(opened.session) ?? modelStateFromInitialize(opened.initialize);
26030
26682
  if (!modelState)
26031
26683
  throw new GrokTransportError("protocolError", "Grok returned an invalid Model catalog");
26684
+ const nativeModelId = modelState.currentModel.id;
26685
+ const nativeThinkingOptionId = modelState.currentThinkingOptionId;
26032
26686
  const retainedConfiguration = sourceConfiguration;
26033
26687
  if ((input.kind === "rollbackLastTurn" || input.kind === "fork") && retainedConfiguration) {
26034
26688
  const operation = input.kind === "rollbackLastTurn" ? "Rewind" : "Fork";
@@ -26041,7 +26695,6 @@ var GrokAdapter = class {
26041
26695
  throw new GrokTransportError("protocolError", `Grok Thinking option is unavailable after ${operation}`);
26042
26696
  }
26043
26697
  if (retainedConfiguration.model.id !== modelState.currentModel.id || retainedConfiguration.thinkingOptionId !== modelState.currentThinkingOptionId) {
26044
- await transport.setModel(retainedConfiguration.model.id, retainedConfiguration.thinkingOptionId);
26045
26698
  modelState.currentModel = retainedConfiguration.model;
26046
26699
  if (retainedConfiguration.thinkingOptionId) {
26047
26700
  modelState.currentThinkingOptionId = retainedConfiguration.thinkingOptionId;
@@ -26060,7 +26713,6 @@ var GrokAdapter = class {
26060
26713
  throw new GrokTransportError("protocolError", "Requested Grok Thinking option is unavailable");
26061
26714
  }
26062
26715
  if (selectedModel.id !== modelState.currentModel.id || selectedThinking !== modelState.currentThinkingOptionId) {
26063
- await transport.setModel(selectedModel.id, selectedThinking);
26064
26716
  modelState.currentModel = selectedModel;
26065
26717
  if (selectedThinking)
26066
26718
  modelState.currentThinkingOptionId = selectedThinking;
@@ -26068,8 +26720,21 @@ var GrokAdapter = class {
26068
26720
  delete modelState.currentThinkingOptionId;
26069
26721
  }
26070
26722
  }
26723
+ const contextWindow = modelState.defaultContextWindowTokensByModel.get(modelState.currentModel.id);
26724
+ if (modelState.currentModel.id !== nativeModelId || modelState.currentThinkingOptionId !== nativeThinkingOptionId || contextWindow !== void 0 && modelState.contextWindowTokensByModel.get(modelState.currentModel.id) !== contextWindow) {
26725
+ await transport.setModel(modelState.currentModel.id, modelState.currentThinkingOptionId, contextWindow);
26726
+ if (contextWindow !== void 0) {
26727
+ modelState.contextWindowTokensByModel = new Map([
26728
+ ...modelState.contextWindowTokensByModel,
26729
+ [modelState.currentModel.id, contextWindow]
26730
+ ]);
26731
+ }
26732
+ }
26071
26733
  const history = await transport.getHistory();
26072
- const initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26734
+ let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26735
+ if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {
26736
+ initialUsage = combineUsage(initialUsage, { contextWindowTokens: contextWindow });
26737
+ }
26073
26738
  const environment = input.environment ?? this.#environment;
26074
26739
  const sessionDirectory = grokNativeSessionDirectory(environment ? { cwd, environment } : { cwd }, opened.sessionId);
26075
26740
  const openedSession = new GrokHarnessSession(cwd, transport, opened, modelState, () => this.#sessions.delete(openedSession), {