@karlorz/codexhost-cli-darwin-x64 0.13.3-6 → 0.14.0-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 (33) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +539 -95
  4. package/app/console-web.js +879 -73
  5. package/app/cpa-live-voice-hook.js +605 -37
  6. package/app/desktop-controller.mjs +94 -9
  7. package/app/host-runtime.mjs +1662 -642
  8. package/app/plugins/antigravity/plugin.mjs +113 -13
  9. package/app/plugins/claude-code/plugin.mjs +429 -26
  10. package/app/plugins/codebuddy/plugin.mjs +139 -22
  11. package/app/plugins/codex-usage/plugin.mjs +198 -74
  12. package/app/plugins/copilot/assets/icon.png +0 -0
  13. package/app/plugins/copilot/manifest.json +26 -0
  14. package/app/plugins/copilot/plugin.mjs +34645 -0
  15. package/app/plugins/cursor-cli/plugin.mjs +20877 -44973
  16. package/app/plugins/deepseek-harness/plugin.mjs +105 -11
  17. package/app/plugins/enabled.json +1 -0
  18. package/app/plugins/grok/plugin.mjs +1073 -214
  19. package/app/plugins/hermes/plugin.mjs +102 -9
  20. package/app/plugins/kimi-code/plugin.mjs +98 -7
  21. package/app/plugins/kiro-cli/plugin.mjs +98 -7
  22. package/app/plugins/omp/plugin.mjs +2177 -2000
  23. package/app/plugins/opencode/plugin.mjs +107 -11
  24. package/app/plugins/pi/plugin.mjs +2554 -2285
  25. package/app/plugins/qoder/plugin.mjs +105 -11
  26. package/app/plugins/qoder-cn/plugin.mjs +105 -11
  27. package/app/plugins/workbuddy/plugin.mjs +400 -46
  28. package/app/plugins/zcode/plugin.mjs +106 -11
  29. package/app/renderer-extension.js +2717 -1237
  30. package/bin/codexhost +0 -0
  31. package/libexec/codexhost-shim +0 -0
  32. package/libexec/codexhost-updater +0 -0
  33. package/package.json +1 -1
@@ -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,46 +579,10 @@ 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
- // dist/grok-credential-export.js
584
+ // dist/grok-text-item-id.js
582
585
  import { createHash } from "node:crypto";
583
- import { readFile as readFile2 } from "node:fs/promises";
584
- import os3 from "node:os";
585
- import path6 from "node:path";
586
- async function readGrokCredentials(environment) {
587
- if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
588
- return [];
589
- try {
590
- const home = environment.GROK_HOME ?? path6.join(environment.HOME ?? os3.homedir(), ".grok");
591
- const auth = JSON.parse(await readFile2(path6.join(home, "auth.json"), "utf8"));
592
- const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
593
- const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
594
- if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
595
- return [];
596
- if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
597
- return [];
598
- const expires = Date.parse(entry.expires_at);
599
- if (!Number.isFinite(expires))
600
- return [];
601
- return [
602
- {
603
- source: {
604
- id: `grok:${createHash("sha256").update(entry.user_id).digest("hex")}`,
605
- harnessId: "grok",
606
- provider: "xai",
607
- label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
608
- },
609
- oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
610
- }
611
- ];
612
- } catch {
613
- return [];
614
- }
615
- }
616
-
617
- // dist/grok-adapter.js
618
- import path16 from "node:path";
619
586
 
620
587
  // ../../../node_modules/zod/v4/classic/external.js
621
588
  var external_exports = {};
