@codexhost/cli-win32-arm64 0.12.2 → 0.13.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 (55) 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 +4924 -935
  6. package/app/desktop-controller.mjs +252 -41
  7. package/app/host-runtime.mjs +5312 -1442
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +275 -41
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +1045 -355
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +5930 -5357
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +16703 -0
  16. package/app/plugins/cursor-cli/manifest.json +17 -0
  17. package/app/plugins/cursor-cli/plugin.mjs +350 -76
  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 +797 -241
  21. package/app/plugins/enabled.json +2 -1
  22. package/app/plugins/grok/manifest.json +21 -1
  23. package/app/plugins/grok/plugin.mjs +883 -258
  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 +277 -32
  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 +554 -35
  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 +283 -21
  33. package/app/plugins/omp/manifest.json +21 -1
  34. package/app/plugins/omp/plugin.mjs +2737 -1956
  35. package/app/plugins/opencode/manifest.json +18 -1
  36. package/app/plugins/opencode/plugin.mjs +693 -146
  37. package/app/plugins/pi/manifest.json +32 -0
  38. package/app/plugins/pi/plugin.mjs +2809 -2254
  39. package/app/plugins/qoder/manifest.json +18 -1
  40. package/app/plugins/qoder/plugin.mjs +584 -80
  41. package/app/plugins/qoder-cn/manifest.json +18 -1
  42. package/app/plugins/qoder-cn/plugin.mjs +584 -80
  43. package/app/plugins/workbuddy/manifest.json +18 -0
  44. package/app/plugins/workbuddy/plugin.mjs +6316 -5745
  45. package/app/plugins/zcode/manifest.json +19 -1
  46. package/app/plugins/zcode/plugin.mjs +1065 -259
  47. package/app/renderer-extension.js +1485 -1570
  48. package/bin/codexhost.exe +0 -0
  49. package/libexec/codexhost-node-repl.exe +0 -0
  50. package/libexec/codexhost-shim.exe +0 -0
  51. package/libexec/codexhost-updater.exe +0 -0
  52. package/licenses/Cordis-LICENSE.txt +21 -0
  53. package/licenses/Cosmokit-LICENSE.txt +21 -0
  54. package/package.json +1 -1
  55. 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/zod/v4/classic/external.js
418
578
  var external_exports = {};
