@liberseek/boft-cli-linux-x64 0.7.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.txt +8 -0
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +232 -21
  5. package/app/console-web.js +9669 -5390
  6. package/app/desktop-controller.mjs +252 -42
  7. package/app/host-runtime.mjs +5361 -1491
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +276 -42
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +1055 -391
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +5931 -5358
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +16750 -0
  16. package/app/plugins/cursor-cli/manifest.json +18 -1
  17. package/app/plugins/cursor-cli/plugin.mjs +351 -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 +798 -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 +898 -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 +278 -33
  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 +555 -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 +284 -22
  33. package/app/plugins/muse/manifest.json +18 -1
  34. package/app/plugins/muse/plugin.mjs +251 -17
  35. package/app/plugins/omp/manifest.json +21 -1
  36. package/app/plugins/omp/plugin.mjs +2741 -1960
  37. package/app/plugins/opencode/manifest.json +18 -1
  38. package/app/plugins/opencode/plugin.mjs +694 -147
  39. package/app/plugins/pi/manifest.json +32 -0
  40. package/app/plugins/pi/plugin.mjs +3396 -2841
  41. package/app/plugins/qoder/manifest.json +18 -1
  42. package/app/plugins/qoder/plugin.mjs +585 -81
  43. package/app/plugins/qoder-cn/manifest.json +18 -1
  44. package/app/plugins/qoder-cn/plugin.mjs +585 -81
  45. package/app/plugins/workbuddy/manifest.json +18 -0
  46. package/app/plugins/workbuddy/plugin.mjs +6317 -5746
  47. package/app/plugins/zcode/manifest.json +19 -1
  48. package/app/plugins/zcode/plugin.mjs +1066 -260
  49. package/app/renderer-extension.js +2731 -2427
  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 +1 -1
  56. package/app/plugins/kiro-cli/assets/icon.svg +0 -5
