@karlorz/codexhost-cli-win32-x64 0.13.3-6 → 0.13.3-7

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.
@@ -408,10 +408,13 @@ function usageSessionTitle(value) {
408
408
  return void 0;
409
409
  if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
410
410
  return normalized;
411
- const characters = [...normalized];
412
- if (characters.length <= MAX_SESSION_TITLE_LENGTH)
413
- return normalized;
414
- return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
411
+ let title = "";
412
+ for (const character of normalized) {
413
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
414
+ break;
415
+ title += character;
416
+ }
417
+ return `${title.trimEnd()}…`;
415
418
  }
416
419
  function sessionIdOk(value) {
417
420
  return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
@@ -576,7 +579,7 @@ function createGrokUsageStatistics(environment) {
576
579
  }
577
580
 
578
581
  // dist/grok-adapter.js
579
- import { randomUUID } from "node:crypto";
582
+ import { randomUUID as randomUUID2 } from "node:crypto";
580
583
 
581
584
  // dist/grok-credential-export.js
582
585
  import { createHash } from "node:crypto";
@@ -615,7 +618,7 @@ async function readGrokCredentials(environment) {
615
618
  }
616
619
 
617
620
  // dist/grok-adapter.js
618
- import path16 from "node:path";
621
+ import path18 from "node:path";
619
622
 
620
623
  // ../../../node_modules/zod/v4/classic/external.js
621
624
  var external_exports = {};
@@ -1383,10 +1386,10 @@ function mergeDefs(...defs) {
1383
1386
  function cloneDef(schema) {
1384
1387
  return mergeDefs(schema._zod.def);
1385
1388
  }
1386
- function getElementAtPath(obj, path17) {
1387
- if (!path17)
1389
+ function getElementAtPath(obj, path19) {
1390
+ if (!path19)
1388
1391
  return obj;
1389
- return path17.reduce((acc, key) => acc?.[key], obj);
1392
+ return path19.reduce((acc, key) => acc?.[key], obj);
1390
1393
  }
1391
1394
  function promiseAllObject(promisesObj) {
1392
1395
  const keys = Object.keys(promisesObj);
@@ -1795,11 +1798,11 @@ function explicitlyAborted(x, startIndex = 0) {
1795
1798
  }
1796
1799
  return false;
1797
1800
  }
1798
- function prefixIssues(path17, issues) {
1801
+ function prefixIssues(path19, issues) {
1799
1802
  return issues.map((iss) => {
1800
1803
  var _a3;
1801
1804
  (_a3 = iss).path ?? (_a3.path = []);
1802
- iss.path.unshift(path17);
1805
+ iss.path.unshift(path19);
1803
1806
  return iss;
1804
1807
  });
1805
1808
  }
@@ -1946,16 +1949,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1946
1949
  }
1947
1950
  function formatError(error53, mapper = (issue2) => issue2.message) {
1948
1951
  const fieldErrors = { _errors: [] };
1949
- const processError = (error54, path17 = []) => {
1952
+ const processError = (error54, path19 = []) => {
1950
1953
  for (const issue2 of error54.issues) {
1951
1954
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1952
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1955
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1953
1956
  } else if (issue2.code === "invalid_key") {
1954
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1957
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1955
1958
  } else if (issue2.code === "invalid_element") {
1956
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1959
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1957
1960
  } else {
1958
- const fullpath = [...path17, ...issue2.path];
1961
+ const fullpath = [...path19, ...issue2.path];
1959
1962
  if (fullpath.length === 0) {
1960
1963
  fieldErrors._errors.push(mapper(issue2));
1961
1964
  } else {
@@ -1982,17 +1985,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1982
1985
  }
1983
1986
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1984
1987
  const result = { errors: [] };
1985
- const processError = (error54, path17 = []) => {
1988
+ const processError = (error54, path19 = []) => {
1986
1989
  var _a3, _b;
1987
1990
  for (const issue2 of error54.issues) {
1988
1991
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1989
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1992
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1990
1993
  } else if (issue2.code === "invalid_key") {
1991
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1994
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1992
1995
  } else if (issue2.code === "invalid_element") {
1993
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1996
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1994
1997
  } else {
1995
- const fullpath = [...path17, ...issue2.path];
1998
+ const fullpath = [...path19, ...issue2.path];
1996
1999
  if (fullpath.length === 0) {
1997
2000
  result.errors.push(mapper(issue2));
1998
2001
  continue;
@@ -2024,8 +2027,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
2024
2027
  }
2025
2028
  function toDotPath(_path) {
2026
2029
  const segs = [];
2027
- const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2028
- for (const seg of path17) {
2030
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2031
+ for (const seg of path19) {
2029
2032
  if (typeof seg === "number")
2030
2033
  segs.push(`[${seg}]`);
2031
2034
  else if (typeof seg === "symbol")
@@ -14717,13 +14720,13 @@ function resolveRef(ref, ctx) {
14717
14720
  if (!ref.startsWith("#")) {
14718
14721
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14719
14722
  }
14720
- const path17 = ref.slice(1).split("/").filter(Boolean);
14721
- if (path17.length === 0) {
14723
+ const path19 = ref.slice(1).split("/").filter(Boolean);
14724
+ if (path19.length === 0) {
14722
14725
  return ctx.rootSchema;
14723
14726
  }
14724
14727
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14725
- if (path17[0] === defsKey) {
14726
- const key = path17[1];
14728
+ if (path19[0] === defsKey) {
14729
+ const key = path19[1];
14727
14730
  if (!key || !ctx.defs[key]) {
14728
14731
  throw new Error(`Reference not found: ${ref}`);
14729
14732
  }
@@ -15440,6 +15443,8 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15440
15443
  "codexhost/harness/installation",
15441
15444
  "codexhost/harness/launch-settings/get",
15442
15445
  "codexhost/harness/launch-settings/set",
15446
+ "codexhost/harness/grok-computer-use/get",
15447
+ "codexhost/harness/grok-computer-use/set",
15443
15448
  "codexhost/harness/web-ui/open",
15444
15449
  "codexhost/harness/accounts/sources",
15445
15450
  "codexhost/harness/accounts/list",
@@ -15968,7 +15973,9 @@ var harnessInspectionSchema = external_exports.union([
15968
15973
  var harnessInspectParamsSchema = external_exports.object({
15969
15974
  harnessId: harnessIdSchema,
15970
15975
  cwd: nonBlankTextSchema2.max(16384).optional(),
15971
- refresh: external_exports.boolean().optional()
15976
+ refresh: external_exports.boolean().optional(),
15977
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15978
+ purpose: external_exports.literal("availability").optional()
15972
15979
  }).strict();
15973
15980
  var harnessWebUiOpenParamsSchema = external_exports.object({
15974
15981
  harnessId: harnessIdSchema
@@ -16142,6 +16149,26 @@ var harnessLaunchSettingsSchema = external_exports.object({
16142
16149
  restartRequired: external_exports.boolean()
16143
16150
  }).strict();
16144
16151
 
16152
+ // ../../shared-contracts/dist/grok-computer-use.js
16153
+ var grokComputerUseGetSchema = external_exports.object({}).strict();
16154
+ var grokComputerUseSetSchema = external_exports.object({
16155
+ enabled: external_exports.boolean().optional(),
16156
+ browser: external_exports.boolean().optional()
16157
+ }).strict().refine((value) => value.enabled !== void 0 || value.browser !== void 0, {
16158
+ message: "Expected enabled or browser"
16159
+ });
16160
+ var grokComputerUseSettingsSchema = external_exports.object({
16161
+ enabled: external_exports.boolean(),
16162
+ available: external_exports.boolean(),
16163
+ unavailableReason: external_exports.string().min(1).max(500).optional(),
16164
+ browser: external_exports.boolean().optional(),
16165
+ browserFilesPresent: external_exports.boolean().optional(),
16166
+ browserAvailable: external_exports.boolean().optional(),
16167
+ browserUnavailableReason: external_exports.string().min(1).max(500).optional(),
16168
+ applyFailed: external_exports.boolean().optional(),
16169
+ applyError: external_exports.string().min(1).max(500).optional()
16170
+ }).strict();
16171
+
16145
16172
  // ../../shared-contracts/dist/harness-installation.js
16146
16173
  var harnessInstallationParamsSchema = external_exports.object({
16147
16174
  harnessId: harnessIdSchema,
@@ -16588,6 +16615,320 @@ var voiceSettingsStateSchema = external_exports.strictObject({
16588
16615
  // ../../shared-contracts/dist/index.js
16589
16616
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16590
16617
 
16618
+ // ../../harness-plugin-files/dist/grok-computer-use.js
16619
+ import { randomUUID } from "node:crypto";
16620
+ import { access, mkdir as mkdir2, readFile as readFile3, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
16621
+ import os4 from "node:os";
16622
+ import path8 from "node:path";
16623
+
16624
+ // ../../harness-plugin-files/dist/grok-computer-use-lock.js
16625
+ import { mkdir, rm as rm2 } from "node:fs/promises";
16626
+ import path7 from "node:path";
16627
+ import { setTimeout as delay } from "node:timers/promises";
16628
+ async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
16629
+ const locks = [
16630
+ .../* @__PURE__ */ new Set([
16631
+ path7.join(dataDirectory2, ".grok-computer-use.lock"),
16632
+ path7.join(grokHome4, ".codexhost-cua.lock")
16633
+ ])
16634
+ ].sort();
16635
+ const acquired = [];
16636
+ const deadline = Date.now() + 5e3;
16637
+ try {
16638
+ for (const lock of locks) {
16639
+ await mkdir(path7.dirname(lock), { recursive: true, mode: 448 });
16640
+ for (; ; ) {
16641
+ try {
16642
+ await mkdir(lock, { mode: 448 });
16643
+ acquired.push(lock);
16644
+ break;
16645
+ } catch (error53) {
16646
+ if (error53.code !== "EEXIST")
16647
+ throw error53;
16648
+ if (Date.now() >= deadline)
16649
+ throw new Error("Grok Computer Use settings are locked");
16650
+ await delay(25);
16651
+ }
16652
+ }
16653
+ }
16654
+ return await operation();
16655
+ } finally {
16656
+ for (const lock of acquired.reverse())
16657
+ await rm2(lock, { recursive: true });
16658
+ }
16659
+ }
16660
+
16661
+ // ../../harness-plugin-files/dist/grok-computer-use.js
16662
+ var GROK_BROWSER_BINDING_SUPPORTED = false;
16663
+ var PREFERENCE_FILE = "grok-computer-use.json";
16664
+ var TABLE = "[mcp_servers.cua_repl]";
16665
+ var ENV_TABLE = "[mcp_servers.cua_repl.env]";
16666
+ var APPLY_FAILED = "Could not apply Grok Computer Use settings to Grok config.";
16667
+ var GrokComputerUseError = class extends Error {
16668
+ constructor(message) {
16669
+ super(message);
16670
+ this.name = "GrokComputerUseError";
16671
+ }
16672
+ };
16673
+ function dataDirectory(environment) {
16674
+ return environment.CODEXHOST_DATA_DIR ? path8.resolve(environment.CODEXHOST_DATA_DIR) : path8.join(os4.homedir(), ".codexhost");
16675
+ }
16676
+ function grokHome2(environment) {
16677
+ return environment.GROK_HOME ? path8.resolve(environment.GROK_HOME) : path8.join(environment.HOME ?? os4.homedir(), ".grok");
16678
+ }
16679
+ function chatgptApp(environment, platform) {
16680
+ if (environment.CODEXHOST_CHATGPT_APP)
16681
+ return path8.resolve(environment.CODEXHOST_CHATGPT_APP);
16682
+ if (platform === "darwin")
16683
+ return "/Applications/ChatGPT.app";
16684
+ return void 0;
16685
+ }
16686
+ async function isFile(target) {
16687
+ try {
16688
+ await access(target);
16689
+ return true;
16690
+ } catch {
16691
+ return false;
16692
+ }
16693
+ }
16694
+ function isNotFound(error53) {
16695
+ return Boolean(error53 && typeof error53 === "object" && "code" in error53 && error53.code === "ENOENT");
16696
+ }
16697
+ async function writeAtomically(file2, content) {
16698
+ await mkdir2(path8.dirname(file2), { recursive: true, mode: 448 });
16699
+ const temporary = `${file2}.${randomUUID()}.tmp`;
16700
+ try {
16701
+ await writeFile2(temporary, content, { mode: 384, flag: "wx" });
16702
+ await rename(temporary, file2);
16703
+ } finally {
16704
+ await rm3(temporary, { force: true });
16705
+ }
16706
+ }
16707
+ function launchPaths(environment, platform) {
16708
+ const app = chatgptApp(environment, platform);
16709
+ if (!app)
16710
+ return void 0;
16711
+ const resources = path8.join(app, "Contents", "Resources");
16712
+ const cuaNode = path8.join(resources, "cua_node");
16713
+ return {
16714
+ node: path8.join(cuaNode, "bin", "node"),
16715
+ cuaRepl: path8.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
16716
+ nodeRepl: path8.join(cuaNode, "bin", "node_repl"),
16717
+ nodeModules: path8.join(cuaNode, "lib", "node_modules"),
16718
+ codexCli: path8.join(resources, "codex-cli", "bin", "codex"),
16719
+ skyApp: path8.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
16720
+ codexHome: path8.join(environment.HOME ?? os4.homedir(), ".codex"),
16721
+ browserDesktop: path8.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
16722
+ };
16723
+ }
16724
+ async function sharedRuntimePresent(launch) {
16725
+ const present = await Promise.all([launch.node, launch.cuaRepl, launch.nodeRepl].map(isFile));
16726
+ return present.every(Boolean);
16727
+ }
16728
+ async function computerFilesPresent(launch) {
16729
+ const present = await Promise.all([isFile(launch.skyApp), isFile(launch.codexCli)]);
16730
+ return present.every(Boolean);
16731
+ }
16732
+ async function browserFilesPresent(launch) {
16733
+ return isFile(path8.join(launch.browserDesktop, "package.json"));
16734
+ }
16735
+ async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
16736
+ const launch = launchPaths(environment, platform);
16737
+ if (!launch || !await sharedRuntimePresent(launch))
16738
+ return void 0;
16739
+ return launch;
16740
+ }
16741
+ function tableRange(text, header) {
16742
+ const lines = text.split(/\n/);
16743
+ let start = -1;
16744
+ for (let index = 0; index < lines.length; index += 1) {
16745
+ if (lines[index] === header) {
16746
+ start = index;
16747
+ break;
16748
+ }
16749
+ }
16750
+ if (start < 0)
16751
+ return void 0;
16752
+ let end = lines.length;
16753
+ for (let index = start + 1; index < lines.length; index += 1) {
16754
+ const line = lines[index] ?? "";
16755
+ if (line.startsWith("[") && line.endsWith("]")) {
16756
+ end = index;
16757
+ break;
16758
+ }
16759
+ }
16760
+ return { start, end };
16761
+ }
16762
+ function removeTables(text, headers) {
16763
+ let current = text;
16764
+ for (const header of headers) {
16765
+ const range = tableRange(current, header);
16766
+ if (!range)
16767
+ continue;
16768
+ const lines = current.split(/\n/);
16769
+ lines.splice(range.start, range.end - range.start);
16770
+ current = lines.join("\n");
16771
+ }
16772
+ return current.replace(/\n{3,}/g, "\n\n");
16773
+ }
16774
+ function cuaReplEnabledInToml(text) {
16775
+ const range = tableRange(text, TABLE);
16776
+ if (!range)
16777
+ return false;
16778
+ const body = text.split(/\n/).slice(range.start, range.end);
16779
+ for (const line of body) {
16780
+ if (/^enabled\s*=\s*false\b/u.test(line))
16781
+ return false;
16782
+ if (/^enabled\s*=\s*true\b/u.test(line))
16783
+ return true;
16784
+ }
16785
+ return true;
16786
+ }
16787
+ function inferredSurfaces(text) {
16788
+ if (!cuaReplEnabledInToml(text))
16789
+ return { enabled: false, browser: false };
16790
+ const range = tableRange(text, ENV_TABLE);
16791
+ const body = range ? text.split(/\n/).slice(range.start, range.end).join("\n") : "";
16792
+ const literal2 = /^CUA_REPL_ENABLED_SURFACES\s*=\s*(["'])([^"']*)\1\s*(?:#.*)?$/mu.exec(body);
16793
+ if (!literal2)
16794
+ return { enabled: true, browser: false };
16795
+ const surfaces = new Set(literal2[2]?.split(",").map((surface) => surface.trim()));
16796
+ return { enabled: surfaces.has("computer"), browser: surfaces.has("browser") };
16797
+ }
16798
+ function stanza(launch, state) {
16799
+ const trusted = `${launch.codexHome}:${launch.nodeModules}`;
16800
+ const services = {};
16801
+ if (state.browser)
16802
+ services.browser = "@oai/browser-desktop/service";
16803
+ if (state.enabled)
16804
+ services.sky = "@oai/sky/service";
16805
+ const surfaces = [state.browser ? "browser" : "", state.enabled ? "computer" : ""].filter(Boolean).join(",");
16806
+ const backends = state.browser ? 'BROWSER_USE_AVAILABLE_BACKENDS = "iab"\n' : "";
16807
+ const active = state.enabled || state.browser;
16808
+ return `${TABLE}
16809
+ command = ${JSON.stringify(launch.node)}
16810
+ args = [${JSON.stringify(launch.cuaRepl)}]
16811
+ enabled = ${active ? "true" : "false"}
16812
+ startup_timeout_sec = 120
16813
+
16814
+ ${ENV_TABLE}
16815
+ NODE_REPL_TRUSTED_SERVICES = ${JSON.stringify(JSON.stringify(services))}
16816
+ NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(trusted)}
16817
+ NODE_REPL_NODE_PATH = ${JSON.stringify(launch.node)}
16818
+ CODEX_HOME = ${JSON.stringify(launch.codexHome)}
16819
+ CUA_REPL_NODE_REPL_PATH = ${JSON.stringify(launch.nodeRepl)}
16820
+ NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(launch.nodeModules)}
16821
+ NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
16822
+ SKY_CUA_SERVICE_PATH = ${JSON.stringify(launch.skyApp)}
16823
+ CODEX_CLI_PATH = ${JSON.stringify(launch.codexCli)}
16824
+ ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
16825
+ `;
16826
+ }
16827
+ async function readPreference(environment) {
16828
+ try {
16829
+ const document = JSON.parse(await readFile3(path8.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
16830
+ return {
16831
+ ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
16832
+ ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
16833
+ ...typeof document.applyError === "string" && document.applyError ? { applyError: document.applyError } : {}
16834
+ };
16835
+ } catch (error53) {
16836
+ if (isNotFound(error53))
16837
+ return void 0;
16838
+ throw new GrokComputerUseError("Could not read Grok Computer Use settings");
16839
+ }
16840
+ }
16841
+ async function writePreference(environment, state) {
16842
+ const document = {
16843
+ ...typeof state.enabled === "boolean" ? { enabled: state.enabled } : {},
16844
+ ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
16845
+ ...state.applyError ? { applyError: state.applyError } : {}
16846
+ };
16847
+ await writeAtomically(path8.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
16848
+ `);
16849
+ }
16850
+ async function readGrokConfig(environment) {
16851
+ try {
16852
+ return await readFile3(path8.join(grokHome2(environment), "config.toml"), "utf8");
16853
+ } catch (error53) {
16854
+ if (isNotFound(error53))
16855
+ return "";
16856
+ throw new GrokComputerUseError("Could not read Grok config");
16857
+ }
16858
+ }
16859
+ async function writeGrokConfig(environment, text) {
16860
+ await writeAtomically(path8.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
16861
+ `);
16862
+ }
16863
+ async function currentState(environment, preference) {
16864
+ const resolved = preference ?? await readPreference(environment);
16865
+ const inferred = resolved?.enabled === void 0 ? inferredSurfaces(await readGrokConfig(environment)) : void 0;
16866
+ return {
16867
+ enabled: resolved?.enabled ?? inferred?.enabled ?? false,
16868
+ browser: resolved ? resolved.browser ?? false : inferred?.browser ?? false,
16869
+ ...resolved?.applyError ? { applyError: resolved.applyError } : {}
16870
+ };
16871
+ }
16872
+ async function surfaceFiles(launch) {
16873
+ if (!launch)
16874
+ return { computer: false, browser: false };
16875
+ const [computer, browser] = await Promise.all([
16876
+ computerFilesPresent(launch),
16877
+ browserFilesPresent(launch)
16878
+ ]);
16879
+ return { computer, browser };
16880
+ }
16881
+ async function writeConfigForState(state, launch, files, environment) {
16882
+ const current = await readGrokConfig(environment);
16883
+ const range = tableRange(current, TABLE);
16884
+ const effective = {
16885
+ enabled: state.enabled && files.computer,
16886
+ browser: state.browser && files.browser && GROK_BROWSER_BINDING_SUPPORTED
16887
+ };
16888
+ if (!effective.enabled && !effective.browser && !range)
16889
+ return;
16890
+ if (!launch) {
16891
+ if (!range)
16892
+ return;
16893
+ const lines = current.split(/\n/);
16894
+ const body = lines.slice(range.start, range.end);
16895
+ const replaced = body.map((line) => /^enabled\s*=/u.test(line) ? "enabled = false" : line);
16896
+ if (!replaced.some((line) => /^enabled\s*=/u.test(line))) {
16897
+ replaced.splice(1, 0, "enabled = false");
16898
+ }
16899
+ lines.splice(range.start, range.end - range.start, ...replaced);
16900
+ await writeGrokConfig(environment, lines.join("\n"));
16901
+ return;
16902
+ }
16903
+ const stripped = removeTables(current, [ENV_TABLE, TABLE]).replace(/\s+$/u, "\n");
16904
+ await writeGrokConfig(environment, `${stripped.trimEnd()}
16905
+
16906
+ ${stanza(launch, effective)}`);
16907
+ }
16908
+ async function applyGrokComputerUsePreference(environment = process.env, platform = process.platform) {
16909
+ await withGrokComputerUseLock(dataDirectory(environment), grokHome2(environment), async () => {
16910
+ const preference = await readPreference(environment);
16911
+ if (preference === void 0)
16912
+ return;
16913
+ const launch = await discoverGrokComputerUseLaunch(environment, platform);
16914
+ const files = await surfaceFiles(launch);
16915
+ const state = await currentState(environment, preference);
16916
+ try {
16917
+ await writeConfigForState(state, launch, files, environment);
16918
+ if (state.applyError)
16919
+ await writePreference(environment, { enabled: state.enabled, browser: state.browser });
16920
+ } catch (error53) {
16921
+ const applyError = error53 instanceof GrokComputerUseError ? error53.message : APPLY_FAILED;
16922
+ await writePreference(environment, {
16923
+ enabled: state.enabled,
16924
+ browser: state.browser,
16925
+ applyError
16926
+ }).catch(() => void 0);
16927
+ throw error53 instanceof GrokComputerUseError ? error53 : new GrokComputerUseError(APPLY_FAILED);
16928
+ }
16929
+ });
16930
+ }
16931
+
16591
16932
  // ../../harness-adapter/dist/approval.js
16592
16933
  function invalidRequest(message) {
16593
16934
  return { code: "invalidRequest", message, retryable: false };
@@ -16915,9 +17256,9 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
16915
17256
 
16916
17257
  // dist/acp-transport.js
16917
17258
  import { spawn, spawnSync } from "node:child_process";
16918
- import { readdir, readFile as readFile3 } from "node:fs/promises";
16919
- import os5 from "node:os";
16920
- import path13 from "node:path";
17259
+ import { readdir, readFile as readFile4 } from "node:fs/promises";
17260
+ import os6 from "node:os";
17261
+ import path15 from "node:path";
16921
17262
  import { Readable, Writable } from "node:stream";
16922
17263
 
16923
17264
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -21105,8 +21446,8 @@ function parseGrokAvailableCommands(value) {
21105
21446
  });
21106
21447
  }
21107
21448
  function isGrokSkill(command) {
21108
- const path17 = command.meta?.path;
21109
- return typeof path17 === "string" && /(^|[\\/])SKILL\.md$/u.test(path17) || typeof command.meta?.qualifiedName === "string";
21449
+ const path19 = command.meta?.path;
21450
+ return typeof path19 === "string" && /(^|[\\/])SKILL\.md$/u.test(path19) || typeof command.meta?.qualifiedName === "string";
21110
21451
  }
21111
21452
  function grokLiveCommands(native) {
21112
21453
  return native.map((command) => ({
@@ -21117,7 +21458,7 @@ function grokLiveCommands(native) {
21117
21458
  }
21118
21459
 
21119
21460
  // dist/command.js
21120
- import path7 from "node:path";
21461
+ import path9 from "node:path";
21121
21462
  var GrokExecutableError = class extends Error {
21122
21463
  code = "GROK_NOT_FOUND";
21123
21464
  };
@@ -21146,7 +21487,7 @@ function resolveGrokExecutable(input = {}) {
21146
21487
  });
21147
21488
  if (!resolution)
21148
21489
  throw new GrokExecutableError("Grok CLI is not installed");
21149
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
21490
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path9.resolve(resolution.executable);
21150
21491
  }
21151
21492
  function grokInvocation(command, platform = process.platform, modelId) {
21152
21493
  const arguments_ = ["agent", "--no-leader"];
@@ -21159,11 +21500,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
21159
21500
 
21160
21501
  // dist/grok-fork.js
21161
21502
  import { isDeepStrictEqual } from "node:util";
21162
- import path11 from "node:path";
21503
+ import path13 from "node:path";
21163
21504
 
21164
21505
  // dist/grok-file-change.js
21165
21506
  import { Buffer as Buffer2 } from "node:buffer";
21166
- import path8 from "node:path";
21507
+ import path10 from "node:path";
21167
21508
 
21168
21509
  // ../../../node_modules/diff/libesm/diff/base.js
21169
21510
  var Diff = class {
@@ -21265,16 +21606,16 @@ var Diff = class {
21265
21606
  }
21266
21607
  }
21267
21608
  }
21268
- addToPath(path17, added, removed, oldPosInc, options) {
21269
- const last = path17.lastComponent;
21609
+ addToPath(path19, added, removed, oldPosInc, options) {
21610
+ const last = path19.lastComponent;
21270
21611
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21271
21612
  return {
21272
- oldPos: path17.oldPos + oldPosInc,
21613
+ oldPos: path19.oldPos + oldPosInc,
21273
21614
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21274
21615
  };
21275
21616
  } else {
21276
21617
  return {
21277
- oldPos: path17.oldPos + oldPosInc,
21618
+ oldPos: path19.oldPos + oldPosInc,
21278
21619
  lastComponent: { count: 1, added, removed, previousComponent: last }
21279
21620
  };
21280
21621
  }
@@ -21587,13 +21928,13 @@ function isRecord5(value) {
21587
21928
  return typeof value === "object" && value !== null && !Array.isArray(value);
21588
21929
  }
21589
21930
  function validAbsolutePath(value) {
21590
- return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21931
+ return typeof value === "string" && path10.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21591
21932
  }
21592
21933
  function displayPath(nativePath, cwd) {
21593
- const resolvedCwd = path8.resolve(cwd);
21594
- const resolvedPath = path8.resolve(nativePath);
21595
- const relative = path8.relative(resolvedCwd, resolvedPath);
21596
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
21934
+ const resolvedCwd = path10.resolve(cwd);
21935
+ const resolvedPath = path10.resolve(nativePath);
21936
+ const relative = path10.relative(resolvedCwd, resolvedPath);
21937
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
21597
21938
  const selected = inside ? relative : resolvedPath;
21598
21939
  const normalized = selected.replaceAll("\\", "/");
21599
21940
  if (normalized.length === 0 || normalized === ".")
@@ -21654,12 +21995,12 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21654
21995
  }
21655
21996
 
21656
21997
  // dist/grok-generated-image.js
21657
- import path10 from "node:path";
21998
+ import path12 from "node:path";
21658
21999
 
21659
22000
  // dist/local-media-markdown.js
21660
22001
  import { existsSync, statSync } from "node:fs";
21661
- import os4 from "node:os";
21662
- import path9 from "node:path";
22002
+ import os5 from "node:os";
22003
+ import path11 from "node:path";
21663
22004
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21664
22005
  ".aac",
21665
22006
  ".gif",
@@ -21678,14 +22019,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21678
22019
  ".webp"
21679
22020
  ]);
21680
22021
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21681
- const roots = [path9.resolve(cwd)];
22022
+ const roots = [path11.resolve(cwd)];
21682
22023
  if (sessionDirectory) {
21683
- const session = path9.resolve(sessionDirectory);
21684
- roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
22024
+ const session = path11.resolve(sessionDirectory);
22025
+ roots.push(session, path11.join(session, "videos"), path11.join(session, "images"));
21685
22026
  }
21686
- const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
22027
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? os5.homedir();
21687
22028
  if (home)
21688
- roots.push(path9.join(home, "Downloads"));
22029
+ roots.push(path11.join(home, "Downloads"));
21689
22030
  return roots;
21690
22031
  }
21691
22032
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -21786,7 +22127,7 @@ function parseInlineCode(text, start) {
21786
22127
  return { closed: false, content: text.slice(start + 1), end: text.length };
21787
22128
  }
21788
22129
  function mediaMarkdownImage(absolutePath) {
21789
- const name = path9.basename(absolutePath).replaceAll("]", "\\]");
22130
+ const name = path11.basename(absolutePath).replaceAll("]", "\\]");
21790
22131
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21791
22132
  }
21792
22133
  function parseMarkdownImage(text, start) {
@@ -21911,11 +22252,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21911
22252
  if (!hasMediaExtension(stripped))
21912
22253
  return null;
21913
22254
  if (isAbsoluteMediaPath(stripped)) {
21914
- const absolute = path9.resolve(stripped);
22255
+ const absolute = path11.resolve(stripped);
21915
22256
  return exists(absolute) ? absolute : null;
21916
22257
  }
21917
22258
  for (const root of roots) {
21918
- const absolute = path9.resolve(root, stripped);
22259
+ const absolute = path11.resolve(root, stripped);
21919
22260
  if (exists(absolute))
21920
22261
  return absolute;
21921
22262
  }
@@ -21937,11 +22278,11 @@ function stripFileUrl(value) {
21937
22278
  }
21938
22279
  }
21939
22280
  function isAbsoluteMediaPath(value) {
21940
- return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
22281
+ return path11.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21941
22282
  }
21942
22283
  function hasMediaExtension(value) {
21943
22284
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21944
- return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
22285
+ return MEDIA_EXTENSIONS.has(path11.extname(pathname).toLowerCase());
21945
22286
  }
21946
22287
  function mediaFileExists(absolutePath) {
21947
22288
  try {
@@ -21971,7 +22312,7 @@ function fromNativeRecord(value, exists) {
21971
22312
  const savedPath = stringField(value, "path");
21972
22313
  if (!validAbsolutePath(savedPath))
21973
22314
  return null;
21974
- const resolved = path10.resolve(savedPath);
22315
+ const resolved = path12.resolve(savedPath);
21975
22316
  if (!exists(resolved))
21976
22317
  return null;
21977
22318
  const filename = stringField(value, "filename");
@@ -23037,11 +23378,11 @@ function parseGrokForkResponse(value) {
23037
23378
  }
23038
23379
  function projectRelativePath(value, cwds) {
23039
23380
  const normalized = value.replaceAll("\\", "/");
23040
- if (!path11.isAbsolute(value))
23381
+ if (!path13.isAbsolute(value))
23041
23382
  return normalized;
23042
23383
  for (const cwd of cwds) {
23043
- const relative = path11.relative(path11.resolve(cwd), path11.resolve(value));
23044
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`)) {
23384
+ const relative = path13.relative(path13.resolve(cwd), path13.resolve(value));
23385
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path13.sep}`)) {
23045
23386
  return relative.replaceAll("\\", "/");
23046
23387
  }
23047
23388
  }
@@ -23106,8 +23447,8 @@ async function forkGrokSession(input) {
23106
23447
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
23107
23448
  };
23108
23449
  }
23109
- const sourceCwd = path11.resolve(located.cwd);
23110
- const targetCwd = path11.resolve(input.cwd);
23450
+ const sourceCwd = path13.resolve(located.cwd);
23451
+ const targetCwd = path13.resolve(input.cwd);
23111
23452
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
23112
23453
  if (!source.ok)
23113
23454
  return source;
@@ -23290,7 +23631,7 @@ function parseGrokCompactResult(value, cancelled = false) {
23290
23631
  }
23291
23632
 
23292
23633
  // dist/grok-rewind.js
23293
- import path12 from "node:path";
23634
+ import path14 from "node:path";
23294
23635
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
23295
23636
  function error52(code, message, retryable = false) {
23296
23637
  return { code, message, retryable };
@@ -23363,8 +23704,8 @@ async function rewindGrokLastTurn(input) {
23363
23704
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
23364
23705
  };
23365
23706
  }
23366
- const sourceCwd = path12.resolve(located.cwd);
23367
- const targetCwd = path12.resolve(input.cwd);
23707
+ const sourceCwd = path14.resolve(located.cwd);
23708
+ const targetCwd = path14.resolve(input.cwd);
23368
23709
  if (sourceCwd !== targetCwd) {
23369
23710
  return {
23370
23711
  ok: false,
@@ -23418,6 +23759,195 @@ async function rewindGrokLastTurn(input) {
23418
23759
  return { ok: true, value: { sessionId } };
23419
23760
  }
23420
23761
 
23762
+ // dist/grok-elicitation.js
23763
+ var GROK_MCP_ELICIT_METHOD = "_x.ai/mcp/elicit";
23764
+ var GROK_ELICIT_TITLE_MAX_LENGTH = 150;
23765
+ var GROK_ELICIT_DESCRIPTION_MAX_LENGTH = 500;
23766
+ var FORM_KEYS = /* @__PURE__ */ new Set([
23767
+ "sessionId",
23768
+ "toolCallId",
23769
+ "serverName",
23770
+ "message",
23771
+ "mode",
23772
+ "requestedSchema",
23773
+ "persist"
23774
+ ]);
23775
+ var URL_KEYS = /* @__PURE__ */ new Set([
23776
+ "sessionId",
23777
+ "toolCallId",
23778
+ "serverName",
23779
+ "message",
23780
+ "mode",
23781
+ "url",
23782
+ "elicitationId"
23783
+ ]);
23784
+ var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required"]);
23785
+ var GROK_CLOCK_ELICIT_FIXTURE = {
23786
+ sessionId: "session-1",
23787
+ toolCallId: "elicit-clock-1",
23788
+ serverName: "cua_repl",
23789
+ message: 'Allow Computer Use to use "Clock"?',
23790
+ mode: "form"
23791
+ };
23792
+ var GROK_CLOCK_ELICIT_PERSIST_FIXTURE = {
23793
+ ...GROK_CLOCK_ELICIT_FIXTURE,
23794
+ persist: ["session", "always"]
23795
+ };
23796
+ function isRecord13(value) {
23797
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23798
+ }
23799
+ function nonEmptyString(value) {
23800
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
23801
+ }
23802
+ function hasOnlyKeys(record2, allowed) {
23803
+ return Object.keys(record2).every((key) => allowed.has(key));
23804
+ }
23805
+ function clampText(value, max) {
23806
+ return value.length <= max ? value : value.slice(0, max);
23807
+ }
23808
+ function parsePersistOffer(value) {
23809
+ if (value === void 0)
23810
+ return void 0;
23811
+ if (!Array.isArray(value) || value.length === 0)
23812
+ return "invalid";
23813
+ let session = false;
23814
+ let always = false;
23815
+ const seen = /* @__PURE__ */ new Set();
23816
+ for (const item of value) {
23817
+ if (typeof item !== "string" || item !== item.trim())
23818
+ return "invalid";
23819
+ if (seen.has(item))
23820
+ return "invalid";
23821
+ seen.add(item);
23822
+ if (item === "session")
23823
+ session = true;
23824
+ else if (item === "always")
23825
+ always = true;
23826
+ else
23827
+ return "invalid";
23828
+ }
23829
+ const out = [];
23830
+ if (session)
23831
+ out.push("session");
23832
+ if (always)
23833
+ out.push("always");
23834
+ return out.length > 0 ? out : "invalid";
23835
+ }
23836
+ function schemaIsSupportedEmptyObject(schema) {
23837
+ if (!isRecord13(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
23838
+ return false;
23839
+ }
23840
+ if (schema.properties !== void 0) {
23841
+ if (!isRecord13(schema.properties) || Object.keys(schema.properties).length !== 0)
23842
+ return false;
23843
+ }
23844
+ if (schema.required !== void 0) {
23845
+ if (!Array.isArray(schema.required) || schema.required.length !== 0)
23846
+ return false;
23847
+ }
23848
+ return true;
23849
+ }
23850
+ function parseGrokMcpElicitParams(params) {
23851
+ if (!isRecord13(params))
23852
+ return { status: "invalid", message: "elicitation params must be an object" };
23853
+ const sessionId = nonEmptyString(params.sessionId);
23854
+ const toolCallId = nonEmptyString(params.toolCallId);
23855
+ const serverName = nonEmptyString(params.serverName);
23856
+ const message = nonEmptyString(params.message);
23857
+ if (!sessionId || !toolCallId || !serverName || !message) {
23858
+ return {
23859
+ status: "invalid",
23860
+ message: "elicitation requires sessionId, toolCallId, serverName, and message"
23861
+ };
23862
+ }
23863
+ if (params.mode === "url") {
23864
+ if (!hasOnlyKeys(params, URL_KEYS)) {
23865
+ return { status: "invalid", message: "URL elicitation contains unreviewed fields" };
23866
+ }
23867
+ if (!nonEmptyString(params.url) || !nonEmptyString(params.elicitationId)) {
23868
+ return { status: "invalid", message: "URL elicitation requires url and elicitationId" };
23869
+ }
23870
+ return { status: "unsupported" };
23871
+ }
23872
+ if (params.mode !== "form") {
23873
+ return { status: "invalid", message: "elicitation mode must be form or url" };
23874
+ }
23875
+ if (!hasOnlyKeys(params, FORM_KEYS)) {
23876
+ return { status: "invalid", message: "form elicitation contains unreviewed fields" };
23877
+ }
23878
+ if (params.requestedSchema !== void 0) {
23879
+ if (!isRecord13(params.requestedSchema)) {
23880
+ return { status: "invalid", message: "requestedSchema must be an object" };
23881
+ }
23882
+ if (!schemaIsSupportedEmptyObject(params.requestedSchema))
23883
+ return { status: "unsupported" };
23884
+ }
23885
+ const persist = parsePersistOffer(params.persist);
23886
+ if (persist === "invalid") {
23887
+ return {
23888
+ status: "invalid",
23889
+ message: "persist must be a unique array of session and/or always"
23890
+ };
23891
+ }
23892
+ return {
23893
+ status: "form",
23894
+ request: {
23895
+ sessionId,
23896
+ toolCallId,
23897
+ serverName,
23898
+ message,
23899
+ mode: "form",
23900
+ ...persist ? { persist } : {}
23901
+ }
23902
+ };
23903
+ }
23904
+ function grokMcpElicitAccept(persist) {
23905
+ return { outcome: "accept", content: {}, ...persist ? { persist } : {} };
23906
+ }
23907
+ function grokMcpElicitDecline() {
23908
+ return { outcome: "decline" };
23909
+ }
23910
+ function grokMcpElicitCancel() {
23911
+ return { outcome: "cancel" };
23912
+ }
23913
+ function grokMcpElicitResponseForAction(effect) {
23914
+ if (effect === "allowOnce")
23915
+ return grokMcpElicitAccept();
23916
+ if (effect === "allowAlways")
23917
+ return grokMcpElicitAccept("always");
23918
+ if (effect === "deny")
23919
+ return grokMcpElicitDecline();
23920
+ return grokMcpElicitCancel();
23921
+ }
23922
+ function grokMcpElicitApprovalActions(persist) {
23923
+ const actions = [
23924
+ { id: "allow-once", label: "Allow once", effect: "allowOnce" }
23925
+ ];
23926
+ if (persist?.includes("always")) {
23927
+ actions.push({ id: "allow-always", label: "Always allow", effect: "allowAlways" });
23928
+ }
23929
+ actions.push({ id: "deny", label: "Deny", effect: "deny" });
23930
+ return actions;
23931
+ }
23932
+ function projectGrokMcpElicitApproval(input) {
23933
+ const title = clampText(`${input.request.serverName}: ${input.request.message}`, GROK_ELICIT_TITLE_MAX_LENGTH);
23934
+ const description = clampText(input.request.message, GROK_ELICIT_DESCRIPTION_MAX_LENGTH);
23935
+ return {
23936
+ type: "approval",
23937
+ interactionId: input.interactionId,
23938
+ turnId: input.turnId,
23939
+ title,
23940
+ description,
23941
+ subject: { type: "nativeAction" },
23942
+ actions: grokMcpElicitApprovalActions(input.request.persist)
23943
+ };
23944
+ }
23945
+ function grokElicitationResolvedToolCallId(update) {
23946
+ if (!isRecord13(update) || update.sessionUpdate !== "interaction_resolved")
23947
+ return void 0;
23948
+ return nonEmptyString(update.tool_call_id) ?? nonEmptyString(update.toolCallId);
23949
+ }
23950
+
23421
23951
  // dist/permission-modes.js
23422
23952
  var nativePermissionModes = /* @__PURE__ */ new Set(["ask", "auto", "always-approve"]);
23423
23953
  var GROK_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("ask");
@@ -23504,16 +24034,16 @@ var GrokTransportError = class extends Error {
23504
24034
  this.name = "GrokTransportError";
23505
24035
  }
23506
24036
  };
23507
- function isRecord13(value) {
24037
+ function isRecord14(value) {
23508
24038
  return typeof value === "object" && value !== null && !Array.isArray(value);
23509
24039
  }
23510
24040
  function acpToolName(update, metadata) {
23511
- if (!isRecord13(update))
24041
+ if (!isRecord14(update))
23512
24042
  return void 0;
23513
24043
  if (typeof update.name === "string" && update.name.length > 0)
23514
24044
  return update.name;
23515
- const meta3 = isRecord13(update._meta) ? update._meta : metadata;
23516
- const tool = meta3 && isRecord13(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
24045
+ const meta3 = isRecord14(update._meta) ? update._meta : metadata;
24046
+ const tool = meta3 && isRecord14(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23517
24047
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
23518
24048
  }
23519
24049
  function errorText(error53) {
@@ -23569,7 +24099,7 @@ function signalProcessTree(child, signal) {
23569
24099
  try {
23570
24100
  process.kill(-child.pid, signal);
23571
24101
  } catch (error53) {
23572
- if (!isRecord13(error53) || error53.code !== "ESRCH")
24102
+ if (!isRecord14(error53) || error53.code !== "ESRCH")
23573
24103
  throw error53;
23574
24104
  }
23575
24105
  }
@@ -23612,6 +24142,14 @@ function transportEvent(update, metadata) {
23612
24142
  const subagent = grokSubagentEventFromUpdate(extension);
23613
24143
  if (subagent)
23614
24144
  return subagent;
24145
+ const resolvedToolCallId = grokElicitationResolvedToolCallId(extension);
24146
+ if (resolvedToolCallId) {
24147
+ return {
24148
+ type: "elicitation.resolved",
24149
+ toolCallId: resolvedToolCallId,
24150
+ ...metadata ? { metadata } : {}
24151
+ };
24152
+ }
23615
24153
  switch (update.sessionUpdate) {
23616
24154
  case "user_message_chunk":
23617
24155
  case "agent_message_chunk":
@@ -23659,34 +24197,34 @@ function transportEvent(update, metadata) {
23659
24197
  }
23660
24198
  function grokHomeDir(options) {
23661
24199
  const environment = { ...process.env, ...options.environment };
23662
- const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23663
- return environment.GROK_HOME ?? path13.join(home, ".grok");
24200
+ const home = environment.HOME ?? environment.USERPROFILE ?? os6.homedir();
24201
+ return environment.GROK_HOME ?? path15.join(home, ".grok");
23664
24202
  }
23665
24203
  function grokNativeSessionDirectory(options, sessionId) {
23666
- return path13.join(grokHomeDir(options), "sessions", encodeURIComponent(path13.resolve(options.cwd)), sessionId);
24204
+ return path15.join(grokHomeDir(options), "sessions", encodeURIComponent(path15.resolve(options.cwd)), sessionId);
23667
24205
  }
23668
24206
  function nativeSessionFile(options, sessionId, fileName) {
23669
- return path13.join(grokNativeSessionDirectory(options, sessionId), fileName);
24207
+ return path15.join(grokNativeSessionDirectory(options, sessionId), fileName);
23670
24208
  }
23671
24209
  function nativeHistoryPath(options, sessionId) {
23672
24210
  return nativeSessionFile(options, sessionId, "updates.jsonl");
23673
24211
  }
23674
24212
  async function readNativeSignals(options, sessionId) {
23675
24213
  try {
23676
- return JSON.parse(await readFile3(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
24214
+ return JSON.parse(await readFile4(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23677
24215
  } catch {
23678
24216
  return void 0;
23679
24217
  }
23680
24218
  }
23681
24219
  function isMissingFile(error53) {
23682
- return isRecord13(error53) && error53.code === "ENOENT";
24220
+ return isRecord14(error53) && error53.code === "ENOENT";
23683
24221
  }
23684
24222
  async function locateGrokNativeSession(options, sessionId) {
23685
24223
  if (sessionId.length === 0)
23686
24224
  return null;
23687
24225
  let entries;
23688
24226
  try {
23689
- entries = await readdir(path13.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
24227
+ entries = await readdir(path15.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23690
24228
  } catch (error53) {
23691
24229
  if (isMissingFile(error53))
23692
24230
  return null;
@@ -23700,9 +24238,9 @@ async function locateGrokNativeSession(options, sessionId) {
23700
24238
  continue;
23701
24239
  let summaryRaw;
23702
24240
  try {
23703
- summaryRaw = await readFile3(path13.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
24241
+ summaryRaw = await readFile4(path15.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23704
24242
  } catch (error53) {
23705
- if (isMissingFile(error53) || isRecord13(error53) && error53.code === "ENOTDIR")
24243
+ if (isMissingFile(error53) || isRecord14(error53) && error53.code === "ENOTDIR")
23706
24244
  continue;
23707
24245
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
23708
24246
  cause: error53
@@ -23714,11 +24252,11 @@ async function locateGrokNativeSession(options, sessionId) {
23714
24252
  } catch {
23715
24253
  continue;
23716
24254
  }
23717
- if (!isRecord13(parsed))
24255
+ if (!isRecord14(parsed))
23718
24256
  continue;
23719
24257
  const info = parsed.info;
23720
- const cwd = isRecord13(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path13.resolve(info.cwd) : path13.resolve(decodeURIComponent(entry.name));
23721
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path13.resolve(parsed.source_workspace_dir) : void 0;
24258
+ const cwd = isRecord14(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path15.resolve(info.cwd) : path15.resolve(decodeURIComponent(entry.name));
24259
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path15.resolve(parsed.source_workspace_dir) : void 0;
23722
24260
  matches.push({
23723
24261
  cwd,
23724
24262
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23728,7 +24266,7 @@ async function locateGrokNativeSession(options, sessionId) {
23728
24266
  }
23729
24267
  async function readGrokNativeHistory(options, sessionId) {
23730
24268
  try {
23731
- return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path13.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
24269
+ return parseNativeHistory(await readFile4(nativeHistoryPath({ ...options, cwd: path15.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23732
24270
  } catch (error53) {
23733
24271
  if (isMissingFile(error53))
23734
24272
  return [];
@@ -23750,12 +24288,12 @@ function parseNativeHistory(contents, sessionId) {
23750
24288
  } catch {
23751
24289
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23752
24290
  }
23753
- if (!isRecord13(record2) || !isRecord13(record2.params))
24291
+ if (!isRecord14(record2) || !isRecord14(record2.params))
23754
24292
  continue;
23755
24293
  const params = record2.params;
23756
- if (params.sessionId !== sessionId || !isRecord13(params.update))
24294
+ if (params.sessionId !== sessionId || !isRecord14(params.update))
23757
24295
  continue;
23758
- const metadata = isRecord13(params._meta) ? params._meta : void 0;
24296
+ const metadata = isRecord14(params._meta) ? params._meta : void 0;
23759
24297
  const event = transportEvent(params.update, metadata);
23760
24298
  if (event)
23761
24299
  events.push(metadata ? { ...event, metadata } : event);
@@ -23817,7 +24355,7 @@ var GrokAcpTransport = class {
23817
24355
  if (!this.#connection)
23818
24356
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
23819
24357
  const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
23820
- return isRecord13(result) ? result.usage : void 0;
24358
+ return isRecord14(result) ? result.usage : void 0;
23821
24359
  }
23822
24360
  async readHistory(sessionId, cwd = this.#options.cwd) {
23823
24361
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -23987,6 +24525,7 @@ var GrokAcpTransport = class {
23987
24525
  const connection = new ClientSideConnection(() => ({
23988
24526
  sessionUpdate: (params) => this.#handleUpdate(params),
23989
24527
  requestPermission: (params) => this.#handlePermission(params),
24528
+ extMethod: (method, params) => this.#handleExtMethod(method, params),
23990
24529
  extNotification: (method, params) => this.#handleExtensionNotification(method, params)
23991
24530
  }), stream);
23992
24531
  this.#connection = connection;
@@ -24007,14 +24546,14 @@ var GrokAcpTransport = class {
24007
24546
  this.#initialize = initialize;
24008
24547
  return initialize;
24009
24548
  }
24010
- async runTurn(text, onEvent, onPermission) {
24549
+ async runTurn(text, onEvent, onPermission, onElicitation) {
24011
24550
  const connection = this.#connection;
24012
24551
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
24013
24552
  throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
24014
24553
  }
24015
24554
  if (this.#activePrompt)
24016
24555
  throw new Error("Grok ACP Session already has an active Prompt");
24017
- const active = { onEvent, onPermission };
24556
+ const active = { onEvent, onPermission, onElicitation };
24018
24557
  this.#activePrompt = active;
24019
24558
  try {
24020
24559
  return await connection.prompt({
@@ -24075,7 +24614,7 @@ var GrokAcpTransport = class {
24075
24614
  }
24076
24615
  } : {}
24077
24616
  });
24078
- if (!isRecord13(response) || !isRecord13(response._meta) || !isRecord13(response._meta.model)) {
24617
+ if (!isRecord14(response) || !isRecord14(response._meta) || !isRecord14(response._meta.model)) {
24079
24618
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
24080
24619
  }
24081
24620
  const selected = response._meta.model.Ok;
@@ -24127,7 +24666,7 @@ var GrokAcpTransport = class {
24127
24666
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
24128
24667
  return;
24129
24668
  }
24130
- const metadata = isRecord13(notification._meta) ? notification._meta : void 0;
24669
+ const metadata = isRecord14(notification._meta) ? notification._meta : void 0;
24131
24670
  const event = transportEvent(notification.update, metadata);
24132
24671
  if (!event)
24133
24672
  return;
@@ -24142,7 +24681,7 @@ var GrokAcpTransport = class {
24142
24681
  #handleExtensionNotification(method, params) {
24143
24682
  if (!isGrokExtensionSessionUpdateMethod(method))
24144
24683
  return;
24145
- if (typeof params.sessionId !== "string" || !isRecord13(params.update))
24684
+ if (typeof params.sessionId !== "string" || !isRecord14(params.update))
24146
24685
  return;
24147
24686
  this.#handleUpdate(params);
24148
24687
  }
@@ -24152,6 +24691,22 @@ var GrokAcpTransport = class {
24152
24691
  }
24153
24692
  return this.#activePrompt.onPermission({ request: params, options: params.options });
24154
24693
  }
24694
+ async #handleExtMethod(method, params) {
24695
+ if (method !== GROK_MCP_ELICIT_METHOD) {
24696
+ throw RequestError.methodNotFound(method);
24697
+ }
24698
+ const parsed = parseGrokMcpElicitParams(params);
24699
+ if (parsed.status === "invalid") {
24700
+ throw RequestError.invalidParams(void 0, parsed.message);
24701
+ }
24702
+ if (parsed.status === "unsupported" || this.#closed || this.#closing || this.#replay !== null || this.#activeCompact !== null || !this.#activePrompt) {
24703
+ return { ...grokMcpElicitCancel() };
24704
+ }
24705
+ if (parsed.request.sessionId !== this.#sessionId) {
24706
+ return { ...grokMcpElicitCancel() };
24707
+ }
24708
+ return { ...await this.#activePrompt.onElicitation(parsed.request) };
24709
+ }
24155
24710
  #fault(error53) {
24156
24711
  if (this.#closing || this.#closed)
24157
24712
  return;
@@ -24161,8 +24716,8 @@ var GrokAcpTransport = class {
24161
24716
 
24162
24717
  // dist/session-import.js
24163
24718
  import { createReadStream as createReadStream2 } from "node:fs";
24164
- import { opendir as opendir2, readFile as readFile4, stat } from "node:fs/promises";
24165
- import path14 from "node:path";
24719
+ import { opendir as opendir2, readFile as readFile5, stat } from "node:fs/promises";
24720
+ import path16 from "node:path";
24166
24721
  import { createInterface as createInterface2 } from "node:readline";
24167
24722
 
24168
24723
  // ../../harness-adapter/dist/session-import.js
@@ -24283,11 +24838,11 @@ var SessionImportScope = class {
24283
24838
  // dist/session-import.js
24284
24839
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
24285
24840
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
24286
- function isRecord14(value) {
24841
+ function isRecord15(value) {
24287
24842
  return typeof value === "object" && value !== null && !Array.isArray(value);
24288
24843
  }
24289
24844
  async function readJson(file2, signal) {
24290
- return JSON.parse(await readFile4(file2, { encoding: "utf8", signal }));
24845
+ return JSON.parse(await readFile5(file2, { encoding: "utf8", signal }));
24291
24846
  }
24292
24847
  function processAlive(pid) {
24293
24848
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -24296,7 +24851,7 @@ function processAlive(pid) {
24296
24851
  process.kill(pid, 0);
24297
24852
  return true;
24298
24853
  } catch (error53) {
24299
- return isRecord14(error53) && error53.code === "EPERM";
24854
+ return isRecord15(error53) && error53.code === "EPERM";
24300
24855
  }
24301
24856
  }
24302
24857
  async function firstUserText(file2, signal) {
@@ -24313,10 +24868,10 @@ async function firstUserText(file2, signal) {
24313
24868
  } catch {
24314
24869
  continue;
24315
24870
  }
24316
- const update = isRecord14(entry) && isRecord14(entry.params) ? entry.params.update : null;
24317
- if (!isRecord14(update) || update.sessionUpdate !== "user_message_chunk")
24871
+ const update = isRecord15(entry) && isRecord15(entry.params) ? entry.params.update : null;
24872
+ if (!isRecord15(update) || update.sessionUpdate !== "user_message_chunk")
24318
24873
  continue;
24319
- const text = isRecord14(update.content) ? update.content.text : null;
24874
+ const text = isRecord15(update.content) ? update.content.text : null;
24320
24875
  return typeof text === "string" ? text : "";
24321
24876
  }
24322
24877
  return null;
@@ -24383,7 +24938,7 @@ var GrokSessionImport = class {
24383
24938
  const active = /* @__PURE__ */ new Set();
24384
24939
  let entries;
24385
24940
  try {
24386
- entries = await readJson(path14.join(this.#home(), "active_sessions.json"), signal);
24941
+ entries = await readJson(path16.join(this.#home(), "active_sessions.json"), signal);
24387
24942
  } catch (error53) {
24388
24943
  signal.throwIfAborted();
24389
24944
  if (isStorageAccessError(error53))
@@ -24393,14 +24948,14 @@ var GrokSessionImport = class {
24393
24948
  if (!Array.isArray(entries))
24394
24949
  return active;
24395
24950
  for (const entry of entries) {
24396
- if (isRecord14(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24951
+ if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24397
24952
  active.add(entry.session_id);
24398
24953
  }
24399
24954
  return active;
24400
24955
  }
24401
24956
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
24402
24957
  async #sessionDirectories(signal) {
24403
- const root = path14.join(this.#home(), "sessions");
24958
+ const root = path16.join(this.#home(), "sessions");
24404
24959
  const found = /* @__PURE__ */ new Map();
24405
24960
  const info = await optionalLstat(root);
24406
24961
  if (!info)
@@ -24411,7 +24966,7 @@ var GrokSessionImport = class {
24411
24966
  signal.throwIfAborted();
24412
24967
  if (!workspace.isDirectory())
24413
24968
  continue;
24414
- const workspaceDirectory = path14.join(root, workspace.name);
24969
+ const workspaceDirectory = path16.join(root, workspace.name);
24415
24970
  const sessions = await opendir2(workspaceDirectory).catch((error53) => {
24416
24971
  if (isMissingFileError(error53))
24417
24972
  return null;
@@ -24424,7 +24979,7 @@ var GrokSessionImport = class {
24424
24979
  if (!session.isDirectory())
24425
24980
  continue;
24426
24981
  const directories = found.get(session.name) ?? [];
24427
- directories.push(path14.join(workspaceDirectory, session.name));
24982
+ directories.push(path16.join(workspaceDirectory, session.name));
24428
24983
  found.set(session.name, directories);
24429
24984
  }
24430
24985
  }
@@ -24432,25 +24987,25 @@ var GrokSessionImport = class {
24432
24987
  }
24433
24988
  async #candidate(sessionDirectory, active, signal) {
24434
24989
  signal.throwIfAborted();
24435
- const nativeSessionId = path14.basename(sessionDirectory);
24990
+ const nativeSessionId = path16.basename(sessionDirectory);
24436
24991
  const files = [
24437
- path14.join(sessionDirectory, "summary.json"),
24438
- path14.join(sessionDirectory, "updates.jsonl")
24992
+ path16.join(sessionDirectory, "summary.json"),
24993
+ path16.join(sessionDirectory, "updates.jsonl")
24439
24994
  ];
24440
24995
  return readStableFiles(files, async ([summaryInfo, updates]) => {
24441
24996
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24442
24997
  return null;
24443
24998
  try {
24444
24999
  const summary = await readJson(files[0], signal);
24445
- if (!isRecord14(summary) || !isRecord14(summary.info) || summary.info.id !== nativeSessionId)
25000
+ if (!isRecord15(summary) || !isRecord15(summary.info) || summary.info.id !== nativeSessionId)
24446
25001
  return null;
24447
25002
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24448
25003
  return null;
24449
25004
  const nativeCwd = summary.info.cwd;
24450
- if (typeof nativeCwd !== "string" || !path14.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
25005
+ if (typeof nativeCwd !== "string" || !path16.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24451
25006
  return null;
24452
- const cwd = path14.resolve(nativeCwd);
24453
- if (encodeURIComponent(cwd) !== path14.basename(path14.dirname(sessionDirectory)))
25007
+ const cwd = path16.resolve(nativeCwd);
25008
+ if (encodeURIComponent(cwd) !== path16.basename(path16.dirname(sessionDirectory)))
24454
25009
  return null;
24455
25010
  if (!(await stat(cwd)).isDirectory())
24456
25011
  return null;
@@ -24669,7 +25224,7 @@ var GrokSubagentLifecycle = class {
24669
25224
  };
24670
25225
 
24671
25226
  // dist/grok-models.js
24672
- function isRecord15(value) {
25227
+ function isRecord16(value) {
24673
25228
  return typeof value === "object" && value !== null && !Array.isArray(value);
24674
25229
  }
24675
25230
  function nonBlank(value) {
@@ -24681,7 +25236,7 @@ function thinkingOptions(value) {
24681
25236
  const seen = /* @__PURE__ */ new Set();
24682
25237
  const options = [];
24683
25238
  for (const candidate of value) {
24684
- if (!isRecord15(candidate) || !nonBlank(candidate.label))
25239
+ if (!isRecord16(candidate) || !nonBlank(candidate.label))
24685
25240
  continue;
24686
25241
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
24687
25242
  if (!id.success || seen.has(id.data))
@@ -24692,7 +25247,7 @@ function thinkingOptions(value) {
24692
25247
  return options;
24693
25248
  }
24694
25249
  function parseGrokModelState(value) {
24695
- if (!isRecord15(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
25250
+ if (!isRecord16(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24696
25251
  return null;
24697
25252
  }
24698
25253
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -24704,12 +25259,12 @@ function parseGrokModelState(value) {
24704
25259
  const models = [];
24705
25260
  let currentThinkingOptionId;
24706
25261
  for (const candidate of value.availableModels) {
24707
- if (!isRecord15(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
25262
+ if (!isRecord16(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24708
25263
  continue;
24709
25264
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
24710
25265
  if (!ref.success)
24711
25266
  continue;
24712
- const metadata = isRecord15(candidate._meta) ? candidate._meta : {};
25267
+ const metadata = isRecord16(candidate._meta) ? candidate._meta : {};
24713
25268
  const options2 = thinkingOptions(metadata.reasoningEfforts);
24714
25269
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
24715
25270
  defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
@@ -24748,10 +25303,10 @@ function parseGrokModelState(value) {
24748
25303
  };
24749
25304
  }
24750
25305
  function modelStateFromInitialize(response) {
24751
- return parseGrokModelState(isRecord15(response._meta) ? response._meta.modelState : void 0);
25306
+ return parseGrokModelState(isRecord16(response._meta) ? response._meta.modelState : void 0);
24752
25307
  }
24753
25308
  function modelStateFromSessionResponse(response) {
24754
- return parseGrokModelState(isRecord15(response) ? response.models : void 0);
25309
+ return parseGrokModelState(isRecord16(response) ? response.models : void 0);
24755
25310
  }
24756
25311
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24757
25312
  const selectedModel = model2;
@@ -24770,12 +25325,12 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
24770
25325
  }
24771
25326
 
24772
25327
  // dist/grok-credits.js
24773
- import { readFile as readFile5 } from "node:fs/promises";
24774
- import os6 from "node:os";
24775
- import path15 from "node:path";
25328
+ import { readFile as readFile6 } from "node:fs/promises";
25329
+ import os7 from "node:os";
25330
+ import path17 from "node:path";
24776
25331
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
24777
25332
  var REQUEST_TIMEOUT_MS = 15e3;
24778
- function isRecord16(value) {
25333
+ function isRecord17(value) {
24779
25334
  return typeof value === "object" && value !== null && !Array.isArray(value);
24780
25335
  }
24781
25336
  function finitePercent(value) {
@@ -24784,15 +25339,15 @@ function finitePercent(value) {
24784
25339
  return Math.min(100, Math.max(0, value));
24785
25340
  }
24786
25341
  function nonNegativeCentValue(value) {
24787
- if (!isRecord16(value))
25342
+ if (!isRecord17(value))
24788
25343
  return void 0;
24789
25344
  const amount = value.val === void 0 ? 0 : value.val;
24790
25345
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
24791
25346
  return void 0;
24792
25347
  return amount;
24793
25348
  }
24794
- function grokHome2(environment) {
24795
- return environment.GROK_HOME ?? path15.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
25349
+ function grokHome3(environment) {
25350
+ return environment.GROK_HOME ?? path17.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
24796
25351
  }
24797
25352
  function periodTypeFrom(value) {
24798
25353
  if (typeof value !== "string")
@@ -24808,7 +25363,7 @@ function productUsageFrom(value) {
24808
25363
  if (!Array.isArray(value))
24809
25364
  return void 0;
24810
25365
  const products = value.flatMap((entry) => {
24811
- if (!isRecord16(entry) || typeof entry.product !== "string")
25366
+ if (!isRecord17(entry) || typeof entry.product !== "string")
24812
25367
  return [];
24813
25368
  const usagePercent = finitePercent(entry.usagePercent);
24814
25369
  const labels = {
@@ -24829,10 +25384,10 @@ function productUsageFrom(value) {
24829
25384
  return products.length > 0 ? products : void 0;
24830
25385
  }
24831
25386
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24832
- if (!isRecord16(value) || !isRecord16(value.config))
25387
+ if (!isRecord17(value) || !isRecord17(value.config))
24833
25388
  return null;
24834
25389
  const config2 = value.config;
24835
- const period = isRecord16(config2.currentPeriod) ? config2.currentPeriod : void 0;
25390
+ const period = isRecord17(config2.currentPeriod) ? config2.currentPeriod : void 0;
24836
25391
  const periodType = periodTypeFrom(period?.type);
24837
25392
  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);
24838
25393
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24859,11 +25414,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24859
25414
  };
24860
25415
  }
24861
25416
  function selectAccessToken(auth, now) {
24862
- if (!isRecord16(auth))
25417
+ if (!isRecord17(auth))
24863
25418
  return null;
24864
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord16(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
25419
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord17(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
24865
25420
  for (const [, value] of entries) {
24866
- if (!isRecord16(value) || typeof value.key !== "string")
25421
+ if (!isRecord17(value) || typeof value.key !== "string")
24867
25422
  continue;
24868
25423
  if (typeof value.expires_at === "string") {
24869
25424
  const expiresAt = Date.parse(value.expires_at);
@@ -24884,8 +25439,8 @@ async function fetchGrokAccount(input = {}) {
24884
25439
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24885
25440
  return null;
24886
25441
  const now = input.now ?? /* @__PURE__ */ new Date();
24887
- const authPath = path15.join(grokHome2(environment), "auth.json");
24888
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile5(authPath, "utf8");
25442
+ const authPath = path17.join(grokHome3(environment), "auth.json");
25443
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile6(authPath, "utf8");
24889
25444
  const token = selectAccessToken(JSON.parse(raw), now);
24890
25445
  if (!token)
24891
25446
  return null;
@@ -24934,7 +25489,7 @@ async function fetchGrokCredits(input = {}) {
24934
25489
 
24935
25490
  // dist/grok-usage.js
24936
25491
  var USD_TICKS_PER_DOLLAR = 1e10;
24937
- function isRecord17(value) {
25492
+ function isRecord18(value) {
24938
25493
  return typeof value === "object" && value !== null && !Array.isArray(value);
24939
25494
  }
24940
25495
  function optionalToken(value) {
@@ -24951,7 +25506,7 @@ function combineUsage(base, next) {
24951
25506
  return base === null ? next : parseHostUsage({ ...base, ...next });
24952
25507
  }
24953
25508
  function usageFromNative(value) {
24954
- if (!isRecord17(value))
25509
+ if (!isRecord18(value))
24955
25510
  return null;
24956
25511
  const inputTokens = optionalToken(value.inputTokens);
24957
25512
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24975,7 +25530,7 @@ function usageFromNative(value) {
24975
25530
  }
24976
25531
  }
24977
25532
  function usageFromResponse(value) {
24978
- if (!isRecord17(value))
25533
+ if (!isRecord18(value))
24979
25534
  return null;
24980
25535
  const buckets = [
24981
25536
  value.input_tokens,
@@ -25075,7 +25630,7 @@ var GrokTurnUsage = class {
25075
25630
  }
25076
25631
  };
25077
25632
  function usageFromSignals(value) {
25078
- if (!isRecord17(value))
25633
+ if (!isRecord18(value))
25079
25634
  return null;
25080
25635
  try {
25081
25636
  return parseHostUsage({
@@ -25095,7 +25650,7 @@ var summedUsageFields = [
25095
25650
  "totalTokens"
25096
25651
  ];
25097
25652
  function nativeCostTicks(value) {
25098
- if (!isRecord17(value))
25653
+ if (!isRecord18(value))
25099
25654
  return void 0;
25100
25655
  const ticks = value.costUsdTicks;
25101
25656
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -25103,7 +25658,7 @@ function nativeCostTicks(value) {
25103
25658
  return ticks;
25104
25659
  }
25105
25660
  function sessionCostFromNative(value, initialCostUsd) {
25106
- if (!isRecord17(value))
25661
+ if (!isRecord18(value))
25107
25662
  return void 0;
25108
25663
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
25109
25664
  return void 0;
@@ -25132,7 +25687,7 @@ function sessionUsageFromHistory(events) {
25132
25687
  continue;
25133
25688
  const usage = usageFromNative(event.usage);
25134
25689
  const ticks2 = nativeCostTicks(event.usage);
25135
- const complete = isRecord17(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
25690
+ const complete = isRecord18(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
25136
25691
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
25137
25692
  }
25138
25693
  if (latestByKey.size === 0)
@@ -25186,7 +25741,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
25186
25741
  function usageFromUpdate(update, metadata, contextWindowTokens) {
25187
25742
  try {
25188
25743
  if (update?.sessionUpdate === "usage_update") {
25189
- const cost = isRecord17(update.cost) ? update.cost : null;
25744
+ const cost = isRecord18(update.cost) ? update.cost : null;
25190
25745
  return parseHostUsage({
25191
25746
  contextUsedTokens: update.used,
25192
25747
  contextWindowTokens: update.size,
@@ -25436,6 +25991,7 @@ var GrokHarnessSession = class {
25436
25991
  subagents: this.#createSubagents(),
25437
25992
  completedItems: [],
25438
25993
  approvals: /* @__PURE__ */ new Map(),
25994
+ elicitations: /* @__PURE__ */ new Map(),
25439
25995
  cancellationRequested: false,
25440
25996
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
25441
25997
  completion,
@@ -25443,7 +25999,7 @@ var GrokHarnessSession = class {
25443
25999
  };
25444
26000
  this.#active = active;
25445
26001
  this.#event({ type: "turn.started", turnId: command.turnId });
25446
- void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request)).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
26002
+ void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestElicitation(active, request)).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
25447
26003
  status: "failed",
25448
26004
  error: normalizeError(error53, "nativeFailure")
25449
26005
  }));
@@ -25525,6 +26081,7 @@ var GrokHarnessSession = class {
25525
26081
  subagents: this.#createSubagents(),
25526
26082
  completedItems: [],
25527
26083
  approvals: /* @__PURE__ */ new Map(),
26084
+ elicitations: /* @__PURE__ */ new Map(),
25528
26085
  cancellationRequested: false,
25529
26086
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
25530
26087
  completion,
@@ -25679,6 +26236,7 @@ var GrokHarnessSession = class {
25679
26236
  for (const approval of active.approvals.values()) {
25680
26237
  approval.resolve({ outcome: { outcome: "cancelled" } });
25681
26238
  }
26239
+ this.#cancelActiveElicitations(active);
25682
26240
  try {
25683
26241
  await this.#transport.cancel();
25684
26242
  return { ok: true, value: { cancellationRequested: true } };
@@ -25688,8 +26246,9 @@ var GrokHarnessSession = class {
25688
26246
  }
25689
26247
  async #respond(command) {
25690
26248
  const active = this.#active;
25691
- const pending = active?.approvals.get(command.interactionId);
25692
- if (!active || !pending)
26249
+ const permission = active?.approvals.get(command.interactionId);
26250
+ const elicitation = active?.elicitations.get(command.interactionId);
26251
+ if (!active || !permission && !elicitation)
25693
26252
  return { ok: false, error: invalidState("Grok Approval is not pending") };
25694
26253
  if (command.response.type !== "approval") {
25695
26254
  return {
@@ -25701,10 +26260,30 @@ var GrokHarnessSession = class {
25701
26260
  }
25702
26261
  };
25703
26262
  }
25704
- const validation = validateHostApprovalResponse(pending.interaction, command.response);
26263
+ const response = command.response;
26264
+ if (elicitation) {
26265
+ const validation2 = validateHostApprovalResponse(elicitation.interaction, response);
26266
+ if (validation2)
26267
+ return { ok: false, error: validation2 };
26268
+ const action = elicitation.interaction.actions.find(({ id }) => id === response.actionId);
26269
+ if (!action)
26270
+ return {
26271
+ ok: false,
26272
+ error: {
26273
+ code: "invalidRequest",
26274
+ message: "Grok Approval action is unavailable",
26275
+ retryable: false
26276
+ }
26277
+ };
26278
+ this.#settleElicitation(active, elicitation, grokMcpElicitResponseForAction(action.effect === "allowOnce" || action.effect === "allowAlways" ? action.effect : "deny"), "responded");
26279
+ return { ok: true, value: { accepted: true } };
26280
+ }
26281
+ if (!permission)
26282
+ return { ok: false, error: invalidState("Grok Approval is not pending") };
26283
+ const validation = validateHostApprovalResponse(permission.interaction, response);
25705
26284
  if (validation)
25706
26285
  return { ok: false, error: validation };
25707
- const option = pending.options.get(command.response.actionId);
26286
+ const option = permission.options.get(response.actionId);
25708
26287
  if (!option)
25709
26288
  return {
25710
26289
  ok: false,
@@ -25715,7 +26294,7 @@ var GrokHarnessSession = class {
25715
26294
  }
25716
26295
  };
25717
26296
  active.approvals.delete(command.interactionId);
25718
- pending.resolve({ outcome: { outcome: "selected", optionId: option.optionId } });
26297
+ permission.resolve({ outcome: { outcome: "selected", optionId: option.optionId } });
25719
26298
  this.#event({
25720
26299
  type: "interaction.closed",
25721
26300
  interactionId: command.interactionId,
@@ -25744,10 +26323,57 @@ var GrokHarnessSession = class {
25744
26323
  actions
25745
26324
  };
25746
26325
  return new Promise((resolve) => {
25747
- active.approvals.set(interactionId, { interaction, options, resolve });
26326
+ active.approvals.set(interactionId, {
26327
+ kind: "permission",
26328
+ interaction,
26329
+ options,
26330
+ resolve
26331
+ });
25748
26332
  this.#channel.emit({ kind: "interaction", interaction });
25749
26333
  });
25750
26334
  }
26335
+ #requestElicitation(active, request) {
26336
+ if (this.#active !== active || this.#phase !== "open" || active.cancellationRequested) {
26337
+ return Promise.resolve(grokMcpElicitCancel());
26338
+ }
26339
+ for (const pending of active.elicitations.values()) {
26340
+ if (pending.nativeToolCallId === request.toolCallId) {
26341
+ return Promise.resolve(grokMcpElicitCancel());
26342
+ }
26343
+ }
26344
+ const interactionId = hostInteractionIdSchema.parse(this.#randomUUID());
26345
+ const interaction = projectGrokMcpElicitApproval({
26346
+ interactionId,
26347
+ turnId: active.command.turnId,
26348
+ request
26349
+ });
26350
+ return new Promise((resolve) => {
26351
+ active.elicitations.set(interactionId, {
26352
+ kind: "elicitation",
26353
+ nativeToolCallId: request.toolCallId,
26354
+ interaction,
26355
+ resolve
26356
+ });
26357
+ this.#channel.emit({ kind: "interaction", interaction });
26358
+ });
26359
+ }
26360
+ #settleElicitation(active, pending, response, reason) {
26361
+ if (!active.elicitations.has(pending.interaction.interactionId))
26362
+ return;
26363
+ active.elicitations.delete(pending.interaction.interactionId);
26364
+ pending.resolve(response);
26365
+ this.#event({
26366
+ type: "interaction.closed",
26367
+ interactionId: pending.interaction.interactionId,
26368
+ turnId: active.command.turnId,
26369
+ reason
26370
+ });
26371
+ }
26372
+ #cancelActiveElicitations(active) {
26373
+ for (const pending of [...active.elicitations.values()]) {
26374
+ this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
26375
+ }
26376
+ }
25751
26377
  #handleEvent(active, event) {
25752
26378
  if (this.#active !== active || this.#phase !== "open")
25753
26379
  return;
@@ -25776,6 +26402,12 @@ var GrokHarnessSession = class {
25776
26402
  else if (event.type === "compaction.completed") {
25777
26403
  active.compactionTerminal = event;
25778
26404
  this.#completeCompaction(active, event);
26405
+ } else if (event.type === "elicitation.resolved") {
26406
+ for (const pending of [...active.elicitations.values()]) {
26407
+ if (pending.nativeToolCallId === event.toolCallId) {
26408
+ this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
26409
+ }
26410
+ }
25779
26411
  } else if (event.type === "usage" || event.type === "turn.completed")
25780
26412
  return;
25781
26413
  }
@@ -26184,6 +26816,7 @@ var GrokHarnessSession = class {
26184
26816
  reason: "cancelled"
26185
26817
  });
26186
26818
  }
26819
+ this.#cancelActiveElicitations(active);
26187
26820
  this.#active = null;
26188
26821
  if (usage || this.#usage)
26189
26822
  this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
@@ -26221,6 +26854,7 @@ var GrokHarnessSession = class {
26221
26854
  active.cancellationRequested = true;
26222
26855
  for (const approval of active.approvals.values())
26223
26856
  approval.resolve({ outcome: { outcome: "cancelled" } });
26857
+ this.#cancelActiveElicitations(active);
26224
26858
  await this.#transport.cancel().catch(() => void 0);
26225
26859
  await Promise.race([
26226
26860
  active.completion,
@@ -26312,7 +26946,7 @@ var GrokAdapter = class {
26312
26946
  this.usageStatistics = createGrokUsageStatistics(options.environment ?? process.env);
26313
26947
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
26314
26948
  this.#dependencies = dependencies ?? {
26315
- randomUUID,
26949
+ randomUUID: randomUUID2,
26316
26950
  createTransport: (transportOptions) => new GrokAcpTransport({ ...options, ...transportOptions })
26317
26951
  };
26318
26952
  this.#fetchCredits = this.#dependencies.fetchCredits ?? ((input) => fetchGrokCredits(input.environment ? { environment: input.environment } : this.#environment ? { environment: this.#environment } : {}));
@@ -26358,7 +26992,7 @@ var GrokAdapter = class {
26358
26992
  async inspect(input = {}) {
26359
26993
  if (this.#closePromise)
26360
26994
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
26361
- const cwd = path16.resolve(input.cwd ?? process.cwd());
26995
+ const cwd = path18.resolve(input.cwd ?? process.cwd());
26362
26996
  if (!input.refresh) {
26363
26997
  const cached2 = this.#inspectionCache.get(cwd);
26364
26998
  if (cached2)
@@ -26420,7 +27054,20 @@ var GrokAdapter = class {
26420
27054
  }
26421
27055
  };
26422
27056
  }
26423
- const cwd = path16.resolve(input.cwd);
27057
+ try {
27058
+ await applyGrokComputerUsePreference(this.#environment ?? process.env);
27059
+ } catch {
27060
+ console.warn("Could not apply Grok Computer Use settings");
27061
+ return {
27062
+ ok: false,
27063
+ error: {
27064
+ code: "unavailable",
27065
+ message: "Could not apply Grok Computer Use settings. Retry after fixing Grok config.",
27066
+ retryable: true
27067
+ }
27068
+ };
27069
+ }
27070
+ const cwd = path18.resolve(input.cwd);
26424
27071
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
26425
27072
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
26426
27073
  return {