@@ -1180,10 +1340,10 @@ function mergeDefs(...defs) {
1180
1340
  function cloneDef(schema) {
1181
1341
  return mergeDefs(schema._zod.def);
1182
1342
  }
1183
- function getElementAtPath(obj, path14) {
1184
- if (!path14)
1343
+ function getElementAtPath(obj, path16) {
1344
+ if (!path16)
1185
1345
  return obj;
1186
- return path14.reduce((acc, key) => acc?.[key], obj);
1346
+ return path16.reduce((acc, key) => acc?.[key], obj);
1187
1347
  }
1188
1348
  function promiseAllObject(promisesObj) {
1189
1349
  const keys = Object.keys(promisesObj);
@@ -1592,11 +1752,11 @@ function explicitlyAborted(x, startIndex = 0) {
1592
1752
  }
1593
1753
  return false;
1594
1754
  }
1595
- function prefixIssues(path14, issues) {
1755
+ function prefixIssues(path16, issues) {
1596
1756
  return issues.map((iss) => {
1597
1757
  var _a3;
1598
1758
  (_a3 = iss).path ?? (_a3.path = []);
1599
- iss.path.unshift(path14);
1759
+ iss.path.unshift(path16);
1600
1760
  return iss;
1601
1761
  });
1602
1762
  }
@@ -1743,16 +1903,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1743
1903
  }
1744
1904
  function formatError(error53, mapper = (issue2) => issue2.message) {
1745
1905
  const fieldErrors = { _errors: [] };
1746
- const processError = (error54, path14 = []) => {
1906
+ const processError = (error54, path16 = []) => {
1747
1907
  for (const issue2 of error54.issues) {
1748
1908
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1749
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1909
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1750
1910
  } else if (issue2.code === "invalid_key") {
1751
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1911
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1752
1912
  } else if (issue2.code === "invalid_element") {
1753
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1913
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1754
1914
  } else {
1755
- const fullpath = [...path14, ...issue2.path];
1915
+ const fullpath = [...path16, ...issue2.path];
1756
1916
  if (fullpath.length === 0) {
1757
1917
  fieldErrors._errors.push(mapper(issue2));
1758
1918
  } else {
@@ -1779,17 +1939,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1779
1939
  }
1780
1940
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1781
1941
  const result = { errors: [] };
1782
- const processError = (error54, path14 = []) => {
1942
+ const processError = (error54, path16 = []) => {
1783
1943
  var _a3, _b;
1784
1944
  for (const issue2 of error54.issues) {
1785
1945
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1786
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1946
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1787
1947
  } else if (issue2.code === "invalid_key") {
1788
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1948
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1789
1949
  } else if (issue2.code === "invalid_element") {
1790
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1950
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1791
1951
  } else {
1792
- const fullpath = [...path14, ...issue2.path];
1952
+ const fullpath = [...path16, ...issue2.path];
1793
1953
  if (fullpath.length === 0) {
1794
1954
  result.errors.push(mapper(issue2));
1795
1955
  continue;
@@ -1821,8 +1981,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1821
1981
  }
1822
1982
  function toDotPath(_path) {
1823
1983
  const segs = [];
1824
- const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1825
- for (const seg of path14) {
1984
+ const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1985
+ for (const seg of path16) {
1826
1986
  if (typeof seg === "number")
1827
1987
  segs.push(`[${seg}]`);
1828
1988
  else if (typeof seg === "symbol")
@@ -5050,8 +5210,8 @@ function az_default() {
5050
5210
  }
5051
5211
 
5052
5212
  // ../../../node_modules/zod/v4/locales/be.js
5053
- function getBelarusianPlural(count, one, few, many) {
5054
- const absCount = Math.abs(count);
5213
+ function getBelarusianPlural(count3, one, few, many) {
5214
+ const absCount = Math.abs(count3);
5055
5215
  const lastDigit = absCount % 10;
5056
5216
  const lastTwoDigits = absCount % 100;
5057
5217
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -7129,8 +7289,8 @@ function hu_default() {
7129
7289
  }
7130
7290
 
7131
7291
  // ../../../node_modules/zod/v4/locales/hy.js
7132
- function getArmenianPlural(count, one, many) {
7133
- return Math.abs(count) === 1 ? one : many;
7292
+ function getArmenianPlural(count3, one, many) {
7293
+ return Math.abs(count3) === 1 ? one : many;
7134
7294
  }
7135
7295
  function withDefiniteArticle(word) {
7136
7296
  if (!word)
@@ -9258,8 +9418,8 @@ function ro_default() {
9258
9418
  }
9259
9419
 
9260
9420
  // ../../../node_modules/zod/v4/locales/ru.js
9261
- function getRussianPlural(count, one, few, many) {
9262
- const absCount = Math.abs(count);
9421
+ function getRussianPlural(count3, one, few, many) {
9422
+ const absCount = Math.abs(count3);
9263
9423
  const lastDigit = absCount % 10;
9264
9424
  const lastTwoDigits = absCount % 100;
9265
9425
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14514,13 +14674,13 @@ function resolveRef(ref, ctx) {
14514
14674
  if (!ref.startsWith("#")) {
14515
14675
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14516
14676
  }
14517
- const path14 = ref.slice(1).split("/").filter(Boolean);
14518
- if (path14.length === 0) {
14677
+ const path16 = ref.slice(1).split("/").filter(Boolean);
14678
+ if (path16.length === 0) {
14519
14679
  return ctx.rootSchema;
14520
14680
  }
14521
14681
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14522
- if (path14[0] === defsKey) {
14523
- const key = path14[1];
14682
+ if (path16[0] === defsKey) {
14683
+ const key = path16[1];
14524
14684
  if (!key || !ctx.defs[key]) {
14525
14685
  throw new Error(`Reference not found: ${ref}`);
14526
14686
  }
@@ -14928,6 +15088,15 @@ function date4(params) {
14928
15088
  // ../../../node_modules/zod/v4/classic/external.js
14929
15089
  config(en_default());
14930
15090
 
15091
+ // ../../shared-contracts/dist/delegation-read.js
15092
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15093
+ var delegationReadParamsSchema = external_exports.strictObject({
15094
+ threadId: external_exports.string().min(1).max(1024),
15095
+ view: external_exports.enum(["result", "messages"]),
15096
+ cursor: external_exports.string().min(1).max(8192).optional(),
15097
+ limit: external_exports.number().int().min(1).max(100).optional()
15098
+ });
15099
+
14931
15100
  // ../../shared-contracts/dist/credential-imports.js
14932
15101
  var credentialSourceSchema = external_exports.object({
14933
15102
  id: external_exports.string().min(1).max(256),
@@ -14998,6 +15167,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
14998
15167
  initializeOnly: external_exports.boolean().optional()
14999
15168
  });
15000
15169
 
15170
+ // ../../shared-contracts/dist/model-price-overrides.js
15171
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
15172
+ var modelPriceOverrideSchema = external_exports.strictObject({
15173
+ input: usdPerMillionTokens,
15174
+ output: usdPerMillionTokens,
15175
+ cacheRead: usdPerMillionTokens.optional(),
15176
+ cacheWrite: usdPerMillionTokens.optional(),
15177
+ cacheWrite1h: usdPerMillionTokens.optional()
15178
+ });
15179
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
15180
+ var modelPriceOverridesSchema = external_exports.strictObject({
15181
+ /** Absolute path of the Host's `pricing.json`. */
15182
+ path: external_exports.string(),
15183
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
15184
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
15185
+ error: external_exports.string().nullable()
15186
+ });
15187
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
15188
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
15189
+ key: modelPriceKeySchema,
15190
+ price: modelPriceOverrideSchema.nullable(),
15191
+ previousKey: modelPriceKeySchema.optional()
15192
+ });
15193
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
15194
+ model: modelPriceKeySchema
15195
+ });
15196
+ var modelPriceSuggestionSchema = external_exports.strictObject({
15197
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
15198
+ official: external_exports.boolean().optional(),
15199
+ canonicalModelId: external_exports.string().min(1).optional(),
15200
+ provider: external_exports.string().min(1).max(512),
15201
+ model: external_exports.string().min(1).max(512),
15202
+ price: modelPriceOverrideSchema
15203
+ });
15204
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
15205
+ price: modelPriceOverrideSchema.nullable(),
15206
+ /** Local catalog suggestions only; never used automatically for pricing. */
15207
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
15208
+ });
15209
+
15210
+ // ../../shared-contracts/dist/usage-statistics.js
15211
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
15212
+ var count2 = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
15213
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
15214
+ var harness = external_exports.string().min(1).max(128);
15215
+ var model = external_exports.string().min(1).max(512);
15216
+ var project = external_exports.string().min(1).max(4096);
15217
+ var usageStatisticsParamsSchema = external_exports.strictObject({
15218
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
15219
+ harness: harness.optional(),
15220
+ model: model.nullable().optional(),
15221
+ project: project.nullable().optional(),
15222
+ /** One local date inside the range. */
15223
+ date: localDate.optional()
15224
+ });
15225
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
15226
+ requests: count2,
15227
+ inputTokens: count2,
15228
+ cachedInputTokens: count2,
15229
+ cacheWriteInputTokens: count2,
15230
+ cacheKnownInputTokens: count2,
15231
+ outputTokens: count2,
15232
+ reasoningOutputTokens: count2,
15233
+ /** USD at the public price, summed over the priced requests only. */
15234
+ costUsd: external_exports.number().finite().min(0),
15235
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
15236
+ unpricedRequests: count2,
15237
+ /**
15238
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
15239
+ * cost, and not as unpriced.
15240
+ */
15241
+ unmeteredRequests: count2
15242
+ });
15243
+ var totals = usageStatisticsTotalsSchema.shape;
15244
+ var usageStatisticsSessionSchema = external_exports.strictObject({
15245
+ harness,
15246
+ sessionId: external_exports.string().min(1).max(512),
15247
+ project: project.nullable(),
15248
+ /** Models the session used, most requests first. */
15249
+ models: external_exports.array(model).max(16),
15250
+ firstAtMs: count2,
15251
+ lastAtMs: count2,
15252
+ ...totals
15253
+ });
15254
+ var usageStatisticsResultSchema = external_exports.strictObject({
15255
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
15256
+ /** First local date of the range; null for all time. */
15257
+ from: localDate.nullable(),
15258
+ to: localDate,
15259
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
15260
+ filters: external_exports.strictObject({
15261
+ harness: harness.nullable(),
15262
+ model: model.nullable(),
15263
+ unknownModel: external_exports.boolean(),
15264
+ project: project.nullable(),
15265
+ unknownProject: external_exports.boolean(),
15266
+ date: localDate.nullable()
15267
+ }),
15268
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
15269
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count2, read: count2 }),
15270
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
15271
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
15272
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
15273
+ options: external_exports.strictObject({
15274
+ harnesses: external_exports.array(harness).max(256),
15275
+ models: external_exports.array(model.nullable()).max(4096),
15276
+ projects: external_exports.array(project.nullable()).max(4096)
15277
+ }),
15278
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
15279
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
15280
+ */
15281
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
15282
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
15283
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
15284
+ */
15285
+ credits: external_exports.array(external_exports.strictObject({
15286
+ harness,
15287
+ model: model.nullable(),
15288
+ credits: external_exports.number().finite().min(0),
15289
+ reportedRequests: count2,
15290
+ requests: count2
15291
+ })).max(4096).optional(),
15292
+ /** All filters applied. */
15293
+ totals: usageStatisticsTotalsSchema,
15294
+ /** Each date and Harness of the range: every filter except the day. */
15295
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
15296
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
15297
+ hourly: external_exports.array(external_exports.strictObject({
15298
+ weekday: external_exports.number().int().min(0).max(6),
15299
+ hour: external_exports.number().int().min(0).max(23),
15300
+ ...totals
15301
+ })).max(168),
15302
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
15303
+ byModel: external_exports.array(external_exports.strictObject({
15304
+ model: model.nullable(),
15305
+ ...totals,
15306
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
15307
+ harnessPricedRequests: count2
15308
+ })).max(4096),
15309
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
15310
+ /**
15311
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
15312
+ * requests without a native session are not listed here but count everywhere else.
15313
+ */
15314
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
15315
+ });
15316
+
15001
15317
  // ../../shared-contracts/dist/ids.js
15002
15318
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15003
15319
  message: "Identifier must not be empty or whitespace"
@@ -15045,6 +15361,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15045
15361
  "codexhost/account/list",
15046
15362
  "codexhost/account/refresh",
15047
15363
  "codexhost/account/usage/inspect",
15364
+ "codexhost/usage/model-prices/get",
15365
+ "codexhost/usage/model-prices/set",
15366
+ "codexhost/usage/model-prices/default",
15367
+ "codexhost/usage/statistics/get",
15048
15368
  "codexhost/update/check",
15049
15369
  "codexhost/update/start",
15050
15370
  "codexhost/update/status"
@@ -15109,6 +15429,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15109
15429
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
15110
15430
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
15111
15431
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15432
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15112
15433
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
15113
15434
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
15114
15435
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -15120,7 +15441,11 @@ var threadUsageSnapshotSchema = external_exports.object({
15120
15441
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
15121
15442
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15122
15443
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
15123
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
15444
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15445
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15446
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15447
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15448
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15124
15449
  }).strict().superRefine((usage, context) => {
15125
15450
  if (Object.keys(usage).length === 0) {
15126
15451
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -15141,6 +15466,20 @@ var threadUsageSnapshotSchema = external_exports.object({
15141
15466
  path: ["contextWindowTokens"]
15142
15467
  });
15143
15468
  }
15469
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
15470
+ context.addIssue({
15471
+ code: "custom",
15472
+ message: "Thread Usage costSource must be provided with totalCostUsd",
15473
+ path: ["costSource"]
15474
+ });
15475
+ }
15476
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
15477
+ context.addIssue({
15478
+ code: "custom",
15479
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
15480
+ path: ["unpricedModels"]
15481
+ });
15482
+ }
15144
15483
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
15145
15484
  context.addIssue({
15146
15485
  code: "custom",
@@ -15395,27 +15734,27 @@ var harnessModelCatalogSchema = external_exports.object({
15395
15734
  }).strict().superRefine((catalog, context) => {
15396
15735
  const refs = /* @__PURE__ */ new Set();
15397
15736
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15398
- for (const [index, model] of catalog.models.entries()) {
15399
- if (refs.has(model.ref.id)) {
15737
+ for (const [index, model2] of catalog.models.entries()) {
15738
+ if (refs.has(model2.ref.id)) {
15400
15739
  context.addIssue({
15401
15740
  code: "custom",
15402
15741
  message: "Model Catalog refs must be unique",
15403
15742
  path: ["models", index, "ref", "id"]
15404
15743
  });
15405
15744
  }
15406
- refs.add(model.ref.id);
15407
- if (model.fastModel) {
15408
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15745
+ refs.add(model2.ref.id);
15746
+ if (model2.fastModel) {
15747
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15409
15748
  context.addIssue({
15410
15749
  code: "custom",
15411
15750
  message: "Fast Model refs must be distinct and unique",
15412
15751
  path: ["models", index, "fastModel"]
15413
15752
  });
15414
15753
  }
15415
- refs.add(model.fastModel.id);
15754
+ refs.add(model2.fastModel.id);
15416
15755
  }
15417
15756
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15418
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
15757
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
15419
15758
  if (supportedThinkingIds.has(optionId)) {
15420
15759
  context.addIssue({
15421
15760
  code: "custom",
@@ -15609,13 +15948,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
15609
15948
  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);
15610
15949
  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");
15611
15950
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15951
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15952
+ var harnessInstallationGuideSchema = external_exports.object({
15953
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15954
+ before: localizedTextSchema.optional(),
15955
+ after: localizedTextSchema.optional(),
15956
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15957
+ }).strict();
15612
15958
  var pluginPresentationShape = {
15613
15959
  id: harnessPluginIdSchema,
15614
15960
  name: external_exports.string().trim().min(1).max(128),
15615
15961
  version: external_exports.string().min(1).max(128),
15962
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15963
+ kind: external_exports.literal("usage").optional(),
15964
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15965
+ iconStyle: external_exports.object({
15966
+ vector: external_exports.object({
15967
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15968
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15969
+ paths: external_exports.array(external_exports.object({
15970
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15971
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15972
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15973
+ }).strict()).min(1).max(32)
15974
+ }).strict().optional(),
15975
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15976
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15977
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15978
+ }).strict().optional(),
15979
+ installation: harnessInstallationGuideSchema.optional(),
15980
+ notice: localizedTextSchema.optional(),
15616
15981
  /** The factory accepts a persisted local entrypoint through its construction context. */
15617
15982
  launchCommand: external_exports.literal(true).optional(),
15618
15983
  links: external_exports.object({
15984
+ website: documentationUrlSchema.optional(),
15619
15985
  documentation: documentationUrlSchema.optional(),
15620
15986
  installation: documentationUrlSchema.optional()
15621
15987
  }).strict().optional()
@@ -16034,6 +16400,11 @@ var codexSshDraftSchema = external_exports.strictObject({
16034
16400
  });
16035
16401
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
16036
16402
  external_exports.strictObject({ action: external_exports.literal("list") }),
16403
+ external_exports.strictObject({
16404
+ action: external_exports.literal("read-thread"),
16405
+ hostId: hostId.refine((id) => id !== "local"),
16406
+ input: delegationReadParamsSchema
16407
+ }),
16037
16408
  external_exports.strictObject({
16038
16409
  action: external_exports.literal("save"),
16039
16410
  draft: codexSshDraftSchema,
@@ -16136,10 +16507,12 @@ var tokenFields = [
16136
16507
  ];
16137
16508
  var safeIntegerFields = [
16138
16509
  "planFiveHourResetsAtUnix",
16139
- "planSevenDayResetsAtUnix"
16510
+ "planSevenDayResetsAtUnix",
16511
+ "timeToFirstOutputMs"
16140
16512
  ];
16141
16513
  var percentFields = [
16142
16514
  "cacheHitRatePercent",
16515
+ "sessionCacheHitRatePercent",
16143
16516
  "planFiveHourUsedPercent",
16144
16517
  "planSevenDayUsedPercent"
16145
16518
  ];
@@ -16147,16 +16520,20 @@ var usageFields = /* @__PURE__ */ new Set([
16147
16520
  ...tokenFields,
16148
16521
  ...safeIntegerFields,
16149
16522
  ...percentFields,
16523
+ "sessionCacheUsage",
16150
16524
  "totalCostUsd",
16151
16525
  "totalCredits",
16152
16526
  "contextUsagePercent",
16153
- "outputTokensPerSecond"
16527
+ "outputTokensPerSecond",
16528
+ "apiOutputTokensPerSecond",
16529
+ "costSource",
16530
+ "unpricedModels"
16154
16531
  ]);
16155
- function isRecord(value) {
16532
+ function isRecord2(value) {
16156
16533
  return typeof value === "object" && value !== null && !Array.isArray(value);
16157
16534
  }
16158
16535
  function parseHostUsage(value) {
16159
- if (!isRecord(value))
16536
+ if (!isRecord2(value))
16160
16537
  throw new Error("Harness Usage must be an object");
16161
16538
  const keys = Object.keys(value);
16162
16539
  if (keys.length === 0)
@@ -16166,7 +16543,11 @@ function parseHostUsage(value) {
16166
16543
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16167
16544
  }
16168
16545
  }
16169
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16546
+ for (const field of [
16547
+ "totalCredits",
16548
+ "contextUsagePercent",
16549
+ "apiOutputTokensPerSecond"
16550
+ ]) {
16170
16551
  const candidate = value[field];
16171
16552
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16172
16553
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -16196,6 +16577,12 @@ function parseHostUsage(value) {
16196
16577
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16197
16578
  }
16198
16579
  }
16580
+ if (value.sessionCacheUsage !== void 0) {
16581
+ const totals2 = value.sessionCacheUsage;
16582
+ if (!isRecord2(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) {
16583
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
16584
+ }
16585
+ }
16199
16586
  const hasContextUsed = value.contextUsedTokens !== void 0;
16200
16587
  const hasContextWindow = value.contextWindowTokens !== void 0;
16201
16588
  if (hasContextUsed !== hasContextWindow) {
@@ -16210,8 +16597,43 @@ function parseHostUsage(value) {
16210
16597
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
16211
16598
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
16212
16599
  }
16600
+ if (value.costSource !== void 0) {
16601
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
16602
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
16603
+ }
16604
+ if (value.totalCostUsd === void 0) {
16605
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
16606
+ }
16607
+ }
16608
+ if (value.unpricedModels !== void 0) {
16609
+ const models = value.unpricedModels;
16610
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
16611
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
16612
+ }
16613
+ if (value.costSource !== "publicPrice") {
16614
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16615
+ }
16616
+ return { ...value, unpricedModels: [...models] };
16617
+ }
16213
16618
  return { ...value };
16214
16619
  }
16620
+ var requestTokenFields = [
16621
+ "inputTokens",
16622
+ "cachedInputTokens",
16623
+ "cacheWriteInputTokens",
16624
+ "cacheWrite1hInputTokens",
16625
+ "outputTokens",
16626
+ "reasoningOutputTokens",
16627
+ "startedAtMs",
16628
+ "completedAtMs"
16629
+ ];
16630
+ var requestFields = /* @__PURE__ */ new Set([
16631
+ ...requestTokenFields,
16632
+ "requestId",
16633
+ "historical",
16634
+ "model",
16635
+ "provider"
16636
+ ]);
16215
16637
 
16216
16638
  // ../../harness-adapter/dist/live-command-catalog.js
16217
16639
  var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
@@ -16333,9 +16755,9 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
16333
16755
 
16334
16756
  // dist/acp-transport.js
16335
16757
  import { spawn, spawnSync } from "node:child_process";
16336
- import { readdir, readFile as readFile2 } from "node:fs/promises";
16337
- import os4 from "node:os";
16338
- import path10 from "node:path";
16758
+ import { readdir, readFile as readFile3 } from "node:fs/promises";
16759
+ import os5 from "node:os";
16760
+ import path12 from "node:path";
16339
16761
  import { Readable, Writable } from "node:stream";
16340
16762
 
16341
16763
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -18073,17 +18495,17 @@ function isResponseMessage(value) {
18073
18495
  function isNotificationMessage(value) {
18074
18496
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
18075
18497
  }
18076
- function isRecord2(value) {
18498
+ function isRecord3(value) {
18077
18499
  return typeof value === "object" && value !== null;
18078
18500
  }
18079
18501
  function isJsonRpcEnvelope(value) {
18080
- return isRecord2(value) && value["jsonrpc"] === "2.0";
18502
+ return isRecord3(value) && value["jsonrpc"] === "2.0";
18081
18503
  }
18082
18504
  function isJsonRpcId(value) {
18083
18505
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
18084
18506
  }
18085
18507
  function isResponseShapedMessage(value) {
18086
- return isRecord2(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
18508
+ return isRecord3(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
18087
18509
  }
18088
18510
  function isResponseBatch(batch) {
18089
18511
  let hasValidCall = false;
@@ -18093,7 +18515,7 @@ function isResponseBatch(batch) {
18093
18515
  for (const entry of batch) {
18094
18516
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
18095
18517
  hasValidResponse ||= isResponseMessage(entry);
18096
- if (!isRecord2(entry)) {
18518
+ if (!isRecord3(entry)) {
18097
18519
  continue;
18098
18520
  }
18099
18521
  hasCallShape ||= "method" in entry;
@@ -18108,13 +18530,13 @@ function isResponseBatch(batch) {
18108
18530
  return hasResponseShape && !hasCallShape;
18109
18531
  }
18110
18532
  function cancelRequestId(params) {
18111
- if (!isRecord2(params) || !isJsonRpcId(params["requestId"])) {
18533
+ if (!isRecord3(params) || !isJsonRpcId(params["requestId"])) {
18112
18534
  return void 0;
18113
18535
  }
18114
18536
  return params["requestId"];
18115
18537
  }
18116
18538
  function isErrorResponse(value) {
18117
- return isRecord2(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
18539
+ return isRecord3(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
18118
18540
  }
18119
18541
  var Handled = {
18120
18542
  /**
@@ -18605,7 +19027,7 @@ var Connection = class {
18605
19027
  this.receiveBatch(message);
18606
19028
  return;
18607
19029
  }
18608
- if (!isRecord2(message)) {
19030
+ if (!isRecord3(message)) {
18609
19031
  console.error("Invalid message", { message });
18610
19032
  return;
18611
19033
  }
@@ -18622,9 +19044,9 @@ var Connection = class {
18622
19044
  return;
18623
19045
  }
18624
19046
  const responseBatch = isResponseBatch(batch);
18625
- const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
19047
+ const responseCount = responseBatch ? 0 : batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 0 : 1), 0);
18626
19048
  let remaining = responseCount;
18627
- let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
19049
+ let remainingNotifications = batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 1 : 0), 0);
18628
19050
  let responseSent = false;
18629
19051
  const responses = [];
18630
19052
  const sendResponsesIfReady = async () => {
@@ -18668,7 +19090,7 @@ var Connection = class {
18668
19090
  if (this.abortController.signal.aborted) {
18669
19091
  return Promise.resolve();
18670
19092
  }
18671
- if (!isRecord2(message)) {
19093
+ if (!isRecord3(message)) {
18672
19094
  console.error("Invalid message", { message });
18673
19095
  return Promise.resolve();
18674
19096
  }
@@ -19038,7 +19460,7 @@ function ndJsonStream(output, input) {
19038
19460
  if (trimmedLine) {
19039
19461
  try {
19040
19462
  const message = JSON.parse(trimmedLine);
19041
- if (isRecord2(message) || Array.isArray(message)) {
19463
+ if (isRecord3(message) || Array.isArray(message)) {
19042
19464
  controller.enqueue(message);
19043
19465
  } else {
19044
19466
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
@@ -20501,14 +20923,14 @@ var ClientSideConnection = class {
20501
20923
 
20502
20924
  // dist/grok-slash-commands.js
20503
20925
  var GROK_LIVE_COMMAND_ID_PREFIX = "grok.slash.";
20504
- function isRecord3(value) {
20926
+ function isRecord4(value) {
20505
20927
  return typeof value === "object" && value !== null && !Array.isArray(value);
20506
20928
  }
20507
20929
  function parseGrokAvailableCommands(value) {
20508
20930
  if (!Array.isArray(value))
20509
20931
  return [];
20510
20932
  return value.flatMap((entry) => {
20511
- if (!isRecord3(entry))
20933
+ if (!isRecord4(entry))
20512
20934
  return [];
20513
20935
  const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
20514
20936
  if (!name)
@@ -20517,14 +20939,14 @@ function parseGrokAvailableCommands(value) {
20517
20939
  {
20518
20940
  name,
20519
20941
  description: typeof entry.description === "string" ? entry.description : "",
20520
- meta: isRecord3(entry._meta) ? entry._meta : null
20942
+ meta: isRecord4(entry._meta) ? entry._meta : null
20521
20943
  }
20522
20944
  ];
20523
20945
  });
20524
20946
  }
20525
20947
  function isGrokSkill(command) {
20526
- const path14 = command.meta?.path;
20527
- return typeof path14 === "string" && /(^|[\\/])SKILL\.md$/u.test(path14) || typeof command.meta?.qualifiedName === "string";
20948
+ const path16 = command.meta?.path;
20949
+ return typeof path16 === "string" && /(^|[\\/])SKILL\.md$/u.test(path16) || typeof command.meta?.qualifiedName === "string";
20528
20950
  }
20529
20951
  function grokLiveCommands(native) {
20530
20952
  return native.map((command) => ({
@@ -20535,7 +20957,7 @@ function grokLiveCommands(native) {
20535
20957
  }
20536
20958
 
20537
20959
  // dist/command.js
20538
- import path5 from "node:path";
20960
+ import path7 from "node:path";
20539
20961
  var GrokExecutableError = class extends Error {
20540
20962
  code = "GROK_NOT_FOUND";
20541
20963
  };
@@ -20564,7 +20986,7 @@ function resolveGrokExecutable(input = {}) {
20564
20986
  });
20565
20987
  if (!resolution)
20566
20988
  throw new GrokExecutableError("Grok CLI is not installed");
20567
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
20989
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
20568
20990
  }
20569
20991
  function grokInvocation(command, platform = process.platform, modelId) {
20570
20992
  const arguments_ = ["agent", "--no-leader"];
@@ -20577,11 +20999,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
20577
20999
 
20578
21000
  // dist/grok-fork.js
20579
21001
  import { isDeepStrictEqual } from "node:util";
20580
- import path8 from "node:path";
21002
+ import path10 from "node:path";
20581
21003
 
20582
21004
  // dist/grok-file-change.js
20583
21005
  import { Buffer as Buffer2 } from "node:buffer";
20584
- import path6 from "node:path";
21006
+ import path8 from "node:path";
20585
21007
 
20586
21008
  // ../../../node_modules/diff/libesm/diff/base.js
20587
21009
  var Diff = class {
@@ -20683,16 +21105,16 @@ var Diff = class {
20683
21105
  }
20684
21106
  }
20685
21107
  }
20686
- addToPath(path14, added, removed, oldPosInc, options) {
20687
- const last = path14.lastComponent;
21108
+ addToPath(path16, added, removed, oldPosInc, options) {
21109
+ const last = path16.lastComponent;
20688
21110
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20689
21111
  return {
20690
- oldPos: path14.oldPos + oldPosInc,
21112
+ oldPos: path16.oldPos + oldPosInc,
20691
21113
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20692
21114
  };
20693
21115
  } else {
20694
21116
  return {
20695
- oldPos: path14.oldPos + oldPosInc,
21117
+ oldPos: path16.oldPos + oldPosInc,
20696
21118
  lastComponent: { count: 1, added, removed, previousComponent: last }
20697
21119
  };
20698
21120
  }
@@ -21001,17 +21423,17 @@ function splitLines(text) {
21001
21423
  // dist/grok-file-change.js
21002
21424
  var DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT = 4 * 1024 * 1024;
21003
21425
  var MAX_GROK_FILE_CHANGES_PER_TOOL = 32;
21004
- function isRecord4(value) {
21426
+ function isRecord5(value) {
21005
21427
  return typeof value === "object" && value !== null && !Array.isArray(value);
21006
21428
  }
21007
21429
  function validAbsolutePath(value) {
21008
- return typeof value === "string" && path6.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21430
+ return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21009
21431
  }
21010
21432
  function displayPath(nativePath, cwd) {
21011
- const resolvedCwd = path6.resolve(cwd);
21012
- const resolvedPath = path6.resolve(nativePath);
21013
- const relative = path6.relative(resolvedCwd, resolvedPath);
21014
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path6.sep}`);
21433
+ const resolvedCwd = path8.resolve(cwd);
21434
+ const resolvedPath = path8.resolve(nativePath);
21435
+ const relative = path8.relative(resolvedCwd, resolvedPath);
21436
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
21015
21437
  const selected = inside ? relative : resolvedPath;
21016
21438
  const normalized = selected.replaceAll("\\", "/");
21017
21439
  if (normalized.length === 0 || normalized === ".")
@@ -21052,7 +21474,7 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21052
21474
  return null;
21053
21475
  const candidates = [];
21054
21476
  for (const entry of content) {
21055
- if (isRecord4(entry) && entry.type === "diff")
21477
+ if (isRecord5(entry) && entry.type === "diff")
21056
21478
  candidates.push(entry);
21057
21479
  }
21058
21480
  if (candidates.length === 0 || candidates.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
@@ -21073,8 +21495,8 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21073
21495
 
21074
21496
  // dist/local-media-markdown.js
21075
21497
  import { existsSync, statSync } from "node:fs";
21076
- import os3 from "node:os";
21077
- import path7 from "node:path";
21498
+ import os4 from "node:os";
21499
+ import path9 from "node:path";
21078
21500
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21079
21501
  ".aac",
21080
21502
  ".gif",
@@ -21093,14 +21515,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21093
21515
  ".webp"
21094
21516
  ]);
21095
21517
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21096
- const roots = [path7.resolve(cwd)];
21518
+ const roots = [path9.resolve(cwd)];
21097
21519
  if (sessionDirectory) {
21098
- const session = path7.resolve(sessionDirectory);
21099
- roots.push(session, path7.join(session, "videos"), path7.join(session, "images"));
21520
+ const session = path9.resolve(sessionDirectory);
21521
+ roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
21100
21522
  }
21101
- const home = process.env.HOME ?? process.env.USERPROFILE ?? os3.homedir();
21523
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
21102
21524
  if (home)
21103
- roots.push(path7.join(home, "Downloads"));
21525
+ roots.push(path9.join(home, "Downloads"));
21104
21526
  return roots;
21105
21527
  }
21106
21528
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -21201,7 +21623,7 @@ function parseInlineCode(text, start) {
21201
21623
  return { closed: false, content: text.slice(start + 1), end: text.length };
21202
21624
  }
21203
21625
  function mediaMarkdownImage(absolutePath) {
21204
- const name = path7.basename(absolutePath).replaceAll("]", "\\]");
21626
+ const name = path9.basename(absolutePath).replaceAll("]", "\\]");
21205
21627
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21206
21628
  }
21207
21629
  function parseMarkdownImage(text, start) {
@@ -21326,11 +21748,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21326
21748
  if (!hasMediaExtension(stripped))
21327
21749
  return null;
21328
21750
  if (isAbsoluteMediaPath(stripped)) {
21329
- const absolute = path7.resolve(stripped);
21751
+ const absolute = path9.resolve(stripped);
21330
21752
  return exists(absolute) ? absolute : null;
21331
21753
  }
21332
21754
  for (const root of roots) {
21333
- const absolute = path7.resolve(root, stripped);
21755
+ const absolute = path9.resolve(root, stripped);
21334
21756
  if (exists(absolute))
21335
21757
  return absolute;
21336
21758
  }
@@ -21352,11 +21774,11 @@ function stripFileUrl(value) {
21352
21774
  }
21353
21775
  }
21354
21776
  function isAbsoluteMediaPath(value) {
21355
- return path7.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21777
+ return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21356
21778
  }
21357
21779
  function hasMediaExtension(value) {
21358
21780
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21359
- return MEDIA_EXTENSIONS.has(path7.extname(pathname).toLowerCase());
21781
+ return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
21360
21782
  }
21361
21783
  function mediaFileExists(absolutePath) {
21362
21784
  try {
@@ -21369,14 +21791,14 @@ function mediaFileExists(absolutePath) {
21369
21791
  // dist/grok-tool-output.js
21370
21792
  var DEFAULT_GROK_TOOL_OUTPUT_LIMIT = 64e3;
21371
21793
  var EXECUTE_TOOL_NAMES = /* @__PURE__ */ new Set(["bash", "run_terminal_command", "shell", "cursor_shell"]);
21372
- function isRecord5(value) {
21794
+ function isRecord6(value) {
21373
21795
  return typeof value === "object" && value !== null && !Array.isArray(value);
21374
21796
  }
21375
21797
  function stringField(value, key) {
21376
- return isRecord5(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21798
+ return isRecord6(value) && typeof value[key] === "string" && value[key].length > 0 ? value[key] : void 0;
21377
21799
  }
21378
21800
  function numberField(value, key) {
21379
- if (!isRecord5(value))
21801
+ if (!isRecord6(value))
21380
21802
  return void 0;
21381
21803
  const field = value[key];
21382
21804
  if (field === null)
@@ -21399,7 +21821,7 @@ function firstReadableText(...candidates) {
21399
21821
  for (const candidate of candidates) {
21400
21822
  if (typeof candidate === "string" && candidate.length > 0)
21401
21823
  return candidate;
21402
- if (isRecord5(candidate)) {
21824
+ if (isRecord6(candidate)) {
21403
21825
  const nested = stringField(candidate, "content") ?? stringField(candidate, "text") ?? stringField(candidate, "tool_result") ?? stringField(candidate, "raw_output");
21404
21826
  if (nested)
21405
21827
  return nested;
@@ -21422,7 +21844,7 @@ function grokToolArguments(rawInput) {
21422
21844
  if (!parsed.success)
21423
21845
  return {};
21424
21846
  const argumentsValue = parsed.data;
21425
- if (!isRecord5(argumentsValue) || stringField(argumentsValue, "path"))
21847
+ if (!isRecord6(argumentsValue) || stringField(argumentsValue, "path"))
21426
21848
  return argumentsValue;
21427
21849
  const targetFile = stringField(argumentsValue, "target_file");
21428
21850
  return targetFile ? { ...argumentsValue, path: targetFile } : argumentsValue;
@@ -21435,7 +21857,7 @@ function grokCommand(name, kind, rawInput) {
21435
21857
  return command;
21436
21858
  if (name && EXECUTE_TOOL_NAMES.has(name))
21437
21859
  return command;
21438
- return isRecord5(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21860
+ return isRecord6(rawInput) && rawInput.variant === "Bash" ? command : void 0;
21439
21861
  }
21440
21862
  function grokCommandCwd(rawInput, fallback) {
21441
21863
  return stringField(rawInput, "cwd") ?? fallback;
@@ -21462,11 +21884,11 @@ function acpContentText(content) {
21462
21884
  if (!Array.isArray(content))
21463
21885
  return "";
21464
21886
  return content.flatMap((entry) => {
21465
- if (!isRecord5(entry))
21887
+ if (!isRecord6(entry))
21466
21888
  return [];
21467
21889
  if (entry.type === "text" && typeof entry.text === "string")
21468
21890
  return [entry.text];
21469
- if (entry.type !== "content" || !isRecord5(entry.content))
21891
+ if (entry.type !== "content" || !isRecord6(entry.content))
21470
21892
  return [];
21471
21893
  return entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : [];
21472
21894
  }).join("\n");
@@ -21477,10 +21899,10 @@ function acpContentImages(content, remainingBytes) {
21477
21899
  const images = [];
21478
21900
  let remaining = remainingBytes;
21479
21901
  for (const entry of content) {
21480
- if (!isRecord5(entry))
21902
+ if (!isRecord6(entry))
21481
21903
  continue;
21482
21904
  const image = entry.type === "image" ? entry : entry.type === "content" ? entry.content : null;
21483
- if (!isRecord5(image) || image.type !== "image")
21905
+ if (!isRecord6(image) || image.type !== "image")
21484
21906
  continue;
21485
21907
  const mimeType = stringField(image, "mimeType") ?? stringField(image, "mime_type");
21486
21908
  const data = stringField(image, "data");
@@ -21503,14 +21925,14 @@ function bashOutput(rawOutput) {
21503
21925
  function rawOutputProjection(rawOutput) {
21504
21926
  if (typeof rawOutput === "string")
21505
21927
  return rawOutput.length > 0 ? { text: rawOutput } : {};
21506
- if (!isRecord5(rawOutput))
21928
+ if (!isRecord6(rawOutput))
21507
21929
  return {};
21508
21930
  if (rawOutput.type === "Bash" || rawOutput.variant === "Bash" || numberField(rawOutput, "exit_code") !== void 0 || numberField(rawOutput, "exitCode") !== void 0) {
21509
21931
  const bash = bashOutput(rawOutput);
21510
21932
  if (bash.text !== void 0 || bash.exitCode !== void 0)
21511
21933
  return bash;
21512
21934
  }
21513
- 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);
21935
+ 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);
21514
21936
  if (text)
21515
21937
  return { text };
21516
21938
  if (typeof rawOutput.match_count === "number" && Number.isFinite(rawOutput.match_count)) {
@@ -21574,11 +21996,11 @@ var WAIT_TOOL_NAMES = /* @__PURE__ */ new Set([
21574
21996
  var KILL_TOOL_NAMES = /* @__PURE__ */ new Set(["kill_command_or_subagent", "kill_task"]);
21575
21997
  var DESCRIPTION_LIMIT = 500;
21576
21998
  var SUMMARY_LIMIT = 2e3;
21577
- function isRecord6(value) {
21999
+ function isRecord7(value) {
21578
22000
  return typeof value === "object" && value !== null && !Array.isArray(value);
21579
22001
  }
21580
22002
  function idField(value, key) {
21581
- if (!isRecord6(value))
22003
+ if (!isRecord7(value))
21582
22004
  return void 0;
21583
22005
  const field = value[key];
21584
22006
  if (typeof field === "string") {
@@ -21590,7 +22012,7 @@ function idField(value, key) {
21590
22012
  return void 0;
21591
22013
  }
21592
22014
  function stringField2(value, key) {
21593
- if (!isRecord6(value) || typeof value[key] !== "string")
22015
+ if (!isRecord7(value) || typeof value[key] !== "string")
21594
22016
  return void 0;
21595
22017
  const trimmed = value[key].trim();
21596
22018
  return trimmed.length > 0 ? trimmed : void 0;
@@ -21613,7 +22035,7 @@ function collectIds(value) {
21613
22035
  };
21614
22036
  push(idField(value, "task_id"));
21615
22037
  push(idField(value, "subagent_id"));
21616
- if (isRecord6(value)) {
22038
+ if (isRecord7(value)) {
21617
22039
  const list = value.task_ids ?? value.subagent_ids;
21618
22040
  if (Array.isArray(list)) {
21619
22041
  for (const entry of list)
@@ -21632,7 +22054,7 @@ function grokSubagentOperation(name, title, rawInput) {
21632
22054
  return "send";
21633
22055
  if (SPAWN_TOOL_NAMES.has(id))
21634
22056
  return "spawn";
21635
- if (isRecord6(rawInput) && rawInput.variant === "Task")
22057
+ if (isRecord7(rawInput) && rawInput.variant === "Task")
21636
22058
  return "spawn";
21637
22059
  return null;
21638
22060
  }
@@ -21655,7 +22077,7 @@ function grokSubagentRole(rawInput) {
21655
22077
  return bounded(stringField2(rawInput, "subagent_type") ?? stringField2(rawInput, "agent_type") ?? stringField2(rawInput, "type"), DESCRIPTION_LIMIT);
21656
22078
  }
21657
22079
  function grokSubagentBackground(rawInput) {
21658
- if (!isRecord6(rawInput))
22080
+ if (!isRecord7(rawInput))
21659
22081
  return true;
21660
22082
  if (rawInput.background === false || rawInput.run_in_background === false)
21661
22083
  return false;
@@ -21693,7 +22115,7 @@ function grokSubagentResultSummary(...candidates) {
21693
22115
  return void 0;
21694
22116
  }
21695
22117
  function grokSubagentEventFromUpdate(update) {
21696
- if (!isRecord6(update) || typeof update.sessionUpdate !== "string")
22118
+ if (!isRecord7(update) || typeof update.sessionUpdate !== "string")
21697
22119
  return null;
21698
22120
  const nativeSubagentId = idField(update, "subagent_id") ?? idField(update, "child_session_id");
21699
22121
  if (!nativeSubagentId)
@@ -21701,13 +22123,13 @@ function grokSubagentEventFromUpdate(update) {
21701
22123
  if (update.sessionUpdate === "subagent_spawned") {
21702
22124
  const description = bounded(stringField2(update, "description"), DESCRIPTION_LIMIT);
21703
22125
  const role = bounded(stringField2(update, "subagent_type") ?? stringField2(update, "role"), DESCRIPTION_LIMIT);
21704
- const model = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
22126
+ const model2 = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
21705
22127
  return {
21706
22128
  type: "subagent.spawned",
21707
22129
  nativeSubagentId,
21708
22130
  ...description ? { description } : {},
21709
22131
  ...role ? { role } : {},
21710
- ...model ? { model } : {}
22132
+ ...model2 ? { model: model2 } : {}
21711
22133
  };
21712
22134
  }
21713
22135
  if (update.sessionUpdate === "subagent_finished") {
@@ -21754,14 +22176,14 @@ function grokSubagentWaitSettlements(input) {
21754
22176
  return ids.map((id) => ({ id, status: overall }));
21755
22177
  }
21756
22178
  function taskOutputResults(rawOutput) {
21757
- if (!isRecord6(rawOutput))
22179
+ if (!isRecord7(rawOutput))
21758
22180
  return [];
21759
22181
  if (Array.isArray(rawOutput.results)) {
21760
- return rawOutput.results.filter(isRecord6);
22182
+ return rawOutput.results.filter(isRecord7);
21761
22183
  }
21762
22184
  const nested = firstRecord(rawOutput.MultiResult, rawOutput.multiResult, rawOutput.multi_result);
21763
22185
  if (nested && Array.isArray(nested.results)) {
21764
- return nested.results.filter(isRecord6);
22186
+ return nested.results.filter(isRecord7);
21765
22187
  }
21766
22188
  const single = firstRecord(rawOutput.Result, rawOutput.result);
21767
22189
  if (single)
@@ -21772,7 +22194,7 @@ function taskOutputResults(rawOutput) {
21772
22194
  }
21773
22195
  function firstRecord(...values) {
21774
22196
  for (const value of values) {
21775
- if (isRecord6(value))
22197
+ if (isRecord7(value))
21776
22198
  return value;
21777
22199
  }
21778
22200
  return void 0;
@@ -21795,7 +22217,7 @@ function taskOutputTextSettlements(rawOutput, content, ids) {
21795
22217
  return settled;
21796
22218
  }
21797
22219
  function taskOutputStatus(rawOutput, content) {
21798
- if (isRecord6(rawOutput) && typeof rawOutput.status === "string")
22220
+ if (isRecord7(rawOutput) && typeof rawOutput.status === "string")
21799
22221
  return rawOutput.status;
21800
22222
  const text = extractText(content) ?? extractText(rawOutput);
21801
22223
  if (!text)
@@ -21854,7 +22276,7 @@ function extractText(value, depth = 0) {
21854
22276
  const joined = parts.join("\n").trim();
21855
22277
  return joined.length > 0 ? joined : void 0;
21856
22278
  }
21857
- if (!isRecord6(value))
22279
+ if (!isRecord7(value))
21858
22280
  return void 0;
21859
22281
  if (typeof value.text === "string" && value.text.trim().length > 0)
21860
22282
  return value.text.trim();
@@ -22213,7 +22635,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22213
22635
  rememberSubagentAlias(event.callId, nativeSubagentId);
22214
22636
  const prompt = grokSubagentPrompt(event.rawInput);
22215
22637
  const role = grokSubagentRole(event.rawInput);
22216
- const model = grokSubagentModel(event.rawInput);
22638
+ const model2 = grokSubagentModel(event.rawInput);
22217
22639
  subagents.set(event.callId, {
22218
22640
  type: "subagentDelegation",
22219
22641
  itemId: stableId("subagent", turnIndex, ++messageIndex),
@@ -22225,7 +22647,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22225
22647
  ...nativeSubagentId ? { nativeSubagentId } : {},
22226
22648
  description: grokSubagentDescription(event.rawInput, event.title),
22227
22649
  ...role ? { role } : {},
22228
- ...model ? { model } : {},
22650
+ ...model2 ? { model: model2 } : {},
22229
22651
  background: grokSubagentBackground(event.rawInput),
22230
22652
  status: "running"
22231
22653
  }
@@ -22324,11 +22746,11 @@ var GROK_SESSION_DELETE_METHOD = "_x.ai/session/delete";
22324
22746
  function error51(code, message, retryable = false) {
22325
22747
  return { code, message, retryable };
22326
22748
  }
22327
- function isRecord7(value) {
22749
+ function isRecord8(value) {
22328
22750
  return typeof value === "object" && value !== null && !Array.isArray(value);
22329
22751
  }
22330
22752
  function isGrokMethodNotFound(error53) {
22331
- if (isRecord7(error53) && error53.code === -32601)
22753
+ if (isRecord8(error53) && error53.code === -32601)
22332
22754
  return true;
22333
22755
  const message = error53 instanceof Error ? error53.message : String(error53);
22334
22756
  return /method not found/iu.test(message);
@@ -22346,10 +22768,10 @@ function buildGrokForkParams(input) {
22346
22768
  };
22347
22769
  }
22348
22770
  function parseGrokForkResponse(value) {
22349
- if (!isRecord7(value) || value.error !== void 0)
22771
+ if (!isRecord8(value) || value.error !== void 0)
22350
22772
  return null;
22351
- const payload = typeof value.newSessionId !== "string" && isRecord7(value.result) ? value.result : value;
22352
- if (!isRecord7(payload) || payload.error !== void 0)
22773
+ const payload = typeof value.newSessionId !== "string" && isRecord8(value.result) ? value.result : value;
22774
+ if (!isRecord8(payload) || payload.error !== void 0)
22353
22775
  return null;
22354
22776
  if (typeof payload.newSessionId !== "string" || payload.newSessionId.length === 0)
22355
22777
  return null;
@@ -22365,11 +22787,11 @@ function parseGrokForkResponse(value) {
22365
22787
  }
22366
22788
  function projectRelativePath(value, cwds) {
22367
22789
  const normalized = value.replaceAll("\\", "/");
22368
- if (!path8.isAbsolute(value))
22790
+ if (!path10.isAbsolute(value))
22369
22791
  return normalized;
22370
22792
  for (const cwd of cwds) {
22371
- const relative = path8.relative(path8.resolve(cwd), path8.resolve(value));
22372
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`)) {
22793
+ const relative = path10.relative(path10.resolve(cwd), path10.resolve(value));
22794
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`)) {
22373
22795
  return relative.replaceAll("\\", "/");
22374
22796
  }
22375
22797
  }
@@ -22434,8 +22856,8 @@ async function forkGrokSession(input) {
22434
22856
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
22435
22857
  };
22436
22858
  }
22437
- const sourceCwd = path8.resolve(located.cwd);
22438
- const targetCwd = path8.resolve(input.cwd);
22859
+ const sourceCwd = path10.resolve(located.cwd);
22860
+ const targetCwd = path10.resolve(input.cwd);
22439
22861
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
22440
22862
  if (!source.ok)
22441
22863
  return source;
@@ -22510,9 +22932,10 @@ async function forkGrokSession(input) {
22510
22932
  // dist/grok-compaction.js
22511
22933
  var GROK_SESSION_UPDATE_EXTENSION_METHODS = [
22512
22934
  "_x.ai/session/update",
22513
- "x.ai/session_notification"
22935
+ "x.ai/session_notification",
22936
+ "_x.ai/session_notification"
22514
22937
  ];
22515
- function isRecord8(value) {
22938
+ function isRecord9(value) {
22516
22939
  return typeof value === "object" && value !== null && !Array.isArray(value);
22517
22940
  }
22518
22941
  function optionalNonNegativeInt(value) {
@@ -22533,7 +22956,7 @@ function isGrokExtensionSessionUpdateMethod(method) {
22533
22956
  return GROK_SESSION_UPDATE_EXTENSION_METHODS.includes(method);
22534
22957
  }
22535
22958
  function grokCompactionEventFromUpdate(update) {
22536
- if (!isRecord8(update) || typeof update.sessionUpdate !== "string")
22959
+ if (!isRecord9(update) || typeof update.sessionUpdate !== "string")
22537
22960
  return null;
22538
22961
  const tokensUsed = optionalNonNegativeInt(firstPresent(update, ["tokensUsed", "tokens_used"]));
22539
22962
  const contextWindowTokens = optionalNonNegativeInt(firstPresent(update, ["contextWindowTokens", "contextWindow", "context_window"]));
@@ -22572,7 +22995,7 @@ function grokCompactionEventFromUpdate(update) {
22572
22995
  // dist/grok-manual-compaction.js
22573
22996
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
22574
22997
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
22575
- function isRecord9(value) {
22998
+ function isRecord10(value) {
22576
22999
  return typeof value === "object" && value !== null && !Array.isArray(value);
22577
23000
  }
22578
23001
  function optionalNonNegativeInt2(value) {
@@ -22584,7 +23007,7 @@ function optionalErrorMessage2(value) {
22584
23007
  function parseGrokCompactResult(value, cancelled = false) {
22585
23008
  if (cancelled)
22586
23009
  return { outcome: "cancelled" };
22587
- if (!isRecord9(value))
23010
+ if (!isRecord10(value))
22588
23011
  return { outcome: "succeeded" };
22589
23012
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
22590
23013
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -22617,12 +23040,12 @@ function parseGrokCompactResult(value, cancelled = false) {
22617
23040
  }
22618
23041
 
22619
23042
  // dist/grok-rewind.js
22620
- import path9 from "node:path";
23043
+ import path11 from "node:path";
22621
23044
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
22622
23045
  function error52(code, message, retryable = false) {
22623
23046
  return { code, message, retryable };
22624
23047
  }
22625
- function isRecord10(value) {
23048
+ function isRecord11(value) {
22626
23049
  return typeof value === "object" && value !== null && !Array.isArray(value);
22627
23050
  }
22628
23051
  function buildGrokRewindParams(input) {
@@ -22634,10 +23057,10 @@ function buildGrokRewindParams(input) {
22634
23057
  };
22635
23058
  }
22636
23059
  function parseGrokRewindResponse(value) {
22637
- if (!isRecord10(value))
23060
+ if (!isRecord11(value))
22638
23061
  return null;
22639
- const payload = typeof value.success !== "boolean" && isRecord10(value.result) ? value.result : value;
22640
- if (!isRecord10(payload) || typeof payload.success !== "boolean")
23062
+ const payload = typeof value.success !== "boolean" && isRecord11(value.result) ? value.result : value;
23063
+ if (!isRecord11(payload) || typeof payload.success !== "boolean")
22641
23064
  return null;
22642
23065
  return rewindPayload(payload);
22643
23066
  }
@@ -22690,8 +23113,8 @@ async function rewindGrokLastTurn(input) {
22690
23113
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
22691
23114
  };
22692
23115
  }
22693
- const sourceCwd = path9.resolve(located.cwd);
22694
- const targetCwd = path9.resolve(input.cwd);
23116
+ const sourceCwd = path11.resolve(located.cwd);
23117
+ const targetCwd = path11.resolve(input.cwd);
22695
23118
  if (sourceCwd !== targetCwd) {
22696
23119
  return {
22697
23120
  ok: false,
@@ -22794,16 +23217,16 @@ var GrokTransportError = class extends Error {
22794
23217
  this.name = "GrokTransportError";
22795
23218
  }
22796
23219
  };
22797
- function isRecord11(value) {
23220
+ function isRecord12(value) {
22798
23221
  return typeof value === "object" && value !== null && !Array.isArray(value);
22799
23222
  }
22800
23223
  function acpToolName(update, metadata) {
22801
- if (!isRecord11(update))
23224
+ if (!isRecord12(update))
22802
23225
  return void 0;
22803
23226
  if (typeof update.name === "string" && update.name.length > 0)
22804
23227
  return update.name;
22805
- const meta3 = isRecord11(update._meta) ? update._meta : metadata;
22806
- const tool = meta3 && isRecord11(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23228
+ const meta3 = isRecord12(update._meta) ? update._meta : metadata;
23229
+ const tool = meta3 && isRecord12(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
22807
23230
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
22808
23231
  }
22809
23232
  function errorText(error53) {
@@ -22859,12 +23282,27 @@ function signalProcessTree(child, signal) {
22859
23282
  try {
22860
23283
  process.kill(-child.pid, signal);
22861
23284
  } catch (error53) {
22862
- if (!isRecord11(error53) || error53.code !== "ESRCH")
23285
+ if (!isRecord12(error53) || error53.code !== "ESRCH")
22863
23286
  throw error53;
22864
23287
  }
22865
23288
  }
22866
23289
  function transportEvent(update, metadata) {
22867
23290
  const extension = update;
23291
+ if (extension.sessionUpdate === "response_completed") {
23292
+ return {
23293
+ type: "response.completed",
23294
+ ...extension.usage !== void 0 ? { usage: extension.usage } : {},
23295
+ ...typeof extension.message_id === "string" && extension.message_id ? { messageId: extension.message_id } : {},
23296
+ ...metadata ? { metadata } : {}
23297
+ };
23298
+ }
23299
+ if (extension.sessionUpdate === "tool_call_delta_chunk" && typeof extension.arguments_delta === "string") {
23300
+ return {
23301
+ type: "tool.input.delta",
23302
+ text: extension.arguments_delta,
23303
+ ...metadata ? { metadata } : {}
23304
+ };
23305
+ }
22868
23306
  if (extension.sessionUpdate === "turn_completed" && typeof extension.prompt_id === "string" && extension.prompt_id.length > 0 && typeof extension.stop_reason === "string") {
22869
23307
  return {
22870
23308
  type: "turn.completed",
@@ -22934,34 +23372,34 @@ function transportEvent(update, metadata) {
22934
23372
  }
22935
23373
  function grokHomeDir(options) {
22936
23374
  const environment = { ...process.env, ...options.environment };
22937
- const home = environment.HOME ?? environment.USERPROFILE ?? os4.homedir();
22938
- return environment.GROK_HOME ?? path10.join(home, ".grok");
23375
+ const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23376
+ return environment.GROK_HOME ?? path12.join(home, ".grok");
22939
23377
  }
22940
23378
  function grokNativeSessionDirectory(options, sessionId) {
22941
- return path10.join(grokHomeDir(options), "sessions", encodeURIComponent(path10.resolve(options.cwd)), sessionId);
23379
+ return path12.join(grokHomeDir(options), "sessions", encodeURIComponent(path12.resolve(options.cwd)), sessionId);
22942
23380
  }
22943
23381
  function nativeSessionFile(options, sessionId, fileName) {
22944
- return path10.join(grokNativeSessionDirectory(options, sessionId), fileName);
23382
+ return path12.join(grokNativeSessionDirectory(options, sessionId), fileName);
22945
23383
  }
22946
23384
  function nativeHistoryPath(options, sessionId) {
22947
23385
  return nativeSessionFile(options, sessionId, "updates.jsonl");
22948
23386
  }
22949
23387
  async function readNativeSignals(options, sessionId) {
22950
23388
  try {
22951
- return JSON.parse(await readFile2(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23389
+ return JSON.parse(await readFile3(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
22952
23390
  } catch {
22953
23391
  return void 0;
22954
23392
  }
22955
23393
  }
22956
23394
  function isMissingFile(error53) {
22957
- return isRecord11(error53) && error53.code === "ENOENT";
23395
+ return isRecord12(error53) && error53.code === "ENOENT";
22958
23396
  }
22959
23397
  async function locateGrokNativeSession(options, sessionId) {
22960
23398
  if (sessionId.length === 0)
22961
23399
  return null;
22962
23400
  let entries;
22963
23401
  try {
22964
- entries = await readdir(path10.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23402
+ entries = await readdir(path12.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
22965
23403
  } catch (error53) {
22966
23404
  if (isMissingFile(error53))
22967
23405
  return null;
@@ -22975,9 +23413,9 @@ async function locateGrokNativeSession(options, sessionId) {
22975
23413
  continue;
22976
23414
  let summaryRaw;
22977
23415
  try {
22978
- summaryRaw = await readFile2(path10.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23416
+ summaryRaw = await readFile3(path12.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
22979
23417
  } catch (error53) {
22980
- if (isMissingFile(error53) || isRecord11(error53) && error53.code === "ENOTDIR")
23418
+ if (isMissingFile(error53) || isRecord12(error53) && error53.code === "ENOTDIR")
22981
23419
  continue;
22982
23420
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
22983
23421
  cause: error53
@@ -22989,11 +23427,11 @@ async function locateGrokNativeSession(options, sessionId) {
22989
23427
  } catch {
22990
23428
  continue;
22991
23429
  }
22992
- if (!isRecord11(parsed))
23430
+ if (!isRecord12(parsed))
22993
23431
  continue;
22994
23432
  const info = parsed.info;
22995
- const cwd = isRecord11(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path10.resolve(info.cwd) : path10.resolve(decodeURIComponent(entry.name));
22996
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path10.resolve(parsed.source_workspace_dir) : void 0;
23433
+ const cwd = isRecord12(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path12.resolve(info.cwd) : path12.resolve(decodeURIComponent(entry.name));
23434
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path12.resolve(parsed.source_workspace_dir) : void 0;
22997
23435
  matches.push({
22998
23436
  cwd,
22999
23437
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23003,7 +23441,7 @@ async function locateGrokNativeSession(options, sessionId) {
23003
23441
  }
23004
23442
  async function readGrokNativeHistory(options, sessionId) {
23005
23443
  try {
23006
- return parseNativeHistory(await readFile2(nativeHistoryPath({ ...options, cwd: path10.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23444
+ return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path12.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23007
23445
  } catch (error53) {
23008
23446
  if (isMissingFile(error53))
23009
23447
  return [];
@@ -23025,12 +23463,12 @@ function parseNativeHistory(contents, sessionId) {
23025
23463
  } catch {
23026
23464
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23027
23465
  }
23028
- if (!isRecord11(record2) || !isRecord11(record2.params))
23466
+ if (!isRecord12(record2) || !isRecord12(record2.params))
23029
23467
  continue;
23030
23468
  const params = record2.params;
23031
- if (params.sessionId !== sessionId || !isRecord11(params.update))
23469
+ if (params.sessionId !== sessionId || !isRecord12(params.update))
23032
23470
  continue;
23033
- const metadata = isRecord11(params._meta) ? params._meta : void 0;
23471
+ const metadata = isRecord12(params._meta) ? params._meta : void 0;
23034
23472
  const event = transportEvent(params.update, metadata);
23035
23473
  if (event)
23036
23474
  events.push(metadata ? { ...event, metadata } : event);
@@ -23087,6 +23525,13 @@ var GrokAcpTransport = class {
23087
23525
  async getHistory() {
23088
23526
  return this.readHistory(this.sessionId);
23089
23527
  }
23528
+ /** Native cumulative usage since this process attached, not persisted Session totals. */
23529
+ async getUsage() {
23530
+ if (!this.#connection)
23531
+ throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
23532
+ const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
23533
+ return isRecord12(result) ? result.usage : void 0;
23534
+ }
23090
23535
  async readHistory(sessionId, cwd = this.#options.cwd) {
23091
23536
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
23092
23537
  }
@@ -23289,6 +23734,7 @@ var GrokAcpTransport = class {
23289
23734
  prompt: [{ type: "text", text }]
23290
23735
  });
23291
23736
  } finally {
23737
+ await yieldToEventLoop();
23292
23738
  if (this.#activePrompt === active)
23293
23739
  this.#activePrompt = null;
23294
23740
  }
@@ -23327,16 +23773,17 @@ var GrokAcpTransport = class {
23327
23773
  this.#activeCompact = null;
23328
23774
  }
23329
23775
  }
23330
- async setModel(modelId, reasoningEffort) {
23776
+ async setModel(modelId, reasoningEffort, contextWindowTokens) {
23331
23777
  const connection = this.#connection;
23332
23778
  if (!connection || !this.#sessionId)
23333
23779
  throw new Error("Grok ACP Session is unavailable");
23334
23780
  const response = await connection.request("session/set_model", {
23335
23781
  sessionId: this.#sessionId,
23336
23782
  modelId,
23337
- ...reasoningEffort ? { reasoningEffort } : {}
23783
+ ...reasoningEffort ? { reasoningEffort } : {},
23784
+ ...contextWindowTokens !== void 0 ? { _meta: { contextWindow: contextWindowTokens } } : {}
23338
23785
  });
23339
- if (!isRecord11(response) || !isRecord11(response._meta) || !isRecord11(response._meta.model)) {
23786
+ if (!isRecord12(response) || !isRecord12(response._meta) || !isRecord12(response._meta.model)) {
23340
23787
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
23341
23788
  }
23342
23789
  const selected = response._meta.model.Ok;
@@ -23388,7 +23835,7 @@ var GrokAcpTransport = class {
23388
23835
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
23389
23836
  return;
23390
23837
  }
23391
- const metadata = isRecord11(notification._meta) ? notification._meta : void 0;
23838
+ const metadata = isRecord12(notification._meta) ? notification._meta : void 0;
23392
23839
  const event = transportEvent(notification.update, metadata);
23393
23840
  if (!event)
23394
23841
  return;
@@ -23403,7 +23850,7 @@ var GrokAcpTransport = class {
23403
23850
  #handleExtensionNotification(method, params) {
23404
23851
  if (!isGrokExtensionSessionUpdateMethod(method))
23405
23852
  return;
23406
- if (typeof params.sessionId !== "string" || !isRecord11(params.update))
23853
+ if (typeof params.sessionId !== "string" || !isRecord12(params.update))
23407
23854
  return;
23408
23855
  this.#handleUpdate(params);
23409
23856
  }
@@ -23421,13 +23868,13 @@ var GrokAcpTransport = class {
23421
23868
  };
23422
23869
 
23423
23870
  // dist/session-import.js
23424
- import { createReadStream } from "node:fs";
23425
- import { opendir, readFile as readFile3, stat } from "node:fs/promises";
23426
- import path11 from "node:path";
23427
- import { createInterface } from "node:readline";
23871
+ import { createReadStream as createReadStream2 } from "node:fs";
23872
+ import { opendir as opendir2, readFile as readFile4, stat } from "node:fs/promises";
23873
+ import path13 from "node:path";
23874
+ import { createInterface as createInterface2 } from "node:readline";
23428
23875
 
23429
23876
  // ../../harness-adapter/dist/session-import.js
23430
- import { lstat } from "node:fs/promises";
23877
+ import { lstat as lstat2 } from "node:fs/promises";
23431
23878
  var SessionImportChangedError = class extends Error {
23432
23879
  constructor(message = "Native Session changed during discovery; refresh and retry") {
23433
23880
  super(message);
@@ -23446,7 +23893,7 @@ function isStorageAccessError(error53) {
23446
23893
  }
23447
23894
  async function optionalLstat(file2) {
23448
23895
  try {
23449
- return await lstat(file2);
23896
+ return await lstat2(file2);
23450
23897
  } catch (error53) {
23451
23898
  if (isMissingFileError(error53))
23452
23899
  return null;
@@ -23544,11 +23991,11 @@ var SessionImportScope = class {
23544
23991
  // dist/session-import.js
23545
23992
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
23546
23993
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
23547
- function isRecord12(value) {
23994
+ function isRecord13(value) {
23548
23995
  return typeof value === "object" && value !== null && !Array.isArray(value);
23549
23996
  }
23550
23997
  async function readJson(file2, signal) {
23551
- return JSON.parse(await readFile3(file2, { encoding: "utf8", signal }));
23998
+ return JSON.parse(await readFile4(file2, { encoding: "utf8", signal }));
23552
23999
  }
23553
24000
  function processAlive(pid) {
23554
24001
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -23557,12 +24004,12 @@ function processAlive(pid) {
23557
24004
  process.kill(pid, 0);
23558
24005
  return true;
23559
24006
  } catch (error53) {
23560
- return isRecord12(error53) && error53.code === "EPERM";
24007
+ return isRecord13(error53) && error53.code === "EPERM";
23561
24008
  }
23562
24009
  }
23563
24010
  async function firstUserText(file2, signal) {
23564
- const stream = createReadStream(file2, { encoding: "utf8", signal });
23565
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
24011
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
24012
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
23566
24013
  try {
23567
24014
  for await (const line of lines) {
23568
24015
  signal.throwIfAborted();
@@ -23574,10 +24021,10 @@ async function firstUserText(file2, signal) {
23574
24021
  } catch {
23575
24022
  continue;
23576
24023
  }
23577
- const update = isRecord12(entry) && isRecord12(entry.params) ? entry.params.update : null;
23578
- if (!isRecord12(update) || update.sessionUpdate !== "user_message_chunk")
24024
+ const update = isRecord13(entry) && isRecord13(entry.params) ? entry.params.update : null;
24025
+ if (!isRecord13(update) || update.sessionUpdate !== "user_message_chunk")
23579
24026
  continue;
23580
- const text = isRecord12(update.content) ? update.content.text : null;
24027
+ const text = isRecord13(update.content) ? update.content.text : null;
23581
24028
  return typeof text === "string" ? text : "";
23582
24029
  }
23583
24030
  return null;
@@ -23644,7 +24091,7 @@ var GrokSessionImport = class {
23644
24091
  const active = /* @__PURE__ */ new Set();
23645
24092
  let entries;
23646
24093
  try {
23647
- entries = await readJson(path11.join(this.#home(), "active_sessions.json"), signal);
24094
+ entries = await readJson(path13.join(this.#home(), "active_sessions.json"), signal);
23648
24095
  } catch (error53) {
23649
24096
  signal.throwIfAborted();
23650
24097
  if (isStorageAccessError(error53))
@@ -23654,26 +24101,26 @@ var GrokSessionImport = class {
23654
24101
  if (!Array.isArray(entries))
23655
24102
  return active;
23656
24103
  for (const entry of entries) {
23657
- if (isRecord12(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24104
+ if (isRecord13(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
23658
24105
  active.add(entry.session_id);
23659
24106
  }
23660
24107
  return active;
23661
24108
  }
23662
24109
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
23663
24110
  async #sessionDirectories(signal) {
23664
- const root = path11.join(this.#home(), "sessions");
24111
+ const root = path13.join(this.#home(), "sessions");
23665
24112
  const found = /* @__PURE__ */ new Map();
23666
24113
  const info = await optionalLstat(root);
23667
24114
  if (!info)
23668
24115
  return found;
23669
24116
  if (!info.isDirectory())
23670
24117
  throw new Error("Grok Session store is not a directory");
23671
- for await (const workspace of await opendir(root)) {
24118
+ for await (const workspace of await opendir2(root)) {
23672
24119
  signal.throwIfAborted();
23673
24120
  if (!workspace.isDirectory())
23674
24121
  continue;
23675
- const workspaceDirectory = path11.join(root, workspace.name);
23676
- const sessions = await opendir(workspaceDirectory).catch((error53) => {
24122
+ const workspaceDirectory = path13.join(root, workspace.name);
24123
+ const sessions = await opendir2(workspaceDirectory).catch((error53) => {
23677
24124
  if (isMissingFileError(error53))
23678
24125
  return null;
23679
24126
  throw error53;
@@ -23685,7 +24132,7 @@ var GrokSessionImport = class {
23685
24132
  if (!session.isDirectory())
23686
24133
  continue;
23687
24134
  const directories = found.get(session.name) ?? [];
23688
- directories.push(path11.join(workspaceDirectory, session.name));
24135
+ directories.push(path13.join(workspaceDirectory, session.name));
23689
24136
  found.set(session.name, directories);
23690
24137
  }
23691
24138
  }
@@ -23693,25 +24140,25 @@ var GrokSessionImport = class {
23693
24140
  }
23694
24141
  async #candidate(sessionDirectory, active, signal) {
23695
24142
  signal.throwIfAborted();
23696
- const nativeSessionId = path11.basename(sessionDirectory);
24143
+ const nativeSessionId = path13.basename(sessionDirectory);
23697
24144
  const files = [
23698
- path11.join(sessionDirectory, "summary.json"),
23699
- path11.join(sessionDirectory, "updates.jsonl")
24145
+ path13.join(sessionDirectory, "summary.json"),
24146
+ path13.join(sessionDirectory, "updates.jsonl")
23700
24147
  ];
23701
24148
  return readStableFiles(files, async ([summaryInfo, updates]) => {
23702
24149
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
23703
24150
  return null;
23704
24151
  try {
23705
24152
  const summary = await readJson(files[0], signal);
23706
- if (!isRecord12(summary) || !isRecord12(summary.info) || summary.info.id !== nativeSessionId)
24153
+ if (!isRecord13(summary) || !isRecord13(summary.info) || summary.info.id !== nativeSessionId)
23707
24154
  return null;
23708
24155
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
23709
24156
  return null;
23710
24157
  const nativeCwd = summary.info.cwd;
23711
- if (typeof nativeCwd !== "string" || !path11.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24158
+ if (typeof nativeCwd !== "string" || !path13.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
23712
24159
  return null;
23713
- const cwd = path11.resolve(nativeCwd);
23714
- if (encodeURIComponent(cwd) !== path11.basename(path11.dirname(sessionDirectory)))
24160
+ const cwd = path13.resolve(nativeCwd);
24161
+ if (encodeURIComponent(cwd) !== path13.basename(path13.dirname(sessionDirectory)))
23715
24162
  return null;
23716
24163
  if (!(await stat(cwd)).isDirectory())
23717
24164
  return null;
@@ -23930,7 +24377,7 @@ var GrokSubagentLifecycle = class {
23930
24377
  };
23931
24378
 
23932
24379
  // dist/grok-models.js
23933
- function isRecord13(value) {
24380
+ function isRecord14(value) {
23934
24381
  return typeof value === "object" && value !== null && !Array.isArray(value);
23935
24382
  }
23936
24383
  function nonBlank(value) {
@@ -23942,7 +24389,7 @@ function thinkingOptions(value) {
23942
24389
  const seen = /* @__PURE__ */ new Set();
23943
24390
  const options = [];
23944
24391
  for (const candidate of value) {
23945
- if (!isRecord13(candidate) || !nonBlank(candidate.label))
24392
+ if (!isRecord14(candidate) || !nonBlank(candidate.label))
23946
24393
  continue;
23947
24394
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
23948
24395
  if (!id.success || seen.has(id.data))
@@ -23953,7 +24400,7 @@ function thinkingOptions(value) {
23953
24400
  return options;
23954
24401
  }
23955
24402
  function parseGrokModelState(value) {
23956
- if (!isRecord13(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24403
+ if (!isRecord14(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
23957
24404
  return null;
23958
24405
  }
23959
24406
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -23961,16 +24408,20 @@ function parseGrokModelState(value) {
23961
24408
  return null;
23962
24409
  const allThinking = /* @__PURE__ */ new Map();
23963
24410
  const contextWindowTokensByModel = /* @__PURE__ */ new Map();
24411
+ const defaultContextWindowTokensByModel = /* @__PURE__ */ new Map();
23964
24412
  const models = [];
23965
24413
  let currentThinkingOptionId;
23966
24414
  for (const candidate of value.availableModels) {
23967
- if (!isRecord13(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24415
+ if (!isRecord14(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
23968
24416
  continue;
23969
24417
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
23970
24418
  if (!ref.success)
23971
24419
  continue;
23972
- const metadata = isRecord13(candidate._meta) ? candidate._meta : {};
24420
+ const metadata = isRecord14(candidate._meta) ? candidate._meta : {};
23973
24421
  const options2 = thinkingOptions(metadata.reasoningEfforts);
24422
+ if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
24423
+ defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
24424
+ }
23974
24425
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
23975
24426
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
23976
24427
  }
@@ -23994,6 +24445,7 @@ function parseGrokModelState(value) {
23994
24445
  return {
23995
24446
  currentModel: currentModel.data,
23996
24447
  contextWindowTokensByModel,
24448
+ defaultContextWindowTokensByModel,
23997
24449
  ...currentThinkingOptionId ? { currentThinkingOptionId } : {},
23998
24450
  catalog: {
23999
24451
  models,
@@ -24004,13 +24456,13 @@ function parseGrokModelState(value) {
24004
24456
  };
24005
24457
  }
24006
24458
  function modelStateFromInitialize(response) {
24007
- return parseGrokModelState(isRecord13(response._meta) ? response._meta.modelState : void 0);
24459
+ return parseGrokModelState(isRecord14(response._meta) ? response._meta.modelState : void 0);
24008
24460
  }
24009
24461
  function modelStateFromSessionResponse(response) {
24010
- return parseGrokModelState(isRecord13(response) ? response.models : void 0);
24462
+ return parseGrokModelState(isRecord14(response) ? response.models : void 0);
24011
24463
  }
24012
- function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24013
- const selectedModel = model;
24464
+ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24465
+ const selectedModel = model2;
24014
24466
  const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === selectedModel.id);
24015
24467
  const availableThinkingOptions = catalogModel?.supportedThinkingOptionIds?.flatMap((id) => {
24016
24468
  const option = modelState.catalog.thinkingOptions.find((candidate) => candidate.id === id);
@@ -24026,12 +24478,12 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
24026
24478
  }
24027
24479
 
24028
24480
  // dist/grok-credits.js
24029
- import { readFile as readFile4 } from "node:fs/promises";
24030
- import os5 from "node:os";
24031
- import path12 from "node:path";
24481
+ import { readFile as readFile5 } from "node:fs/promises";
24482
+ import os6 from "node:os";
24483
+ import path14 from "node:path";
24032
24484
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
24033
24485
  var REQUEST_TIMEOUT_MS = 15e3;
24034
- function isRecord14(value) {
24486
+ function isRecord15(value) {
24035
24487
  return typeof value === "object" && value !== null && !Array.isArray(value);
24036
24488
  }
24037
24489
  function finitePercent(value) {
@@ -24040,15 +24492,15 @@ function finitePercent(value) {
24040
24492
  return Math.min(100, Math.max(0, value));
24041
24493
  }
24042
24494
  function nonNegativeCentValue(value) {
24043
- if (!isRecord14(value))
24495
+ if (!isRecord15(value))
24044
24496
  return void 0;
24045
24497
  const amount = value.val === void 0 ? 0 : value.val;
24046
24498
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
24047
24499
  return void 0;
24048
24500
  return amount;
24049
24501
  }
24050
- function grokHome(environment) {
24051
- return environment.GROK_HOME ?? path12.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
24502
+ function grokHome2(environment) {
24503
+ return environment.GROK_HOME ?? path14.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
24052
24504
  }
24053
24505
  function periodTypeFrom(value) {
24054
24506
  if (typeof value !== "string")
@@ -24064,7 +24516,7 @@ function productUsageFrom(value) {
24064
24516
  if (!Array.isArray(value))
24065
24517
  return void 0;
24066
24518
  const products = value.flatMap((entry) => {
24067
- if (!isRecord14(entry) || typeof entry.product !== "string")
24519
+ if (!isRecord15(entry) || typeof entry.product !== "string")
24068
24520
  return [];
24069
24521
  const usagePercent = finitePercent(entry.usagePercent);
24070
24522
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -24072,10 +24524,10 @@ function productUsageFrom(value) {
24072
24524
  return products.length > 0 ? products : void 0;
24073
24525
  }
24074
24526
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24075
- if (!isRecord14(value) || !isRecord14(value.config))
24527
+ if (!isRecord15(value) || !isRecord15(value.config))
24076
24528
  return null;
24077
24529
  const config2 = value.config;
24078
- const period = isRecord14(config2.currentPeriod) ? config2.currentPeriod : void 0;
24530
+ const period = isRecord15(config2.currentPeriod) ? config2.currentPeriod : void 0;
24079
24531
  const periodType = periodTypeFrom(period?.type);
24080
24532
  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);
24081
24533
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24102,11 +24554,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24102
24554
  };
24103
24555
  }
24104
24556
  function selectAccessToken(auth, now) {
24105
- if (!isRecord14(auth))
24557
+ if (!isRecord15(auth))
24106
24558
  return null;
24107
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord14(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")));
24559
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord15(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")));
24108
24560
  for (const [, value] of entries) {
24109
- if (!isRecord14(value) || typeof value.key !== "string")
24561
+ if (!isRecord15(value) || typeof value.key !== "string")
24110
24562
  continue;
24111
24563
  if (typeof value.expires_at === "string") {
24112
24564
  const expiresAt = Date.parse(value.expires_at);
@@ -24127,8 +24579,8 @@ async function fetchGrokAccount(input = {}) {
24127
24579
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24128
24580
  return null;
24129
24581
  const now = input.now ?? /* @__PURE__ */ new Date();
24130
- const authPath = path12.join(grokHome(environment), "auth.json");
24131
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile4(authPath, "utf8");
24582
+ const authPath = path14.join(grokHome2(environment), "auth.json");
24583
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile5(authPath, "utf8");
24132
24584
  const token = selectAccessToken(JSON.parse(raw), now);
24133
24585
  if (!token)
24134
24586
  return null;
@@ -24177,7 +24629,7 @@ async function fetchGrokCredits(input = {}) {
24177
24629
 
24178
24630
  // dist/grok-usage.js
24179
24631
  var USD_TICKS_PER_DOLLAR = 1e10;
24180
- function isRecord15(value) {
24632
+ function isRecord16(value) {
24181
24633
  return typeof value === "object" && value !== null && !Array.isArray(value);
24182
24634
  }
24183
24635
  function optionalToken(value) {
@@ -24194,7 +24646,7 @@ function combineUsage(base, next) {
24194
24646
  return base === null ? next : parseHostUsage({ ...base, ...next });
24195
24647
  }
24196
24648
  function usageFromNative(value) {
24197
- if (!isRecord15(value))
24649
+ if (!isRecord16(value))
24198
24650
  return null;
24199
24651
  const inputTokens = optionalToken(value.inputTokens);
24200
24652
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24217,11 +24669,108 @@ function usageFromNative(value) {
24217
24669
  return null;
24218
24670
  }
24219
24671
  }
24220
- function usageFromPrompt(response) {
24221
- return response.usage ? usageFromNative(response.usage) : null;
24672
+ function usageFromResponse(value) {
24673
+ if (!isRecord16(value))
24674
+ return null;
24675
+ const buckets = [
24676
+ value.input_tokens,
24677
+ value.cache_read_input_tokens,
24678
+ value.cache_creation_input_tokens
24679
+ ];
24680
+ const inputTokens = buckets.every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0) ? buckets.reduce((sum, n) => sum + n, 0) : void 0;
24681
+ const outputTokens = optionalToken(value.output_tokens);
24682
+ return usageFromNative({
24683
+ inputTokens,
24684
+ outputTokens,
24685
+ cachedReadTokens: value.cache_read_input_tokens,
24686
+ cacheCreationTokens: value.cache_creation_input_tokens,
24687
+ reasoningTokens: value.reasoning_tokens,
24688
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
24689
+ });
24222
24690
  }
24691
+ var GrokTurnUsage = class {
24692
+ #totals = {};
24693
+ #seen = /* @__PURE__ */ new Set();
24694
+ #cacheComplete;
24695
+ #compacting = false;
24696
+ #startedAtMs;
24697
+ #streamKey;
24698
+ #outputTokens = 0;
24699
+ #durationMs = 0;
24700
+ #latestCacheHit;
24701
+ constructor(base, emptySession = false) {
24702
+ for (const field of summedUsageFields) {
24703
+ const value = base?.[field];
24704
+ if (value !== void 0)
24705
+ this.#totals[field] = value;
24706
+ }
24707
+ this.#cacheComplete = base?.sessionCacheUsage !== void 0 || emptySession;
24708
+ }
24709
+ observe(event) {
24710
+ if (event.type === "compaction.started" || event.type === "compaction.completed") {
24711
+ this.#startedAtMs = void 0;
24712
+ this.#streamKey = void 0;
24713
+ this.#compacting = event.type === "compaction.started";
24714
+ }
24715
+ if (this.#compacting)
24716
+ return null;
24717
+ if (event.type === "subagent.spawned")
24718
+ this.#cacheComplete = false;
24719
+ if (event.type === "agent.text" || event.type === "agent.thought" || event.type === "tool.input.delta") {
24720
+ if (!event.text)
24721
+ return null;
24722
+ const key = event.metadata?.streamStartMs;
24723
+ if (key !== void 0 && this.#streamKey !== void 0 && key !== this.#streamKey)
24724
+ this.#startedAtMs = void 0;
24725
+ if (key !== void 0)
24726
+ this.#streamKey = key;
24727
+ this.#startedAtMs ??= Date.now();
24728
+ }
24729
+ if (event.type !== "response.completed")
24730
+ return null;
24731
+ if (event.messageId) {
24732
+ if (this.#seen.has(event.messageId))
24733
+ return null;
24734
+ this.#seen.add(event.messageId);
24735
+ }
24736
+ const duration3 = this.#startedAtMs === void 0 ? 0 : Date.now() - this.#startedAtMs;
24737
+ this.#startedAtMs = void 0;
24738
+ this.#streamKey = void 0;
24739
+ const usage = usageFromResponse(event.usage);
24740
+ this.#latestCacheHit = usage?.cacheHitRatePercent;
24741
+ if (usage?.inputTokens === void 0 || usage.cachedInputTokens === void 0)
24742
+ this.#cacheComplete = false;
24743
+ if (usage) {
24744
+ for (const field of summedUsageFields) {
24745
+ const value = usage[field];
24746
+ if (value !== void 0)
24747
+ this.#totals[field] = (this.#totals[field] ?? 0) + value;
24748
+ }
24749
+ if (duration3 > 0 && usage.outputTokens !== void 0) {
24750
+ this.#outputTokens += usage.outputTokens;
24751
+ this.#durationMs += duration3;
24752
+ }
24753
+ }
24754
+ return this.snapshot();
24755
+ }
24756
+ metrics() {
24757
+ return {
24758
+ ...this.#durationMs > 0 ? { outputTokensPerSecond: this.#outputTokens * 1e3 / this.#durationMs } : {},
24759
+ ...this.#latestCacheHit !== void 0 ? { cacheHitRatePercent: this.#latestCacheHit } : {}
24760
+ };
24761
+ }
24762
+ snapshot() {
24763
+ const inputTokens = this.#totals.inputTokens;
24764
+ const cachedInputTokens = this.#totals.cachedInputTokens;
24765
+ return {
24766
+ ...this.#totals,
24767
+ ...this.metrics(),
24768
+ ...this.#cacheComplete && inputTokens !== void 0 && cachedInputTokens !== void 0 ? { sessionCacheUsage: { inputTokens, cachedInputTokens } } : {}
24769
+ };
24770
+ }
24771
+ };
24223
24772
  function usageFromSignals(value) {
24224
- if (!isRecord15(value))
24773
+ if (!isRecord16(value))
24225
24774
  return null;
24226
24775
  try {
24227
24776
  return parseHostUsage({
@@ -24241,13 +24790,23 @@ var summedUsageFields = [
24241
24790
  "totalTokens"
24242
24791
  ];
24243
24792
  function nativeCostTicks(value) {
24244
- if (!isRecord15(value))
24793
+ if (!isRecord16(value))
24245
24794
  return void 0;
24246
24795
  const ticks = value.costUsdTicks;
24247
24796
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
24248
24797
  return void 0;
24249
24798
  return ticks;
24250
24799
  }
24800
+ function sessionCostFromNative(value, initialCostUsd) {
24801
+ if (!isRecord16(value))
24802
+ return void 0;
24803
+ if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
24804
+ return void 0;
24805
+ if (value.usageIsIncomplete !== void 0 && value.usageIsIncomplete !== false)
24806
+ return void 0;
24807
+ const ticks = nativeCostTicks(value);
24808
+ return ticks === void 0 ? void 0 : optionalCostUsd(Math.round(initialCostUsd * USD_TICKS_PER_DOLLAR) + ticks);
24809
+ }
24251
24810
  function historyTurnKey(event, index) {
24252
24811
  const key = event.nativeTurnKey;
24253
24812
  if (typeof key === "string" && key.startsWith("task-completed-"))
@@ -24256,7 +24815,6 @@ function historyTurnKey(event, index) {
24256
24815
  }
24257
24816
  function sessionUsageFromHistory(events) {
24258
24817
  const latestByKey = /* @__PURE__ */ new Map();
24259
- let lastCacheHitRatePercent;
24260
24818
  let index = 0;
24261
24819
  for (const event of events) {
24262
24820
  if (event?.type !== "turn.completed")
@@ -24265,26 +24823,26 @@ function sessionUsageFromHistory(events) {
24265
24823
  index += 1;
24266
24824
  if (key === null)
24267
24825
  continue;
24268
- const usage = usageFromNative(event.usage);
24269
- if (!usage)
24826
+ if (event.usage === void 0 && latestByKey.has(key))
24270
24827
  continue;
24828
+ const usage = usageFromNative(event.usage);
24271
24829
  const ticks2 = nativeCostTicks(event.usage);
24272
- latestByKey.set(key, ticks2 === void 0 ? { usage } : { usage, ticks: ticks2 });
24273
- if (usage.cacheHitRatePercent !== void 0) {
24274
- lastCacheHitRatePercent = usage.cacheHitRatePercent;
24275
- }
24830
+ const complete = isRecord16(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
24831
+ latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
24276
24832
  }
24277
24833
  if (latestByKey.size === 0)
24278
24834
  return null;
24279
- const totals = {};
24835
+ const totals2 = {};
24280
24836
  let ticks = 0;
24281
24837
  let hasTicks = false;
24282
24838
  for (const entry of latestByKey.values()) {
24839
+ if (!entry.usage)
24840
+ continue;
24283
24841
  for (const field of summedUsageFields) {
24284
24842
  const value = entry.usage[field];
24285
24843
  if (value === void 0)
24286
24844
  continue;
24287
- totals[field] = (totals[field] ?? 0) + value;
24845
+ totals2[field] = (totals2[field] ?? 0) + value;
24288
24846
  }
24289
24847
  if (entry.ticks === void 0)
24290
24848
  continue;
@@ -24294,9 +24852,14 @@ function sessionUsageFromHistory(events) {
24294
24852
  const totalCostUsd = hasTicks ? optionalCostUsd(ticks) : void 0;
24295
24853
  try {
24296
24854
  return parseHostUsage({
24297
- ...totals,
24855
+ ...totals2,
24298
24856
  ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
24299
- ...lastCacheHitRatePercent !== void 0 ? { cacheHitRatePercent: lastCacheHitRatePercent } : {}
24857
+ ...[...latestByKey.values()].every((entry) => entry.complete) && totals2.inputTokens !== void 0 && totals2.cachedInputTokens !== void 0 ? {
24858
+ sessionCacheUsage: {
24859
+ inputTokens: totals2.inputTokens,
24860
+ cachedInputTokens: totals2.cachedInputTokens
24861
+ }
24862
+ } : {}
24300
24863
  });
24301
24864
  } catch {
24302
24865
  return null;
@@ -24318,7 +24881,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
24318
24881
  function usageFromUpdate(update, metadata, contextWindowTokens) {
24319
24882
  try {
24320
24883
  if (update?.sessionUpdate === "usage_update") {
24321
- const cost = isRecord15(update.cost) ? update.cost : null;
24884
+ const cost = isRecord16(update.cost) ? update.cost : null;
24322
24885
  return parseHostUsage({
24323
24886
  contextUsedTokens: update.used,
24324
24887
  contextWindowTokens: update.size,
@@ -24449,6 +25012,8 @@ var GrokHarnessSession = class {
24449
25012
  #phase = "open";
24450
25013
  #state;
24451
25014
  #usage = null;
25015
+ #initialCostUsd;
25016
+ #costRequest = 0;
24452
25017
  constructor(cwd, transport, opened, modelState, onClosed, options) {
24453
25018
  this.#cwd = cwd;
24454
25019
  this.#sessionDirectory = options.sessionDirectory;
@@ -24462,6 +25027,7 @@ var GrokHarnessSession = class {
24462
25027
  this.#toolOutputLimit = options.toolOutputLimit;
24463
25028
  this.initialUsage = options.initialUsage ?? null;
24464
25029
  this.#usage = this.initialUsage;
25030
+ this.#initialCostUsd = this.initialUsage?.totalCostUsd ?? 0;
24465
25031
  this.capabilities = capabilitiesForModels(modelState);
24466
25032
  this.commands = {
24467
25033
  list: async () => ({ ok: true, value: this.#liveCommandCatalog() }),
@@ -24550,6 +25116,7 @@ var GrokHarnessSession = class {
24550
25116
  });
24551
25117
  const active = {
24552
25118
  command,
25119
+ usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
24553
25120
  agent: null,
24554
25121
  agentMessageId: null,
24555
25122
  rawAgentText: "",
@@ -24725,9 +25292,9 @@ var GrokHarnessSession = class {
24725
25292
  }
24726
25293
  async #selectThinking(command) {
24727
25294
  const parsed = harnessThinkingOptionIdSchema.safeParse(command.thinkingOptionId);
24728
- const model = this.#state.effectiveModel;
24729
- const available = this.#modelState.catalog.models.find(({ ref }) => ref.id === model?.id);
24730
- if (!parsed.success || !model || !available?.supportedThinkingOptionIds?.includes(parsed.data)) {
25295
+ const model2 = this.#state.effectiveModel;
25296
+ const available = this.#modelState.catalog.models.find(({ ref }) => ref.id === model2?.id);
25297
+ if (!parsed.success || !model2 || !available?.supportedThinkingOptionIds?.includes(parsed.data)) {
24731
25298
  return {
24732
25299
  ok: false,
24733
25300
  error: {
@@ -24737,9 +25304,9 @@ var GrokHarnessSession = class {
24737
25304
  }
24738
25305
  };
24739
25306
  }
24740
- return this.#configure(model, parsed.data);
25307
+ return this.#configure(model2, parsed.data);
24741
25308
  }
24742
- async #configure(model, thinkingOptionId) {
25309
+ async #configure(model2, thinkingOptionId) {
24743
25310
  if (this.#configuring) {
24744
25311
  return {
24745
25312
  ok: false,
@@ -24752,9 +25319,20 @@ var GrokHarnessSession = class {
24752
25319
  }
24753
25320
  this.#configuring = true;
24754
25321
  try {
24755
- await this.#transport.setModel(model.id, thinkingOptionId);
24756
- this.#state = stateForGrokModel(this.#modelState, { nativeRef: nativeRef(this.#transport.sessionId) }, model, thinkingOptionId, this.#state.effectivePermissionModeId);
25322
+ const contextWindow = this.#modelState.defaultContextWindowTokensByModel.get(model2.id);
25323
+ await this.#transport.setModel(model2.id, thinkingOptionId, contextWindow);
25324
+ if (contextWindow !== void 0) {
25325
+ this.#modelState.contextWindowTokensByModel = new Map([
25326
+ ...this.#modelState.contextWindowTokensByModel,
25327
+ [model2.id, contextWindow]
25328
+ ]);
25329
+ }
25330
+ this.#state = stateForGrokModel(this.#modelState, { nativeRef: nativeRef(this.#transport.sessionId) }, model2, thinkingOptionId, this.#state.effectivePermissionModeId);
24757
25331
  this.#event({ type: "session.state.changed", state: this.#state });
25332
+ const selectedWindow = this.#modelState.contextWindowTokensByModel.get(model2.id);
25333
+ if (selectedWindow !== void 0 && this.#usage?.contextUsedTokens !== void 0) {
25334
+ this.#publishUsage({ contextWindowTokens: selectedWindow });
25335
+ }
24758
25336
  return { ok: true, value: { completed: true } };
24759
25337
  } catch (error53) {
24760
25338
  return { ok: false, error: normalizeError(error53, "nativeFailure") };
@@ -24867,6 +25445,11 @@ var GrokHarnessSession = class {
24867
25445
  #handleEvent(active, event) {
24868
25446
  if (this.#active !== active || this.#phase !== "open")
24869
25447
  return;
25448
+ const requestUsage = active.usage?.observe(event);
25449
+ if (requestUsage) {
25450
+ this.#publishUsage(requestUsage, active.command.turnId, true);
25451
+ void this.#refreshCost(active);
25452
+ }
24870
25453
  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);
24871
25454
  if (contextUsage)
24872
25455
  this.#publishUsage(contextUsage, active.command.turnId);
@@ -24890,6 +25473,17 @@ var GrokHarnessSession = class {
24890
25473
  } else if (event.type === "usage" || event.type === "turn.completed")
24891
25474
  return;
24892
25475
  }
25476
+ async #refreshCost(active) {
25477
+ const request = ++this.#costRequest;
25478
+ try {
25479
+ const totalCostUsd = sessionCostFromNative(await this.#transport.getUsage(), this.#initialCostUsd);
25480
+ if (this.#active !== active || this.#phase !== "open" || request !== this.#costRequest)
25481
+ return;
25482
+ if (totalCostUsd !== void 0)
25483
+ this.#publishUsage({ totalCostUsd }, active.command.turnId);
25484
+ } catch {
25485
+ }
25486
+ }
24893
25487
  #startCompaction(active, event) {
24894
25488
  if (active.compactionItem)
24895
25489
  return;
@@ -25002,14 +25596,14 @@ var GrokHarnessSession = class {
25002
25596
  const prompt = grokSubagentPrompt(event.rawInput);
25003
25597
  const role = grokSubagentRole(event.rawInput);
25004
25598
  const nativeSubagentId = grokNativeSubagentId(event.rawInput);
25005
- const model = grokSubagentModel(event.rawInput);
25599
+ const model2 = grokSubagentModel(event.rawInput);
25006
25600
  active.subagents.start(active.command.turnId, {
25007
25601
  callId: event.callId,
25008
25602
  operation,
25009
25603
  description: grokSubagentDescription(event.rawInput, event.title),
25010
25604
  ...prompt ? { prompt } : {},
25011
25605
  ...role ? { role } : {},
25012
- ...model ? { model } : {},
25606
+ ...model2 ? { model: model2 } : {},
25013
25607
  background: grokSubagentBackground(event.rawInput),
25014
25608
  ...nativeSubagentId ? { nativeSubagentId } : {}
25015
25609
  });
@@ -25234,8 +25828,18 @@ var GrokHarnessSession = class {
25234
25828
  outcome = { status: "failed", error: normalizeError(error53, "protocolError") };
25235
25829
  }
25236
25830
  }
25831
+ const promptUsage = response?.usage ?? response?._meta?.usage;
25832
+ if (nativeTurnRef && promptUsage !== void 0 && !history.some((event) => event.type === "turn.completed" && event.nativeTurnKey === nativeTurnRef.nativeTurnKey && event.usage !== void 0)) {
25833
+ history.push({
25834
+ type: "turn.completed",
25835
+ nativeTurnKey: nativeTurnRef.nativeTurnKey,
25836
+ stopReason: response?.stopReason ?? "end_turn",
25837
+ usage: promptUsage
25838
+ });
25839
+ }
25840
+ const usage = sessionUsageFromHistory(history);
25237
25841
  await this.#refreshCredits().catch(() => void 0);
25238
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, sessionUsageFromHistory(history) ?? (response ? usageFromPrompt(response) : null), nativeTurnRef);
25842
+ this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
25239
25843
  }
25240
25844
  #finish(active, outcome, usage = null, nativeTurnRef) {
25241
25845
  if (this.#active !== active)
@@ -25262,8 +25866,8 @@ var GrokHarnessSession = class {
25262
25866
  });
25263
25867
  }
25264
25868
  this.#active = null;
25265
- if (usage)
25266
- this.#publishUsage(usage, active.command.turnId);
25869
+ if (usage || this.#usage)
25870
+ this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
25267
25871
  this.#event({
25268
25872
  type: "turn.completed",
25269
25873
  turnId: active.command.turnId,
@@ -25272,8 +25876,14 @@ var GrokHarnessSession = class {
25272
25876
  });
25273
25877
  active.resolveCompletion();
25274
25878
  }
25275
- #publishUsage(usage, observedForTurnId) {
25276
- const merged = combineUsage(this.#usage, usage);
25879
+ #publishUsage(usage, observedForTurnId, replaceMetrics = false) {
25880
+ const base = this.#usage ? { ...this.#usage } : null;
25881
+ if (base && replaceMetrics) {
25882
+ delete base.outputTokensPerSecond;
25883
+ delete base.cacheHitRatePercent;
25884
+ delete base.sessionCacheUsage;
25885
+ }
25886
+ const merged = combineUsage(base, usage);
25277
25887
  if (merged === null || JSON.stringify(merged) === JSON.stringify(this.#usage))
25278
25888
  return;
25279
25889
  this.#usage = merged;
@@ -25331,6 +25941,7 @@ var GrokAdapter = class {
25331
25941
  liveCommandCatalog = true;
25332
25942
  harnessId = grokHarnessId;
25333
25943
  sessionImport;
25944
+ usageStatistics;
25334
25945
  subagents = {
25335
25946
  readSnapshot: async (input) => {
25336
25947
  if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
@@ -25379,6 +25990,7 @@ var GrokAdapter = class {
25379
25990
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
25380
25991
  this.#environment = options.environment;
25381
25992
  this.sessionImport = new GrokSessionImport(options.environment);
25993
+ this.usageStatistics = createGrokUsageStatistics(options.environment ?? process.env);
25382
25994
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
25383
25995
  this.#dependencies = dependencies ?? {
25384
25996
  randomUUID,
@@ -25422,7 +26034,7 @@ var GrokAdapter = class {
25422
26034
  async inspect(input = {}) {
25423
26035
  if (this.#closePromise)
25424
26036
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
25425
- const cwd = path13.resolve(input.cwd ?? process.cwd());
26037
+ const cwd = path15.resolve(input.cwd ?? process.cwd());
25426
26038
  if (!input.refresh) {
25427
26039
  const cached2 = this.#inspectionCache.get(cwd);
25428
26040
  if (cached2)
@@ -25484,7 +26096,7 @@ var GrokAdapter = class {
25484
26096
  }
25485
26097
  };
25486
26098
  }
25487
- const cwd = path13.resolve(input.cwd);
26099
+ const cwd = path15.resolve(input.cwd);
25488
26100
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
25489
26101
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
25490
26102
  return {
@@ -25588,6 +26200,8 @@ var GrokAdapter = class {
25588
26200
  const modelState = modelStateFromSessionResponse(opened.session) ?? modelStateFromInitialize(opened.initialize);
25589
26201
  if (!modelState)
25590
26202
  throw new GrokTransportError("protocolError", "Grok returned an invalid Model catalog");
26203
+ const nativeModelId = modelState.currentModel.id;
26204
+ const nativeThinkingOptionId = modelState.currentThinkingOptionId;
25591
26205
  const retainedConfiguration = sourceConfiguration;
25592
26206
  if ((input.kind === "rollbackLastTurn" || input.kind === "fork") && retainedConfiguration) {
25593
26207
  const operation = input.kind === "rollbackLastTurn" ? "Rewind" : "Fork";
@@ -25600,7 +26214,6 @@ var GrokAdapter = class {
25600
26214
  throw new GrokTransportError("protocolError", `Grok Thinking option is unavailable after ${operation}`);
25601
26215
  }
25602
26216
  if (retainedConfiguration.model.id !== modelState.currentModel.id || retainedConfiguration.thinkingOptionId !== modelState.currentThinkingOptionId) {
25603
- await transport.setModel(retainedConfiguration.model.id, retainedConfiguration.thinkingOptionId);
25604
26217
  modelState.currentModel = retainedConfiguration.model;
25605
26218
  if (retainedConfiguration.thinkingOptionId) {
25606
26219
  modelState.currentThinkingOptionId = retainedConfiguration.thinkingOptionId;
@@ -25619,7 +26232,6 @@ var GrokAdapter = class {
25619
26232
  throw new GrokTransportError("protocolError", "Requested Grok Thinking option is unavailable");
25620
26233
  }
25621
26234
  if (selectedModel.id !== modelState.currentModel.id || selectedThinking !== modelState.currentThinkingOptionId) {
25622
- await transport.setModel(selectedModel.id, selectedThinking);
25623
26235
  modelState.currentModel = selectedModel;
25624
26236
  if (selectedThinking)
25625
26237
  modelState.currentThinkingOptionId = selectedThinking;
@@ -25627,8 +26239,21 @@ var GrokAdapter = class {
25627
26239
  delete modelState.currentThinkingOptionId;
25628
26240
  }
25629
26241
  }
26242
+ const contextWindow = modelState.defaultContextWindowTokensByModel.get(modelState.currentModel.id);
26243
+ if (modelState.currentModel.id !== nativeModelId || modelState.currentThinkingOptionId !== nativeThinkingOptionId || contextWindow !== void 0 && modelState.contextWindowTokensByModel.get(modelState.currentModel.id) !== contextWindow) {
26244
+ await transport.setModel(modelState.currentModel.id, modelState.currentThinkingOptionId, contextWindow);
26245
+ if (contextWindow !== void 0) {
26246
+ modelState.contextWindowTokensByModel = new Map([
26247
+ ...modelState.contextWindowTokensByModel,
26248
+ [modelState.currentModel.id, contextWindow]
26249
+ ]);
26250
+ }
26251
+ }
25630
26252
  const history = await transport.getHistory();
25631
- const initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26253
+ let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26254
+ if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {
26255
+ initialUsage = combineUsage(initialUsage, { contextWindowTokens: contextWindow });
26256
+ }
25632
26257
  const environment = input.environment ?? this.#environment;
25633
26258
  const sessionDirectory = grokNativeSessionDirectory(environment ? { cwd, environment } : { cwd }, opened.sessionId);
25634
26259
  const openedSession = new GrokHarnessSession(cwd, transport, opened, modelState, () => this.#sessions.delete(openedSession), {