@@ -372,20 +372,180 @@ 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
+ function sessionIdOk(value) {
388
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
389
+ }
390
+ function cwdOk(value) {
391
+ 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("\\\\"));
392
+ }
393
+ function withUsageSession(entry, session) {
394
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
395
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
396
+ if (sessionId === void 0 && cwd === void 0)
397
+ return entry;
398
+ return {
399
+ ...entry,
400
+ ...sessionId !== void 0 ? { sessionId } : {},
401
+ ...cwd !== void 0 ? { cwd } : {}
402
+ };
403
+ }
404
+ async function jsonlUsageSources(root, maxDepth, signal) {
405
+ const sources = [];
406
+ const visit = async (directory, depth) => {
407
+ signal.throwIfAborted();
408
+ const entries = await opendir(directory).catch((error53) => {
409
+ if (error53.code === "ENOENT")
410
+ return null;
411
+ throw error53;
412
+ });
413
+ if (!entries)
414
+ return;
415
+ for await (const entry of entries) {
416
+ signal.throwIfAborted();
417
+ const file2 = path4.join(directory, entry.name);
418
+ if (entry.isDirectory()) {
419
+ if (depth < maxDepth)
420
+ await visit(file2, depth + 1);
421
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
422
+ const info = await lstat(file2).catch(() => null);
423
+ if (info?.isFile() && info.size > 0) {
424
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
425
+ }
426
+ }
427
+ }
428
+ };
429
+ await visit(root, 0);
430
+ return sources;
431
+ }
432
+ async function* jsonlRecords(file2, marker, signal) {
433
+ const lines = createInterface({
434
+ input: createReadStream(file2, { encoding: "utf8", signal }),
435
+ crlfDelay: Infinity
436
+ });
437
+ for await (const line of lines) {
438
+ if (!line.includes(marker))
439
+ continue;
440
+ let value;
441
+ try {
442
+ value = JSON.parse(line);
443
+ } catch {
444
+ continue;
445
+ }
446
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
447
+ yield value;
448
+ }
449
+ }
450
+ }
451
+ function nativeTimeMs(value) {
452
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
453
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
454
+ }
455
+
456
+ // dist/usage-statistics.js
457
+ function isRecord(value) {
458
+ return typeof value === "object" && value !== null && !Array.isArray(value);
459
+ }
460
+ var USD_TICKS = 1e10;
461
+ function count(value) {
462
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
463
+ }
464
+ function grokHome(environment) {
465
+ return environment.GROK_HOME || path5.join(environment.HOME || os2.homedir(), ".grok");
466
+ }
467
+ async function forkedAtMs(directory) {
468
+ try {
469
+ const summary = JSON.parse(await readFile(path5.join(directory, "summary.json"), "utf8"));
470
+ return isRecord(summary) && typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null;
471
+ } catch {
472
+ return null;
473
+ }
474
+ }
475
+ function grokSession(file2) {
476
+ const directory = path5.dirname(file2);
477
+ let cwd;
478
+ try {
479
+ cwd = decodeURIComponent(path5.basename(path5.dirname(directory)));
480
+ } catch {
481
+ cwd = void 0;
482
+ }
483
+ return { sessionId: path5.basename(directory), cwd };
484
+ }
485
+ async function readGrokUsage(file2, signal) {
486
+ const forkedAt = await forkedAtMs(path5.dirname(file2));
487
+ const session = grokSession(file2);
488
+ const entries = [];
489
+ for await (const line of jsonlRecords(file2, '"turn_completed"', signal)) {
490
+ const params = isRecord(line.params) ? line.params : {};
491
+ const update = isRecord(params.update) ? params.update : {};
492
+ const usage = isRecord(update.usage) ? update.usage : {};
493
+ if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
494
+ continue;
495
+ const meta3 = isRecord(params._meta) ? params._meta : {};
496
+ const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
497
+ if (at === null || forkedAt !== null && at <= forkedAt)
498
+ continue;
499
+ for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
500
+ if (!isRecord(value))
501
+ continue;
502
+ const input = count(value.inputTokens);
503
+ const output = count(value.outputTokens);
504
+ const cached2 = count(value.cachedReadTokens);
505
+ const written = count(value.cacheCreationTokens ?? 0);
506
+ const reasoning = count(value.reasoningTokens);
507
+ const ticks = count(value.costUsdTicks);
508
+ if (input === null || output === null || value.totalTokens !== input + output)
509
+ continue;
510
+ const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
511
+ entries.push(withUsageSession({
512
+ id: `${update.prompt_id}:${model2}`,
513
+ occurredAtMs: at,
514
+ model: model2,
515
+ inputTokens: input,
516
+ ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
517
+ outputTokens: output,
518
+ ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
519
+ // A turn Grok marks incomplete has no cost of its own; it counts as free rather
520
+ // than as a model without a price.
521
+ ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
522
+ }, session));
523
+ }
524
+ }
525
+ return entries;
526
+ }
527
+ function createGrokUsageStatistics(environment) {
528
+ return Object.freeze({
529
+ // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
530
+ listSources: async (signal) => (await jsonlUsageSources(path5.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path5.basename(source.id) === "updates.jsonl"),
531
+ readSource: (id, signal) => readGrokUsage(id, signal)
532
+ });
533
+ }
534
+
375
535
  // dist/grok-adapter.js
376
536
  import { randomUUID } from "node:crypto";
377
537
 
378
538
  // dist/grok-credential-export.js
379
539
  import { createHash } from "node:crypto";
380
- import { readFile } from "node:fs/promises";
381
- import os2 from "node:os";
382
- import path4 from "node:path";
540
+ import { readFile as readFile2 } from "node:fs/promises";
541
+ import os3 from "node:os";
542
+ import path6 from "node:path";
383
543
  async function readGrokCredentials(environment) {
384
544
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
385
545
  return [];
386
546
  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"));
547
+ const home = environment.GROK_HOME ?? path6.join(environment.HOME ?? os3.homedir(), ".grok");
548
+ const auth = JSON.parse(await readFile2(path6.join(home, "auth.json"), "utf8"));
389
549
  const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
390
550
  const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
391
551
  if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
@@ -412,7 +572,7 @@ async function readGrokCredentials(environment) {
412
572
  }
413
573
 
414
574
  // dist/grok-adapter.js
415
- import path13 from "node:path";
575
+ import path15 from "node:path";
416
576
 
417
577
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
418
578
  var AGENT_METHODS = {
@@ -1232,10 +1392,10 @@ function mergeDefs(...defs) {
1232
1392
  function cloneDef(schema) {
1233
1393
  return mergeDefs(schema._zod.def);
1234
1394
  }
1235
- function getElementAtPath(obj, path14) {
1236
- if (!path14)
1395
+ function getElementAtPath(obj, path16) {
1396
+ if (!path16)
1237
1397
  return obj;
1238
- return path14.reduce((acc, key) => acc?.[key], obj);
1398
+ return path16.reduce((acc, key) => acc?.[key], obj);
1239
1399
  }
1240
1400
  function promiseAllObject(promisesObj) {
1241
1401
  const keys = Object.keys(promisesObj);
@@ -1644,11 +1804,11 @@ function explicitlyAborted(x, startIndex = 0) {
1644
1804
  }
1645
1805
  return false;
1646
1806
  }
1647
- function prefixIssues(path14, issues) {
1807
+ function prefixIssues(path16, issues) {
1648
1808
  return issues.map((iss) => {
1649
1809
  var _a3;
1650
1810
  (_a3 = iss).path ?? (_a3.path = []);
1651
- iss.path.unshift(path14);
1811
+ iss.path.unshift(path16);
1652
1812
  return iss;
1653
1813
  });
1654
1814
  }
@@ -1795,16 +1955,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1795
1955
  }
1796
1956
  function formatError(error53, mapper = (issue2) => issue2.message) {
1797
1957
  const fieldErrors = { _errors: [] };
1798
- const processError = (error54, path14 = []) => {
1958
+ const processError = (error54, path16 = []) => {
1799
1959
  for (const issue2 of error54.issues) {
1800
1960
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1801
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1961
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1802
1962
  } else if (issue2.code === "invalid_key") {
1803
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1963
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1804
1964
  } else if (issue2.code === "invalid_element") {
1805
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1965
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1806
1966
  } else {
1807
- const fullpath = [...path14, ...issue2.path];
1967
+ const fullpath = [...path16, ...issue2.path];
1808
1968
  if (fullpath.length === 0) {
1809
1969
  fieldErrors._errors.push(mapper(issue2));
1810
1970
  } else {
@@ -1831,17 +1991,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1831
1991
  }
1832
1992
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1833
1993
  const result = { errors: [] };
1834
- const processError = (error54, path14 = []) => {
1994
+ const processError = (error54, path16 = []) => {
1835
1995
  var _a3, _b;
1836
1996
  for (const issue2 of error54.issues) {
1837
1997
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1838
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1998
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1839
1999
  } else if (issue2.code === "invalid_key") {
1840
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
2000
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1841
2001
  } else if (issue2.code === "invalid_element") {
1842
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
2002
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1843
2003
  } else {
1844
- const fullpath = [...path14, ...issue2.path];
2004
+ const fullpath = [...path16, ...issue2.path];
1845
2005
  if (fullpath.length === 0) {
1846
2006
  result.errors.push(mapper(issue2));
1847
2007
  continue;
@@ -1873,8 +2033,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1873
2033
  }
1874
2034
  function toDotPath(_path) {
1875
2035
  const segs = [];
1876
- const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1877
- for (const seg of path14) {
2036
+ const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2037
+ for (const seg of path16) {
1878
2038
  if (typeof seg === "number")
1879
2039
  segs.push(`[${seg}]`);
1880
2040
  else if (typeof seg === "symbol")
@@ -5102,8 +5262,8 @@ function az_default() {
5102
5262
  }
5103
5263
 
5104
5264
  // ../../../node_modules/zod/v4/locales/be.js
5105
- function getBelarusianPlural(count, one, few, many) {
5106
- const absCount = Math.abs(count);
5265
+ function getBelarusianPlural(count3, one, few, many) {
5266
+ const absCount = Math.abs(count3);
5107
5267
  const lastDigit = absCount % 10;
5108
5268
  const lastTwoDigits = absCount % 100;
5109
5269
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -7181,8 +7341,8 @@ function hu_default() {
7181
7341
  }
7182
7342
 
7183
7343
  // ../../../node_modules/zod/v4/locales/hy.js
7184
- function getArmenianPlural(count, one, many) {
7185
- return Math.abs(count) === 1 ? one : many;
7344
+ function getArmenianPlural(count3, one, many) {
7345
+ return Math.abs(count3) === 1 ? one : many;
7186
7346
  }
7187
7347
  function withDefiniteArticle(word) {
7188
7348
  if (!word)
@@ -9310,8 +9470,8 @@ function ro_default() {
9310
9470
  }
9311
9471
 
9312
9472
  // ../../../node_modules/zod/v4/locales/ru.js
9313
- function getRussianPlural(count, one, few, many) {
9314
- const absCount = Math.abs(count);
9473
+ function getRussianPlural(count3, one, few, many) {
9474
+ const absCount = Math.abs(count3);
9315
9475
  const lastDigit = absCount % 10;
9316
9476
  const lastTwoDigits = absCount % 100;
9317
9477
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14566,13 +14726,13 @@ function resolveRef(ref, ctx) {
14566
14726
  if (!ref.startsWith("#")) {
14567
14727
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14568
14728
  }
14569
- const path14 = ref.slice(1).split("/").filter(Boolean);
14570
- if (path14.length === 0) {
14729
+ const path16 = ref.slice(1).split("/").filter(Boolean);
14730
+ if (path16.length === 0) {
14571
14731
  return ctx.rootSchema;
14572
14732
  }
14573
14733
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14574
- if (path14[0] === defsKey) {
14575
- const key = path14[1];
14734
+ if (path16[0] === defsKey) {
14735
+ const key = path16[1];
14576
14736
  if (!key || !ctx.defs[key]) {
14577
14737
  throw new Error(`Reference not found: ${ref}`);
14578
14738
  }
@@ -16663,17 +16823,17 @@ function isResponseMessage(value) {
16663
16823
  function isNotificationMessage(value) {
16664
16824
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
16665
16825
  }
16666
- function isRecord(value) {
16826
+ function isRecord2(value) {
16667
16827
  return typeof value === "object" && value !== null;
16668
16828
  }
16669
16829
  function isJsonRpcEnvelope(value) {
16670
- return isRecord(value) && value["jsonrpc"] === "2.0";
16830
+ return isRecord2(value) && value["jsonrpc"] === "2.0";
16671
16831
  }
16672
16832
  function isJsonRpcId(value) {
16673
16833
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
16674
16834
  }
16675
16835
  function isResponseShapedMessage(value) {
16676
- return isRecord(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
16836
+ return isRecord2(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
16677
16837
  }
16678
16838
  function isResponseBatch(batch) {
16679
16839
  let hasValidCall = false;
@@ -16683,7 +16843,7 @@ function isResponseBatch(batch) {
16683
16843
  for (const entry of batch) {
16684
16844
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
16685
16845
  hasValidResponse ||= isResponseMessage(entry);
16686
- if (!isRecord(entry)) {
16846
+ if (!isRecord2(entry)) {
16687
16847
  continue;
16688
16848
  }
16689
16849
  hasCallShape ||= "method" in entry;
@@ -16698,13 +16858,13 @@ function isResponseBatch(batch) {
16698
16858
  return hasResponseShape && !hasCallShape;
16699
16859
  }
16700
16860
  function cancelRequestId(params) {
16701
- if (!isRecord(params) || !isJsonRpcId(params["requestId"])) {
16861
+ if (!isRecord2(params) || !isJsonRpcId(params["requestId"])) {
16702
16862
  return void 0;
16703
16863
  }
16704
16864
  return params["requestId"];
16705
16865
  }
16706
16866
  function isErrorResponse(value) {
16707
- return isRecord(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
16867
+ return isRecord2(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
16708
16868
  }
16709
16869
  var Handled = {
16710
16870
  /**
@@ -17195,7 +17355,7 @@ var Connection = class {
17195
17355
  this.receiveBatch(message);
17196
17356
  return;
17197
17357
  }
17198
- if (!isRecord(message)) {
17358
+ if (!isRecord2(message)) {
17199
17359
  console.error("Invalid message", { message });
17200
17360
  return;
17201
17361
  }
@@ -17212,9 +17372,9 @@ var Connection = class {
17212
17372
  return;
17213
17373
  }
17214
17374
  const responseBatch = isResponseBatch(batch);
17215
- const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
17375
+ const responseCount = responseBatch ? 0 : batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 0 : 1), 0);
17216
17376
  let remaining = responseCount;
17217
- let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
17377
+ let remainingNotifications = batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 1 : 0), 0);
17218
17378
  let responseSent = false;
17219
17379
  const responses = [];
17220
17380
  const sendResponsesIfReady = async () => {
@@ -17258,7 +17418,7 @@ var Connection = class {
17258
17418
  if (this.abortController.signal.aborted) {
17259
17419
  return Promise.resolve();
17260
17420
  }
17261
- if (!isRecord(message)) {
17421
+ if (!isRecord2(message)) {
17262
17422
  console.error("Invalid message", { message });
17263
17423
  return Promise.resolve();
17264
17424
  }
@@ -17628,7 +17788,7 @@ function ndJsonStream(output, input) {
17628
17788
  if (trimmedLine) {
17629
17789
  try {
17630
17790
  const message = JSON.parse(trimmedLine);
17631
- if (isRecord(message) || Array.isArray(message)) {
17791
+ if (isRecord2(message) || Array.isArray(message)) {
17632
17792
  controller.enqueue(message);
17633
17793
  } else {
17634
17794
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
@@ -19089,6 +19249,15 @@ var ClientSideConnection = class {
19089
19249
  }
19090
19250
  };
19091
19251
 
19252
+ // ../../shared-contracts/dist/delegation-read.js
19253
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
19254
+ var delegationReadParamsSchema = external_exports.strictObject({
19255
+ threadId: external_exports.string().min(1).max(1024),
19256
+ view: external_exports.enum(["result", "messages"]),
19257
+ cursor: external_exports.string().min(1).max(8192).optional(),
19258
+ limit: external_exports.number().int().min(1).max(100).optional()
19259
+ });
19260
+
19092
19261
  // ../../shared-contracts/dist/credential-imports.js
19093
19262
  var credentialSourceSchema = external_exports.object({
19094
19263
  id: external_exports.string().min(1).max(256),
@@ -19159,6 +19328,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
19159
19328
  initializeOnly: external_exports.boolean().optional()
19160
19329
  });
19161
19330
 
19331
+ // ../../shared-contracts/dist/model-price-overrides.js
19332
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
19333
+ var modelPriceOverrideSchema = external_exports.strictObject({
19334
+ input: usdPerMillionTokens,
19335
+ output: usdPerMillionTokens,
19336
+ cacheRead: usdPerMillionTokens.optional(),
19337
+ cacheWrite: usdPerMillionTokens.optional(),
19338
+ cacheWrite1h: usdPerMillionTokens.optional()
19339
+ });
19340
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
19341
+ var modelPriceOverridesSchema = external_exports.strictObject({
19342
+ /** Absolute path of the Host's `pricing.json`. */
19343
+ path: external_exports.string(),
19344
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
19345
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
19346
+ error: external_exports.string().nullable()
19347
+ });
19348
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
19349
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
19350
+ key: modelPriceKeySchema,
19351
+ price: modelPriceOverrideSchema.nullable(),
19352
+ previousKey: modelPriceKeySchema.optional()
19353
+ });
19354
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
19355
+ model: modelPriceKeySchema
19356
+ });
19357
+ var modelPriceSuggestionSchema = external_exports.strictObject({
19358
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
19359
+ official: external_exports.boolean().optional(),
19360
+ canonicalModelId: external_exports.string().min(1).optional(),
19361
+ provider: external_exports.string().min(1).max(512),
19362
+ model: external_exports.string().min(1).max(512),
19363
+ price: modelPriceOverrideSchema
19364
+ });
19365
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
19366
+ price: modelPriceOverrideSchema.nullable(),
19367
+ /** Local catalog suggestions only; never used automatically for pricing. */
19368
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
19369
+ });
19370
+
19371
+ // ../../shared-contracts/dist/usage-statistics.js
19372
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
19373
+ var count2 = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
19374
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
19375
+ var harness = external_exports.string().min(1).max(128);
19376
+ var model = external_exports.string().min(1).max(512);
19377
+ var project = external_exports.string().min(1).max(4096);
19378
+ var usageStatisticsParamsSchema = external_exports.strictObject({
19379
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
19380
+ harness: harness.optional(),
19381
+ model: model.nullable().optional(),
19382
+ project: project.nullable().optional(),
19383
+ /** One local date inside the range. */
19384
+ date: localDate.optional()
19385
+ });
19386
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
19387
+ requests: count2,
19388
+ inputTokens: count2,
19389
+ cachedInputTokens: count2,
19390
+ cacheWriteInputTokens: count2,
19391
+ cacheKnownInputTokens: count2,
19392
+ outputTokens: count2,
19393
+ reasoningOutputTokens: count2,
19394
+ /** USD at the public price, summed over the priced requests only. */
19395
+ costUsd: external_exports.number().finite().min(0),
19396
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
19397
+ unpricedRequests: count2,
19398
+ /**
19399
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
19400
+ * cost, and not as unpriced.
19401
+ */
19402
+ unmeteredRequests: count2
19403
+ });
19404
+ var totals = usageStatisticsTotalsSchema.shape;
19405
+ var usageStatisticsSessionSchema = external_exports.strictObject({
19406
+ harness,
19407
+ sessionId: external_exports.string().min(1).max(512),
19408
+ project: project.nullable(),
19409
+ /** Models the session used, most requests first. */
19410
+ models: external_exports.array(model).max(16),
19411
+ firstAtMs: count2,
19412
+ lastAtMs: count2,
19413
+ ...totals
19414
+ });
19415
+ var usageStatisticsResultSchema = external_exports.strictObject({
19416
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
19417
+ /** First local date of the range; null for all time. */
19418
+ from: localDate.nullable(),
19419
+ to: localDate,
19420
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
19421
+ filters: external_exports.strictObject({
19422
+ harness: harness.nullable(),
19423
+ model: model.nullable(),
19424
+ unknownModel: external_exports.boolean(),
19425
+ project: project.nullable(),
19426
+ unknownProject: external_exports.boolean(),
19427
+ date: localDate.nullable()
19428
+ }),
19429
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
19430
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count2, read: count2 }),
19431
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
19432
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
19433
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
19434
+ options: external_exports.strictObject({
19435
+ harnesses: external_exports.array(harness).max(256),
19436
+ models: external_exports.array(model.nullable()).max(4096),
19437
+ projects: external_exports.array(project.nullable()).max(4096)
19438
+ }),
19439
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
19440
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
19441
+ */
19442
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
19443
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
19444
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
19445
+ */
19446
+ credits: external_exports.array(external_exports.strictObject({
19447
+ harness,
19448
+ model: model.nullable(),
19449
+ credits: external_exports.number().finite().min(0),
19450
+ reportedRequests: count2,
19451
+ requests: count2
19452
+ })).max(4096).optional(),
19453
+ /** All filters applied. */
19454
+ totals: usageStatisticsTotalsSchema,
19455
+ /** Each date and Harness of the range: every filter except the day. */
19456
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
19457
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
19458
+ hourly: external_exports.array(external_exports.strictObject({
19459
+ weekday: external_exports.number().int().min(0).max(6),
19460
+ hour: external_exports.number().int().min(0).max(23),
19461
+ ...totals
19462
+ })).max(168),
19463
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
19464
+ byModel: external_exports.array(external_exports.strictObject({
19465
+ model: model.nullable(),
19466
+ ...totals,
19467
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
19468
+ harnessPricedRequests: count2
19469
+ })).max(4096),
19470
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
19471
+ /**
19472
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
19473
+ * requests without a native session are not listed here but count everywhere else.
19474
+ */
19475
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
19476
+ });
19477
+
19162
19478
  // ../../shared-contracts/dist/ids.js
19163
19479
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
19164
19480
  message: "Identifier must not be empty or whitespace"
@@ -19180,13 +19496,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
19180
19496
  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
19497
  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
19498
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
19499
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
19500
+ var harnessInstallationGuideSchema = external_exports.object({
19501
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
19502
+ before: localizedTextSchema.optional(),
19503
+ after: localizedTextSchema.optional(),
19504
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
19505
+ }).strict();
19183
19506
  var pluginPresentationShape = {
19184
19507
  id: harnessPluginIdSchema,
19185
19508
  name: external_exports.string().trim().min(1).max(128),
19186
19509
  version: external_exports.string().min(1).max(128),
19510
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
19511
+ kind: external_exports.literal("usage").optional(),
19512
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
19513
+ iconStyle: external_exports.object({
19514
+ vector: external_exports.object({
19515
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
19516
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
19517
+ paths: external_exports.array(external_exports.object({
19518
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
19519
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
19520
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
19521
+ }).strict()).min(1).max(32)
19522
+ }).strict().optional(),
19523
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
19524
+ borderRadius: external_exports.number().min(0).max(50).optional(),
19525
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
19526
+ }).strict().optional(),
19527
+ installation: harnessInstallationGuideSchema.optional(),
19528
+ notice: localizedTextSchema.optional(),
19187
19529
  /** The factory accepts a persisted local entrypoint through its construction context. */
19188
19530
  launchCommand: external_exports.literal(true).optional(),
19189
19531
  links: external_exports.object({
19532
+ website: documentationUrlSchema.optional(),
19190
19533
  documentation: documentationUrlSchema.optional(),
19191
19534
  installation: documentationUrlSchema.optional()
19192
19535
  }).strict().optional()
@@ -19263,6 +19606,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
19263
19606
  "codexhost/account/list",
19264
19607
  "codexhost/account/refresh",
19265
19608
  "codexhost/account/usage/inspect",
19609
+ "codexhost/usage/model-prices/get",
19610
+ "codexhost/usage/model-prices/set",
19611
+ "codexhost/usage/model-prices/default",
19612
+ "codexhost/usage/statistics/get",
19266
19613
  "codexhost/update/check",
19267
19614
  "codexhost/update/start",
19268
19615
  "codexhost/update/status"
@@ -19327,6 +19674,7 @@ var threadUsageSnapshotSchema = external_exports.object({
19327
19674
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
19328
19675
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
19329
19676
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
19677
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
19330
19678
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
19331
19679
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
19332
19680
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -19338,7 +19686,11 @@ var threadUsageSnapshotSchema = external_exports.object({
19338
19686
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
19339
19687
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
19340
19688
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
19341
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
19689
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
19690
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
19691
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
19692
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
19693
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
19342
19694
  }).strict().superRefine((usage, context) => {
19343
19695
  if (Object.keys(usage).length === 0) {
19344
19696
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -19359,6 +19711,20 @@ var threadUsageSnapshotSchema = external_exports.object({
19359
19711
  path: ["contextWindowTokens"]
19360
19712
  });
19361
19713
  }
19714
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
19715
+ context.addIssue({
19716
+ code: "custom",
19717
+ message: "Thread Usage costSource must be provided with totalCostUsd",
19718
+ path: ["costSource"]
19719
+ });
19720
+ }
19721
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
19722
+ context.addIssue({
19723
+ code: "custom",
19724
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
19725
+ path: ["unpricedModels"]
19726
+ });
19727
+ }
19362
19728
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
19363
19729
  context.addIssue({
19364
19730
  code: "custom",
@@ -19628,27 +19994,27 @@ var harnessModelCatalogSchema = external_exports.object({
19628
19994
  }).strict().superRefine((catalog, context) => {
19629
19995
  const refs = /* @__PURE__ */ new Set();
19630
19996
  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)) {
19997
+ for (const [index, model2] of catalog.models.entries()) {
19998
+ if (refs.has(model2.ref.id)) {
19633
19999
  context.addIssue({
19634
20000
  code: "custom",
19635
20001
  message: "Model Catalog refs must be unique",
19636
20002
  path: ["models", index, "ref", "id"]
19637
20003
  });
19638
20004
  }
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)) {
20005
+ refs.add(model2.ref.id);
20006
+ if (model2.fastModel) {
20007
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
19642
20008
  context.addIssue({
19643
20009
  code: "custom",
19644
20010
  message: "Fast Model refs must be distinct and unique",
19645
20011
  path: ["models", index, "fastModel"]
19646
20012
  });
19647
20013
  }
19648
- refs.add(model.fastModel.id);
20014
+ refs.add(model2.fastModel.id);
19649
20015
  }
19650
20016
  const supportedThinkingIds = /* @__PURE__ */ new Set();
19651
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
20017
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
19652
20018
  if (supportedThinkingIds.has(optionId)) {
19653
20019
  context.addIssue({
19654
20020
  code: "custom",
@@ -20242,6 +20608,11 @@ var codexSshDraftSchema = external_exports.strictObject({
20242
20608
  });
20243
20609
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
20244
20610
  external_exports.strictObject({ action: external_exports.literal("list") }),
20611
+ external_exports.strictObject({
20612
+ action: external_exports.literal("read-thread"),
20613
+ hostId: hostId.refine((id) => id !== "local"),
20614
+ input: delegationReadParamsSchema
20615
+ }),
20245
20616
  external_exports.strictObject({
20246
20617
  action: external_exports.literal("save"),
20247
20618
  draft: codexSshDraftSchema,
@@ -20373,7 +20744,6 @@ var tokenFields = [
20373
20744
  "cachedInputTokens",
20374
20745
  "cacheWriteInputTokens",
20375
20746
  "outputTokens",
20376
- "outputTokensPerSecond",
20377
20747
  "reasoningOutputTokens",
20378
20748
  "totalTokens",
20379
20749
  "contextWindowTokens",
@@ -20381,10 +20751,12 @@ var tokenFields = [
20381
20751
  ];
20382
20752
  var safeIntegerFields = [
20383
20753
  "planFiveHourResetsAtUnix",
20384
- "planSevenDayResetsAtUnix"
20754
+ "planSevenDayResetsAtUnix",
20755
+ "timeToFirstOutputMs"
20385
20756
  ];
20386
20757
  var percentFields = [
20387
20758
  "cacheHitRatePercent",
20759
+ "sessionCacheHitRatePercent",
20388
20760
  "planFiveHourUsedPercent",
20389
20761
  "planSevenDayUsedPercent"
20390
20762
  ];
@@ -20392,15 +20764,20 @@ var usageFields = /* @__PURE__ */ new Set([
20392
20764
  ...tokenFields,
20393
20765
  ...safeIntegerFields,
20394
20766
  ...percentFields,
20767
+ "sessionCacheUsage",
20395
20768
  "totalCostUsd",
20396
20769
  "totalCredits",
20397
- "contextUsagePercent"
20770
+ "contextUsagePercent",
20771
+ "outputTokensPerSecond",
20772
+ "apiOutputTokensPerSecond",
20773
+ "costSource",
20774
+ "unpricedModels"
20398
20775
  ]);
20399
- function isRecord2(value) {
20776
+ function isRecord3(value) {
20400
20777
  return typeof value === "object" && value !== null && !Array.isArray(value);
20401
20778
  }
20402
20779
  function parseHostUsage(value) {
20403
- if (!isRecord2(value))
20780
+ if (!isRecord3(value))
20404
20781
  throw new Error("Harness Usage must be an object");
20405
20782
  const keys = Object.keys(value);
20406
20783
  if (keys.length === 0)
@@ -20410,7 +20787,11 @@ function parseHostUsage(value) {
20410
20787
  throw new Error(`Harness Usage contains unknown field '${key}'`);
20411
20788
  }
20412
20789
  }
20413
- for (const field of ["totalCredits", "contextUsagePercent"]) {
20790
+ for (const field of [
20791
+ "totalCredits",
20792
+ "contextUsagePercent",
20793
+ "apiOutputTokensPerSecond"
20794
+ ]) {
20414
20795
  const candidate = value[field];
20415
20796
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
20416
20797
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -20446,6 +20827,12 @@ function parseHostUsage(value) {
20446
20827
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
20447
20828
  }
20448
20829
  }
20830
+ if (value.sessionCacheUsage !== void 0) {
20831
+ const totals2 = value.sessionCacheUsage;
20832
+ 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) {
20833
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
20834
+ }
20835
+ }
20449
20836
  const hasContextUsed = value.contextUsedTokens !== void 0;
20450
20837
  const hasContextWindow = value.contextWindowTokens !== void 0;
20451
20838
  if (hasContextUsed !== hasContextWindow) {
@@ -20460,8 +20847,43 @@ function parseHostUsage(value) {
20460
20847
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
20461
20848
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
20462
20849
  }
20850
+ if (value.costSource !== void 0) {
20851
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
20852
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
20853
+ }
20854
+ if (value.totalCostUsd === void 0) {
20855
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
20856
+ }
20857
+ }
20858
+ if (value.unpricedModels !== void 0) {
20859
+ const models = value.unpricedModels;
20860
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
20861
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
20862
+ }
20863
+ if (value.costSource !== "publicPrice") {
20864
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
20865
+ }
20866
+ return { ...value, unpricedModels: [...models] };
20867
+ }
20463
20868
  return { ...value };
20464
20869
  }
20870
+ var requestTokenFields = [
20871
+ "inputTokens",
20872
+ "cachedInputTokens",
20873
+ "cacheWriteInputTokens",
20874
+ "cacheWrite1hInputTokens",
20875
+ "outputTokens",
20876
+ "reasoningOutputTokens",
20877
+ "startedAtMs",
20878
+ "completedAtMs"
20879
+ ];
20880
+ var requestFields = /* @__PURE__ */ new Set([
20881
+ ...requestTokenFields,
20882
+ "requestId",
20883
+ "historical",
20884
+ "model",
20885
+ "provider"
20886
+ ]);
20465
20887
 
20466
20888
  // ../../harness-adapter/dist/live-command-catalog.js
20467
20889
  var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
@@ -20583,21 +21005,21 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
20583
21005
 
20584
21006
  // dist/acp-transport.js
20585
21007
  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";
21008
+ import { readdir, readFile as readFile3 } from "node:fs/promises";
21009
+ import os5 from "node:os";
21010
+ import path12 from "node:path";
20589
21011
  import { Readable, Writable } from "node:stream";
20590
21012
 
20591
21013
  // dist/grok-slash-commands.js
20592
21014
  var GROK_LIVE_COMMAND_ID_PREFIX = "grok.slash.";
20593
- function isRecord3(value) {
21015
+ function isRecord4(value) {
20594
21016
  return typeof value === "object" && value !== null && !Array.isArray(value);
20595
21017
  }
20596
21018
  function parseGrokAvailableCommands(value) {
20597
21019
  if (!Array.isArray(value))
20598
21020
  return [];
20599
21021
  return value.flatMap((entry) => {
20600
- if (!isRecord3(entry))
21022
+ if (!isRecord4(entry))
20601
21023
  return [];
20602
21024
  const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
20603
21025
  if (!name)
@@ -20606,14 +21028,14 @@ function parseGrokAvailableCommands(value) {
20606
21028
  {
20607
21029
  name,
20608
21030
  description: typeof entry.description === "string" ? entry.description : "",
20609
- meta: isRecord3(entry._meta) ? entry._meta : null
21031
+ meta: isRecord4(entry._meta) ? entry._meta : null
20610
21032
  }
20611
21033
  ];
20612
21034
  });
20613
21035
  }
20614
21036
  function isGrokSkill(command) {
20615
- const path14 = command.meta?.path;
20616
- return typeof path14 === "string" && /(^|[\\/])SKILL\.md$/u.test(path14) || typeof command.meta?.qualifiedName === "string";
21037
+ const path16 = command.meta?.path;
21038
+ return typeof path16 === "string" && /(^|[\\/])SKILL\.md$/u.test(path16) || typeof command.meta?.qualifiedName === "string";
20617
21039
  }
20618
21040
  function grokLiveCommands(native) {
20619
21041
  return native.map((command) => ({
@@ -20624,7 +21046,7 @@ function grokLiveCommands(native) {
20624
21046
  }
20625
21047
 
20626
21048
  // dist/command.js
20627
- import path5 from "node:path";
21049
+ import path7 from "node:path";
20628
21050
  var GrokExecutableError = class extends Error {
20629
21051
  code = "GROK_NOT_FOUND";
20630
21052
  };
@@ -20653,7 +21075,7 @@ function resolveGrokExecutable(input = {}) {
20653
21075
  });
20654
21076
  if (!resolution)
20655
21077
  throw new GrokExecutableError("Grok CLI is not installed");
20656
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
21078
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
20657
21079
  }
20658
21080
  function grokInvocation(command, platform = process.platform, modelId) {
20659
21081
  const arguments_ = ["agent", "--no-leader"];
@@ -20666,11 +21088,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
20666
21088
 
20667
21089
  // dist/grok-fork.js
20668
21090
  import { isDeepStrictEqual } from "node:util";
20669
- import path8 from "node:path";
21091
+ import path10 from "node:path";
20670
21092
 
20671
21093
  // dist/grok-file-change.js
20672
21094
  import { Buffer as Buffer2 } from "node:buffer";
20673
- import path6 from "node:path";
21095
+ import path8 from "node:path";
20674
21096
 
20675
21097
  // ../../../node_modules/diff/libesm/diff/base.js
20676
21098
  var Diff = class {
@@ -20772,16 +21194,16 @@ var Diff = class {
20772
21194
  }
20773
21195
  }
20774
21196
  }
20775
- addToPath(path14, added, removed, oldPosInc, options) {
20776
- const last = path14.lastComponent;
21197
+ addToPath(path16, added, removed, oldPosInc, options) {
21198
+ const last = path16.lastComponent;
20777
21199
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20778
21200
  return {
20779
- oldPos: path14.oldPos + oldPosInc,
21201
+ oldPos: path16.oldPos + oldPosInc,
20780
21202
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20781
21203
  };
20782
21204
  } else {
20783
21205
  return {
20784
- oldPos: path14.oldPos + oldPosInc,
21206
+ oldPos: path16.oldPos + oldPosInc,
20785
21207
  lastComponent: { count: 1, added, removed, previousComponent: last }
20786
21208
  };
20787
21209
  }
@@ -21090,17 +21512,17 @@ function splitLines(text) {
21090
21512
  // dist/grok-file-change.js
21091
21513
  var DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT = 4 * 1024 * 1024;
21092
21514
  var MAX_GROK_FILE_CHANGES_PER_TOOL = 32;
21093
- function isRecord4(value) {
21515
+ function isRecord5(value) {
21094
21516
  return typeof value === "object" && value !== null && !Array.isArray(value);
21095
21517
  }
21096
21518
  function validAbsolutePath(value) {
21097
- return typeof value === "string" && path6.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21519
+ return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21098
21520
  }
21099
21521
  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}`);
21522
+ const resolvedCwd = path8.resolve(cwd);
21523
+ const resolvedPath = path8.resolve(nativePath);
21524
+ const relative = path8.relative(resolvedCwd, resolvedPath);
21525
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
21104
21526
  const selected = inside ? relative : resolvedPath;
21105
21527
  const normalized = selected.replaceAll("\\", "/");
21106
21528
  if (normalized.length === 0 || normalized === ".")
@@ -21141,7 +21563,7 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21141
21563
  return null;
21142
21564
  const candidates = [];
21143
21565
  for (const entry of content) {
21144
- if (isRecord4(entry) && entry.type === "diff")
21566
+ if (isRecord5(entry) && entry.type === "diff")
21145
21567
  candidates.push(entry);
21146
21568
  }
21147
21569
  if (candidates.length === 0 || candidates.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
@@ -21162,8 +21584,8 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21162
21584
 
21163
21585
  // dist/local-media-markdown.js
21164
21586
  import { existsSync, statSync } from "node:fs";
21165
- import os3 from "node:os";
21166
- import path7 from "node:path";
21587
+ import os4 from "node:os";
21588
+ import path9 from "node:path";
21167
21589
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21168
21590
  ".aac",
21169
21591
  ".gif",
@@ -21182,14 +21604,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21182
21604
  ".webp"
21183
21605
  ]);
21184
21606
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21185
- const roots = [path7.resolve(cwd)];
21607
+ const roots = [path9.resolve(cwd)];
21186
21608
  if (sessionDirectory) {
21187
- const session = path7.resolve(sessionDirectory);
21188
- roots.push(session, path7.join(session, "videos"), path7.join(session, "images"));
21609
+ const session = path9.resolve(sessionDirectory);
21610
+ roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
21189
21611
  }
21190
- const home = process.env.HOME ?? process.env.USERPROFILE ?? os3.homedir();
21612
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
21191
21613
  if (home)
21192
- roots.push(path7.join(home, "Downloads"));
21614
+ roots.push(path9.join(home, "Downloads"));
21193
21615
  return roots;
21194
21616
  }
21195
21617
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -21290,7 +21712,7 @@ function parseInlineCode(text, start) {
21290
21712
  return { closed: false, content: text.slice(start + 1), end: text.length };
21291
21713
  }
21292
21714
  function mediaMarkdownImage(absolutePath) {
21293
- const name = path7.basename(absolutePath).replaceAll("]", "\\]");
21715
+ const name = path9.basename(absolutePath).replaceAll("]", "\\]");
21294
21716
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21295
21717
  }
21296
21718
  function parseMarkdownImage(text, start) {
@@ -21415,11 +21837,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21415
21837
  if (!hasMediaExtension(stripped))
21416
21838
  return null;
21417
21839
  if (isAbsoluteMediaPath(stripped)) {
21418
- const absolute = path7.resolve(stripped);
21840
+ const absolute = path9.resolve(stripped);
21419
21841
  return exists(absolute) ? absolute : null;
21420
21842
  }
21421
21843
  for (const root of roots) {
21422
- const absolute = path7.resolve(root, stripped);
21844
+ const absolute = path9.resolve(root, stripped);
21423
21845
  if (exists(absolute))
21424
21846
  return absolute;
21425
21847
  }
@@ -21441,11 +21863,11 @@ function stripFileUrl(value) {
21441
21863
  }
21442
21864
  }
21443
21865
  function isAbsoluteMediaPath(value) {
21444
- return path7.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21866
+ return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21445
21867
  }
21446
21868
  function hasMediaExtension(value) {
21447
21869
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21448
- return MEDIA_EXTENSIONS.has(path7.extname(pathname).toLowerCase());
21870
+ return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
21449
21871
  }
21450
21872
  function mediaFileExists(absolutePath) {
21451
21873
  try {
@@ -21458,14 +21880,14 @@ function mediaFileExists(absolutePath) {
21458
21880
  // dist/grok-tool-output.js
21459
21881
  var DEFAULT_GROK_TOOL_OUTPUT_LIMIT = 64e3;
21460
21882
  var EXECUTE_TOOL_NAMES = /* @__PURE__ */ new Set(["bash", "run_terminal_command", "shell", "cursor_shell"]);
21461
- function isRecord5(value) {
21883
+ function isRecord6(value) {
21462
21884
  return typeof value === "object" && value !== null && !Array.isArray(value);
21463
21885
  }
21464
21886
  function stringField(value, key) {
21465
- return isRecord5(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21887
+ return isRecord6(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21466
21888
  }
21467
21889
  function numberField(value, key) {
21468
- if (!isRecord5(value))
21890
+ if (!isRecord6(value))
21469
21891
  return void 0;
21470
21892
  const field = value[key];
21471
21893
  if (field === null)
@@ -21488,7 +21910,7 @@ function firstReadableText(...candidates) {
21488
21910
  for (const candidate of candidates) {
21489
21911
  if (typeof candidate === "string" && candidate.length > 0)
21490
21912
  return candidate;
21491
- if (isRecord5(candidate)) {
21913
+ if (isRecord6(candidate)) {
21492
21914
  const nested = stringField(candidate, "content") ?? stringField(candidate, "text") ?? stringField(candidate, "tool_result") ?? stringField(candidate, "raw_output");
21493
21915
  if (nested)
21494
21916
  return nested;
@@ -21511,7 +21933,7 @@ function grokToolArguments(rawInput) {
21511
21933
  if (!parsed.success)
21512
21934
  return {};
21513
21935
  const argumentsValue = parsed.data;
21514
- if (!isRecord5(argumentsValue) || stringField(argumentsValue, "path"))
21936
+ if (!isRecord6(argumentsValue) || stringField(argumentsValue, "path"))
21515
21937
  return argumentsValue;
21516
21938
  const targetFile = stringField(argumentsValue, "target_file");
21517
21939
  return targetFile ? { ...argumentsValue, path: targetFile } : argumentsValue;
@@ -21524,7 +21946,7 @@ function grokCommand(name, kind, rawInput) {
21524
21946
  return command;
21525
21947
  if (name && EXECUTE_TOOL_NAMES.has(name))
21526
21948
  return command;
21527
- return isRecord5(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21949
+ return isRecord6(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21528
21950
  }
21529
21951
  function grokCommandCwd(rawInput, fallback) {
21530
21952
  return stringField(rawInput, "cwd") ?? fallback;
@@ -21551,11 +21973,11 @@ function acpContentText(content) {
21551
21973
  if (!Array.isArray(content))
21552
21974
  return "";
21553
21975
  return content.flatMap((entry) => {
21554
- if (!isRecord5(entry))
21976
+ if (!isRecord6(entry))
21555
21977
  return [];
21556
21978
  if (entry.type === "text" && typeof entry.text === "string")
21557
21979
  return [entry.text];
21558
- if (entry.type !== "content" || !isRecord5(entry.content))
21980
+ if (entry.type !== "content" || !isRecord6(entry.content))
21559
21981
  return [];
21560
21982
  return entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : [];
21561
21983
  }).join("\n");
@@ -21566,10 +21988,10 @@ function acpContentImages(content, remainingBytes) {
21566
21988
  const images = [];
21567
21989
  let remaining = remainingBytes;
21568
21990
  for (const entry of content) {
21569
- if (!isRecord5(entry))
21991
+ if (!isRecord6(entry))
21570
21992
  continue;
21571
21993
  const image = entry.type === "image" ? entry : entry.type === "content" ? entry.content : null;
21572
- if (!isRecord5(image) || image.type !== "image")
21994
+ if (!isRecord6(image) || image.type !== "image")
21573
21995
  continue;
21574
21996
  const mimeType = stringField(image, "mimeType") ?? stringField(image, "mime_type");
21575
21997
  const data = stringField(image, "data");
@@ -21592,14 +22014,14 @@ function bashOutput(rawOutput) {
21592
22014
  function rawOutputProjection(rawOutput) {
21593
22015
  if (typeof rawOutput === "string")
21594
22016
  return rawOutput.length > 0 ? { text: rawOutput } : {};
21595
- if (!isRecord5(rawOutput))
22017
+ if (!isRecord6(rawOutput))
21596
22018
  return {};
21597
22019
  if (rawOutput.type === "Bash" || rawOutput.variant === "Bash" || numberField(rawOutput, "exit_code") !== void 0 || numberField(rawOutput, "exitCode") !== void 0) {
21598
22020
  const bash = bashOutput(rawOutput);
21599
22021
  if (bash.text !== void 0 || bash.exitCode !== void 0)
21600
22022
  return bash;
21601
22023
  }
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);
22024
+ 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
22025
  if (text)
21604
22026
  return { text };
21605
22027
  if (typeof rawOutput.match_count === "number" && Number.isFinite(rawOutput.match_count)) {
@@ -21663,11 +22085,11 @@ var WAIT_TOOL_NAMES = /* @__PURE__ */ new Set([
21663
22085
  var KILL_TOOL_NAMES = /* @__PURE__ */ new Set(["kill_command_or_subagent", "kill_task"]);
21664
22086
  var DESCRIPTION_LIMIT = 500;
21665
22087
  var SUMMARY_LIMIT = 2e3;
21666
- function isRecord6(value) {
22088
+ function isRecord7(value) {
21667
22089
  return typeof value === "object" && value !== null && !Array.isArray(value);
21668
22090
  }
21669
22091
  function idField(value, key) {
21670
- if (!isRecord6(value))
22092
+ if (!isRecord7(value))
21671
22093
  return void 0;
21672
22094
  const field = value[key];
21673
22095
  if (typeof field === "string") {
@@ -21679,7 +22101,7 @@ function idField(value, key) {
21679
22101
  return void 0;
21680
22102
  }
21681
22103
  function stringField2(value, key) {
21682
- if (!isRecord6(value) || typeof value[key] !== "string")
22104
+ if (!isRecord7(value) || typeof value[key] !== "string")
21683
22105
  return void 0;
21684
22106
  const trimmed = value[key].trim();
21685
22107
  return trimmed.length > 0 ? trimmed : void 0;
@@ -21702,7 +22124,7 @@ function collectIds(value) {
21702
22124
  };
21703
22125
  push(idField(value, "task_id"));
21704
22126
  push(idField(value, "subagent_id"));
21705
- if (isRecord6(value)) {
22127
+ if (isRecord7(value)) {
21706
22128
  const list = value.task_ids ?? value.subagent_ids;
21707
22129
  if (Array.isArray(list)) {
21708
22130
  for (const entry of list)
@@ -21721,7 +22143,7 @@ function grokSubagentOperation(name, title, rawInput) {
21721
22143
  return "send";
21722
22144
  if (SPAWN_TOOL_NAMES.has(id))
21723
22145
  return "spawn";
21724
- if (isRecord6(rawInput) && rawInput.variant === "Task")
22146
+ if (isRecord7(rawInput) && rawInput.variant === "Task")
21725
22147
  return "spawn";
21726
22148
  return null;
21727
22149
  }
@@ -21744,7 +22166,7 @@ function grokSubagentRole(rawInput) {
21744
22166
  return bounded(stringField2(rawInput, "subagent_type") ?? stringField2(rawInput, "agent_type") ?? stringField2(rawInput, "type"), DESCRIPTION_LIMIT);
21745
22167
  }
21746
22168
  function grokSubagentBackground(rawInput) {
21747
- if (!isRecord6(rawInput))
22169
+ if (!isRecord7(rawInput))
21748
22170
  return true;
21749
22171
  if (rawInput.background === false || rawInput.run_in_background === false)
21750
22172
  return false;
@@ -21782,7 +22204,7 @@ function grokSubagentResultSummary(...candidates) {
21782
22204
  return void 0;
21783
22205
  }
21784
22206
  function grokSubagentEventFromUpdate(update) {
21785
- if (!isRecord6(update) || typeof update.sessionUpdate !== "string")
22207
+ if (!isRecord7(update) || typeof update.sessionUpdate !== "string")
21786
22208
  return null;
21787
22209
  const nativeSubagentId = idField(update, "subagent_id") ?? idField(update, "child_session_id");
21788
22210
  if (!nativeSubagentId)
@@ -21790,13 +22212,13 @@ function grokSubagentEventFromUpdate(update) {
21790
22212
  if (update.sessionUpdate === "subagent_spawned") {
21791
22213
  const description = bounded(stringField2(update, "description"), DESCRIPTION_LIMIT);
21792
22214
  const role = bounded(stringField2(update, "subagent_type") ?? stringField2(update, "role"), DESCRIPTION_LIMIT);
21793
- const model = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
22215
+ const model2 = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
21794
22216
  return {
21795
22217
  type: "subagent.spawned",
21796
22218
  nativeSubagentId,
21797
22219
  ...description ? { description } : {},
21798
22220
  ...role ? { role } : {},
21799
- ...model ? { model } : {}
22221
+ ...model2 ? { model: model2 } : {}
21800
22222
  };
21801
22223
  }
21802
22224
  if (update.sessionUpdate === "subagent_finished") {
@@ -21843,14 +22265,14 @@ function grokSubagentWaitSettlements(input) {
21843
22265
  return ids.map((id) => ({ id, status: overall }));
21844
22266
  }
21845
22267
  function taskOutputResults(rawOutput) {
21846
- if (!isRecord6(rawOutput))
22268
+ if (!isRecord7(rawOutput))
21847
22269
  return [];
21848
22270
  if (Array.isArray(rawOutput.results)) {
21849
- return rawOutput.results.filter(isRecord6);
22271
+ return rawOutput.results.filter(isRecord7);
21850
22272
  }
21851
22273
  const nested = firstRecord(rawOutput.MultiResult, rawOutput.multiResult, rawOutput.multi_result);
21852
22274
  if (nested && Array.isArray(nested.results)) {
21853
- return nested.results.filter(isRecord6);
22275
+ return nested.results.filter(isRecord7);
21854
22276
  }
21855
22277
  const single = firstRecord(rawOutput.Result, rawOutput.result);
21856
22278
  if (single)
@@ -21861,7 +22283,7 @@ function taskOutputResults(rawOutput) {
21861
22283
  }
21862
22284
  function firstRecord(...values) {
21863
22285
  for (const value of values) {
21864
- if (isRecord6(value))
22286
+ if (isRecord7(value))
21865
22287
  return value;
21866
22288
  }
21867
22289
  return void 0;
@@ -21884,7 +22306,7 @@ function taskOutputTextSettlements(rawOutput, content, ids) {
21884
22306
  return settled;
21885
22307
  }
21886
22308
  function taskOutputStatus(rawOutput, content) {
21887
- if (isRecord6(rawOutput) && typeof rawOutput.status === "string")
22309
+ if (isRecord7(rawOutput) && typeof rawOutput.status === "string")
21888
22310
  return rawOutput.status;
21889
22311
  const text = extractText(content) ?? extractText(rawOutput);
21890
22312
  if (!text)
@@ -21943,7 +22365,7 @@ function extractText(value, depth = 0) {
21943
22365
  const joined = parts.join("\n").trim();
21944
22366
  return joined.length > 0 ? joined : void 0;
21945
22367
  }
21946
- if (!isRecord6(value))
22368
+ if (!isRecord7(value))
21947
22369
  return void 0;
21948
22370
  if (typeof value.text === "string" && value.text.trim().length > 0)
21949
22371
  return value.text.trim();
@@ -22302,7 +22724,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22302
22724
  rememberSubagentAlias(event.callId, nativeSubagentId);
22303
22725
  const prompt = grokSubagentPrompt(event.rawInput);
22304
22726
  const role = grokSubagentRole(event.rawInput);
22305
- const model = grokSubagentModel(event.rawInput);
22727
+ const model2 = grokSubagentModel(event.rawInput);
22306
22728
  subagents.set(event.callId, {
22307
22729
  type: "subagentDelegation",
22308
22730
  itemId: stableId("subagent", turnIndex, ++messageIndex),
@@ -22314,7 +22736,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22314
22736
  ...nativeSubagentId ? { nativeSubagentId } : {},
22315
22737
  description: grokSubagentDescription(event.rawInput, event.title),
22316
22738
  ...role ? { role } : {},
22317
- ...model ? { model } : {},
22739
+ ...model2 ? { model: model2 } : {},
22318
22740
  background: grokSubagentBackground(event.rawInput),
22319
22741
  status: "running"
22320
22742
  }
@@ -22413,11 +22835,11 @@ var GROK_SESSION_DELETE_METHOD = "_x.ai/session/delete";
22413
22835
  function error51(code, message, retryable = false) {
22414
22836
  return { code, message, retryable };
22415
22837
  }
22416
- function isRecord7(value) {
22838
+ function isRecord8(value) {
22417
22839
  return typeof value === "object" && value !== null && !Array.isArray(value);
22418
22840
  }
22419
22841
  function isGrokMethodNotFound(error53) {
22420
- if (isRecord7(error53) && error53.code === -32601)
22842
+ if (isRecord8(error53) && error53.code === -32601)
22421
22843
  return true;
22422
22844
  const message = error53 instanceof Error ? error53.message : String(error53);
22423
22845
  return /method not found/iu.test(message);
@@ -22435,10 +22857,10 @@ function buildGrokForkParams(input) {
22435
22857
  };
22436
22858
  }
22437
22859
  function parseGrokForkResponse(value) {
22438
- if (!isRecord7(value) || value.error !== void 0)
22860
+ if (!isRecord8(value) || value.error !== void 0)
22439
22861
  return null;
22440
- const payload = typeof value.newSessionId !== "string" && isRecord7(value.result) ? value.result : value;
22441
- if (!isRecord7(payload) || payload.error !== void 0)
22862
+ const payload = typeof value.newSessionId !== "string" && isRecord8(value.result) ? value.result : value;
22863
+ if (!isRecord8(payload) || payload.error !== void 0)
22442
22864
  return null;
22443
22865
  if (typeof payload.newSessionId !== "string" || payload.newSessionId.length === 0)
22444
22866
  return null;
@@ -22454,11 +22876,11 @@ function parseGrokForkResponse(value) {
22454
22876
  }
22455
22877
  function projectRelativePath(value, cwds) {
22456
22878
  const normalized = value.replaceAll("\\", "/");
22457
- if (!path8.isAbsolute(value))
22879
+ if (!path10.isAbsolute(value))
22458
22880
  return normalized;
22459
22881
  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}`)) {
22882
+ const relative = path10.relative(path10.resolve(cwd), path10.resolve(value));
22883
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`)) {
22462
22884
  return relative.replaceAll("\\", "/");
22463
22885
  }
22464
22886
  }
@@ -22523,8 +22945,8 @@ async function forkGrokSession(input) {
22523
22945
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
22524
22946
  };
22525
22947
  }
22526
- const sourceCwd = path8.resolve(located.cwd);
22527
- const targetCwd = path8.resolve(input.cwd);
22948
+ const sourceCwd = path10.resolve(located.cwd);
22949
+ const targetCwd = path10.resolve(input.cwd);
22528
22950
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
22529
22951
  if (!source.ok)
22530
22952
  return source;
@@ -22599,9 +23021,10 @@ async function forkGrokSession(input) {
22599
23021
  // dist/grok-compaction.js
22600
23022
  var GROK_SESSION_UPDATE_EXTENSION_METHODS = [
22601
23023
  "_x.ai/session/update",
22602
- "x.ai/session_notification"
23024
+ "x.ai/session_notification",
23025
+ "_x.ai/session_notification"
22603
23026
  ];
22604
- function isRecord8(value) {
23027
+ function isRecord9(value) {
22605
23028
  return typeof value === "object" && value !== null && !Array.isArray(value);
22606
23029
  }
22607
23030
  function optionalNonNegativeInt(value) {
@@ -22622,7 +23045,7 @@ function isGrokExtensionSessionUpdateMethod(method) {
22622
23045
  return GROK_SESSION_UPDATE_EXTENSION_METHODS.includes(method);
22623
23046
  }
22624
23047
  function grokCompactionEventFromUpdate(update) {
22625
- if (!isRecord8(update) || typeof update.sessionUpdate !== "string")
23048
+ if (!isRecord9(update) || typeof update.sessionUpdate !== "string")
22626
23049
  return null;
22627
23050
  const tokensUsed = optionalNonNegativeInt(firstPresent(update, ["tokensUsed", "tokens_used"]));
22628
23051
  const contextWindowTokens = optionalNonNegativeInt(firstPresent(update, ["contextWindowTokens", "contextWindow", "context_window"]));
@@ -22661,7 +23084,7 @@ function grokCompactionEventFromUpdate(update) {
22661
23084
  // dist/grok-manual-compaction.js
22662
23085
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
22663
23086
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
22664
- function isRecord9(value) {
23087
+ function isRecord10(value) {
22665
23088
  return typeof value === "object" && value !== null && !Array.isArray(value);
22666
23089
  }
22667
23090
  function optionalNonNegativeInt2(value) {
@@ -22673,7 +23096,7 @@ function optionalErrorMessage2(value) {
22673
23096
  function parseGrokCompactResult(value, cancelled = false) {
22674
23097
  if (cancelled)
22675
23098
  return { outcome: "cancelled" };
22676
- if (!isRecord9(value))
23099
+ if (!isRecord10(value))
22677
23100
  return { outcome: "succeeded" };
22678
23101
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
22679
23102
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -22706,12 +23129,12 @@ function parseGrokCompactResult(value, cancelled = false) {
22706
23129
  }
22707
23130
 
22708
23131
  // dist/grok-rewind.js
22709
- import path9 from "node:path";
23132
+ import path11 from "node:path";
22710
23133
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
22711
23134
  function error52(code, message, retryable = false) {
22712
23135
  return { code, message, retryable };
22713
23136
  }
22714
- function isRecord10(value) {
23137
+ function isRecord11(value) {
22715
23138
  return typeof value === "object" && value !== null && !Array.isArray(value);
22716
23139
  }
22717
23140
  function buildGrokRewindParams(input) {
@@ -22723,10 +23146,10 @@ function buildGrokRewindParams(input) {
22723
23146
  };
22724
23147
  }
22725
23148
  function parseGrokRewindResponse(value) {
22726
- if (!isRecord10(value))
23149
+ if (!isRecord11(value))
22727
23150
  return null;
22728
- const payload = typeof value.success !== "boolean" && isRecord10(value.result) ? value.result : value;
22729
- if (!isRecord10(payload) || typeof payload.success !== "boolean")
23151
+ const payload = typeof value.success !== "boolean" && isRecord11(value.result) ? value.result : value;
23152
+ if (!isRecord11(payload) || typeof payload.success !== "boolean")
22730
23153
  return null;
22731
23154
  return rewindPayload(payload);
22732
23155
  }
@@ -22779,8 +23202,8 @@ async function rewindGrokLastTurn(input) {
22779
23202
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
22780
23203
  };
22781
23204
  }
22782
- const sourceCwd = path9.resolve(located.cwd);
22783
- const targetCwd = path9.resolve(input.cwd);
23205
+ const sourceCwd = path11.resolve(located.cwd);
23206
+ const targetCwd = path11.resolve(input.cwd);
22784
23207
  if (sourceCwd !== targetCwd) {
22785
23208
  return {
22786
23209
  ok: false,
@@ -22842,7 +23265,7 @@ var GROK_PLAN_STAY_VALUE = "stay";
22842
23265
  var GROK_PLAN_STAY_LABEL = "Stay in plan mode";
22843
23266
  var GROK_PLAN_OUTCOME_APPROVED = "approved";
22844
23267
  var GROK_PLAN_OUTCOME_CANCELLED = "cancelled";
22845
- function isRecord11(value) {
23268
+ function isRecord12(value) {
22846
23269
  return typeof value === "object" && value !== null && !Array.isArray(value);
22847
23270
  }
22848
23271
  function stringField3(value, ...keys) {
@@ -22854,9 +23277,9 @@ function stringField3(value, ...keys) {
22854
23277
  return void 0;
22855
23278
  }
22856
23279
  function parseGrokExitPlanModeParams(params) {
22857
- if (!isRecord11(params))
23280
+ if (!isRecord12(params))
22858
23281
  return null;
22859
- const nested = isRecord11(params.input) ? params.input : params;
23282
+ const nested = isRecord12(params.input) ? params.input : params;
22860
23283
  const plan = stringField3(nested, "planContent", "plan_content", "plan") ?? stringField3(params, "planContent", "plan_content", "plan") ?? null;
22861
23284
  const planFilePath = stringField3(nested, "planFilePath", "plan_file_path") ?? stringField3(params, "planFilePath", "plan_file_path");
22862
23285
  const sessionId = stringField3(params, "sessionId", "session_id");
@@ -22928,7 +23351,7 @@ var GROK_ACP_CLIENT_CAPABILITIES = {
22928
23351
  "x.ai/exit_plan_mode": true
22929
23352
  }
22930
23353
  };
22931
- function isRecord12(value) {
23354
+ function isRecord13(value) {
22932
23355
  return typeof value === "object" && value !== null && !Array.isArray(value);
22933
23356
  }
22934
23357
  function stringField4(value, ...keys) {
@@ -22957,15 +23380,15 @@ function isGrokExitPlanModeMethod(method) {
22957
23380
  function questionsPayload(params) {
22958
23381
  if (Array.isArray(params.questions))
22959
23382
  return params.questions;
22960
- if (isRecord12(params.input) && Array.isArray(params.input.questions))
23383
+ if (isRecord13(params.input) && Array.isArray(params.input.questions))
22961
23384
  return params.input.questions;
22962
- if (isRecord12(params.askUserQuestion) && Array.isArray(params.askUserQuestion.questions)) {
23385
+ if (isRecord13(params.askUserQuestion) && Array.isArray(params.askUserQuestion.questions)) {
22963
23386
  return params.askUserQuestion.questions;
22964
23387
  }
22965
23388
  return void 0;
22966
23389
  }
22967
23390
  function parseOption(value, labels) {
22968
- if (!isRecord12(value))
23391
+ if (!isRecord13(value))
22969
23392
  return null;
22970
23393
  const label = stringField4(value, "label");
22971
23394
  if (!label || labels.has(label))
@@ -22980,7 +23403,7 @@ function parseOption(value, labels) {
22980
23403
  };
22981
23404
  }
22982
23405
  function parseQuestion(value, questions) {
22983
- if (!isRecord12(value))
23406
+ if (!isRecord13(value))
22984
23407
  return null;
22985
23408
  const question = stringField4(value, "question");
22986
23409
  if (!question || questions.has(question))
@@ -23005,7 +23428,7 @@ function parseQuestion(value, questions) {
23005
23428
  };
23006
23429
  }
23007
23430
  function parseGrokAskUserQuestionParams(params) {
23008
- if (!isRecord12(params))
23431
+ if (!isRecord13(params))
23009
23432
  return null;
23010
23433
  const rawQuestions = questionsPayload(params);
23011
23434
  if (!Array.isArray(rawQuestions) || rawQuestions.length === 0)
@@ -23120,16 +23543,16 @@ var GrokTransportError = class extends Error {
23120
23543
  this.name = "GrokTransportError";
23121
23544
  }
23122
23545
  };
23123
- function isRecord13(value) {
23546
+ function isRecord14(value) {
23124
23547
  return typeof value === "object" && value !== null && !Array.isArray(value);
23125
23548
  }
23126
23549
  function acpToolName(update, metadata) {
23127
- if (!isRecord13(update))
23550
+ if (!isRecord14(update))
23128
23551
  return void 0;
23129
23552
  if (typeof update.name === "string" && update.name.length > 0)
23130
23553
  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;
23554
+ const meta3 = isRecord14(update._meta) ? update._meta : metadata;
23555
+ const tool = meta3 && isRecord14(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23133
23556
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
23134
23557
  }
23135
23558
  function errorText(error53) {
@@ -23185,12 +23608,27 @@ function signalProcessTree(child, signal) {
23185
23608
  try {
23186
23609
  process.kill(-child.pid, signal);
23187
23610
  } catch (error53) {
23188
- if (!isRecord13(error53) || error53.code !== "ESRCH")
23611
+ if (!isRecord14(error53) || error53.code !== "ESRCH")
23189
23612
  throw error53;
23190
23613
  }
23191
23614
  }
23192
23615
  function transportEvent(update, metadata) {
23193
23616
  const extension = update;
23617
+ if (extension.sessionUpdate === "response_completed") {
23618
+ return {
23619
+ type: "response.completed",
23620
+ ...extension.usage !== void 0 ? { usage: extension.usage } : {},
23621
+ ...typeof extension.message_id === "string" && extension.message_id ? { messageId: extension.message_id } : {},
23622
+ ...metadata ? { metadata } : {}
23623
+ };
23624
+ }
23625
+ if (extension.sessionUpdate === "tool_call_delta_chunk" && typeof extension.arguments_delta === "string") {
23626
+ return {
23627
+ type: "tool.input.delta",
23628
+ text: extension.arguments_delta,
23629
+ ...metadata ? { metadata } : {}
23630
+ };
23631
+ }
23194
23632
  if (extension.sessionUpdate === "turn_completed" && typeof extension.prompt_id === "string" && extension.prompt_id.length > 0 && typeof extension.stop_reason === "string") {
23195
23633
  return {
23196
23634
  type: "turn.completed",
@@ -23260,34 +23698,34 @@ function transportEvent(update, metadata) {
23260
23698
  }
23261
23699
  function grokHomeDir(options) {
23262
23700
  const environment = { ...process.env, ...options.environment };
23263
- const home = environment.HOME ?? environment.USERPROFILE ?? os4.homedir();
23264
- return environment.GROK_HOME ?? path10.join(home, ".grok");
23701
+ const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23702
+ return environment.GROK_HOME ?? path12.join(home, ".grok");
23265
23703
  }
23266
23704
  function grokNativeSessionDirectory(options, sessionId) {
23267
- return path10.join(grokHomeDir(options), "sessions", encodeURIComponent(path10.resolve(options.cwd)), sessionId);
23705
+ return path12.join(grokHomeDir(options), "sessions", encodeURIComponent(path12.resolve(options.cwd)), sessionId);
23268
23706
  }
23269
23707
  function nativeSessionFile(options, sessionId, fileName) {
23270
- return path10.join(grokNativeSessionDirectory(options, sessionId), fileName);
23708
+ return path12.join(grokNativeSessionDirectory(options, sessionId), fileName);
23271
23709
  }
23272
23710
  function nativeHistoryPath(options, sessionId) {
23273
23711
  return nativeSessionFile(options, sessionId, "updates.jsonl");
23274
23712
  }
23275
23713
  async function readNativeSignals(options, sessionId) {
23276
23714
  try {
23277
- return JSON.parse(await readFile2(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23715
+ return JSON.parse(await readFile3(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23278
23716
  } catch {
23279
23717
  return void 0;
23280
23718
  }
23281
23719
  }
23282
23720
  function isMissingFile(error53) {
23283
- return isRecord13(error53) && error53.code === "ENOENT";
23721
+ return isRecord14(error53) && error53.code === "ENOENT";
23284
23722
  }
23285
23723
  async function locateGrokNativeSession(options, sessionId) {
23286
23724
  if (sessionId.length === 0)
23287
23725
  return null;
23288
23726
  let entries;
23289
23727
  try {
23290
- entries = await readdir(path10.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23728
+ entries = await readdir(path12.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23291
23729
  } catch (error53) {
23292
23730
  if (isMissingFile(error53))
23293
23731
  return null;
@@ -23301,9 +23739,9 @@ async function locateGrokNativeSession(options, sessionId) {
23301
23739
  continue;
23302
23740
  let summaryRaw;
23303
23741
  try {
23304
- summaryRaw = await readFile2(path10.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23742
+ summaryRaw = await readFile3(path12.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23305
23743
  } catch (error53) {
23306
- if (isMissingFile(error53) || isRecord13(error53) && error53.code === "ENOTDIR")
23744
+ if (isMissingFile(error53) || isRecord14(error53) && error53.code === "ENOTDIR")
23307
23745
  continue;
23308
23746
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
23309
23747
  cause: error53
@@ -23315,11 +23753,11 @@ async function locateGrokNativeSession(options, sessionId) {
23315
23753
  } catch {
23316
23754
  continue;
23317
23755
  }
23318
- if (!isRecord13(parsed))
23756
+ if (!isRecord14(parsed))
23319
23757
  continue;
23320
23758
  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;
23759
+ const cwd = isRecord14(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path12.resolve(info.cwd) : path12.resolve(decodeURIComponent(entry.name));
23760
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path12.resolve(parsed.source_workspace_dir) : void 0;
23323
23761
  matches.push({
23324
23762
  cwd,
23325
23763
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23329,7 +23767,7 @@ async function locateGrokNativeSession(options, sessionId) {
23329
23767
  }
23330
23768
  async function readGrokNativeHistory(options, sessionId) {
23331
23769
  try {
23332
- return parseNativeHistory(await readFile2(nativeHistoryPath({ ...options, cwd: path10.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23770
+ return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path12.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23333
23771
  } catch (error53) {
23334
23772
  if (isMissingFile(error53))
23335
23773
  return [];
@@ -23351,12 +23789,12 @@ function parseNativeHistory(contents, sessionId) {
23351
23789
  } catch {
23352
23790
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23353
23791
  }
23354
- if (!isRecord13(record2) || !isRecord13(record2.params))
23792
+ if (!isRecord14(record2) || !isRecord14(record2.params))
23355
23793
  continue;
23356
23794
  const params = record2.params;
23357
- if (params.sessionId !== sessionId || !isRecord13(params.update))
23795
+ if (params.sessionId !== sessionId || !isRecord14(params.update))
23358
23796
  continue;
23359
- const metadata = isRecord13(params._meta) ? params._meta : void 0;
23797
+ const metadata = isRecord14(params._meta) ? params._meta : void 0;
23360
23798
  const event = transportEvent(params.update, metadata);
23361
23799
  if (event)
23362
23800
  events.push(metadata ? { ...event, metadata } : event);
@@ -23413,6 +23851,13 @@ var GrokAcpTransport = class {
23413
23851
  async getHistory() {
23414
23852
  return this.readHistory(this.sessionId);
23415
23853
  }
23854
+ /** Native cumulative usage since this process attached, not persisted Session totals. */
23855
+ async getUsage() {
23856
+ if (!this.#connection)
23857
+ throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
23858
+ const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
23859
+ return isRecord14(result) ? result.usage : void 0;
23860
+ }
23416
23861
  async readHistory(sessionId, cwd = this.#options.cwd) {
23417
23862
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
23418
23863
  }
@@ -23616,6 +24061,7 @@ var GrokAcpTransport = class {
23616
24061
  prompt: [{ type: "text", text }]
23617
24062
  });
23618
24063
  } finally {
24064
+ await yieldToEventLoop();
23619
24065
  if (this.#activePrompt === active)
23620
24066
  this.#activePrompt = null;
23621
24067
  }
@@ -23654,16 +24100,17 @@ var GrokAcpTransport = class {
23654
24100
  this.#activeCompact = null;
23655
24101
  }
23656
24102
  }
23657
- async setModel(modelId, reasoningEffort) {
24103
+ async setModel(modelId, reasoningEffort, contextWindowTokens) {
23658
24104
  const connection = this.#connection;
23659
24105
  if (!connection || !this.#sessionId)
23660
24106
  throw new Error("Grok ACP Session is unavailable");
23661
24107
  const response = await connection.request("session/set_model", {
23662
24108
  sessionId: this.#sessionId,
23663
24109
  modelId,
23664
- ...reasoningEffort ? { reasoningEffort } : {}
24110
+ ...reasoningEffort ? { reasoningEffort } : {},
24111
+ ...contextWindowTokens !== void 0 ? { _meta: { contextWindow: contextWindowTokens } } : {}
23665
24112
  });
23666
- if (!isRecord13(response) || !isRecord13(response._meta) || !isRecord13(response._meta.model)) {
24113
+ if (!isRecord14(response) || !isRecord14(response._meta) || !isRecord14(response._meta.model)) {
23667
24114
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
23668
24115
  }
23669
24116
  const selected = response._meta.model.Ok;
@@ -23715,7 +24162,7 @@ var GrokAcpTransport = class {
23715
24162
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
23716
24163
  return;
23717
24164
  }
23718
- const metadata = isRecord13(notification._meta) ? notification._meta : void 0;
24165
+ const metadata = isRecord14(notification._meta) ? notification._meta : void 0;
23719
24166
  const event = transportEvent(notification.update, metadata);
23720
24167
  if (!event)
23721
24168
  return;
@@ -23730,7 +24177,7 @@ var GrokAcpTransport = class {
23730
24177
  #handleExtensionNotification(method, params) {
23731
24178
  if (!isGrokExtensionSessionUpdateMethod(method))
23732
24179
  return;
23733
- if (typeof params.sessionId !== "string" || !isRecord13(params.update))
24180
+ if (typeof params.sessionId !== "string" || !isRecord14(params.update))
23734
24181
  return;
23735
24182
  this.#handleUpdate(params);
23736
24183
  }
@@ -23758,13 +24205,13 @@ var GrokAcpTransport = class {
23758
24205
  };
23759
24206
 
23760
24207
  // 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";
24208
+ import { createReadStream as createReadStream2 } from "node:fs";
24209
+ import { opendir as opendir2, readFile as readFile4, stat } from "node:fs/promises";
24210
+ import path13 from "node:path";
24211
+ import { createInterface as createInterface2 } from "node:readline";
23765
24212
 
23766
24213
  // ../../harness-adapter/dist/session-import.js
23767
- import { lstat } from "node:fs/promises";
24214
+ import { lstat as lstat2 } from "node:fs/promises";
23768
24215
  var SessionImportChangedError = class extends Error {
23769
24216
  constructor(message = "Native Session changed during discovery; refresh and retry") {
23770
24217
  super(message);
@@ -23783,7 +24230,7 @@ function isStorageAccessError(error53) {
23783
24230
  }
23784
24231
  async function optionalLstat(file2) {
23785
24232
  try {
23786
- return await lstat(file2);
24233
+ return await lstat2(file2);
23787
24234
  } catch (error53) {
23788
24235
  if (isMissingFileError(error53))
23789
24236
  return null;
@@ -23881,11 +24328,11 @@ var SessionImportScope = class {
23881
24328
  // dist/session-import.js
23882
24329
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
23883
24330
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
23884
- function isRecord14(value) {
24331
+ function isRecord15(value) {
23885
24332
  return typeof value === "object" && value !== null && !Array.isArray(value);
23886
24333
  }
23887
24334
  async function readJson(file2, signal) {
23888
- return JSON.parse(await readFile3(file2, { encoding: "utf8", signal }));
24335
+ return JSON.parse(await readFile4(file2, { encoding: "utf8", signal }));
23889
24336
  }
23890
24337
  function processAlive(pid) {
23891
24338
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -23894,12 +24341,12 @@ function processAlive(pid) {
23894
24341
  process.kill(pid, 0);
23895
24342
  return true;
23896
24343
  } catch (error53) {
23897
- return isRecord14(error53) && error53.code === "EPERM";
24344
+ return isRecord15(error53) && error53.code === "EPERM";
23898
24345
  }
23899
24346
  }
23900
24347
  async function firstUserText(file2, signal) {
23901
- const stream = createReadStream(file2, { encoding: "utf8", signal });
23902
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
24348
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
24349
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
23903
24350
  try {
23904
24351
  for await (const line of lines) {
23905
24352
  signal.throwIfAborted();
@@ -23911,10 +24358,10 @@ async function firstUserText(file2, signal) {
23911
24358
  } catch {
23912
24359
  continue;
23913
24360
  }
23914
- const update = isRecord14(entry) && isRecord14(entry.params) ? entry.params.update : null;
23915
- if (!isRecord14(update) || update.sessionUpdate !== "user_message_chunk")
24361
+ const update = isRecord15(entry) && isRecord15(entry.params) ? entry.params.update : null;
24362
+ if (!isRecord15(update) || update.sessionUpdate !== "user_message_chunk")
23916
24363
  continue;
23917
- const text = isRecord14(update.content) ? update.content.text : null;
24364
+ const text = isRecord15(update.content) ? update.content.text : null;
23918
24365
  return typeof text === "string" ? text : "";
23919
24366
  }
23920
24367
  return null;
@@ -23981,7 +24428,7 @@ var GrokSessionImport = class {
23981
24428
  const active = /* @__PURE__ */ new Set();
23982
24429
  let entries;
23983
24430
  try {
23984
- entries = await readJson(path11.join(this.#home(), "active_sessions.json"), signal);
24431
+ entries = await readJson(path13.join(this.#home(), "active_sessions.json"), signal);
23985
24432
  } catch (error53) {
23986
24433
  signal.throwIfAborted();
23987
24434
  if (isStorageAccessError(error53))
@@ -23991,26 +24438,26 @@ var GrokSessionImport = class {
23991
24438
  if (!Array.isArray(entries))
23992
24439
  return active;
23993
24440
  for (const entry of entries) {
23994
- if (isRecord14(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24441
+ if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
23995
24442
  active.add(entry.session_id);
23996
24443
  }
23997
24444
  return active;
23998
24445
  }
23999
24446
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
24000
24447
  async #sessionDirectories(signal) {
24001
- const root = path11.join(this.#home(), "sessions");
24448
+ const root = path13.join(this.#home(), "sessions");
24002
24449
  const found = /* @__PURE__ */ new Map();
24003
24450
  const info = await optionalLstat(root);
24004
24451
  if (!info)
24005
24452
  return found;
24006
24453
  if (!info.isDirectory())
24007
24454
  throw new Error("Grok Session store is not a directory");
24008
- for await (const workspace of await opendir(root)) {
24455
+ for await (const workspace of await opendir2(root)) {
24009
24456
  signal.throwIfAborted();
24010
24457
  if (!workspace.isDirectory())
24011
24458
  continue;
24012
- const workspaceDirectory = path11.join(root, workspace.name);
24013
- const sessions = await opendir(workspaceDirectory).catch((error53) => {
24459
+ const workspaceDirectory = path13.join(root, workspace.name);
24460
+ const sessions = await opendir2(workspaceDirectory).catch((error53) => {
24014
24461
  if (isMissingFileError(error53))
24015
24462
  return null;
24016
24463
  throw error53;
@@ -24022,7 +24469,7 @@ var GrokSessionImport = class {
24022
24469
  if (!session.isDirectory())
24023
24470
  continue;
24024
24471
  const directories = found.get(session.name) ?? [];
24025
- directories.push(path11.join(workspaceDirectory, session.name));
24472
+ directories.push(path13.join(workspaceDirectory, session.name));
24026
24473
  found.set(session.name, directories);
24027
24474
  }
24028
24475
  }
@@ -24030,25 +24477,25 @@ var GrokSessionImport = class {
24030
24477
  }
24031
24478
  async #candidate(sessionDirectory, active, signal) {
24032
24479
  signal.throwIfAborted();
24033
- const nativeSessionId = path11.basename(sessionDirectory);
24480
+ const nativeSessionId = path13.basename(sessionDirectory);
24034
24481
  const files = [
24035
- path11.join(sessionDirectory, "summary.json"),
24036
- path11.join(sessionDirectory, "updates.jsonl")
24482
+ path13.join(sessionDirectory, "summary.json"),
24483
+ path13.join(sessionDirectory, "updates.jsonl")
24037
24484
  ];
24038
24485
  return readStableFiles(files, async ([summaryInfo, updates]) => {
24039
24486
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24040
24487
  return null;
24041
24488
  try {
24042
24489
  const summary = await readJson(files[0], signal);
24043
- if (!isRecord14(summary) || !isRecord14(summary.info) || summary.info.id !== nativeSessionId)
24490
+ if (!isRecord15(summary) || !isRecord15(summary.info) || summary.info.id !== nativeSessionId)
24044
24491
  return null;
24045
24492
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24046
24493
  return null;
24047
24494
  const nativeCwd = summary.info.cwd;
24048
- if (typeof nativeCwd !== "string" || !path11.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24495
+ if (typeof nativeCwd !== "string" || !path13.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24049
24496
  return null;
24050
- const cwd = path11.resolve(nativeCwd);
24051
- if (encodeURIComponent(cwd) !== path11.basename(path11.dirname(sessionDirectory)))
24497
+ const cwd = path13.resolve(nativeCwd);
24498
+ if (encodeURIComponent(cwd) !== path13.basename(path13.dirname(sessionDirectory)))
24052
24499
  return null;
24053
24500
  if (!(await stat(cwd)).isDirectory())
24054
24501
  return null;
@@ -24267,7 +24714,7 @@ var GrokSubagentLifecycle = class {
24267
24714
  };
24268
24715
 
24269
24716
  // dist/grok-models.js
24270
- function isRecord15(value) {
24717
+ function isRecord16(value) {
24271
24718
  return typeof value === "object" && value !== null && !Array.isArray(value);
24272
24719
  }
24273
24720
  function nonBlank(value) {
@@ -24279,7 +24726,7 @@ function thinkingOptions(value) {
24279
24726
  const seen = /* @__PURE__ */ new Set();
24280
24727
  const options = [];
24281
24728
  for (const candidate of value) {
24282
- if (!isRecord15(candidate) || !nonBlank(candidate.label))
24729
+ if (!isRecord16(candidate) || !nonBlank(candidate.label))
24283
24730
  continue;
24284
24731
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
24285
24732
  if (!id.success || seen.has(id.data))
@@ -24290,7 +24737,7 @@ function thinkingOptions(value) {
24290
24737
  return options;
24291
24738
  }
24292
24739
  function parseGrokModelState(value) {
24293
- if (!isRecord15(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24740
+ if (!isRecord16(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24294
24741
  return null;
24295
24742
  }
24296
24743
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -24298,16 +24745,20 @@ function parseGrokModelState(value) {
24298
24745
  return null;
24299
24746
  const allThinking = /* @__PURE__ */ new Map();
24300
24747
  const contextWindowTokensByModel = /* @__PURE__ */ new Map();
24748
+ const defaultContextWindowTokensByModel = /* @__PURE__ */ new Map();
24301
24749
  const models = [];
24302
24750
  let currentThinkingOptionId;
24303
24751
  for (const candidate of value.availableModels) {
24304
- if (!isRecord15(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24752
+ if (!isRecord16(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24305
24753
  continue;
24306
24754
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
24307
24755
  if (!ref.success)
24308
24756
  continue;
24309
- const metadata = isRecord15(candidate._meta) ? candidate._meta : {};
24757
+ const metadata = isRecord16(candidate._meta) ? candidate._meta : {};
24310
24758
  const options2 = thinkingOptions(metadata.reasoningEfforts);
24759
+ if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
24760
+ defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
24761
+ }
24311
24762
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
24312
24763
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
24313
24764
  }
@@ -24331,6 +24782,7 @@ function parseGrokModelState(value) {
24331
24782
  return {
24332
24783
  currentModel: currentModel.data,
24333
24784
  contextWindowTokensByModel,
24785
+ defaultContextWindowTokensByModel,
24334
24786
  ...currentThinkingOptionId ? { currentThinkingOptionId } : {},
24335
24787
  catalog: {
24336
24788
  models,
@@ -24341,13 +24793,13 @@ function parseGrokModelState(value) {
24341
24793
  };
24342
24794
  }
24343
24795
  function modelStateFromInitialize(response) {
24344
- return parseGrokModelState(isRecord15(response._meta) ? response._meta.modelState : void 0);
24796
+ return parseGrokModelState(isRecord16(response._meta) ? response._meta.modelState : void 0);
24345
24797
  }
24346
24798
  function modelStateFromSessionResponse(response) {
24347
- return parseGrokModelState(isRecord15(response) ? response.models : void 0);
24799
+ return parseGrokModelState(isRecord16(response) ? response.models : void 0);
24348
24800
  }
24349
- function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24350
- const selectedModel = model;
24801
+ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24802
+ const selectedModel = model2;
24351
24803
  const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === selectedModel.id);
24352
24804
  const availableThinkingOptions = catalogModel?.supportedThinkingOptionIds?.flatMap((id) => {
24353
24805
  const option = modelState.catalog.thinkingOptions.find((candidate) => candidate.id === id);
@@ -24363,12 +24815,12 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
24363
24815
  }
24364
24816
 
24365
24817
  // 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";
24818
+ import { readFile as readFile5 } from "node:fs/promises";
24819
+ import os6 from "node:os";
24820
+ import path14 from "node:path";
24369
24821
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
24370
24822
  var REQUEST_TIMEOUT_MS = 15e3;
24371
- function isRecord16(value) {
24823
+ function isRecord17(value) {
24372
24824
  return typeof value === "object" && value !== null && !Array.isArray(value);
24373
24825
  }
24374
24826
  function finitePercent(value) {
@@ -24377,15 +24829,15 @@ function finitePercent(value) {
24377
24829
  return Math.min(100, Math.max(0, value));
24378
24830
  }
24379
24831
  function nonNegativeCentValue(value) {
24380
- if (!isRecord16(value))
24832
+ if (!isRecord17(value))
24381
24833
  return void 0;
24382
24834
  const amount = value.val === void 0 ? 0 : value.val;
24383
24835
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
24384
24836
  return void 0;
24385
24837
  return amount;
24386
24838
  }
24387
- function grokHome(environment) {
24388
- return environment.GROK_HOME ?? path12.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
24839
+ function grokHome2(environment) {
24840
+ return environment.GROK_HOME ?? path14.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
24389
24841
  }
24390
24842
  function periodTypeFrom(value) {
24391
24843
  if (typeof value !== "string")
@@ -24401,7 +24853,7 @@ function productUsageFrom(value) {
24401
24853
  if (!Array.isArray(value))
24402
24854
  return void 0;
24403
24855
  const products = value.flatMap((entry) => {
24404
- if (!isRecord16(entry) || typeof entry.product !== "string")
24856
+ if (!isRecord17(entry) || typeof entry.product !== "string")
24405
24857
  return [];
24406
24858
  const usagePercent = finitePercent(entry.usagePercent);
24407
24859
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -24409,10 +24861,10 @@ function productUsageFrom(value) {
24409
24861
  return products.length > 0 ? products : void 0;
24410
24862
  }
24411
24863
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24412
- if (!isRecord16(value) || !isRecord16(value.config))
24864
+ if (!isRecord17(value) || !isRecord17(value.config))
24413
24865
  return null;
24414
24866
  const config2 = value.config;
24415
- const period = isRecord16(config2.currentPeriod) ? config2.currentPeriod : void 0;
24867
+ const period = isRecord17(config2.currentPeriod) ? config2.currentPeriod : void 0;
24416
24868
  const periodType = periodTypeFrom(period?.type);
24417
24869
  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
24870
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24439,11 +24891,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24439
24891
  };
24440
24892
  }
24441
24893
  function selectAccessToken(auth, now) {
24442
- if (!isRecord16(auth))
24894
+ if (!isRecord17(auth))
24443
24895
  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")));
24896
+ 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
24897
  for (const [, value] of entries) {
24446
- if (!isRecord16(value) || typeof value.key !== "string")
24898
+ if (!isRecord17(value) || typeof value.key !== "string")
24447
24899
  continue;
24448
24900
  if (typeof value.expires_at === "string") {
24449
24901
  const expiresAt = Date.parse(value.expires_at);
@@ -24464,8 +24916,8 @@ async function fetchGrokAccount(input = {}) {
24464
24916
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24465
24917
  return null;
24466
24918
  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");
24919
+ const authPath = path14.join(grokHome2(environment), "auth.json");
24920
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile5(authPath, "utf8");
24469
24921
  const token = selectAccessToken(JSON.parse(raw), now);
24470
24922
  if (!token)
24471
24923
  return null;
@@ -24515,7 +24967,7 @@ async function fetchGrokCredits(input = {}) {
24515
24967
 
24516
24968
  // dist/grok-usage.js
24517
24969
  var USD_TICKS_PER_DOLLAR = 1e10;
24518
- function isRecord17(value) {
24970
+ function isRecord18(value) {
24519
24971
  return typeof value === "object" && value !== null && !Array.isArray(value);
24520
24972
  }
24521
24973
  function optionalToken(value) {
@@ -24532,7 +24984,7 @@ function combineUsage(base, next) {
24532
24984
  return base === null ? next : parseHostUsage({ ...base, ...next });
24533
24985
  }
24534
24986
  function usageFromNative(value) {
24535
- if (!isRecord17(value))
24987
+ if (!isRecord18(value))
24536
24988
  return null;
24537
24989
  const nativeInputTokens = optionalToken(value.inputTokens);
24538
24990
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24557,11 +25009,111 @@ function usageFromNative(value) {
24557
25009
  return null;
24558
25010
  }
24559
25011
  }
24560
- function usageFromPrompt(response) {
24561
- return response.usage ? usageFromNative(response.usage) : null;
25012
+ function usageFromResponse(value) {
25013
+ if (!isRecord18(value))
25014
+ return null;
25015
+ const buckets = [
25016
+ value.input_tokens,
25017
+ value.cache_read_input_tokens,
25018
+ value.cache_creation_input_tokens
25019
+ ];
25020
+ const inputTokens = buckets.every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0) ? buckets.reduce((sum, n) => sum + n, 0) : void 0;
25021
+ const outputTokens = optionalToken(value.output_tokens);
25022
+ return usageFromNative({
25023
+ inputTokens,
25024
+ outputTokens,
25025
+ cachedReadTokens: value.cache_read_input_tokens,
25026
+ cacheCreationTokens: value.cache_creation_input_tokens,
25027
+ reasoningTokens: value.reasoning_tokens,
25028
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
25029
+ });
24562
25030
  }
25031
+ var GrokTurnUsage = class {
25032
+ #totals = {};
25033
+ #seen = /* @__PURE__ */ new Set();
25034
+ #cacheComplete;
25035
+ #compacting = false;
25036
+ #startedAtMs;
25037
+ #streamKey;
25038
+ #outputTokens = 0;
25039
+ #durationMs = 0;
25040
+ #latestCacheHit;
25041
+ #sessionInputTokens = 0;
25042
+ constructor(base, emptySession = false) {
25043
+ for (const field of summedUsageFields) {
25044
+ const value = base?.[field];
25045
+ if (value !== void 0)
25046
+ this.#totals[field] = value;
25047
+ }
25048
+ this.#cacheComplete = base?.sessionCacheUsage !== void 0 || emptySession;
25049
+ this.#sessionInputTokens = base?.sessionCacheUsage?.inputTokens ?? 0;
25050
+ }
25051
+ observe(event) {
25052
+ if (event.type === "compaction.started" || event.type === "compaction.completed") {
25053
+ this.#startedAtMs = void 0;
25054
+ this.#streamKey = void 0;
25055
+ this.#compacting = event.type === "compaction.started";
25056
+ }
25057
+ if (this.#compacting)
25058
+ return null;
25059
+ if (event.type === "subagent.spawned")
25060
+ this.#cacheComplete = false;
25061
+ if (event.type === "agent.text" || event.type === "agent.thought" || event.type === "tool.input.delta") {
25062
+ if (!event.text)
25063
+ return null;
25064
+ const key = event.metadata?.streamStartMs;
25065
+ if (key !== void 0 && this.#streamKey !== void 0 && key !== this.#streamKey)
25066
+ this.#startedAtMs = void 0;
25067
+ if (key !== void 0)
25068
+ this.#streamKey = key;
25069
+ this.#startedAtMs ??= Date.now();
25070
+ }
25071
+ if (event.type !== "response.completed")
25072
+ return null;
25073
+ if (event.messageId) {
25074
+ if (this.#seen.has(event.messageId))
25075
+ return null;
25076
+ this.#seen.add(event.messageId);
25077
+ }
25078
+ const duration3 = this.#startedAtMs === void 0 ? 0 : Date.now() - this.#startedAtMs;
25079
+ this.#startedAtMs = void 0;
25080
+ this.#streamKey = void 0;
25081
+ const usage = usageFromResponse(event.usage);
25082
+ this.#latestCacheHit = usage?.cacheHitRatePercent;
25083
+ if (usage?.inputTokens === void 0 || usage.cachedInputTokens === void 0)
25084
+ this.#cacheComplete = false;
25085
+ if (usage) {
25086
+ this.#sessionInputTokens += (usage.inputTokens ?? 0) + (usage.cachedInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0);
25087
+ for (const field of summedUsageFields) {
25088
+ const value = usage[field];
25089
+ if (value !== void 0)
25090
+ this.#totals[field] = (this.#totals[field] ?? 0) + value;
25091
+ }
25092
+ if (duration3 > 0 && usage.outputTokens !== void 0) {
25093
+ this.#outputTokens += usage.outputTokens;
25094
+ this.#durationMs += duration3;
25095
+ }
25096
+ }
25097
+ return this.snapshot();
25098
+ }
25099
+ metrics() {
25100
+ return {
25101
+ ...this.#durationMs > 0 ? { outputTokensPerSecond: this.#outputTokens * 1e3 / this.#durationMs } : {},
25102
+ ...this.#latestCacheHit !== void 0 ? { cacheHitRatePercent: this.#latestCacheHit } : {}
25103
+ };
25104
+ }
25105
+ snapshot() {
25106
+ const inputTokens = this.#totals.inputTokens;
25107
+ const cachedInputTokens = this.#totals.cachedInputTokens;
25108
+ return {
25109
+ ...this.#totals,
25110
+ ...this.metrics(),
25111
+ ...this.#cacheComplete && inputTokens !== void 0 && cachedInputTokens !== void 0 ? { sessionCacheUsage: { inputTokens: this.#sessionInputTokens, cachedInputTokens } } : {}
25112
+ };
25113
+ }
25114
+ };
24563
25115
  function usageFromSignals(value) {
24564
- if (!isRecord17(value))
25116
+ if (!isRecord18(value))
24565
25117
  return null;
24566
25118
  try {
24567
25119
  return parseHostUsage({
@@ -24581,13 +25133,23 @@ var summedUsageFields = [
24581
25133
  "totalTokens"
24582
25134
  ];
24583
25135
  function nativeCostTicks(value) {
24584
- if (!isRecord17(value))
25136
+ if (!isRecord18(value))
24585
25137
  return void 0;
24586
25138
  const ticks = value.costUsdTicks;
24587
25139
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
24588
25140
  return void 0;
24589
25141
  return ticks;
24590
25142
  }
25143
+ function sessionCostFromNative(value, initialCostUsd) {
25144
+ if (!isRecord18(value))
25145
+ return void 0;
25146
+ if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
25147
+ return void 0;
25148
+ if (value.usageIsIncomplete !== void 0 && value.usageIsIncomplete !== false)
25149
+ return void 0;
25150
+ const ticks = nativeCostTicks(value);
25151
+ return ticks === void 0 ? void 0 : optionalCostUsd(Math.round(initialCostUsd * USD_TICKS_PER_DOLLAR) + ticks);
25152
+ }
24591
25153
  function historyTurnKey(event, index) {
24592
25154
  const key = event.nativeTurnKey;
24593
25155
  if (typeof key === "string" && key.startsWith("task-completed-"))
@@ -24596,7 +25158,6 @@ function historyTurnKey(event, index) {
24596
25158
  }
24597
25159
  function sessionUsageFromHistory(events) {
24598
25160
  const latestByKey = /* @__PURE__ */ new Map();
24599
- let lastCacheHitRatePercent;
24600
25161
  let index = 0;
24601
25162
  for (const event of events) {
24602
25163
  if (event?.type !== "turn.completed")
@@ -24605,27 +25166,29 @@ function sessionUsageFromHistory(events) {
24605
25166
  index += 1;
24606
25167
  if (key === null)
24607
25168
  continue;
24608
- const usage = usageFromNative(event.usage);
24609
- if (!usage)
25169
+ if (event.usage === void 0 && latestByKey.has(key))
24610
25170
  continue;
25171
+ const usage = usageFromNative(event.usage);
24611
25172
  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
- }
25173
+ 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;
25174
+ latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
24616
25175
  }
24617
25176
  if (latestByKey.size === 0)
24618
25177
  return null;
24619
- const totals = {};
25178
+ const totals2 = {};
25179
+ let sessionInputTokens = 0;
24620
25180
  let ticks = 0;
24621
25181
  let hasTicks = false;
24622
25182
  for (const entry of latestByKey.values()) {
25183
+ if (!entry.usage)
25184
+ continue;
24623
25185
  for (const field of summedUsageFields) {
24624
25186
  const value = entry.usage[field];
24625
25187
  if (value === void 0)
24626
25188
  continue;
24627
- totals[field] = (totals[field] ?? 0) + value;
25189
+ totals2[field] = (totals2[field] ?? 0) + value;
24628
25190
  }
25191
+ sessionInputTokens += (entry.usage.inputTokens ?? 0) + (entry.usage.cachedInputTokens ?? 0) + (entry.usage.cacheWriteInputTokens ?? 0);
24629
25192
  if (entry.ticks === void 0)
24630
25193
  continue;
24631
25194
  ticks += entry.ticks;
@@ -24634,9 +25197,14 @@ function sessionUsageFromHistory(events) {
24634
25197
  const totalCostUsd = hasTicks ? optionalCostUsd(ticks) : void 0;
24635
25198
  try {
24636
25199
  return parseHostUsage({
24637
- ...totals,
25200
+ ...totals2,
24638
25201
  ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
24639
- ...lastCacheHitRatePercent !== void 0 ? { cacheHitRatePercent: lastCacheHitRatePercent } : {}
25202
+ ...[...latestByKey.values()].every((entry) => entry.complete) && totals2.inputTokens !== void 0 && totals2.cachedInputTokens !== void 0 ? {
25203
+ sessionCacheUsage: {
25204
+ inputTokens: sessionInputTokens,
25205
+ cachedInputTokens: totals2.cachedInputTokens
25206
+ }
25207
+ } : {}
24640
25208
  });
24641
25209
  } catch {
24642
25210
  return null;
@@ -24658,7 +25226,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
24658
25226
  function usageFromUpdate(update, metadata, contextWindowTokens) {
24659
25227
  try {
24660
25228
  if (update?.sessionUpdate === "usage_update") {
24661
- const cost = isRecord17(update.cost) ? update.cost : null;
25229
+ const cost = isRecord18(update.cost) ? update.cost : null;
24662
25230
  return parseHostUsage({
24663
25231
  contextUsedTokens: update.used,
24664
25232
  contextWindowTokens: update.size,
@@ -24790,6 +25358,8 @@ var GrokHarnessSession = class {
24790
25358
  #phase = "open";
24791
25359
  #state;
24792
25360
  #usage = null;
25361
+ #initialCostUsd;
25362
+ #costRequest = 0;
24793
25363
  constructor(cwd, transport, opened, modelState, onClosed, options) {
24794
25364
  this.#cwd = cwd;
24795
25365
  this.#sessionDirectory = options.sessionDirectory;
@@ -24803,6 +25373,7 @@ var GrokHarnessSession = class {
24803
25373
  this.#toolOutputLimit = options.toolOutputLimit;
24804
25374
  this.initialUsage = options.initialUsage ?? null;
24805
25375
  this.#usage = this.initialUsage;
25376
+ this.#initialCostUsd = this.initialUsage?.totalCostUsd ?? 0;
24806
25377
  this.capabilities = capabilitiesForModels(modelState);
24807
25378
  this.commands = {
24808
25379
  list: async () => ({ ok: true, value: this.#liveCommandCatalog() }),
@@ -24891,6 +25462,7 @@ var GrokHarnessSession = class {
24891
25462
  });
24892
25463
  const active = {
24893
25464
  command,
25465
+ usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
24894
25466
  agent: null,
24895
25467
  agentMessageId: null,
24896
25468
  rawAgentText: "",
@@ -25068,9 +25640,9 @@ var GrokHarnessSession = class {
25068
25640
  }
25069
25641
  async #selectThinking(command) {
25070
25642
  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)) {
25643
+ const model2 = this.#state.effectiveModel;
25644
+ const available = this.#modelState.catalog.models.find(({ ref }) => ref.id === model2?.id);
25645
+ if (!parsed.success || !model2 || !available?.supportedThinkingOptionIds?.includes(parsed.data)) {
25074
25646
  return {
25075
25647
  ok: false,
25076
25648
  error: {
@@ -25080,9 +25652,9 @@ var GrokHarnessSession = class {
25080
25652
  }
25081
25653
  };
25082
25654
  }
25083
- return this.#configure(model, parsed.data);
25655
+ return this.#configure(model2, parsed.data);
25084
25656
  }
25085
- async #configure(model, thinkingOptionId) {
25657
+ async #configure(model2, thinkingOptionId) {
25086
25658
  if (this.#configuring) {
25087
25659
  return {
25088
25660
  ok: false,
@@ -25095,9 +25667,20 @@ var GrokHarnessSession = class {
25095
25667
  }
25096
25668
  this.#configuring = true;
25097
25669
  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);
25670
+ const contextWindow = this.#modelState.defaultContextWindowTokensByModel.get(model2.id);
25671
+ await this.#transport.setModel(model2.id, thinkingOptionId, contextWindow);
25672
+ if (contextWindow !== void 0) {
25673
+ this.#modelState.contextWindowTokensByModel = new Map([
25674
+ ...this.#modelState.contextWindowTokensByModel,
25675
+ [model2.id, contextWindow]
25676
+ ]);
25677
+ }
25678
+ this.#state = stateForGrokModel(this.#modelState, { nativeRef: nativeRef(this.#transport.sessionId) }, model2, thinkingOptionId, this.#state.effectivePermissionModeId);
25100
25679
  this.#event({ type: "session.state.changed", state: this.#state });
25680
+ const selectedWindow = this.#modelState.contextWindowTokensByModel.get(model2.id);
25681
+ if (selectedWindow !== void 0 && this.#usage?.contextUsedTokens !== void 0) {
25682
+ this.#publishUsage({ contextWindowTokens: selectedWindow });
25683
+ }
25101
25684
  return { ok: true, value: { completed: true } };
25102
25685
  } catch (error53) {
25103
25686
  return { ok: false, error: normalizeError(error53, "nativeFailure") };
@@ -25310,6 +25893,11 @@ var GrokHarnessSession = class {
25310
25893
  #handleEvent(active, event) {
25311
25894
  if (this.#active !== active || this.#phase !== "open")
25312
25895
  return;
25896
+ const requestUsage = active.usage?.observe(event);
25897
+ if (requestUsage) {
25898
+ this.#publishUsage(requestUsage, active.command.turnId, true);
25899
+ void this.#refreshCost(active);
25900
+ }
25313
25901
  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
25902
  if (contextUsage)
25315
25903
  this.#publishUsage(contextUsage, active.command.turnId);
@@ -25333,6 +25921,17 @@ var GrokHarnessSession = class {
25333
25921
  } else if (event.type === "usage" || event.type === "turn.completed")
25334
25922
  return;
25335
25923
  }
25924
+ async #refreshCost(active) {
25925
+ const request = ++this.#costRequest;
25926
+ try {
25927
+ const totalCostUsd = sessionCostFromNative(await this.#transport.getUsage(), this.#initialCostUsd);
25928
+ if (this.#active !== active || this.#phase !== "open" || request !== this.#costRequest)
25929
+ return;
25930
+ if (totalCostUsd !== void 0)
25931
+ this.#publishUsage({ totalCostUsd }, active.command.turnId);
25932
+ } catch {
25933
+ }
25934
+ }
25336
25935
  #startCompaction(active, event) {
25337
25936
  if (active.compactionItem)
25338
25937
  return;
@@ -25445,14 +26044,14 @@ var GrokHarnessSession = class {
25445
26044
  const prompt = grokSubagentPrompt(event.rawInput);
25446
26045
  const role = grokSubagentRole(event.rawInput);
25447
26046
  const nativeSubagentId = grokNativeSubagentId(event.rawInput);
25448
- const model = grokSubagentModel(event.rawInput);
26047
+ const model2 = grokSubagentModel(event.rawInput);
25449
26048
  active.subagents.start(active.command.turnId, {
25450
26049
  callId: event.callId,
25451
26050
  operation,
25452
26051
  description: grokSubagentDescription(event.rawInput, event.title),
25453
26052
  ...prompt ? { prompt } : {},
25454
26053
  ...role ? { role } : {},
25455
- ...model ? { model } : {},
26054
+ ...model2 ? { model: model2 } : {},
25456
26055
  background: grokSubagentBackground(event.rawInput),
25457
26056
  ...nativeSubagentId ? { nativeSubagentId } : {}
25458
26057
  });
@@ -25674,7 +26273,17 @@ var GrokHarnessSession = class {
25674
26273
  checkpoint = created[0]?.checkpoint;
25675
26274
  } catch {
25676
26275
  }
25677
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, sessionUsageFromHistory(history) ?? (response ? usageFromPrompt(response) : null), nativeTurnRef);
26276
+ const promptUsage = response?.usage ?? response?._meta?.usage;
26277
+ if (nativeTurnRef && promptUsage !== void 0 && !history.some((event) => event.type === "turn.completed" && event.nativeTurnKey === nativeTurnRef.nativeTurnKey && event.usage !== void 0)) {
26278
+ history.push({
26279
+ type: "turn.completed",
26280
+ nativeTurnKey: nativeTurnRef.nativeTurnKey,
26281
+ stopReason: response?.stopReason ?? "end_turn",
26282
+ usage: promptUsage
26283
+ });
26284
+ }
26285
+ const usage = sessionUsageFromHistory(history) ?? usageFromNative(promptUsage);
26286
+ this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
25678
26287
  void this.#refreshCredits().catch(() => void 0);
25679
26288
  }
25680
26289
  #finish(active, outcome, usage = null, nativeTurnRef) {
@@ -25693,8 +26302,8 @@ var GrokHarnessSession = class {
25693
26302
  active.tools.clear();
25694
26303
  this.#closePendingInteractions(active, "cancelled");
25695
26304
  this.#active = null;
25696
- if (usage)
25697
- this.#publishUsage(usage, active.command.turnId);
26305
+ if (usage || this.#usage)
26306
+ this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
25698
26307
  this.#event({
25699
26308
  type: "turn.completed",
25700
26309
  turnId: active.command.turnId,
@@ -25703,8 +26312,14 @@ var GrokHarnessSession = class {
25703
26312
  });
25704
26313
  active.resolveCompletion();
25705
26314
  }
25706
- #publishUsage(usage, observedForTurnId) {
25707
- const merged = combineUsage(this.#usage, usage);
26315
+ #publishUsage(usage, observedForTurnId, replaceMetrics = false) {
26316
+ const base = this.#usage ? { ...this.#usage } : null;
26317
+ if (base && replaceMetrics) {
26318
+ delete base.outputTokensPerSecond;
26319
+ delete base.cacheHitRatePercent;
26320
+ delete base.sessionCacheUsage;
26321
+ }
26322
+ const merged = combineUsage(base, usage);
25708
26323
  if (merged === null || JSON.stringify(merged) === JSON.stringify(this.#usage))
25709
26324
  return;
25710
26325
  this.#usage = merged;
@@ -25766,6 +26381,7 @@ var GrokAdapter = class {
25766
26381
  liveCommandCatalog = true;
25767
26382
  harnessId = grokHarnessId;
25768
26383
  sessionImport;
26384
+ usageStatistics;
25769
26385
  subagents = {
25770
26386
  readSnapshot: async (input) => {
25771
26387
  if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
@@ -25815,6 +26431,7 @@ var GrokAdapter = class {
25815
26431
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
25816
26432
  this.#environment = options.environment;
25817
26433
  this.sessionImport = new GrokSessionImport(options.environment);
26434
+ this.usageStatistics = createGrokUsageStatistics(options.environment ?? process.env);
25818
26435
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
25819
26436
  this.#dependencies = dependencies ?? {
25820
26437
  randomUUID,
@@ -25863,7 +26480,7 @@ var GrokAdapter = class {
25863
26480
  async inspect(input = {}) {
25864
26481
  if (this.#closePromise)
25865
26482
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
25866
- const cwd = path13.resolve(input.cwd ?? process.cwd());
26483
+ const cwd = path15.resolve(input.cwd ?? process.cwd());
25867
26484
  if (!input.refresh) {
25868
26485
  const cached2 = this.#inspectionCache.get(cwd);
25869
26486
  if (cached2)
@@ -25925,7 +26542,7 @@ var GrokAdapter = class {
25925
26542
  }
25926
26543
  };
25927
26544
  }
25928
- const cwd = path13.resolve(input.cwd);
26545
+ const cwd = path15.resolve(input.cwd);
25929
26546
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
25930
26547
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
25931
26548
  return {
@@ -26029,6 +26646,8 @@ var GrokAdapter = class {
26029
26646
  const modelState = modelStateFromSessionResponse(opened.session) ?? modelStateFromInitialize(opened.initialize);
26030
26647
  if (!modelState)
26031
26648
  throw new GrokTransportError("protocolError", "Grok returned an invalid Model catalog");
26649
+ const nativeModelId = modelState.currentModel.id;
26650
+ const nativeThinkingOptionId = modelState.currentThinkingOptionId;
26032
26651
  const retainedConfiguration = sourceConfiguration;
26033
26652
  if ((input.kind === "rollbackLastTurn" || input.kind === "fork") && retainedConfiguration) {
26034
26653
  const operation = input.kind === "rollbackLastTurn" ? "Rewind" : "Fork";
@@ -26041,7 +26660,6 @@ var GrokAdapter = class {
26041
26660
  throw new GrokTransportError("protocolError", `Grok Thinking option is unavailable after ${operation}`);
26042
26661
  }
26043
26662
  if (retainedConfiguration.model.id !== modelState.currentModel.id || retainedConfiguration.thinkingOptionId !== modelState.currentThinkingOptionId) {
26044
- await transport.setModel(retainedConfiguration.model.id, retainedConfiguration.thinkingOptionId);
26045
26663
  modelState.currentModel = retainedConfiguration.model;
26046
26664
  if (retainedConfiguration.thinkingOptionId) {
26047
26665
  modelState.currentThinkingOptionId = retainedConfiguration.thinkingOptionId;
@@ -26060,7 +26678,6 @@ var GrokAdapter = class {
26060
26678
  throw new GrokTransportError("protocolError", "Requested Grok Thinking option is unavailable");
26061
26679
  }
26062
26680
  if (selectedModel.id !== modelState.currentModel.id || selectedThinking !== modelState.currentThinkingOptionId) {
26063
- await transport.setModel(selectedModel.id, selectedThinking);
26064
26681
  modelState.currentModel = selectedModel;
26065
26682
  if (selectedThinking)
26066
26683
  modelState.currentThinkingOptionId = selectedThinking;
@@ -26068,8 +26685,21 @@ var GrokAdapter = class {
26068
26685
  delete modelState.currentThinkingOptionId;
26069
26686
  }
26070
26687
  }
26688
+ const contextWindow = modelState.defaultContextWindowTokensByModel.get(modelState.currentModel.id);
26689
+ if (modelState.currentModel.id !== nativeModelId || modelState.currentThinkingOptionId !== nativeThinkingOptionId || contextWindow !== void 0 && modelState.contextWindowTokensByModel.get(modelState.currentModel.id) !== contextWindow) {
26690
+ await transport.setModel(modelState.currentModel.id, modelState.currentThinkingOptionId, contextWindow);
26691
+ if (contextWindow !== void 0) {
26692
+ modelState.contextWindowTokensByModel = new Map([
26693
+ ...modelState.contextWindowTokensByModel,
26694
+ [modelState.currentModel.id, contextWindow]
26695
+ ]);
26696
+ }
26697
+ }
26071
26698
  const history = await transport.getHistory();
26072
- const initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26699
+ let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26700
+ if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {
26701
+ initialUsage = combineUsage(initialUsage, { contextWindowTokens: contextWindow });
26702
+ }
26073
26703
  const environment = input.environment ?? this.#environment;
26074
26704
  const sessionDirectory = grokNativeSessionDirectory(environment ? { cwd, environment } : { cwd }, opened.sessionId);
26075
26705
  const openedSession = new GrokHarnessSession(cwd, transport, opened, modelState, () => this.#sessions.delete(openedSession), {