@@ -1383,10 +1350,10 @@ function mergeDefs(...defs) {
1383
1350
  function cloneDef(schema) {
1384
1351
  return mergeDefs(schema._zod.def);
1385
1352
  }
1386
- function getElementAtPath(obj, path17) {
1387
- if (!path17)
1353
+ function getElementAtPath(obj, path19) {
1354
+ if (!path19)
1388
1355
  return obj;
1389
- return path17.reduce((acc, key) => acc?.[key], obj);
1356
+ return path19.reduce((acc, key) => acc?.[key], obj);
1390
1357
  }
1391
1358
  function promiseAllObject(promisesObj) {
1392
1359
  const keys = Object.keys(promisesObj);
@@ -1795,11 +1762,11 @@ function explicitlyAborted(x, startIndex = 0) {
1795
1762
  }
1796
1763
  return false;
1797
1764
  }
1798
- function prefixIssues(path17, issues) {
1765
+ function prefixIssues(path19, issues) {
1799
1766
  return issues.map((iss) => {
1800
1767
  var _a3;
1801
1768
  (_a3 = iss).path ?? (_a3.path = []);
1802
- iss.path.unshift(path17);
1769
+ iss.path.unshift(path19);
1803
1770
  return iss;
1804
1771
  });
1805
1772
  }
@@ -1946,16 +1913,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1946
1913
  }
1947
1914
  function formatError(error53, mapper = (issue2) => issue2.message) {
1948
1915
  const fieldErrors = { _errors: [] };
1949
- const processError = (error54, path17 = []) => {
1916
+ const processError = (error54, path19 = []) => {
1950
1917
  for (const issue2 of error54.issues) {
1951
1918
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1952
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1919
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1953
1920
  } else if (issue2.code === "invalid_key") {
1954
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1921
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1955
1922
  } else if (issue2.code === "invalid_element") {
1956
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1923
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1957
1924
  } else {
1958
- const fullpath = [...path17, ...issue2.path];
1925
+ const fullpath = [...path19, ...issue2.path];
1959
1926
  if (fullpath.length === 0) {
1960
1927
  fieldErrors._errors.push(mapper(issue2));
1961
1928
  } else {
@@ -1982,17 +1949,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1982
1949
  }
1983
1950
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1984
1951
  const result = { errors: [] };
1985
- const processError = (error54, path17 = []) => {
1952
+ const processError = (error54, path19 = []) => {
1986
1953
  var _a3, _b;
1987
1954
  for (const issue2 of error54.issues) {
1988
1955
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1989
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1956
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1990
1957
  } else if (issue2.code === "invalid_key") {
1991
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1958
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1992
1959
  } else if (issue2.code === "invalid_element") {
1993
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1960
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1994
1961
  } else {
1995
- const fullpath = [...path17, ...issue2.path];
1962
+ const fullpath = [...path19, ...issue2.path];
1996
1963
  if (fullpath.length === 0) {
1997
1964
  result.errors.push(mapper(issue2));
1998
1965
  continue;
@@ -2024,8 +1991,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
2024
1991
  }
2025
1992
  function toDotPath(_path) {
2026
1993
  const segs = [];
2027
- const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2028
- for (const seg of path17) {
1994
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1995
+ for (const seg of path19) {
2029
1996
  if (typeof seg === "number")
2030
1997
  segs.push(`[${seg}]`);
2031
1998
  else if (typeof seg === "symbol")
@@ -14717,13 +14684,13 @@ function resolveRef(ref, ctx) {
14717
14684
  if (!ref.startsWith("#")) {
14718
14685
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14719
14686
  }
14720
- const path17 = ref.slice(1).split("/").filter(Boolean);
14721
- if (path17.length === 0) {
14687
+ const path19 = ref.slice(1).split("/").filter(Boolean);
14688
+ if (path19.length === 0) {
14722
14689
  return ctx.rootSchema;
14723
14690
  }
14724
14691
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14725
- if (path17[0] === defsKey) {
14726
- const key = path17[1];
14692
+ if (path19[0] === defsKey) {
14693
+ const key = path19[1];
14727
14694
  if (!key || !ctx.defs[key]) {
14728
14695
  throw new Error(`Reference not found: ${ref}`);
14729
14696
  }
@@ -15268,10 +15235,19 @@ var model = external_exports.string().min(1).max(512);
15268
15235
  var project = external_exports.string().min(1).max(4096);
15269
15236
  var usageStatisticsParamsSchema = external_exports.strictObject({
15270
15237
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
15238
+ /** Display timezone for ranges, dates and hourly buckets; omitted means the Host's local zone. */
15239
+ timeZone: external_exports.string().min(1).max(128).refine((value) => {
15240
+ try {
15241
+ new Intl.DateTimeFormat("en", { timeZone: value });
15242
+ return true;
15243
+ } catch {
15244
+ return false;
15245
+ }
15246
+ }, "Unsupported usage statistics timezone").optional(),
15271
15247
  harness: harness.optional(),
15272
15248
  model: model.nullable().optional(),
15273
15249
  project: project.nullable().optional(),
15274
- /** One local date inside the range. */
15250
+ /** One date in the query timezone inside the range. */
15275
15251
  date: localDate.optional()
15276
15252
  });
15277
15253
  var usageStatisticsTotalsSchema = external_exports.strictObject({
@@ -15307,7 +15283,7 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
15307
15283
  });
15308
15284
  var usageStatisticsResultSchema = external_exports.strictObject({
15309
15285
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
15310
- /** First local date of the range; null for all time. */
15286
+ /** First date in the query timezone (Host local when omitted); null for all time. */
15311
15287
  from: localDate.nullable(),
15312
15288
  to: localDate,
15313
15289
  /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
@@ -15347,7 +15323,7 @@ var usageStatisticsResultSchema = external_exports.strictObject({
15347
15323
  totals: usageStatisticsTotalsSchema,
15348
15324
  /** Each date and Harness of the range: every filter except the day. */
15349
15325
  daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
15350
- /** Local weekday (0 = Sunday) and hour, all filters applied. */
15326
+ /** Weekday (0 = Sunday) and hour in the query timezone, all filters applied. */
15351
15327
  hourly: external_exports.array(external_exports.strictObject({
15352
15328
  weekday: external_exports.number().int().min(0).max(6),
15353
15329
  hour: external_exports.number().int().min(0).max(23),
@@ -15438,8 +15414,12 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15438
15414
  "codexhost/harness/display-settings/set",
15439
15415
  "codexhost/harness/inspect",
15440
15416
  "codexhost/harness/installation",
15417
+ "codexhost/harness/installation/start",
15418
+ "codexhost/harness/installation/status",
15441
15419
  "codexhost/harness/launch-settings/get",
15442
15420
  "codexhost/harness/launch-settings/set",
15421
+ "codexhost/harness/grok-computer-use/get",
15422
+ "codexhost/harness/grok-computer-use/set",
15443
15423
  "codexhost/harness/web-ui/open",
15444
15424
  "codexhost/harness/accounts/sources",
15445
15425
  "codexhost/harness/accounts/list",
@@ -15513,7 +15493,18 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15513
15493
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15514
15494
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15515
15495
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15496
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text) => text.length <= maximum));
15497
+ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15498
+ kind: external_exports.literal("countdown"),
15499
+ id: external_exports.string().min(1).max(64),
15500
+ expiresAtUnix: nonNegativeSafeIntegerSchema,
15501
+ label: indicatorTextSchema(256).optional(),
15502
+ tooltip: indicatorTextSchema(1024).optional()
15503
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15504
+ message: "Composer indicator IDs must be unique"
15505
+ });
15516
15506
  var threadUsageSnapshotSchema = external_exports.object({
15507
+ composerIndicators: composerIndicatorsSchema.optional(),
15517
15508
  inputTokens: nonNegativeSafeIntegerSchema.optional(),
15518
15509
  cachedInputTokens: nonNegativeSafeIntegerSchema.optional(),
15519
15510
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15921,7 +15912,9 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15921
15912
  }).strict().optional(),
15922
15913
  autonomousTurns: external_exports.object({
15923
15914
  observe: external_exports.boolean()
15924
- }).strict().optional()
15915
+ }).strict().optional(),
15916
+ /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15917
+ steer: external_exports.boolean().optional()
15925
15918
  }).strict();
15926
15919
  var harnessConfigurationStateSchema = external_exports.object({
15927
15920
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15968,7 +15961,9 @@ var harnessInspectionSchema = external_exports.union([
15968
15961
  var harnessInspectParamsSchema = external_exports.object({
15969
15962
  harnessId: harnessIdSchema,
15970
15963
  cwd: nonBlankTextSchema2.max(16384).optional(),
15971
- refresh: external_exports.boolean().optional()
15964
+ refresh: external_exports.boolean().optional(),
15965
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15966
+ purpose: external_exports.literal("availability").optional()
15972
15967
  }).strict();
15973
15968
  var harnessWebUiOpenParamsSchema = external_exports.object({
15974
15969
  harnessId: harnessIdSchema
@@ -16051,6 +16046,15 @@ var threadOwnershipListResultSchema = external_exports.object({
16051
16046
  seen.add(thread.threadId);
16052
16047
  }
16053
16048
  });
16049
+ var threadSteeringInspectParamsSchema = external_exports.object({
16050
+ threadId: hostThreadIdSchema,
16051
+ /** The text about to be steered; a Harness command always stops and restarts. */
16052
+ text: external_exports.string().optional()
16053
+ }).strict();
16054
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
16055
+ var threadSteeringInspectResultSchema = external_exports.object({
16056
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
16057
+ }).strict();
16054
16058
 
16055
16059
  // ../../shared-contracts/dist/harness-plugins.js
16056
16060
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
@@ -16142,6 +16146,26 @@ var harnessLaunchSettingsSchema = external_exports.object({
16142
16146
  restartRequired: external_exports.boolean()
16143
16147
  }).strict();
16144
16148
 
16149
+ // ../../shared-contracts/dist/grok-computer-use.js
16150
+ var grokComputerUseGetSchema = external_exports.object({}).strict();
16151
+ var grokComputerUseSetSchema = external_exports.object({
16152
+ enabled: external_exports.boolean().optional(),
16153
+ browser: external_exports.boolean().optional()
16154
+ }).strict().refine((value) => value.enabled !== void 0 || value.browser !== void 0, {
16155
+ message: "Expected enabled or browser"
16156
+ });
16157
+ var grokComputerUseSettingsSchema = external_exports.object({
16158
+ enabled: external_exports.boolean(),
16159
+ available: external_exports.boolean(),
16160
+ unavailableReason: external_exports.string().min(1).max(500).optional(),
16161
+ browser: external_exports.boolean().optional(),
16162
+ browserFilesPresent: external_exports.boolean().optional(),
16163
+ browserAvailable: external_exports.boolean().optional(),
16164
+ browserUnavailableReason: external_exports.string().min(1).max(500).optional(),
16165
+ applyFailed: external_exports.boolean().optional(),
16166
+ applyError: external_exports.string().min(1).max(500).optional()
16167
+ }).strict();
16168
+
16145
16169
  // ../../shared-contracts/dist/harness-installation.js
16146
16170
  var harnessInstallationParamsSchema = external_exports.object({
16147
16171
  harnessId: harnessIdSchema,
@@ -16152,6 +16176,10 @@ var harnessInstallationStateSchema = external_exports.object({
16152
16176
  latestVersion: external_exports.string().min(1).max(128),
16153
16177
  updateAvailable: external_exports.boolean(),
16154
16178
  canUpdate: external_exports.boolean(),
16179
+ /** Defaults to CLI; some Harnesses ship only inside a desktop application. */
16180
+ versionKind: external_exports.enum(["cli", "application"]).optional(),
16181
+ /** Official download opened by the user; does not imply an automatic installation. */
16182
+ manualUpdateUrl: external_exports.url().max(2048).refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Manual updates require a credential-free HTTPS URL").optional(),
16155
16183
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
16156
16184
  message: external_exports.string().max(2048).optional(),
16157
16185
  messageCode: external_exports.string().min(1).max(128).optional(),
@@ -16159,6 +16187,20 @@ var harnessInstallationStateSchema = external_exports.object({
16159
16187
  notice: harnessLocalizedTextSchema.optional(),
16160
16188
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
16161
16189
  }).strict();
16190
+ var harnessInstallationTaskParamsSchema = external_exports.object({ taskId: external_exports.string().uuid() }).strict();
16191
+ var harnessInstallationTaskSchema = external_exports.discriminatedUnion("status", [
16192
+ external_exports.object({ taskId: external_exports.string().uuid(), status: external_exports.literal("running") }).strict(),
16193
+ external_exports.object({
16194
+ taskId: external_exports.string().uuid(),
16195
+ status: external_exports.literal("succeeded"),
16196
+ result: harnessInstallationStateSchema
16197
+ }).strict(),
16198
+ external_exports.object({
16199
+ taskId: external_exports.string().uuid(),
16200
+ status: external_exports.literal("failed"),
16201
+ error: external_exports.object({ code: external_exports.number().int(), message: external_exports.string().min(1).max(2048) }).strict()
16202
+ }).strict()
16203
+ ]);
16162
16204
 
16163
16205
  // ../../shared-contracts/dist/codex-accounts.js
16164
16206
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
@@ -16588,6 +16630,365 @@ var voiceSettingsStateSchema = external_exports.strictObject({
16588
16630
  // ../../shared-contracts/dist/index.js
16589
16631
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16590
16632
 
16633
+ // dist/grok-text-item-id.js
16634
+ function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
16635
+ const identity = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
16636
+ return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity).digest("hex")}`);
16637
+ }
16638
+
16639
+ // dist/grok-credential-export.js
16640
+ import { createHash as createHash2 } from "node:crypto";
16641
+ import { readFile as readFile2 } from "node:fs/promises";
16642
+ import os3 from "node:os";
16643
+ import path6 from "node:path";
16644
+ async function readGrokCredentials(environment) {
16645
+ if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
16646
+ return [];
16647
+ try {
16648
+ const home = environment.GROK_HOME ?? path6.join(environment.HOME ?? os3.homedir(), ".grok");
16649
+ const auth = JSON.parse(await readFile2(path6.join(home, "auth.json"), "utf8"));
16650
+ const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
16651
+ const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
16652
+ if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
16653
+ return [];
16654
+ if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
16655
+ return [];
16656
+ const expires = Date.parse(entry.expires_at);
16657
+ if (!Number.isFinite(expires))
16658
+ return [];
16659
+ return [
16660
+ {
16661
+ source: {
16662
+ id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
16663
+ harnessId: "grok",
16664
+ provider: "xai",
16665
+ label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
16666
+ },
16667
+ oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
16668
+ }
16669
+ ];
16670
+ } catch {
16671
+ return [];
16672
+ }
16673
+ }
16674
+
16675
+ // dist/grok-adapter.js
16676
+ import path18 from "node:path";
16677
+
16678
+ // ../../harness-plugin-files/dist/grok-computer-use.js
16679
+ import { randomUUID } from "node:crypto";
16680
+ import { access, mkdir as mkdir2, readFile as readFile3, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
16681
+ import os4 from "node:os";
16682
+ import path8 from "node:path";
16683
+
16684
+ // ../../harness-plugin-files/dist/grok-computer-use-lock.js
16685
+ import { mkdir, rm as rm2 } from "node:fs/promises";
16686
+ import path7 from "node:path";
16687
+ import { setTimeout as delay } from "node:timers/promises";
16688
+ async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
16689
+ const locks = [
16690
+ .../* @__PURE__ */ new Set([
16691
+ path7.join(dataDirectory2, ".grok-computer-use.lock"),
16692
+ path7.join(grokHome4, ".codexhost-cua.lock")
16693
+ ])
16694
+ ].sort();
16695
+ const acquired = [];
16696
+ const deadline = Date.now() + 5e3;
16697
+ try {
16698
+ for (const lock of locks) {
16699
+ await mkdir(path7.dirname(lock), { recursive: true, mode: 448 });
16700
+ for (; ; ) {
16701
+ try {
16702
+ await mkdir(lock, { mode: 448 });
16703
+ acquired.push(lock);
16704
+ break;
16705
+ } catch (error53) {
16706
+ if (error53.code !== "EEXIST")
16707
+ throw error53;
16708
+ if (Date.now() >= deadline)
16709
+ throw new Error("Grok Computer Use settings are locked");
16710
+ await delay(25);
16711
+ }
16712
+ }
16713
+ }
16714
+ return await operation();
16715
+ } finally {
16716
+ for (const lock of acquired.reverse())
16717
+ await rm2(lock, { recursive: true });
16718
+ }
16719
+ }
16720
+
16721
+ // ../../harness-plugin-files/dist/grok-computer-use.js
16722
+ var GROK_BROWSER_BINDING_SUPPORTED = false;
16723
+ var PREFERENCE_FILE = "grok-computer-use.json";
16724
+ var TABLE = "[mcp_servers.cua_repl]";
16725
+ var ENV_TABLE = "[mcp_servers.cua_repl.env]";
16726
+ var APPLY_FAILED = "Could not apply Grok Computer Use settings to Grok config.";
16727
+ var GrokComputerUseError = class extends Error {
16728
+ constructor(message) {
16729
+ super(message);
16730
+ this.name = "GrokComputerUseError";
16731
+ }
16732
+ };
16733
+ function dataDirectory(environment) {
16734
+ return environment.CODEXHOST_DATA_DIR ? path8.resolve(environment.CODEXHOST_DATA_DIR) : path8.join(os4.homedir(), ".codexhost");
16735
+ }
16736
+ function grokHome2(environment) {
16737
+ return environment.GROK_HOME ? path8.resolve(environment.GROK_HOME) : path8.join(environment.HOME ?? os4.homedir(), ".grok");
16738
+ }
16739
+ function chatgptApp(environment, platform) {
16740
+ if (environment.CODEXHOST_CHATGPT_APP)
16741
+ return path8.resolve(environment.CODEXHOST_CHATGPT_APP);
16742
+ if (platform === "darwin")
16743
+ return "/Applications/ChatGPT.app";
16744
+ return void 0;
16745
+ }
16746
+ async function isFile(target) {
16747
+ try {
16748
+ await access(target);
16749
+ return true;
16750
+ } catch {
16751
+ return false;
16752
+ }
16753
+ }
16754
+ function isNotFound(error53) {
16755
+ return Boolean(error53 && typeof error53 === "object" && "code" in error53 && error53.code === "ENOENT");
16756
+ }
16757
+ async function writeAtomically(file2, content) {
16758
+ await mkdir2(path8.dirname(file2), { recursive: true, mode: 448 });
16759
+ const temporary = `${file2}.${randomUUID()}.tmp`;
16760
+ try {
16761
+ await writeFile2(temporary, content, { mode: 384, flag: "wx" });
16762
+ await rename(temporary, file2);
16763
+ } finally {
16764
+ await rm3(temporary, { force: true });
16765
+ }
16766
+ }
16767
+ function launchPaths(environment, platform) {
16768
+ const app = chatgptApp(environment, platform);
16769
+ if (!app)
16770
+ return void 0;
16771
+ const resources = path8.join(app, "Contents", "Resources");
16772
+ const cuaNode = path8.join(resources, "cua_node");
16773
+ return {
16774
+ node: path8.join(cuaNode, "bin", "node"),
16775
+ cuaRepl: path8.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
16776
+ nodeRepl: path8.join(cuaNode, "bin", "node_repl"),
16777
+ nodeModules: path8.join(cuaNode, "lib", "node_modules"),
16778
+ codexCli: path8.join(resources, "codex-cli", "bin", "codex"),
16779
+ skyApp: path8.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
16780
+ codexHome: path8.join(environment.HOME ?? os4.homedir(), ".codex"),
16781
+ browserDesktop: path8.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
16782
+ };
16783
+ }
16784
+ async function sharedRuntimePresent(launch) {
16785
+ const present = await Promise.all([launch.node, launch.cuaRepl, launch.nodeRepl].map(isFile));
16786
+ return present.every(Boolean);
16787
+ }
16788
+ async function computerFilesPresent(launch) {
16789
+ const present = await Promise.all([isFile(launch.skyApp), isFile(launch.codexCli)]);
16790
+ return present.every(Boolean);
16791
+ }
16792
+ async function browserFilesPresent(launch) {
16793
+ return isFile(path8.join(launch.browserDesktop, "package.json"));
16794
+ }
16795
+ async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
16796
+ const launch = launchPaths(environment, platform);
16797
+ if (!launch || !await sharedRuntimePresent(launch))
16798
+ return void 0;
16799
+ return launch;
16800
+ }
16801
+ function tableRange(text, header) {
16802
+ const lines = text.split(/\n/);
16803
+ let start = -1;
16804
+ for (let index = 0; index < lines.length; index += 1) {
16805
+ if (lines[index] === header) {
16806
+ start = index;
16807
+ break;
16808
+ }
16809
+ }
16810
+ if (start < 0)
16811
+ return void 0;
16812
+ let end = lines.length;
16813
+ for (let index = start + 1; index < lines.length; index += 1) {
16814
+ const line = lines[index] ?? "";
16815
+ if (line.startsWith("[") && line.endsWith("]")) {
16816
+ end = index;
16817
+ break;
16818
+ }
16819
+ }
16820
+ return { start, end };
16821
+ }
16822
+ function removeTables(text, headers) {
16823
+ let current = text;
16824
+ for (const header of headers) {
16825
+ const range = tableRange(current, header);
16826
+ if (!range)
16827
+ continue;
16828
+ const lines = current.split(/\n/);
16829
+ lines.splice(range.start, range.end - range.start);
16830
+ current = lines.join("\n");
16831
+ }
16832
+ return current.replace(/\n{3,}/g, "\n\n");
16833
+ }
16834
+ function cuaReplEnabledInToml(text) {
16835
+ const range = tableRange(text, TABLE);
16836
+ if (!range)
16837
+ return false;
16838
+ const body = text.split(/\n/).slice(range.start, range.end);
16839
+ for (const line of body) {
16840
+ if (/^enabled\s*=\s*false\b/u.test(line))
16841
+ return false;
16842
+ if (/^enabled\s*=\s*true\b/u.test(line))
16843
+ return true;
16844
+ }
16845
+ return true;
16846
+ }
16847
+ function inferredSurfaces(text) {
16848
+ if (!cuaReplEnabledInToml(text))
16849
+ return { enabled: false, browser: false };
16850
+ const range = tableRange(text, ENV_TABLE);
16851
+ const body = range ? text.split(/\n/).slice(range.start, range.end).join("\n") : "";
16852
+ const literal2 = /^CUA_REPL_ENABLED_SURFACES\s*=\s*(["'])([^"']*)\1\s*(?:#.*)?$/mu.exec(body);
16853
+ if (!literal2)
16854
+ return { enabled: true, browser: false };
16855
+ const surfaces = new Set(literal2[2]?.split(",").map((surface) => surface.trim()));
16856
+ return { enabled: surfaces.has("computer"), browser: surfaces.has("browser") };
16857
+ }
16858
+ function stanza(launch, state) {
16859
+ const trusted = `${launch.codexHome}:${launch.nodeModules}`;
16860
+ const services = {};
16861
+ if (state.browser)
16862
+ services.browser = "@oai/browser-desktop/service";
16863
+ if (state.enabled)
16864
+ services.sky = "@oai/sky/service";
16865
+ const surfaces = [state.browser ? "browser" : "", state.enabled ? "computer" : ""].filter(Boolean).join(",");
16866
+ const backends = state.browser ? 'BROWSER_USE_AVAILABLE_BACKENDS = "iab"\n' : "";
16867
+ const active = state.enabled || state.browser;
16868
+ return `${TABLE}
16869
+ command = ${JSON.stringify(launch.node)}
16870
+ args = [${JSON.stringify(launch.cuaRepl)}]
16871
+ enabled = ${active ? "true" : "false"}
16872
+ startup_timeout_sec = 120
16873
+
16874
+ ${ENV_TABLE}
16875
+ NODE_REPL_TRUSTED_SERVICES = ${JSON.stringify(JSON.stringify(services))}
16876
+ NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(trusted)}
16877
+ NODE_REPL_NODE_PATH = ${JSON.stringify(launch.node)}
16878
+ CODEX_HOME = ${JSON.stringify(launch.codexHome)}
16879
+ CUA_REPL_NODE_REPL_PATH = ${JSON.stringify(launch.nodeRepl)}
16880
+ NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(launch.nodeModules)}
16881
+ NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
16882
+ SKY_CUA_SERVICE_PATH = ${JSON.stringify(launch.skyApp)}
16883
+ CODEX_CLI_PATH = ${JSON.stringify(launch.codexCli)}
16884
+ ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
16885
+ `;
16886
+ }
16887
+ async function readPreference(environment) {
16888
+ try {
16889
+ const document = JSON.parse(await readFile3(path8.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
16890
+ return {
16891
+ ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
16892
+ ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
16893
+ ...typeof document.applyError === "string" && document.applyError ? { applyError: document.applyError } : {}
16894
+ };
16895
+ } catch (error53) {
16896
+ if (isNotFound(error53))
16897
+ return void 0;
16898
+ throw new GrokComputerUseError("Could not read Grok Computer Use settings");
16899
+ }
16900
+ }
16901
+ async function writePreference(environment, state) {
16902
+ const document = {
16903
+ ...typeof state.enabled === "boolean" ? { enabled: state.enabled } : {},
16904
+ ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
16905
+ ...state.applyError ? { applyError: state.applyError } : {}
16906
+ };
16907
+ await writeAtomically(path8.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
16908
+ `);
16909
+ }
16910
+ async function readGrokConfig(environment) {
16911
+ try {
16912
+ return await readFile3(path8.join(grokHome2(environment), "config.toml"), "utf8");
16913
+ } catch (error53) {
16914
+ if (isNotFound(error53))
16915
+ return "";
16916
+ throw new GrokComputerUseError("Could not read Grok config");
16917
+ }
16918
+ }
16919
+ async function writeGrokConfig(environment, text) {
16920
+ await writeAtomically(path8.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
16921
+ `);
16922
+ }
16923
+ async function currentState(environment, preference) {
16924
+ const resolved = preference ?? await readPreference(environment);
16925
+ const inferred = resolved?.enabled === void 0 ? inferredSurfaces(await readGrokConfig(environment)) : void 0;
16926
+ return {
16927
+ enabled: resolved?.enabled ?? inferred?.enabled ?? false,
16928
+ browser: resolved ? resolved.browser ?? false : inferred?.browser ?? false,
16929
+ ...resolved?.applyError ? { applyError: resolved.applyError } : {}
16930
+ };
16931
+ }
16932
+ async function surfaceFiles(launch) {
16933
+ if (!launch)
16934
+ return { computer: false, browser: false };
16935
+ const [computer, browser] = await Promise.all([
16936
+ computerFilesPresent(launch),
16937
+ browserFilesPresent(launch)
16938
+ ]);
16939
+ return { computer, browser };
16940
+ }
16941
+ async function writeConfigForState(state, launch, files, environment) {
16942
+ const current = await readGrokConfig(environment);
16943
+ const range = tableRange(current, TABLE);
16944
+ const effective = {
16945
+ enabled: state.enabled && files.computer,
16946
+ browser: state.browser && files.browser && GROK_BROWSER_BINDING_SUPPORTED
16947
+ };
16948
+ if (!effective.enabled && !effective.browser && !range)
16949
+ return;
16950
+ if (!launch) {
16951
+ if (!range)
16952
+ return;
16953
+ const lines = current.split(/\n/);
16954
+ const body = lines.slice(range.start, range.end);
16955
+ const replaced = body.map((line) => /^enabled\s*=/u.test(line) ? "enabled = false" : line);
16956
+ if (!replaced.some((line) => /^enabled\s*=/u.test(line))) {
16957
+ replaced.splice(1, 0, "enabled = false");
16958
+ }
16959
+ lines.splice(range.start, range.end - range.start, ...replaced);
16960
+ await writeGrokConfig(environment, lines.join("\n"));
16961
+ return;
16962
+ }
16963
+ const stripped = removeTables(current, [ENV_TABLE, TABLE]).replace(/\s+$/u, "\n");
16964
+ await writeGrokConfig(environment, `${stripped.trimEnd()}
16965
+
16966
+ ${stanza(launch, effective)}`);
16967
+ }
16968
+ async function applyGrokComputerUsePreference(environment = process.env, platform = process.platform) {
16969
+ await withGrokComputerUseLock(dataDirectory(environment), grokHome2(environment), async () => {
16970
+ const preference = await readPreference(environment);
16971
+ if (preference === void 0)
16972
+ return;
16973
+ const launch = await discoverGrokComputerUseLaunch(environment, platform);
16974
+ const files = await surfaceFiles(launch);
16975
+ const state = await currentState(environment, preference);
16976
+ try {
16977
+ await writeConfigForState(state, launch, files, environment);
16978
+ if (state.applyError)
16979
+ await writePreference(environment, { enabled: state.enabled, browser: state.browser });
16980
+ } catch (error53) {
16981
+ const applyError = error53 instanceof GrokComputerUseError ? error53.message : APPLY_FAILED;
16982
+ await writePreference(environment, {
16983
+ enabled: state.enabled,
16984
+ browser: state.browser,
16985
+ applyError
16986
+ }).catch(() => void 0);
16987
+ throw error53 instanceof GrokComputerUseError ? error53 : new GrokComputerUseError(APPLY_FAILED);
16988
+ }
16989
+ });
16990
+ }
16991
+
16591
16992
  // ../../harness-adapter/dist/approval.js
16592
16993
  function invalidRequest(message) {
16593
16994
  return { code: "invalidRequest", message, retryable: false };
@@ -16654,6 +17055,18 @@ function sanitizeDiagnosticTail(value) {
16654
17055
  return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
16655
17056
  }
16656
17057
 
17058
+ // ../../harness-adapter/dist/steer.js
17059
+ function unsupportedSteer(harnessLabel) {
17060
+ return {
17061
+ ok: false,
17062
+ error: {
17063
+ code: "unsupported",
17064
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17065
+ retryable: false
17066
+ }
17067
+ };
17068
+ }
17069
+
16657
17070
  // ../../harness-adapter/dist/usage.js
16658
17071
  var tokenFields = [
16659
17072
  "inputTokens",
@@ -16681,6 +17094,7 @@ var usageFields = /* @__PURE__ */ new Set([
16681
17094
  ...safeIntegerFields,
16682
17095
  ...percentFields,
16683
17096
  "sessionCacheUsage",
17097
+ "composerIndicators",
16684
17098
  "totalCostUsd",
16685
17099
  "totalCredits",
16686
17100
  "contextUsagePercent",
@@ -16703,6 +17117,7 @@ function parseHostUsage(value) {
16703
17117
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16704
17118
  }
16705
17119
  }
17120
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
16706
17121
  for (const field of [
16707
17122
  "totalCredits",
16708
17123
  "contextUsagePercent",
@@ -16773,9 +17188,9 @@ function parseHostUsage(value) {
16773
17188
  if (value.costSource !== "publicPrice") {
16774
17189
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16775
17190
  }
16776
- return { ...value, unpricedModels: [...models] };
17191
+ return { ...value, ...indicators, unpricedModels: [...models] };
16777
17192
  }
16778
- return { ...value };
17193
+ return { ...value, ...indicators };
16779
17194
  }
16780
17195
  var requestTokenFields = [
16781
17196
  "inputTokens",
@@ -16915,9 +17330,9 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
16915
17330
 
16916
17331
  // dist/acp-transport.js
16917
17332
  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";
17333
+ import { readdir, readFile as readFile4 } from "node:fs/promises";
17334
+ import os6 from "node:os";
17335
+ import path15 from "node:path";
16921
17336
  import { Readable, Writable } from "node:stream";
16922
17337
 
16923
17338
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -21105,8 +21520,8 @@ function parseGrokAvailableCommands(value) {
21105
21520
  });
21106
21521
  }
21107
21522
  function isGrokSkill(command) {
21108
- const path17 = command.meta?.path;
21109
- return typeof path17 === "string" && /(^|[\\/])SKILL\.md$/u.test(path17) || typeof command.meta?.qualifiedName === "string";
21523
+ const path19 = command.meta?.path;
21524
+ return typeof path19 === "string" && /(^|[\\/])SKILL\.md$/u.test(path19) || typeof command.meta?.qualifiedName === "string";
21110
21525
  }
21111
21526
  function grokLiveCommands(native) {
21112
21527
  return native.map((command) => ({
@@ -21117,7 +21532,7 @@ function grokLiveCommands(native) {
21117
21532
  }
21118
21533
 
21119
21534
  // dist/command.js
21120
- import path7 from "node:path";
21535
+ import path9 from "node:path";
21121
21536
  var GrokExecutableError = class extends Error {
21122
21537
  code = "GROK_NOT_FOUND";
21123
21538
  };
@@ -21146,7 +21561,7 @@ function resolveGrokExecutable(input = {}) {
21146
21561
  });
21147
21562
  if (!resolution)
21148
21563
  throw new GrokExecutableError("Grok CLI is not installed");
21149
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
21564
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path9.resolve(resolution.executable);
21150
21565
  }
21151
21566
  function grokInvocation(command, platform = process.platform, modelId) {
21152
21567
  const arguments_ = ["agent", "--no-leader"];
@@ -21159,11 +21574,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
21159
21574
 
21160
21575
  // dist/grok-fork.js
21161
21576
  import { isDeepStrictEqual } from "node:util";
21162
- import path11 from "node:path";
21577
+ import path13 from "node:path";
21163
21578
 
21164
21579
  // dist/grok-file-change.js
21165
21580
  import { Buffer as Buffer2 } from "node:buffer";
21166
- import path8 from "node:path";
21581
+ import path10 from "node:path";
21167
21582
 
21168
21583
  // ../../../node_modules/diff/libesm/diff/base.js
21169
21584
  var Diff = class {
@@ -21265,16 +21680,16 @@ var Diff = class {
21265
21680
  }
21266
21681
  }
21267
21682
  }
21268
- addToPath(path17, added, removed, oldPosInc, options) {
21269
- const last = path17.lastComponent;
21683
+ addToPath(path19, added, removed, oldPosInc, options) {
21684
+ const last = path19.lastComponent;
21270
21685
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21271
21686
  return {
21272
- oldPos: path17.oldPos + oldPosInc,
21687
+ oldPos: path19.oldPos + oldPosInc,
21273
21688
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21274
21689
  };
21275
21690
  } else {
21276
21691
  return {
21277
- oldPos: path17.oldPos + oldPosInc,
21692
+ oldPos: path19.oldPos + oldPosInc,
21278
21693
  lastComponent: { count: 1, added, removed, previousComponent: last }
21279
21694
  };
21280
21695
  }
@@ -21587,13 +22002,13 @@ function isRecord5(value) {
21587
22002
  return typeof value === "object" && value !== null && !Array.isArray(value);
21588
22003
  }
21589
22004
  function validAbsolutePath(value) {
21590
- return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
22005
+ return typeof value === "string" && path10.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21591
22006
  }
21592
22007
  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}`);
22008
+ const resolvedCwd = path10.resolve(cwd);
22009
+ const resolvedPath = path10.resolve(nativePath);
22010
+ const relative = path10.relative(resolvedCwd, resolvedPath);
22011
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
21597
22012
  const selected = inside ? relative : resolvedPath;
21598
22013
  const normalized = selected.replaceAll("\\", "/");
21599
22014
  if (normalized.length === 0 || normalized === ".")
@@ -21654,12 +22069,12 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21654
22069
  }
21655
22070
 
21656
22071
  // dist/grok-generated-image.js
21657
- import path10 from "node:path";
22072
+ import path12 from "node:path";
21658
22073
 
21659
22074
  // dist/local-media-markdown.js
21660
22075
  import { existsSync, statSync } from "node:fs";
21661
- import os4 from "node:os";
21662
- import path9 from "node:path";
22076
+ import os5 from "node:os";
22077
+ import path11 from "node:path";
21663
22078
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21664
22079
  ".aac",
21665
22080
  ".gif",
@@ -21678,14 +22093,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21678
22093
  ".webp"
21679
22094
  ]);
21680
22095
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21681
- const roots = [path9.resolve(cwd)];
22096
+ const roots = [path11.resolve(cwd)];
21682
22097
  if (sessionDirectory) {
21683
- const session = path9.resolve(sessionDirectory);
21684
- roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
22098
+ const session = path11.resolve(sessionDirectory);
22099
+ roots.push(session, path11.join(session, "videos"), path11.join(session, "images"));
21685
22100
  }
21686
- const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
22101
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? os5.homedir();
21687
22102
  if (home)
21688
- roots.push(path9.join(home, "Downloads"));
22103
+ roots.push(path11.join(home, "Downloads"));
21689
22104
  return roots;
21690
22105
  }
21691
22106
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -21786,7 +22201,7 @@ function parseInlineCode(text, start) {
21786
22201
  return { closed: false, content: text.slice(start + 1), end: text.length };
21787
22202
  }
21788
22203
  function mediaMarkdownImage(absolutePath) {
21789
- const name = path9.basename(absolutePath).replaceAll("]", "\\]");
22204
+ const name = path11.basename(absolutePath).replaceAll("]", "\\]");
21790
22205
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21791
22206
  }
21792
22207
  function parseMarkdownImage(text, start) {
@@ -21911,11 +22326,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21911
22326
  if (!hasMediaExtension(stripped))
21912
22327
  return null;
21913
22328
  if (isAbsoluteMediaPath(stripped)) {
21914
- const absolute = path9.resolve(stripped);
22329
+ const absolute = path11.resolve(stripped);
21915
22330
  return exists(absolute) ? absolute : null;
21916
22331
  }
21917
22332
  for (const root of roots) {
21918
- const absolute = path9.resolve(root, stripped);
22333
+ const absolute = path11.resolve(root, stripped);
21919
22334
  if (exists(absolute))
21920
22335
  return absolute;
21921
22336
  }
@@ -21937,11 +22352,11 @@ function stripFileUrl(value) {
21937
22352
  }
21938
22353
  }
21939
22354
  function isAbsoluteMediaPath(value) {
21940
- return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
22355
+ return path11.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21941
22356
  }
21942
22357
  function hasMediaExtension(value) {
21943
22358
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21944
- return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
22359
+ return MEDIA_EXTENSIONS.has(path11.extname(pathname).toLowerCase());
21945
22360
  }
21946
22361
  function mediaFileExists(absolutePath) {
21947
22362
  try {
@@ -21971,7 +22386,7 @@ function fromNativeRecord(value, exists) {
21971
22386
  const savedPath = stringField(value, "path");
21972
22387
  if (!validAbsolutePath(savedPath))
21973
22388
  return null;
21974
- const resolved = path10.resolve(savedPath);
22389
+ const resolved = path12.resolve(savedPath);
21975
22390
  if (!exists(resolved))
21976
22391
  return null;
21977
22392
  const filename = stringField(value, "filename");
@@ -22583,7 +22998,11 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22583
22998
  let nativePromptIndex = 0;
22584
22999
  let currentPromptIndex = null;
22585
23000
  let agent = null;
23001
+ let agentMessageId;
23002
+ let agentIndex = 0;
22586
23003
  let reasoning = null;
23004
+ let reasoningMessageId;
23005
+ let reasoningIndex = 0;
22587
23006
  const tools = /* @__PURE__ */ new Map();
22588
23007
  const generatedImages = /* @__PURE__ */ new Map();
22589
23008
  const mediaRoots = grokMediaResolveRoots(cwd, sessionDirectory);
@@ -22781,6 +23200,8 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22781
23200
  });
22782
23201
  turnIndex += 1;
22783
23202
  messageIndex = 0;
23203
+ agentIndex = 0;
23204
+ reasoningIndex = 0;
22784
23205
  nativeTurnKey = null;
22785
23206
  currentPromptIndex = null;
22786
23207
  input = "";
@@ -22794,6 +23215,8 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22794
23215
  });
22795
23216
  turnIndex = turns.length;
22796
23217
  messageIndex = 0;
23218
+ agentIndex = 0;
23219
+ reasoningIndex = 0;
22797
23220
  nativeTurnKey = null;
22798
23221
  nativePromptIndex = event.targetPromptIndex;
22799
23222
  currentPromptIndex = null;
@@ -22858,20 +23281,28 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
22858
23281
  outcome
22859
23282
  });
22860
23283
  } else if (event.type === "agent.text") {
23284
+ if (agent && agentMessageId !== event.messageId)
23285
+ completeAgent();
22861
23286
  if (!agent) {
22862
23287
  completeReasoning();
23288
+ agentMessageId = event.messageId;
23289
+ ++messageIndex;
22863
23290
  agent = {
22864
23291
  type: "agentMessage",
22865
- itemId: stableId("message", turnIndex, ++messageIndex),
23292
+ itemId: grokTextItemId(sessionId, turnIndex, "agentMessage", ++agentIndex),
22866
23293
  text: ""
22867
23294
  };
22868
23295
  }
22869
23296
  agent = { ...agent, text: agent.text + event.text };
22870
23297
  } else if (event.type === "agent.thought") {
23298
+ if (reasoning && reasoningMessageId !== event.messageId)
23299
+ completeReasoning();
22871
23300
  if (!reasoning) {
23301
+ reasoningMessageId = event.messageId;
23302
+ ++messageIndex;
22872
23303
  reasoning = {
22873
23304
  type: "reasoning",
22874
- itemId: stableId("reasoning", turnIndex, ++messageIndex),
23305
+ itemId: grokTextItemId(sessionId, turnIndex, "reasoning", ++reasoningIndex),
22875
23306
  text: ""
22876
23307
  };
22877
23308
  }
@@ -23037,11 +23468,11 @@ function parseGrokForkResponse(value) {
23037
23468
  }
23038
23469
  function projectRelativePath(value, cwds) {
23039
23470
  const normalized = value.replaceAll("\\", "/");
23040
- if (!path11.isAbsolute(value))
23471
+ if (!path13.isAbsolute(value))
23041
23472
  return normalized;
23042
23473
  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}`)) {
23474
+ const relative = path13.relative(path13.resolve(cwd), path13.resolve(value));
23475
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path13.sep}`)) {
23045
23476
  return relative.replaceAll("\\", "/");
23046
23477
  }
23047
23478
  }
@@ -23106,8 +23537,8 @@ async function forkGrokSession(input) {
23106
23537
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
23107
23538
  };
23108
23539
  }
23109
- const sourceCwd = path11.resolve(located.cwd);
23110
- const targetCwd = path11.resolve(input.cwd);
23540
+ const sourceCwd = path13.resolve(located.cwd);
23541
+ const targetCwd = path13.resolve(input.cwd);
23111
23542
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
23112
23543
  if (!source.ok)
23113
23544
  return source;
@@ -23290,7 +23721,7 @@ function parseGrokCompactResult(value, cancelled = false) {
23290
23721
  }
23291
23722
 
23292
23723
  // dist/grok-rewind.js
23293
- import path12 from "node:path";
23724
+ import path14 from "node:path";
23294
23725
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
23295
23726
  function error52(code, message, retryable = false) {
23296
23727
  return { code, message, retryable };
@@ -23363,8 +23794,8 @@ async function rewindGrokLastTurn(input) {
23363
23794
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
23364
23795
  };
23365
23796
  }
23366
- const sourceCwd = path12.resolve(located.cwd);
23367
- const targetCwd = path12.resolve(input.cwd);
23797
+ const sourceCwd = path14.resolve(located.cwd);
23798
+ const targetCwd = path14.resolve(input.cwd);
23368
23799
  if (sourceCwd !== targetCwd) {
23369
23800
  return {
23370
23801
  ok: false,
@@ -23418,6 +23849,195 @@ async function rewindGrokLastTurn(input) {
23418
23849
  return { ok: true, value: { sessionId } };
23419
23850
  }
23420
23851
 
23852
+ // dist/grok-elicitation.js
23853
+ var GROK_MCP_ELICIT_METHOD = "_x.ai/mcp/elicit";
23854
+ var GROK_ELICIT_TITLE_MAX_LENGTH = 150;
23855
+ var GROK_ELICIT_DESCRIPTION_MAX_LENGTH = 500;
23856
+ var FORM_KEYS = /* @__PURE__ */ new Set([
23857
+ "sessionId",
23858
+ "toolCallId",
23859
+ "serverName",
23860
+ "message",
23861
+ "mode",
23862
+ "requestedSchema",
23863
+ "persist"
23864
+ ]);
23865
+ var URL_KEYS = /* @__PURE__ */ new Set([
23866
+ "sessionId",
23867
+ "toolCallId",
23868
+ "serverName",
23869
+ "message",
23870
+ "mode",
23871
+ "url",
23872
+ "elicitationId"
23873
+ ]);
23874
+ var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required"]);
23875
+ var GROK_CLOCK_ELICIT_FIXTURE = {
23876
+ sessionId: "session-1",
23877
+ toolCallId: "elicit-clock-1",
23878
+ serverName: "cua_repl",
23879
+ message: 'Allow Computer Use to use "Clock"?',
23880
+ mode: "form"
23881
+ };
23882
+ var GROK_CLOCK_ELICIT_PERSIST_FIXTURE = {
23883
+ ...GROK_CLOCK_ELICIT_FIXTURE,
23884
+ persist: ["session", "always"]
23885
+ };
23886
+ function isRecord13(value) {
23887
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23888
+ }
23889
+ function nonEmptyString(value) {
23890
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
23891
+ }
23892
+ function hasOnlyKeys(record2, allowed) {
23893
+ return Object.keys(record2).every((key) => allowed.has(key));
23894
+ }
23895
+ function clampText(value, max) {
23896
+ return value.length <= max ? value : value.slice(0, max);
23897
+ }
23898
+ function parsePersistOffer(value) {
23899
+ if (value === void 0)
23900
+ return void 0;
23901
+ if (!Array.isArray(value) || value.length === 0)
23902
+ return "invalid";
23903
+ let session = false;
23904
+ let always = false;
23905
+ const seen = /* @__PURE__ */ new Set();
23906
+ for (const item of value) {
23907
+ if (typeof item !== "string" || item !== item.trim())
23908
+ return "invalid";
23909
+ if (seen.has(item))
23910
+ return "invalid";
23911
+ seen.add(item);
23912
+ if (item === "session")
23913
+ session = true;
23914
+ else if (item === "always")
23915
+ always = true;
23916
+ else
23917
+ return "invalid";
23918
+ }
23919
+ const out = [];
23920
+ if (session)
23921
+ out.push("session");
23922
+ if (always)
23923
+ out.push("always");
23924
+ return out.length > 0 ? out : "invalid";
23925
+ }
23926
+ function schemaIsSupportedEmptyObject(schema) {
23927
+ if (!isRecord13(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
23928
+ return false;
23929
+ }
23930
+ if (schema.properties !== void 0) {
23931
+ if (!isRecord13(schema.properties) || Object.keys(schema.properties).length !== 0)
23932
+ return false;
23933
+ }
23934
+ if (schema.required !== void 0) {
23935
+ if (!Array.isArray(schema.required) || schema.required.length !== 0)
23936
+ return false;
23937
+ }
23938
+ return true;
23939
+ }
23940
+ function parseGrokMcpElicitParams(params) {
23941
+ if (!isRecord13(params))
23942
+ return { status: "invalid", message: "elicitation params must be an object" };
23943
+ const sessionId = nonEmptyString(params.sessionId);
23944
+ const toolCallId = nonEmptyString(params.toolCallId);
23945
+ const serverName = nonEmptyString(params.serverName);
23946
+ const message = nonEmptyString(params.message);
23947
+ if (!sessionId || !toolCallId || !serverName || !message) {
23948
+ return {
23949
+ status: "invalid",
23950
+ message: "elicitation requires sessionId, toolCallId, serverName, and message"
23951
+ };
23952
+ }
23953
+ if (params.mode === "url") {
23954
+ if (!hasOnlyKeys(params, URL_KEYS)) {
23955
+ return { status: "invalid", message: "URL elicitation contains unreviewed fields" };
23956
+ }
23957
+ if (!nonEmptyString(params.url) || !nonEmptyString(params.elicitationId)) {
23958
+ return { status: "invalid", message: "URL elicitation requires url and elicitationId" };
23959
+ }
23960
+ return { status: "unsupported" };
23961
+ }
23962
+ if (params.mode !== "form") {
23963
+ return { status: "invalid", message: "elicitation mode must be form or url" };
23964
+ }
23965
+ if (!hasOnlyKeys(params, FORM_KEYS)) {
23966
+ return { status: "invalid", message: "form elicitation contains unreviewed fields" };
23967
+ }
23968
+ if (params.requestedSchema !== void 0) {
23969
+ if (!isRecord13(params.requestedSchema)) {
23970
+ return { status: "invalid", message: "requestedSchema must be an object" };
23971
+ }
23972
+ if (!schemaIsSupportedEmptyObject(params.requestedSchema))
23973
+ return { status: "unsupported" };
23974
+ }
23975
+ const persist = parsePersistOffer(params.persist);
23976
+ if (persist === "invalid") {
23977
+ return {
23978
+ status: "invalid",
23979
+ message: "persist must be a unique array of session and/or always"
23980
+ };
23981
+ }
23982
+ return {
23983
+ status: "form",
23984
+ request: {
23985
+ sessionId,
23986
+ toolCallId,
23987
+ serverName,
23988
+ message,
23989
+ mode: "form",
23990
+ ...persist ? { persist } : {}
23991
+ }
23992
+ };
23993
+ }
23994
+ function grokMcpElicitAccept(persist) {
23995
+ return { outcome: "accept", content: {}, ...persist ? { persist } : {} };
23996
+ }
23997
+ function grokMcpElicitDecline() {
23998
+ return { outcome: "decline" };
23999
+ }
24000
+ function grokMcpElicitCancel() {
24001
+ return { outcome: "cancel" };
24002
+ }
24003
+ function grokMcpElicitResponseForAction(effect) {
24004
+ if (effect === "allowOnce")
24005
+ return grokMcpElicitAccept();
24006
+ if (effect === "allowAlways")
24007
+ return grokMcpElicitAccept("always");
24008
+ if (effect === "deny")
24009
+ return grokMcpElicitDecline();
24010
+ return grokMcpElicitCancel();
24011
+ }
24012
+ function grokMcpElicitApprovalActions(persist) {
24013
+ const actions = [
24014
+ { id: "allow-once", label: "Allow once", effect: "allowOnce" }
24015
+ ];
24016
+ if (persist?.includes("always")) {
24017
+ actions.push({ id: "allow-always", label: "Always allow", effect: "allowAlways" });
24018
+ }
24019
+ actions.push({ id: "deny", label: "Deny", effect: "deny" });
24020
+ return actions;
24021
+ }
24022
+ function projectGrokMcpElicitApproval(input) {
24023
+ const title = clampText(`${input.request.serverName}: ${input.request.message}`, GROK_ELICIT_TITLE_MAX_LENGTH);
24024
+ const description = clampText(input.request.message, GROK_ELICIT_DESCRIPTION_MAX_LENGTH);
24025
+ return {
24026
+ type: "approval",
24027
+ interactionId: input.interactionId,
24028
+ turnId: input.turnId,
24029
+ title,
24030
+ description,
24031
+ subject: { type: "nativeAction" },
24032
+ actions: grokMcpElicitApprovalActions(input.request.persist)
24033
+ };
24034
+ }
24035
+ function grokElicitationResolvedToolCallId(update) {
24036
+ if (!isRecord13(update) || update.sessionUpdate !== "interaction_resolved")
24037
+ return void 0;
24038
+ return nonEmptyString(update.tool_call_id) ?? nonEmptyString(update.toolCallId);
24039
+ }
24040
+
23421
24041
  // dist/permission-modes.js
23422
24042
  var nativePermissionModes = /* @__PURE__ */ new Set(["ask", "auto", "always-approve"]);
23423
24043
  var GROK_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("ask");
@@ -23493,6 +24113,53 @@ function grokCodexhostSessionMeta(permissionMode) {
23493
24113
  };
23494
24114
  }
23495
24115
 
24116
+ // dist/permission-confirmation.js
24117
+ import { stripVTControlCharacters } from "node:util";
24118
+ var GROK_PERMISSION_MODE_METHOD = "_x.ai/yolo_mode_changed";
24119
+ var permissionManagerLog = "xai_grok_workspace::permission::manager=info";
24120
+ function grokPermissionLogFilter(existing) {
24121
+ return existing ? `${existing},${permissionManagerLog}` : permissionManagerLog;
24122
+ }
24123
+ var GrokPermissionConfirmation = class {
24124
+ #expected;
24125
+ #completion = Promise.withResolvers();
24126
+ #yolo;
24127
+ #auto;
24128
+ #buffer = "";
24129
+ constructor(mode) {
24130
+ this.#expected = grokPermissionModeSessionMeta(mode);
24131
+ }
24132
+ get completed() {
24133
+ return this.#completion.promise;
24134
+ }
24135
+ accept(chunk) {
24136
+ this.#buffer += chunk;
24137
+ let newline2;
24138
+ while ((newline2 = this.#buffer.indexOf("\n")) !== -1) {
24139
+ const line = stripVTControlCharacters(this.#buffer.slice(0, newline2)).trimEnd();
24140
+ this.#buffer = this.#buffer.slice(newline2 + 1);
24141
+ const match = /^\d{4}-\d{2}-\d{2}T\S+\s+INFO\s+(?:.*?: )?(always-approve|auto permission mode) set to: (true|false)$/.exec(line);
24142
+ if (!match)
24143
+ continue;
24144
+ const value = match[2] === "true";
24145
+ if (match[1] === "always-approve")
24146
+ this.#yolo = value;
24147
+ else
24148
+ this.#auto = value;
24149
+ if (this.#yolo !== void 0 && this.#yolo !== this.#expected.yoloMode || this.#auto !== void 0 && this.#auto !== this.#expected.autoMode) {
24150
+ this.reject(new Error("Grok did not apply the requested Permission Mode"));
24151
+ } else if (this.#yolo !== void 0 && this.#auto !== void 0) {
24152
+ this.#completion.resolve(void 0);
24153
+ }
24154
+ }
24155
+ if (this.#buffer.length > 16384)
24156
+ this.#buffer = "";
24157
+ }
24158
+ reject(error53) {
24159
+ this.#completion.reject(error53);
24160
+ }
24161
+ };
24162
+
23496
24163
  // dist/acp-transport.js
23497
24164
  var GrokTransportError = class extends Error {
23498
24165
  kind;
@@ -23504,16 +24171,16 @@ var GrokTransportError = class extends Error {
23504
24171
  this.name = "GrokTransportError";
23505
24172
  }
23506
24173
  };
23507
- function isRecord13(value) {
24174
+ function isRecord14(value) {
23508
24175
  return typeof value === "object" && value !== null && !Array.isArray(value);
23509
24176
  }
23510
24177
  function acpToolName(update, metadata) {
23511
- if (!isRecord13(update))
24178
+ if (!isRecord14(update))
23512
24179
  return void 0;
23513
24180
  if (typeof update.name === "string" && update.name.length > 0)
23514
24181
  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;
24182
+ const meta3 = isRecord14(update._meta) ? update._meta : metadata;
24183
+ const tool = meta3 && isRecord14(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23517
24184
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
23518
24185
  }
23519
24186
  function errorText(error53) {
@@ -23569,7 +24236,7 @@ function signalProcessTree(child, signal) {
23569
24236
  try {
23570
24237
  process.kill(-child.pid, signal);
23571
24238
  } catch (error53) {
23572
- if (!isRecord13(error53) || error53.code !== "ESRCH")
24239
+ if (!isRecord14(error53) || error53.code !== "ESRCH")
23573
24240
  throw error53;
23574
24241
  }
23575
24242
  }
@@ -23612,6 +24279,14 @@ function transportEvent(update, metadata) {
23612
24279
  const subagent = grokSubagentEventFromUpdate(extension);
23613
24280
  if (subagent)
23614
24281
  return subagent;
24282
+ const resolvedToolCallId = grokElicitationResolvedToolCallId(extension);
24283
+ if (resolvedToolCallId) {
24284
+ return {
24285
+ type: "elicitation.resolved",
24286
+ toolCallId: resolvedToolCallId,
24287
+ ...metadata ? { metadata } : {}
24288
+ };
24289
+ }
23615
24290
  switch (update.sessionUpdate) {
23616
24291
  case "user_message_chunk":
23617
24292
  case "agent_message_chunk":
@@ -23659,34 +24334,34 @@ function transportEvent(update, metadata) {
23659
24334
  }
23660
24335
  function grokHomeDir(options) {
23661
24336
  const environment = { ...process.env, ...options.environment };
23662
- const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23663
- return environment.GROK_HOME ?? path13.join(home, ".grok");
24337
+ const home = environment.HOME ?? environment.USERPROFILE ?? os6.homedir();
24338
+ return environment.GROK_HOME ?? path15.join(home, ".grok");
23664
24339
  }
23665
24340
  function grokNativeSessionDirectory(options, sessionId) {
23666
- return path13.join(grokHomeDir(options), "sessions", encodeURIComponent(path13.resolve(options.cwd)), sessionId);
24341
+ return path15.join(grokHomeDir(options), "sessions", encodeURIComponent(path15.resolve(options.cwd)), sessionId);
23667
24342
  }
23668
24343
  function nativeSessionFile(options, sessionId, fileName) {
23669
- return path13.join(grokNativeSessionDirectory(options, sessionId), fileName);
24344
+ return path15.join(grokNativeSessionDirectory(options, sessionId), fileName);
23670
24345
  }
23671
24346
  function nativeHistoryPath(options, sessionId) {
23672
24347
  return nativeSessionFile(options, sessionId, "updates.jsonl");
23673
24348
  }
23674
24349
  async function readNativeSignals(options, sessionId) {
23675
24350
  try {
23676
- return JSON.parse(await readFile3(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
24351
+ return JSON.parse(await readFile4(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
23677
24352
  } catch {
23678
24353
  return void 0;
23679
24354
  }
23680
24355
  }
23681
24356
  function isMissingFile(error53) {
23682
- return isRecord13(error53) && error53.code === "ENOENT";
24357
+ return isRecord14(error53) && error53.code === "ENOENT";
23683
24358
  }
23684
24359
  async function locateGrokNativeSession(options, sessionId) {
23685
24360
  if (sessionId.length === 0)
23686
24361
  return null;
23687
24362
  let entries;
23688
24363
  try {
23689
- entries = await readdir(path13.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
24364
+ entries = await readdir(path15.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23690
24365
  } catch (error53) {
23691
24366
  if (isMissingFile(error53))
23692
24367
  return null;
@@ -23700,9 +24375,9 @@ async function locateGrokNativeSession(options, sessionId) {
23700
24375
  continue;
23701
24376
  let summaryRaw;
23702
24377
  try {
23703
- summaryRaw = await readFile3(path13.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
24378
+ summaryRaw = await readFile4(path15.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23704
24379
  } catch (error53) {
23705
- if (isMissingFile(error53) || isRecord13(error53) && error53.code === "ENOTDIR")
24380
+ if (isMissingFile(error53) || isRecord14(error53) && error53.code === "ENOTDIR")
23706
24381
  continue;
23707
24382
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
23708
24383
  cause: error53
@@ -23714,11 +24389,11 @@ async function locateGrokNativeSession(options, sessionId) {
23714
24389
  } catch {
23715
24390
  continue;
23716
24391
  }
23717
- if (!isRecord13(parsed))
24392
+ if (!isRecord14(parsed))
23718
24393
  continue;
23719
24394
  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;
24395
+ const cwd = isRecord14(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path15.resolve(info.cwd) : path15.resolve(decodeURIComponent(entry.name));
24396
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path15.resolve(parsed.source_workspace_dir) : void 0;
23722
24397
  matches.push({
23723
24398
  cwd,
23724
24399
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23728,7 +24403,7 @@ async function locateGrokNativeSession(options, sessionId) {
23728
24403
  }
23729
24404
  async function readGrokNativeHistory(options, sessionId) {
23730
24405
  try {
23731
- return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path13.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
24406
+ return parseNativeHistory(await readFile4(nativeHistoryPath({ ...options, cwd: path15.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23732
24407
  } catch (error53) {
23733
24408
  if (isMissingFile(error53))
23734
24409
  return [];
@@ -23750,12 +24425,12 @@ function parseNativeHistory(contents, sessionId) {
23750
24425
  } catch {
23751
24426
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23752
24427
  }
23753
- if (!isRecord13(record2) || !isRecord13(record2.params))
24428
+ if (!isRecord14(record2) || !isRecord14(record2.params))
23754
24429
  continue;
23755
24430
  const params = record2.params;
23756
- if (params.sessionId !== sessionId || !isRecord13(params.update))
24431
+ if (params.sessionId !== sessionId || !isRecord14(params.update))
23757
24432
  continue;
23758
- const metadata = isRecord13(params._meta) ? params._meta : void 0;
24433
+ const metadata = isRecord14(params._meta) ? params._meta : void 0;
23759
24434
  const event = transportEvent(params.update, metadata);
23760
24435
  if (event)
23761
24436
  events.push(metadata ? { ...event, metadata } : event);
@@ -23769,6 +24444,8 @@ var GrokAcpTransport = class {
23769
24444
  #child = null;
23770
24445
  #closed = false;
23771
24446
  #closing = false;
24447
+ #closePromise = null;
24448
+ #permissionConfirmation = null;
23772
24449
  #connection = null;
23773
24450
  #initialize = null;
23774
24451
  #replay = null;
@@ -23817,7 +24494,7 @@ var GrokAcpTransport = class {
23817
24494
  if (!this.#connection)
23818
24495
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
23819
24496
  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;
24497
+ return isRecord14(result) ? result.usage : void 0;
23821
24498
  }
23822
24499
  async readHistory(sessionId, cwd = this.#options.cwd) {
23823
24500
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -23969,7 +24646,11 @@ var GrokAcpTransport = class {
23969
24646
  const invocation = grokInvocation(executable, process.platform, this.#startupModelId);
23970
24647
  const child = spawn(invocation.command, invocation.arguments, {
23971
24648
  cwd: this.#options.cwd,
23972
- env: { ...process.env, ...this.#options.environment },
24649
+ env: {
24650
+ ...process.env,
24651
+ ...this.#options.environment,
24652
+ RUST_LOG: grokPermissionLogFilter(this.#options.environment?.RUST_LOG ?? process.env.RUST_LOG)
24653
+ },
23973
24654
  detached: process.platform !== "win32",
23974
24655
  stdio: ["pipe", "pipe", "pipe"],
23975
24656
  windowsHide: true,
@@ -23978,6 +24659,7 @@ var GrokAcpTransport = class {
23978
24659
  this.#child = child;
23979
24660
  child.stderr.on("data", (chunk) => {
23980
24661
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
24662
+ this.#permissionConfirmation?.accept(chunk.toString());
23981
24663
  });
23982
24664
  await withTimeout(new Promise((resolve, reject) => {
23983
24665
  child.once("spawn", resolve);
@@ -23987,6 +24669,7 @@ var GrokAcpTransport = class {
23987
24669
  const connection = new ClientSideConnection(() => ({
23988
24670
  sessionUpdate: (params) => this.#handleUpdate(params),
23989
24671
  requestPermission: (params) => this.#handlePermission(params),
24672
+ extMethod: (method, params) => this.#handleExtMethod(method, params),
23990
24673
  extNotification: (method, params) => this.#handleExtensionNotification(method, params)
23991
24674
  }), stream);
23992
24675
  this.#connection = connection;
@@ -24007,14 +24690,16 @@ var GrokAcpTransport = class {
24007
24690
  this.#initialize = initialize;
24008
24691
  return initialize;
24009
24692
  }
24010
- async runTurn(text, onEvent, onPermission) {
24693
+ async runTurn(text, onEvent, onPermission, onElicitation) {
24011
24694
  const connection = this.#connection;
24012
24695
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
24013
24696
  throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
24014
24697
  }
24015
24698
  if (this.#activePrompt)
24016
24699
  throw new Error("Grok ACP Session already has an active Prompt");
24017
- const active = { onEvent, onPermission };
24700
+ if (this.#permissionConfirmation)
24701
+ throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
24702
+ const active = { onEvent, onPermission, onElicitation };
24018
24703
  this.#activePrompt = active;
24019
24704
  try {
24020
24705
  return await connection.prompt({
@@ -24032,7 +24717,7 @@ var GrokAcpTransport = class {
24032
24717
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
24033
24718
  throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
24034
24719
  }
24035
- if (this.#activePrompt || this.#activeCompact) {
24720
+ if (this.#activePrompt || this.#activeCompact || this.#permissionConfirmation) {
24036
24721
  throw new GrokTransportError("unavailable", "Grok ACP Session already has an active operation");
24037
24722
  }
24038
24723
  const active = { onEvent, cancellationRequested: false };
@@ -24065,6 +24750,8 @@ var GrokAcpTransport = class {
24065
24750
  const connection = this.#connection;
24066
24751
  if (!connection || !this.#sessionId)
24067
24752
  throw new Error("Grok ACP Session is unavailable");
24753
+ if (this.#permissionConfirmation)
24754
+ throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
24068
24755
  const response = await connection.request("session/set_model", {
24069
24756
  sessionId: this.#sessionId,
24070
24757
  modelId,
@@ -24075,7 +24762,7 @@ var GrokAcpTransport = class {
24075
24762
  }
24076
24763
  } : {}
24077
24764
  });
24078
- if (!isRecord13(response) || !isRecord13(response._meta) || !isRecord13(response._meta.model)) {
24765
+ if (!isRecord14(response) || !isRecord14(response._meta) || !isRecord14(response._meta.model)) {
24079
24766
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
24080
24767
  }
24081
24768
  const selected = response._meta.model.Ok;
@@ -24092,14 +24779,57 @@ var GrokAcpTransport = class {
24092
24779
  this.#activeCompact.cancellationRequested = true;
24093
24780
  return connection.cancel({ sessionId: this.#sessionId });
24094
24781
  }
24095
- async close() {
24782
+ async setPermissionMode(permissionModeId) {
24783
+ const mode = decodeGrokPermissionModeId(permissionModeId);
24784
+ const connection = this.#connection;
24785
+ const sessionId = this.#sessionId;
24786
+ if (!connection || !sessionId || this.#closed || this.#closing) {
24787
+ throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
24788
+ }
24789
+ if (this.#activePrompt || this.#activeCompact || this.#permissionConfirmation) {
24790
+ throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
24791
+ }
24792
+ const confirmation = new GrokPermissionConfirmation(mode);
24793
+ this.#permissionConfirmation = confirmation;
24794
+ try {
24795
+ await withTimeout(Promise.all([
24796
+ confirmation.completed,
24797
+ (async () => {
24798
+ const flags = grokPermissionModeSessionMeta(mode);
24799
+ await connection.notify(GROK_PERMISSION_MODE_METHOD, {
24800
+ yolo_mode: flags.yoloMode,
24801
+ auto_mode: flags.autoMode,
24802
+ permission_mode: mode
24803
+ });
24804
+ const response = await connection.request("_x.ai/session/info", { sessionId });
24805
+ if (!isRecord14(response) || !isRecord14(response.result) || response.result.sessionId !== sessionId) {
24806
+ throw new Error("Grok did not confirm the target Session");
24807
+ }
24808
+ })()
24809
+ ]), this.#options.commandTimeoutMs, "Grok Permission Mode confirmation");
24810
+ if (this.#closed || this.#closing)
24811
+ throw new Error("Grok Session closed during configuration");
24812
+ } catch (cause) {
24813
+ const error53 = new GrokTransportError("protocolError", "Grok Permission Mode could not be confirmed; reopen the Session to continue", { cause });
24814
+ this.#fault(error53);
24815
+ await this.close();
24816
+ throw error53;
24817
+ } finally {
24818
+ this.#permissionConfirmation = null;
24819
+ }
24820
+ }
24821
+ close() {
24822
+ return this.#closePromise ??= this.#close();
24823
+ }
24824
+ async #close() {
24096
24825
  if (this.#closed)
24097
24826
  return;
24098
24827
  this.#closing = true;
24828
+ this.#permissionConfirmation?.reject(new Error("Grok Session closed during configuration"));
24099
24829
  const child = this.#child;
24100
24830
  const connection = this.#connection;
24101
24831
  if (connection && this.#sessionId && this.#initialize?.agentCapabilities?.sessionCapabilities?.close) {
24102
- await connection.closeSession({ sessionId: this.#sessionId }).catch(() => void 0);
24832
+ await withTimeout(connection.closeSession({ sessionId: this.#sessionId }), this.#options.closeTimeoutMs, "Grok Session close").catch(() => void 0);
24103
24833
  }
24104
24834
  if (child?.stdin.writable)
24105
24835
  child.stdin.end();
@@ -24127,7 +24857,7 @@ var GrokAcpTransport = class {
24127
24857
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
24128
24858
  return;
24129
24859
  }
24130
- const metadata = isRecord13(notification._meta) ? notification._meta : void 0;
24860
+ const metadata = isRecord14(notification._meta) ? notification._meta : void 0;
24131
24861
  const event = transportEvent(notification.update, metadata);
24132
24862
  if (!event)
24133
24863
  return;
@@ -24142,7 +24872,7 @@ var GrokAcpTransport = class {
24142
24872
  #handleExtensionNotification(method, params) {
24143
24873
  if (!isGrokExtensionSessionUpdateMethod(method))
24144
24874
  return;
24145
- if (typeof params.sessionId !== "string" || !isRecord13(params.update))
24875
+ if (typeof params.sessionId !== "string" || !isRecord14(params.update))
24146
24876
  return;
24147
24877
  this.#handleUpdate(params);
24148
24878
  }
@@ -24152,7 +24882,24 @@ var GrokAcpTransport = class {
24152
24882
  }
24153
24883
  return this.#activePrompt.onPermission({ request: params, options: params.options });
24154
24884
  }
24885
+ async #handleExtMethod(method, params) {
24886
+ if (method !== GROK_MCP_ELICIT_METHOD) {
24887
+ throw RequestError.methodNotFound(method);
24888
+ }
24889
+ const parsed = parseGrokMcpElicitParams(params);
24890
+ if (parsed.status === "invalid") {
24891
+ throw RequestError.invalidParams(void 0, parsed.message);
24892
+ }
24893
+ if (parsed.status === "unsupported" || this.#closed || this.#closing || this.#replay !== null || this.#activeCompact !== null || !this.#activePrompt) {
24894
+ return { ...grokMcpElicitCancel() };
24895
+ }
24896
+ if (parsed.request.sessionId !== this.#sessionId) {
24897
+ return { ...grokMcpElicitCancel() };
24898
+ }
24899
+ return { ...await this.#activePrompt.onElicitation(parsed.request) };
24900
+ }
24155
24901
  #fault(error53) {
24902
+ this.#permissionConfirmation?.reject(error53);
24156
24903
  if (this.#closing || this.#closed)
24157
24904
  return;
24158
24905
  this.#options.onFault?.(error53);
@@ -24161,8 +24908,8 @@ var GrokAcpTransport = class {
24161
24908
 
24162
24909
  // dist/session-import.js
24163
24910
  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";
24911
+ import { opendir as opendir2, readFile as readFile5, stat } from "node:fs/promises";
24912
+ import path16 from "node:path";
24166
24913
  import { createInterface as createInterface2 } from "node:readline";
24167
24914
 
24168
24915
  // ../../harness-adapter/dist/session-import.js
@@ -24283,11 +25030,11 @@ var SessionImportScope = class {
24283
25030
  // dist/session-import.js
24284
25031
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
24285
25032
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
24286
- function isRecord14(value) {
25033
+ function isRecord15(value) {
24287
25034
  return typeof value === "object" && value !== null && !Array.isArray(value);
24288
25035
  }
24289
25036
  async function readJson(file2, signal) {
24290
- return JSON.parse(await readFile4(file2, { encoding: "utf8", signal }));
25037
+ return JSON.parse(await readFile5(file2, { encoding: "utf8", signal }));
24291
25038
  }
24292
25039
  function processAlive(pid) {
24293
25040
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -24296,7 +25043,7 @@ function processAlive(pid) {
24296
25043
  process.kill(pid, 0);
24297
25044
  return true;
24298
25045
  } catch (error53) {
24299
- return isRecord14(error53) && error53.code === "EPERM";
25046
+ return isRecord15(error53) && error53.code === "EPERM";
24300
25047
  }
24301
25048
  }
24302
25049
  async function firstUserText(file2, signal) {
@@ -24313,10 +25060,10 @@ async function firstUserText(file2, signal) {
24313
25060
  } catch {
24314
25061
  continue;
24315
25062
  }
24316
- const update = isRecord14(entry) && isRecord14(entry.params) ? entry.params.update : null;
24317
- if (!isRecord14(update) || update.sessionUpdate !== "user_message_chunk")
25063
+ const update = isRecord15(entry) && isRecord15(entry.params) ? entry.params.update : null;
25064
+ if (!isRecord15(update) || update.sessionUpdate !== "user_message_chunk")
24318
25065
  continue;
24319
- const text = isRecord14(update.content) ? update.content.text : null;
25066
+ const text = isRecord15(update.content) ? update.content.text : null;
24320
25067
  return typeof text === "string" ? text : "";
24321
25068
  }
24322
25069
  return null;
@@ -24383,7 +25130,7 @@ var GrokSessionImport = class {
24383
25130
  const active = /* @__PURE__ */ new Set();
24384
25131
  let entries;
24385
25132
  try {
24386
- entries = await readJson(path14.join(this.#home(), "active_sessions.json"), signal);
25133
+ entries = await readJson(path16.join(this.#home(), "active_sessions.json"), signal);
24387
25134
  } catch (error53) {
24388
25135
  signal.throwIfAborted();
24389
25136
  if (isStorageAccessError(error53))
@@ -24393,14 +25140,14 @@ var GrokSessionImport = class {
24393
25140
  if (!Array.isArray(entries))
24394
25141
  return active;
24395
25142
  for (const entry of entries) {
24396
- if (isRecord14(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
25143
+ if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24397
25144
  active.add(entry.session_id);
24398
25145
  }
24399
25146
  return active;
24400
25147
  }
24401
25148
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
24402
25149
  async #sessionDirectories(signal) {
24403
- const root = path14.join(this.#home(), "sessions");
25150
+ const root = path16.join(this.#home(), "sessions");
24404
25151
  const found = /* @__PURE__ */ new Map();
24405
25152
  const info = await optionalLstat(root);
24406
25153
  if (!info)
@@ -24411,7 +25158,7 @@ var GrokSessionImport = class {
24411
25158
  signal.throwIfAborted();
24412
25159
  if (!workspace.isDirectory())
24413
25160
  continue;
24414
- const workspaceDirectory = path14.join(root, workspace.name);
25161
+ const workspaceDirectory = path16.join(root, workspace.name);
24415
25162
  const sessions = await opendir2(workspaceDirectory).catch((error53) => {
24416
25163
  if (isMissingFileError(error53))
24417
25164
  return null;
@@ -24424,7 +25171,7 @@ var GrokSessionImport = class {
24424
25171
  if (!session.isDirectory())
24425
25172
  continue;
24426
25173
  const directories = found.get(session.name) ?? [];
24427
- directories.push(path14.join(workspaceDirectory, session.name));
25174
+ directories.push(path16.join(workspaceDirectory, session.name));
24428
25175
  found.set(session.name, directories);
24429
25176
  }
24430
25177
  }
@@ -24432,25 +25179,25 @@ var GrokSessionImport = class {
24432
25179
  }
24433
25180
  async #candidate(sessionDirectory, active, signal) {
24434
25181
  signal.throwIfAborted();
24435
- const nativeSessionId = path14.basename(sessionDirectory);
25182
+ const nativeSessionId = path16.basename(sessionDirectory);
24436
25183
  const files = [
24437
- path14.join(sessionDirectory, "summary.json"),
24438
- path14.join(sessionDirectory, "updates.jsonl")
25184
+ path16.join(sessionDirectory, "summary.json"),
25185
+ path16.join(sessionDirectory, "updates.jsonl")
24439
25186
  ];
24440
25187
  return readStableFiles(files, async ([summaryInfo, updates]) => {
24441
25188
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24442
25189
  return null;
24443
25190
  try {
24444
25191
  const summary = await readJson(files[0], signal);
24445
- if (!isRecord14(summary) || !isRecord14(summary.info) || summary.info.id !== nativeSessionId)
25192
+ if (!isRecord15(summary) || !isRecord15(summary.info) || summary.info.id !== nativeSessionId)
24446
25193
  return null;
24447
25194
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24448
25195
  return null;
24449
25196
  const nativeCwd = summary.info.cwd;
24450
- if (typeof nativeCwd !== "string" || !path14.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
25197
+ if (typeof nativeCwd !== "string" || !path16.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24451
25198
  return null;
24452
- const cwd = path14.resolve(nativeCwd);
24453
- if (encodeURIComponent(cwd) !== path14.basename(path14.dirname(sessionDirectory)))
25199
+ const cwd = path16.resolve(nativeCwd);
25200
+ if (encodeURIComponent(cwd) !== path16.basename(path16.dirname(sessionDirectory)))
24454
25201
  return null;
24455
25202
  if (!(await stat(cwd)).isDirectory())
24456
25203
  return null;
@@ -24669,7 +25416,7 @@ var GrokSubagentLifecycle = class {
24669
25416
  };
24670
25417
 
24671
25418
  // dist/grok-models.js
24672
- function isRecord15(value) {
25419
+ function isRecord16(value) {
24673
25420
  return typeof value === "object" && value !== null && !Array.isArray(value);
24674
25421
  }
24675
25422
  function nonBlank(value) {
@@ -24681,7 +25428,7 @@ function thinkingOptions(value) {
24681
25428
  const seen = /* @__PURE__ */ new Set();
24682
25429
  const options = [];
24683
25430
  for (const candidate of value) {
24684
- if (!isRecord15(candidate) || !nonBlank(candidate.label))
25431
+ if (!isRecord16(candidate) || !nonBlank(candidate.label))
24685
25432
  continue;
24686
25433
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
24687
25434
  if (!id.success || seen.has(id.data))
@@ -24692,7 +25439,7 @@ function thinkingOptions(value) {
24692
25439
  return options;
24693
25440
  }
24694
25441
  function parseGrokModelState(value) {
24695
- if (!isRecord15(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
25442
+ if (!isRecord16(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24696
25443
  return null;
24697
25444
  }
24698
25445
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -24704,12 +25451,12 @@ function parseGrokModelState(value) {
24704
25451
  const models = [];
24705
25452
  let currentThinkingOptionId;
24706
25453
  for (const candidate of value.availableModels) {
24707
- if (!isRecord15(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
25454
+ if (!isRecord16(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24708
25455
  continue;
24709
25456
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
24710
25457
  if (!ref.success)
24711
25458
  continue;
24712
- const metadata = isRecord15(candidate._meta) ? candidate._meta : {};
25459
+ const metadata = isRecord16(candidate._meta) ? candidate._meta : {};
24713
25460
  const options2 = thinkingOptions(metadata.reasoningEfforts);
24714
25461
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
24715
25462
  defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
@@ -24748,10 +25495,10 @@ function parseGrokModelState(value) {
24748
25495
  };
24749
25496
  }
24750
25497
  function modelStateFromInitialize(response) {
24751
- return parseGrokModelState(isRecord15(response._meta) ? response._meta.modelState : void 0);
25498
+ return parseGrokModelState(isRecord16(response._meta) ? response._meta.modelState : void 0);
24752
25499
  }
24753
25500
  function modelStateFromSessionResponse(response) {
24754
- return parseGrokModelState(isRecord15(response) ? response.models : void 0);
25501
+ return parseGrokModelState(isRecord16(response) ? response.models : void 0);
24755
25502
  }
24756
25503
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
24757
25504
  const selectedModel = model2;
@@ -24770,12 +25517,12 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
24770
25517
  }
24771
25518
 
24772
25519
  // 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";
25520
+ import { readFile as readFile6 } from "node:fs/promises";
25521
+ import os7 from "node:os";
25522
+ import path17 from "node:path";
24776
25523
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
24777
25524
  var REQUEST_TIMEOUT_MS = 15e3;
24778
- function isRecord16(value) {
25525
+ function isRecord17(value) {
24779
25526
  return typeof value === "object" && value !== null && !Array.isArray(value);
24780
25527
  }
24781
25528
  function finitePercent(value) {
@@ -24784,15 +25531,15 @@ function finitePercent(value) {
24784
25531
  return Math.min(100, Math.max(0, value));
24785
25532
  }
24786
25533
  function nonNegativeCentValue(value) {
24787
- if (!isRecord16(value))
25534
+ if (!isRecord17(value))
24788
25535
  return void 0;
24789
25536
  const amount = value.val === void 0 ? 0 : value.val;
24790
25537
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
24791
25538
  return void 0;
24792
25539
  return amount;
24793
25540
  }
24794
- function grokHome2(environment) {
24795
- return environment.GROK_HOME ?? path15.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
25541
+ function grokHome3(environment) {
25542
+ return environment.GROK_HOME ?? path17.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
24796
25543
  }
24797
25544
  function periodTypeFrom(value) {
24798
25545
  if (typeof value !== "string")
@@ -24808,7 +25555,7 @@ function productUsageFrom(value) {
24808
25555
  if (!Array.isArray(value))
24809
25556
  return void 0;
24810
25557
  const products = value.flatMap((entry) => {
24811
- if (!isRecord16(entry) || typeof entry.product !== "string")
25558
+ if (!isRecord17(entry) || typeof entry.product !== "string")
24812
25559
  return [];
24813
25560
  const usagePercent = finitePercent(entry.usagePercent);
24814
25561
  const labels = {
@@ -24829,10 +25576,10 @@ function productUsageFrom(value) {
24829
25576
  return products.length > 0 ? products : void 0;
24830
25577
  }
24831
25578
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24832
- if (!isRecord16(value) || !isRecord16(value.config))
25579
+ if (!isRecord17(value) || !isRecord17(value.config))
24833
25580
  return null;
24834
25581
  const config2 = value.config;
24835
- const period = isRecord16(config2.currentPeriod) ? config2.currentPeriod : void 0;
25582
+ const period = isRecord17(config2.currentPeriod) ? config2.currentPeriod : void 0;
24836
25583
  const periodType = periodTypeFrom(period?.type);
24837
25584
  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
25585
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24859,11 +25606,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24859
25606
  };
24860
25607
  }
24861
25608
  function selectAccessToken(auth, now) {
24862
- if (!isRecord16(auth))
25609
+ if (!isRecord17(auth))
24863
25610
  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")));
25611
+ 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
25612
  for (const [, value] of entries) {
24866
- if (!isRecord16(value) || typeof value.key !== "string")
25613
+ if (!isRecord17(value) || typeof value.key !== "string")
24867
25614
  continue;
24868
25615
  if (typeof value.expires_at === "string") {
24869
25616
  const expiresAt = Date.parse(value.expires_at);
@@ -24884,8 +25631,8 @@ async function fetchGrokAccount(input = {}) {
24884
25631
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24885
25632
  return null;
24886
25633
  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");
25634
+ const authPath = path17.join(grokHome3(environment), "auth.json");
25635
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile6(authPath, "utf8");
24889
25636
  const token = selectAccessToken(JSON.parse(raw), now);
24890
25637
  if (!token)
24891
25638
  return null;
@@ -24934,7 +25681,7 @@ async function fetchGrokCredits(input = {}) {
24934
25681
 
24935
25682
  // dist/grok-usage.js
24936
25683
  var USD_TICKS_PER_DOLLAR = 1e10;
24937
- function isRecord17(value) {
25684
+ function isRecord18(value) {
24938
25685
  return typeof value === "object" && value !== null && !Array.isArray(value);
24939
25686
  }
24940
25687
  function optionalToken(value) {
@@ -24951,7 +25698,7 @@ function combineUsage(base, next) {
24951
25698
  return base === null ? next : parseHostUsage({ ...base, ...next });
24952
25699
  }
24953
25700
  function usageFromNative(value) {
24954
- if (!isRecord17(value))
25701
+ if (!isRecord18(value))
24955
25702
  return null;
24956
25703
  const inputTokens = optionalToken(value.inputTokens);
24957
25704
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24975,7 +25722,7 @@ function usageFromNative(value) {
24975
25722
  }
24976
25723
  }
24977
25724
  function usageFromResponse(value) {
24978
- if (!isRecord17(value))
25725
+ if (!isRecord18(value))
24979
25726
  return null;
24980
25727
  const buckets = [
24981
25728
  value.input_tokens,
@@ -25075,7 +25822,7 @@ var GrokTurnUsage = class {
25075
25822
  }
25076
25823
  };
25077
25824
  function usageFromSignals(value) {
25078
- if (!isRecord17(value))
25825
+ if (!isRecord18(value))
25079
25826
  return null;
25080
25827
  try {
25081
25828
  return parseHostUsage({
@@ -25095,7 +25842,7 @@ var summedUsageFields = [
25095
25842
  "totalTokens"
25096
25843
  ];
25097
25844
  function nativeCostTicks(value) {
25098
- if (!isRecord17(value))
25845
+ if (!isRecord18(value))
25099
25846
  return void 0;
25100
25847
  const ticks = value.costUsdTicks;
25101
25848
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -25103,7 +25850,7 @@ function nativeCostTicks(value) {
25103
25850
  return ticks;
25104
25851
  }
25105
25852
  function sessionCostFromNative(value, initialCostUsd) {
25106
- if (!isRecord17(value))
25853
+ if (!isRecord18(value))
25107
25854
  return void 0;
25108
25855
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
25109
25856
  return void 0;
@@ -25132,7 +25879,7 @@ function sessionUsageFromHistory(events) {
25132
25879
  continue;
25133
25880
  const usage = usageFromNative(event.usage);
25134
25881
  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;
25882
+ 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
25883
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
25137
25884
  }
25138
25885
  if (latestByKey.size === 0)
@@ -25186,7 +25933,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
25186
25933
  function usageFromUpdate(update, metadata, contextWindowTokens) {
25187
25934
  try {
25188
25935
  if (update?.sessionUpdate === "usage_update") {
25189
- const cost = isRecord17(update.cost) ? update.cost : null;
25936
+ const cost = isRecord18(update.cost) ? update.cost : null;
25190
25937
  return parseHostUsage({
25191
25938
  contextUsedTokens: update.used,
25192
25939
  contextWindowTokens: update.size,
@@ -25226,7 +25973,7 @@ function capabilitiesForModels(modelState) {
25226
25973
  selectModel: modelState.catalog.models.length > 0,
25227
25974
  selectThinkingOption: modelState.catalog.thinkingOptions.length > 0,
25228
25975
  selectPermissionMode: true,
25229
- permissionModeScope: "atCreate"
25976
+ permissionModeScope: "live"
25230
25977
  },
25231
25978
  history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
25232
25979
  subagents: { observe: true, readTranscript: true }
@@ -25380,6 +26127,8 @@ var GrokHarnessSession = class {
25380
26127
  return { ok: false, error: invalidState("Grok Session is not open") };
25381
26128
  if ("commandId" in command)
25382
26129
  return this.#executeHarnessCommand(command);
26130
+ if (command.type === "turn.steer")
26131
+ return unsupportedSteer("Grok");
25383
26132
  if (command.type === "turn.cancel")
25384
26133
  return this.#cancel(command);
25385
26134
  if (command.type === "interaction.respond")
@@ -25422,6 +26171,7 @@ var GrokHarnessSession = class {
25422
26171
  });
25423
26172
  const active = {
25424
26173
  command,
26174
+ textIdentity: { turnIndex: this.#snapshot.turns.length, agentMessage: 0, reasoning: 0 },
25425
26175
  usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
25426
26176
  agent: null,
25427
26177
  agentMessageId: null,
@@ -25436,6 +26186,7 @@ var GrokHarnessSession = class {
25436
26186
  subagents: this.#createSubagents(),
25437
26187
  completedItems: [],
25438
26188
  approvals: /* @__PURE__ */ new Map(),
26189
+ elicitations: /* @__PURE__ */ new Map(),
25439
26190
  cancellationRequested: false,
25440
26191
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
25441
26192
  completion,
@@ -25443,7 +26194,7 @@ var GrokHarnessSession = class {
25443
26194
  };
25444
26195
  this.#active = active;
25445
26196
  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, {
26197
+ 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
26198
  status: "failed",
25448
26199
  error: normalizeError(error53, "nativeFailure")
25449
26200
  }));
@@ -25512,6 +26263,7 @@ var GrokHarnessSession = class {
25512
26263
  });
25513
26264
  const active = {
25514
26265
  command: { type: "turn.start", turnId: command.turnId, input: [] },
26266
+ textIdentity: { turnIndex: this.#snapshot.turns.length, agentMessage: 0, reasoning: 0 },
25515
26267
  agent: null,
25516
26268
  agentMessageId: null,
25517
26269
  rawAgentText: "",
@@ -25525,6 +26277,7 @@ var GrokHarnessSession = class {
25525
26277
  subagents: this.#createSubagents(),
25526
26278
  completedItems: [],
25527
26279
  approvals: /* @__PURE__ */ new Map(),
26280
+ elicitations: /* @__PURE__ */ new Map(),
25528
26281
  cancellationRequested: false,
25529
26282
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
25530
26283
  completion,
@@ -25659,14 +26412,29 @@ var GrokHarnessSession = class {
25659
26412
  }
25660
26413
  };
25661
26414
  }
25662
- return {
25663
- ok: false,
25664
- error: {
25665
- code: "invalidRequest",
25666
- message: "Grok Permission Mode is fixed at Session creation",
25667
- retryable: false
25668
- }
25669
- };
26415
+ if (this.#active || this.#configuring) {
26416
+ return {
26417
+ ok: false,
26418
+ error: {
26419
+ code: "sessionBusy",
26420
+ message: "Grok Session cannot configure permissions during another operation",
26421
+ retryable: true
26422
+ }
26423
+ };
26424
+ }
26425
+ this.#configuring = true;
26426
+ try {
26427
+ await this.#transport.setPermissionMode(command.permissionModeId);
26428
+ if (this.#phase !== "open")
26429
+ return { ok: false, error: invalidState("Grok Session is closed") };
26430
+ this.#state = { ...this.#state, effectivePermissionModeId: command.permissionModeId };
26431
+ this.#event({ type: "session.state.changed", state: this.#state });
26432
+ return { ok: true, value: { completed: true } };
26433
+ } catch (error53) {
26434
+ return { ok: false, error: normalizeError(error53, "nativeFailure") };
26435
+ } finally {
26436
+ this.#configuring = false;
26437
+ }
25670
26438
  }
25671
26439
  async #cancel(command) {
25672
26440
  const active = this.#active;
@@ -25679,6 +26447,7 @@ var GrokHarnessSession = class {
25679
26447
  for (const approval of active.approvals.values()) {
25680
26448
  approval.resolve({ outcome: { outcome: "cancelled" } });
25681
26449
  }
26450
+ this.#cancelActiveElicitations(active);
25682
26451
  try {
25683
26452
  await this.#transport.cancel();
25684
26453
  return { ok: true, value: { cancellationRequested: true } };
@@ -25688,8 +26457,9 @@ var GrokHarnessSession = class {
25688
26457
  }
25689
26458
  async #respond(command) {
25690
26459
  const active = this.#active;
25691
- const pending = active?.approvals.get(command.interactionId);
25692
- if (!active || !pending)
26460
+ const permission = active?.approvals.get(command.interactionId);
26461
+ const elicitation = active?.elicitations.get(command.interactionId);
26462
+ if (!active || !permission && !elicitation)
25693
26463
  return { ok: false, error: invalidState("Grok Approval is not pending") };
25694
26464
  if (command.response.type !== "approval") {
25695
26465
  return {
@@ -25701,10 +26471,30 @@ var GrokHarnessSession = class {
25701
26471
  }
25702
26472
  };
25703
26473
  }
25704
- const validation = validateHostApprovalResponse(pending.interaction, command.response);
26474
+ const response = command.response;
26475
+ if (elicitation) {
26476
+ const validation2 = validateHostApprovalResponse(elicitation.interaction, response);
26477
+ if (validation2)
26478
+ return { ok: false, error: validation2 };
26479
+ const action = elicitation.interaction.actions.find(({ id }) => id === response.actionId);
26480
+ if (!action)
26481
+ return {
26482
+ ok: false,
26483
+ error: {
26484
+ code: "invalidRequest",
26485
+ message: "Grok Approval action is unavailable",
26486
+ retryable: false
26487
+ }
26488
+ };
26489
+ this.#settleElicitation(active, elicitation, grokMcpElicitResponseForAction(action.effect === "allowOnce" || action.effect === "allowAlways" ? action.effect : "deny"), "responded");
26490
+ return { ok: true, value: { accepted: true } };
26491
+ }
26492
+ if (!permission)
26493
+ return { ok: false, error: invalidState("Grok Approval is not pending") };
26494
+ const validation = validateHostApprovalResponse(permission.interaction, response);
25705
26495
  if (validation)
25706
26496
  return { ok: false, error: validation };
25707
- const option = pending.options.get(command.response.actionId);
26497
+ const option = permission.options.get(response.actionId);
25708
26498
  if (!option)
25709
26499
  return {
25710
26500
  ok: false,
@@ -25715,7 +26505,7 @@ var GrokHarnessSession = class {
25715
26505
  }
25716
26506
  };
25717
26507
  active.approvals.delete(command.interactionId);
25718
- pending.resolve({ outcome: { outcome: "selected", optionId: option.optionId } });
26508
+ permission.resolve({ outcome: { outcome: "selected", optionId: option.optionId } });
25719
26509
  this.#event({
25720
26510
  type: "interaction.closed",
25721
26511
  interactionId: command.interactionId,
@@ -25744,10 +26534,57 @@ var GrokHarnessSession = class {
25744
26534
  actions
25745
26535
  };
25746
26536
  return new Promise((resolve) => {
25747
- active.approvals.set(interactionId, { interaction, options, resolve });
26537
+ active.approvals.set(interactionId, {
26538
+ kind: "permission",
26539
+ interaction,
26540
+ options,
26541
+ resolve
26542
+ });
25748
26543
  this.#channel.emit({ kind: "interaction", interaction });
25749
26544
  });
25750
26545
  }
26546
+ #requestElicitation(active, request) {
26547
+ if (this.#active !== active || this.#phase !== "open" || active.cancellationRequested) {
26548
+ return Promise.resolve(grokMcpElicitCancel());
26549
+ }
26550
+ for (const pending of active.elicitations.values()) {
26551
+ if (pending.nativeToolCallId === request.toolCallId) {
26552
+ return Promise.resolve(grokMcpElicitCancel());
26553
+ }
26554
+ }
26555
+ const interactionId = hostInteractionIdSchema.parse(this.#randomUUID());
26556
+ const interaction = projectGrokMcpElicitApproval({
26557
+ interactionId,
26558
+ turnId: active.command.turnId,
26559
+ request
26560
+ });
26561
+ return new Promise((resolve) => {
26562
+ active.elicitations.set(interactionId, {
26563
+ kind: "elicitation",
26564
+ nativeToolCallId: request.toolCallId,
26565
+ interaction,
26566
+ resolve
26567
+ });
26568
+ this.#channel.emit({ kind: "interaction", interaction });
26569
+ });
26570
+ }
26571
+ #settleElicitation(active, pending, response, reason) {
26572
+ if (!active.elicitations.has(pending.interaction.interactionId))
26573
+ return;
26574
+ active.elicitations.delete(pending.interaction.interactionId);
26575
+ pending.resolve(response);
26576
+ this.#event({
26577
+ type: "interaction.closed",
26578
+ interactionId: pending.interaction.interactionId,
26579
+ turnId: active.command.turnId,
26580
+ reason
26581
+ });
26582
+ }
26583
+ #cancelActiveElicitations(active) {
26584
+ for (const pending of [...active.elicitations.values()]) {
26585
+ this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
26586
+ }
26587
+ }
25751
26588
  #handleEvent(active, event) {
25752
26589
  if (this.#active !== active || this.#phase !== "open")
25753
26590
  return;
@@ -25776,6 +26613,12 @@ var GrokHarnessSession = class {
25776
26613
  else if (event.type === "compaction.completed") {
25777
26614
  active.compactionTerminal = event;
25778
26615
  this.#completeCompaction(active, event);
26616
+ } else if (event.type === "elicitation.resolved") {
26617
+ for (const pending of [...active.elicitations.values()]) {
26618
+ if (pending.nativeToolCallId === event.toolCallId) {
26619
+ this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
26620
+ }
26621
+ }
25779
26622
  } else if (event.type === "usage" || event.type === "turn.completed")
25780
26623
  return;
25781
26624
  }
@@ -25843,7 +26686,7 @@ var GrokHarnessSession = class {
25843
26686
  if (!active.agent) {
25844
26687
  active.agent = {
25845
26688
  type: "agentMessage",
25846
- itemId: hostItemIdSchema.parse(this.#randomUUID()),
26689
+ itemId: grokTextItemId(this.#transport.sessionId, active.textIdentity.turnIndex, "agentMessage", ++active.textIdentity.agentMessage),
25847
26690
  text: ""
25848
26691
  };
25849
26692
  active.rawAgentText = "";
@@ -25875,7 +26718,7 @@ var GrokHarnessSession = class {
25875
26718
  if (!active.reasoning) {
25876
26719
  active.reasoning = {
25877
26720
  type: "reasoning",
25878
- itemId: hostItemIdSchema.parse(this.#randomUUID()),
26721
+ itemId: grokTextItemId(this.#transport.sessionId, active.textIdentity.turnIndex, "reasoning", ++active.textIdentity.reasoning),
25879
26722
  text: ""
25880
26723
  };
25881
26724
  this.#event({ type: "item.started", turnId: active.command.turnId, item: active.reasoning });
@@ -26184,6 +27027,7 @@ var GrokHarnessSession = class {
26184
27027
  reason: "cancelled"
26185
27028
  });
26186
27029
  }
27030
+ this.#cancelActiveElicitations(active);
26187
27031
  this.#active = null;
26188
27032
  if (usage || this.#usage)
26189
27033
  this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
@@ -26221,6 +27065,7 @@ var GrokHarnessSession = class {
26221
27065
  active.cancellationRequested = true;
26222
27066
  for (const approval of active.approvals.values())
26223
27067
  approval.resolve({ outcome: { outcome: "cancelled" } });
27068
+ this.#cancelActiveElicitations(active);
26224
27069
  await this.#transport.cancel().catch(() => void 0);
26225
27070
  await Promise.race([
26226
27071
  active.completion,
@@ -26312,7 +27157,7 @@ var GrokAdapter = class {
26312
27157
  this.usageStatistics = createGrokUsageStatistics(options.environment ?? process.env);
26313
27158
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
26314
27159
  this.#dependencies = dependencies ?? {
26315
- randomUUID,
27160
+ randomUUID: randomUUID2,
26316
27161
  createTransport: (transportOptions) => new GrokAcpTransport({ ...options, ...transportOptions })
26317
27162
  };
26318
27163
  this.#fetchCredits = this.#dependencies.fetchCredits ?? ((input) => fetchGrokCredits(input.environment ? { environment: input.environment } : this.#environment ? { environment: this.#environment } : {}));
@@ -26358,7 +27203,7 @@ var GrokAdapter = class {
26358
27203
  async inspect(input = {}) {
26359
27204
  if (this.#closePromise)
26360
27205
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
26361
- const cwd = path16.resolve(input.cwd ?? process.cwd());
27206
+ const cwd = path18.resolve(input.cwd ?? process.cwd());
26362
27207
  if (!input.refresh) {
26363
27208
  const cached2 = this.#inspectionCache.get(cwd);
26364
27209
  if (cached2)
@@ -26420,7 +27265,20 @@ var GrokAdapter = class {
26420
27265
  }
26421
27266
  };
26422
27267
  }
26423
- const cwd = path16.resolve(input.cwd);
27268
+ try {
27269
+ await applyGrokComputerUsePreference(this.#environment ?? process.env);
27270
+ } catch {
27271
+ console.warn("Could not apply Grok Computer Use settings");
27272
+ return {
27273
+ ok: false,
27274
+ error: {
27275
+ code: "unavailable",
27276
+ message: "Could not apply Grok Computer Use settings. Retry after fixing Grok config.",
27277
+ retryable: true
27278
+ }
27279
+ };
27280
+ }
27281
+ const cwd = path18.resolve(input.cwd);
26424
27282
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
26425
27283
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
26426
27284
  return {
@@ -26573,6 +27431,7 @@ var GrokAdapter = class {
26573
27431
  ]);
26574
27432
  }
26575
27433
  }
27434
+ await transport.setPermissionMode(initialPermissionModeId);
26576
27435
  const history = await transport.getHistory();
26577
27436
  let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
26578
27437
  if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {