@codexhost/cli-darwin-x64 0.10.2 → 0.12.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/THIRD_PARTY_NOTICES.txt +4 -0
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +18001 -0
  5. package/app/console-web.js +27674 -0
  6. package/app/desktop-controller.mjs +452 -110
  7. package/app/host-runtime.mjs +6670 -1272
  8. package/app/plugins/antigravity/plugin.mjs +686 -305
  9. package/app/plugins/claude-code/plugin.mjs +2283 -1450
  10. package/app/plugins/codebuddy/plugin.mjs +1272 -506
  11. package/app/plugins/cursor-cli/manifest.json +1 -1
  12. package/app/plugins/cursor-cli/plugin.mjs +1295 -497
  13. package/app/plugins/deepseek-harness/plugin.mjs +4718 -4925
  14. package/app/plugins/enabled.json +2 -1
  15. package/app/plugins/grok/plugin.mjs +1012 -369
  16. package/app/plugins/hermes/plugin.mjs +18587 -22714
  17. package/app/plugins/kimi-code/plugin.mjs +1283 -355
  18. package/app/plugins/kiro-cli/plugin.mjs +840 -299
  19. package/app/plugins/omp/plugin.mjs +1045 -328
  20. package/app/plugins/opencode/plugin.mjs +5341 -1686
  21. package/app/plugins/pi/plugin.mjs +1343 -534
  22. package/app/plugins/qoder/plugin.mjs +913 -258
  23. package/app/plugins/qoder-cn/plugin.mjs +712 -49
  24. package/app/plugins/workbuddy/plugin.mjs +531 -44
  25. package/app/plugins/zcode/assets/icon.svg +8 -0
  26. package/app/plugins/zcode/manifest.json +14 -0
  27. package/app/plugins/zcode/plugin.mjs +19202 -0
  28. package/app/renderer-extension.js +5011 -1899
  29. package/bin/codexhost +0 -0
  30. package/libexec/codexhost-shim +0 -0
  31. package/libexec/codexhost-updater +0 -0
  32. package/licenses/OpenCode-v2-Client-LICENSE.txt +21 -0
  33. package/package.json +1 -1
@@ -5,20 +5,387 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
+ // ../../harness-discovery/dist/environment.js
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ function targetPath(platform) {
12
+ return platform === "win32" ? path.win32 : path.posix;
13
+ }
14
+ function environmentValue(environment, name) {
15
+ const lowered = name.toLowerCase();
16
+ for (const [key, value] of Object.entries(environment)) {
17
+ if (key.toLowerCase() === lowered)
18
+ return value;
19
+ }
20
+ return void 0;
21
+ }
22
+ function pathDelimiter(platform) {
23
+ return platform === "win32" ? ";" : ":";
24
+ }
25
+ function pathDirectories(environment, platform) {
26
+ return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
27
+ }
28
+ function executableExtensions(command, platform, environment) {
29
+ if (platform !== "win32")
30
+ return [""];
31
+ if (targetPath(platform).extname(command) !== "")
32
+ return [""];
33
+ return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
34
+ }
35
+ function isExecutableFile(filePath, platform) {
36
+ try {
37
+ fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
+ return fs.statSync(filePath).isFile();
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+ function subdirectoryNames(directory) {
44
+ try {
45
+ return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
50
+ function newestFirst(names) {
51
+ return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
52
+ }
53
+
54
+ // ../../harness-discovery/dist/invocation.js
55
+ import path2 from "node:path";
56
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
57
+ const extension = path2.win32.extname(command).toLowerCase();
58
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
59
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
60
+ }
61
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
62
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
63
+ return {
64
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
65
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
66
+ windowsVerbatimArguments: true
67
+ };
68
+ }
69
+
70
+ // ../../harness-discovery/dist/node-runtime.js
71
+ import path3 from "node:path";
72
+ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
73
+ const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
74
+ const delimiter = platform === "win32" ? ";" : ":";
75
+ const runtimeDirectory = path3.dirname(runtimeExecutable);
76
+ const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
77
+ const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
78
+ if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
79
+ directories.push(runtimeDirectory);
80
+ }
81
+ return { ...environment, [pathKey]: directories.join(delimiter) };
82
+ }
83
+
84
+ // ../../harness-discovery/dist/resolve.js
85
+ import os from "node:os";
86
+
87
+ // ../../harness-discovery/dist/version-managers.js
88
+ function versionManagerBinaryDirectories(context) {
89
+ const { platform, environment, home } = context;
90
+ const list = context.subdirectories ?? subdirectoryNames;
91
+ const pathFlavor = targetPath(platform);
92
+ const value = (name) => environmentValue(environment, name);
93
+ const directories = [];
94
+ const versioned = (root, ...tail) => {
95
+ for (const version2 of newestFirst(list(root))) {
96
+ directories.push(pathFlavor.join(root, version2, ...tail));
97
+ }
98
+ };
99
+ if (platform === "win32") {
100
+ const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
101
+ const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
102
+ versioned(pathFlavor.join(appData, "nvm"));
103
+ versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
104
+ directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
105
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
106
+ const pnpmHome2 = value("PNPM_HOME");
107
+ if (pnpmHome2)
108
+ directories.push(pnpmHome2);
109
+ directories.push(pathFlavor.join(localAppData, "pnpm"));
110
+ return directories;
111
+ }
112
+ versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
113
+ const fnmRoots = [
114
+ value("FNM_DIR"),
115
+ pathFlavor.join(home, ".local", "share", "fnm"),
116
+ pathFlavor.join(home, "Library", "Application Support", "fnm")
117
+ ].filter((root) => root !== void 0);
118
+ for (const root of fnmRoots) {
119
+ versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
120
+ }
121
+ const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
122
+ versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
123
+ directories.push(pathFlavor.join(voltaHome, "bin"));
124
+ const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
125
+ versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
126
+ directories.push(pathFlavor.join(asdfHome, "shims"));
127
+ const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
128
+ versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
129
+ directories.push(pathFlavor.join(nodenvHome, "shims"));
130
+ versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
131
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
132
+ const pnpmHome = value("PNPM_HOME");
133
+ if (pnpmHome)
134
+ directories.push(pnpmHome);
135
+ directories.push(pathFlavor.join(home, "Library", "pnpm"));
136
+ directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
137
+ for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
138
+ for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
139
+ directories.push(pathFlavor.join(prefix, formula, "bin"));
140
+ }
141
+ }
142
+ return directories;
143
+ }
144
+
145
+ // ../../harness-discovery/dist/resolve.js
146
+ var VERSION_MANAGER_ROOTS = "<version-managers>";
147
+ function installRootExtensions(platform) {
148
+ return platform === "win32" ? [".exe", ".cmd"] : [""];
149
+ }
150
+ function resolveHomeDirectory(input) {
151
+ return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
152
+ }
153
+ function templateVariables(environment, platform, home) {
154
+ const pathFlavor = targetPath(platform);
155
+ return {
156
+ HOME: home,
157
+ USERPROFILE: home,
158
+ APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
159
+ LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
160
+ };
161
+ }
162
+ function joinTemplate(platform, value) {
163
+ const pathFlavor = targetPath(platform);
164
+ const segments = value.split("/");
165
+ const head = segments[0] ?? "";
166
+ const tail = segments.slice(1);
167
+ if (head === "")
168
+ return pathFlavor.join(pathFlavor.sep, ...tail);
169
+ return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
170
+ }
171
+ function expandInstallRoot(template, environment, platform, home) {
172
+ const variables = templateVariables(environment, platform, home);
173
+ let unresolved = false;
174
+ const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
175
+ const value = variables[name] ?? environmentValue(environment, name);
176
+ if (value === void 0 || value === "") {
177
+ unresolved = true;
178
+ return "";
179
+ }
180
+ return value;
181
+ });
182
+ return unresolved ? void 0 : joinTemplate(platform, substituted);
183
+ }
184
+ function installRootDirectories(spec, input, dependencies, platform, home) {
185
+ const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
186
+ const directories = [];
187
+ for (const template of templates) {
188
+ if (template === VERSION_MANAGER_ROOTS) {
189
+ directories.push(...versionManagerBinaryDirectories({
190
+ platform,
191
+ environment: input.environment,
192
+ home,
193
+ ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
194
+ }));
195
+ continue;
196
+ }
197
+ const directory = expandInstallRoot(template, input.environment, platform, home);
198
+ if (directory !== void 0)
199
+ directories.push(directory);
200
+ }
201
+ return directories;
202
+ }
203
+ function harnessCandidates(spec, input, dependencies = {}) {
204
+ const platform = input.platform ?? process.platform;
205
+ const pathFlavor = targetPath(platform);
206
+ const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
207
+ const command = configured ?? spec.command;
208
+ if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
209
+ return [{ candidate: command, source: "configured" }];
210
+ }
211
+ const candidates = [];
212
+ const extensions = executableExtensions(command, platform, input.environment);
213
+ for (const directory of pathDirectories(input.environment, platform)) {
214
+ for (const extension of extensions) {
215
+ candidates.push({
216
+ candidate: pathFlavor.join(directory, command + extension),
217
+ source: "path"
218
+ });
219
+ }
220
+ }
221
+ if (configured !== void 0)
222
+ return candidates;
223
+ const home = resolveHomeDirectory(input);
224
+ for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
225
+ for (const extension of installRootExtensions(platform)) {
226
+ candidates.push({
227
+ candidate: pathFlavor.join(directory, spec.command + extension),
228
+ source: "install-root"
229
+ });
230
+ }
231
+ }
232
+ return candidates;
233
+ }
234
+ function resolveHarnessExecutable(spec, input, dependencies = {}) {
235
+ const platform = input.platform ?? process.platform;
236
+ const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
237
+ const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
238
+ const context = { platform, isExecutable };
239
+ for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
240
+ const executable = runnable(candidate, context);
241
+ if (executable !== void 0 && isExecutable(executable))
242
+ return { executable, source };
243
+ }
244
+ return void 0;
245
+ }
246
+
247
+ // ../../harness-discovery/dist/installation.js
248
+ import { execFile } from "node:child_process";
249
+ import { homedir } from "node:os";
250
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
251
+ const env = withNodeRuntimeOnPath(environment);
252
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
253
+ return new Promise((resolve, reject) => {
254
+ const child = execFile(invocation.command, invocation.arguments, {
255
+ env,
256
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
257
+ encoding: "utf8",
258
+ timeout,
259
+ killSignal: "SIGKILL",
260
+ maxBuffer: 1024 * 1024,
261
+ windowsHide: true,
262
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
263
+ }, (error53, stdout, stderr) => {
264
+ if (error53)
265
+ reject(new Error(error53.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
266
+ else
267
+ resolve((stdout || stderr).trim());
268
+ });
269
+ child.stdin?.end();
270
+ });
271
+ }
272
+ function installationVersion(value) {
273
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
274
+ throw new Error("Harness returned an invalid version");
275
+ return value.trim().replace(/^v/, "");
276
+ }
277
+ function createInstallationManager(options) {
278
+ let checking;
279
+ let updating;
280
+ const check2 = () => checking ??= options.check().finally(() => {
281
+ checking = void 0;
282
+ });
283
+ return (action) => {
284
+ if (updating)
285
+ return updating;
286
+ if (action === "check")
287
+ return check2();
288
+ updating = (async () => {
289
+ const before = await check2();
290
+ if (!before.updateAvailable)
291
+ return before;
292
+ if (!before.canUpdate)
293
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
294
+ await options.update(before);
295
+ const after = await check2();
296
+ if (after.currentVersion === before.currentVersion)
297
+ throw new Error("The Harness version did not change; check the native updater and retry");
298
+ return after;
299
+ })().finally(() => {
300
+ updating = void 0;
301
+ });
302
+ return updating;
303
+ };
304
+ }
305
+ async function fetchInstallationText(url2) {
306
+ const request = async () => {
307
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
308
+ if (!response.ok)
309
+ throw new Error("Could not check the latest Harness version");
310
+ return response.text();
311
+ };
312
+ try {
313
+ return await request();
314
+ } catch (error53) {
315
+ if (error53 instanceof DOMException && (error53.name === "AbortError" || error53.name === "TimeoutError"))
316
+ throw error53;
317
+ return request();
318
+ }
319
+ }
320
+
321
+ // ../../harness-discovery/dist/installer.js
322
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
323
+ import { tmpdir } from "node:os";
324
+ import { join } from "node:path";
325
+ function createHarnessInstaller(environment, source) {
326
+ return async () => {
327
+ if (!["darwin", "linux", "win32"].includes(process.platform))
328
+ throw new Error("Unsupported installation platform");
329
+ const env = withNodeRuntimeOnPath(environment);
330
+ if ("npm" in source) {
331
+ const npm = resolveHarnessExecutable({
332
+ id: "npm",
333
+ command: "npm",
334
+ installRoots: {
335
+ posix: [
336
+ "~/.npm-global/bin",
337
+ "~/.local/bin",
338
+ VERSION_MANAGER_ROOTS,
339
+ "/opt/homebrew/bin",
340
+ "/usr/local/bin",
341
+ "/usr/bin"
342
+ ],
343
+ windows: [
344
+ "${APPDATA}/npm",
345
+ VERSION_MANAGER_ROOTS,
346
+ "${ProgramFiles}/nodejs",
347
+ "${LOCALAPPDATA}/Programs/nodejs"
348
+ ]
349
+ }
350
+ }, { environment: env });
351
+ if (!npm)
352
+ throw new Error("Install Node.js and npm first");
353
+ await runInstallationCommand(npm.executable, ["install", "--global", source.npm], {
354
+ ...env,
355
+ ...source.allowScripts ? { npm_config_allow_scripts: source.allowScripts } : {}
356
+ }, 6e5);
357
+ return;
358
+ }
359
+ const windows = process.platform === "win32";
360
+ const url2 = windows ? source.windows : source.posix;
361
+ if (new URL(url2).protocol !== "https:")
362
+ throw new Error("Installer requires HTTPS");
363
+ const script = await fetchInstallationText(url2);
364
+ const directory = await mkdtemp(join(tmpdir(), "codexhost-installer-"));
365
+ try {
366
+ const file2 = join(directory, windows ? "install.ps1" : "install.sh");
367
+ await writeFile(file2, script, { mode: 384 });
368
+ await runInstallationCommand(windows ? "powershell.exe" : source.shell ?? "bash", windows ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file2] : [file2], env, 6e5);
369
+ } finally {
370
+ await rm(directory, { recursive: true, force: true });
371
+ }
372
+ };
373
+ }
374
+
8
375
  // dist/grok-adapter.js
9
376
  import { randomUUID } from "node:crypto";
10
377
 
11
378
  // dist/grok-credential-export.js
12
379
  import { createHash } from "node:crypto";
13
380
  import { readFile } from "node:fs/promises";
14
- import os from "node:os";
15
- import path from "node:path";
381
+ import os2 from "node:os";
382
+ import path4 from "node:path";
16
383
  async function readGrokCredentials(environment) {
17
384
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
18
385
  return [];
19
386
  try {
20
- const home = environment.GROK_HOME ?? path.join(environment.HOME ?? os.homedir(), ".grok");
21
- const auth = JSON.parse(await readFile(path.join(home, "auth.json"), "utf8"));
387
+ const home = environment.GROK_HOME ?? path4.join(environment.HOME ?? os2.homedir(), ".grok");
388
+ const auth = JSON.parse(await readFile(path4.join(home, "auth.json"), "utf8"));
22
389
  const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
23
390
  const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
24
391
  if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
@@ -45,7 +412,7 @@ async function readGrokCredentials(environment) {
45
412
  }
46
413
 
47
414
  // dist/grok-adapter.js
48
- import path11 from "node:path";
415
+ import path13 from "node:path";
49
416
 
50
417
  // ../../../node_modules/zod/v4/classic/external.js
51
418
  var external_exports = {};
@@ -813,10 +1180,10 @@ function mergeDefs(...defs) {
813
1180
  function cloneDef(schema) {
814
1181
  return mergeDefs(schema._zod.def);
815
1182
  }
816
- function getElementAtPath(obj, path12) {
817
- if (!path12)
1183
+ function getElementAtPath(obj, path14) {
1184
+ if (!path14)
818
1185
  return obj;
819
- return path12.reduce((acc, key) => acc?.[key], obj);
1186
+ return path14.reduce((acc, key) => acc?.[key], obj);
820
1187
  }
821
1188
  function promiseAllObject(promisesObj) {
822
1189
  const keys = Object.keys(promisesObj);
@@ -1225,11 +1592,11 @@ function explicitlyAborted(x, startIndex = 0) {
1225
1592
  }
1226
1593
  return false;
1227
1594
  }
1228
- function prefixIssues(path12, issues) {
1595
+ function prefixIssues(path14, issues) {
1229
1596
  return issues.map((iss) => {
1230
1597
  var _a3;
1231
1598
  (_a3 = iss).path ?? (_a3.path = []);
1232
- iss.path.unshift(path12);
1599
+ iss.path.unshift(path14);
1233
1600
  return iss;
1234
1601
  });
1235
1602
  }
@@ -1376,16 +1743,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1376
1743
  }
1377
1744
  function formatError(error53, mapper = (issue2) => issue2.message) {
1378
1745
  const fieldErrors = { _errors: [] };
1379
- const processError = (error54, path12 = []) => {
1746
+ const processError = (error54, path14 = []) => {
1380
1747
  for (const issue2 of error54.issues) {
1381
1748
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1382
- issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
1749
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1383
1750
  } else if (issue2.code === "invalid_key") {
1384
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1751
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1385
1752
  } else if (issue2.code === "invalid_element") {
1386
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1753
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1387
1754
  } else {
1388
- const fullpath = [...path12, ...issue2.path];
1755
+ const fullpath = [...path14, ...issue2.path];
1389
1756
  if (fullpath.length === 0) {
1390
1757
  fieldErrors._errors.push(mapper(issue2));
1391
1758
  } else {
@@ -1412,17 +1779,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1412
1779
  }
1413
1780
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1414
1781
  const result = { errors: [] };
1415
- const processError = (error54, path12 = []) => {
1782
+ const processError = (error54, path14 = []) => {
1416
1783
  var _a3, _b;
1417
1784
  for (const issue2 of error54.issues) {
1418
1785
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1419
- issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
1786
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1420
1787
  } else if (issue2.code === "invalid_key") {
1421
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1788
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1422
1789
  } else if (issue2.code === "invalid_element") {
1423
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1790
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1424
1791
  } else {
1425
- const fullpath = [...path12, ...issue2.path];
1792
+ const fullpath = [...path14, ...issue2.path];
1426
1793
  if (fullpath.length === 0) {
1427
1794
  result.errors.push(mapper(issue2));
1428
1795
  continue;
@@ -1454,8 +1821,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1454
1821
  }
1455
1822
  function toDotPath(_path) {
1456
1823
  const segs = [];
1457
- const path12 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1458
- for (const seg of path12) {
1824
+ const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1825
+ for (const seg of path14) {
1459
1826
  if (typeof seg === "number")
1460
1827
  segs.push(`[${seg}]`);
1461
1828
  else if (typeof seg === "symbol")
@@ -14147,13 +14514,13 @@ function resolveRef(ref, ctx) {
14147
14514
  if (!ref.startsWith("#")) {
14148
14515
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14149
14516
  }
14150
- const path12 = ref.slice(1).split("/").filter(Boolean);
14151
- if (path12.length === 0) {
14517
+ const path14 = ref.slice(1).split("/").filter(Boolean);
14518
+ if (path14.length === 0) {
14152
14519
  return ctx.rootSchema;
14153
14520
  }
14154
14521
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14155
- if (path12[0] === defsKey) {
14156
- const key = path12[1];
14522
+ if (path14[0] === defsKey) {
14523
+ const key = path14[1];
14157
14524
  if (!key || !ctx.defs[key]) {
14158
14525
  throw new Error(`Reference not found: ${ref}`);
14159
14526
  }
@@ -14616,6 +14983,56 @@ var credentialImportsParamsSchema = external_exports.object({
14616
14983
  request: credentialImportsRequestSchema
14617
14984
  }).strict();
14618
14985
 
14986
+ // ../../shared-contracts/dist/harness-display-settings.js
14987
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
14988
+ agent: external_exports.string().min(1).max(128),
14989
+ section: external_exports.enum(["main", "more", "auto"])
14990
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
14991
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
14992
+ entries: harnessDisplayEntriesSchema.nullable()
14993
+ });
14994
+ var harnessDisplayGetSchema = external_exports.strictObject({});
14995
+ var harnessDisplaySetSchema = external_exports.strictObject({
14996
+ entries: harnessDisplayEntriesSchema,
14997
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
14998
+ initializeOnly: external_exports.boolean().optional()
14999
+ });
15000
+
15001
+ // ../../shared-contracts/dist/console.js
15002
+ var consoleAnnouncementSchema = external_exports.strictObject({
15003
+ title: external_exports.string().trim().min(1).max(200),
15004
+ type: external_exports.enum(["info", "warning", "danger"]),
15005
+ body: external_exports.string().trim().min(1).max(16 * 1024)
15006
+ });
15007
+ var consoleOpenParamsSchema = external_exports.strictObject({});
15008
+ var consoleOpenResultSchema = external_exports.strictObject({
15009
+ /** The console address. */
15010
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
15011
+ });
15012
+ var CONSOLE_HOST_METHODS = Object.freeze([
15013
+ "codexhost/harness/plugins/list",
15014
+ "codexhost/harness/display-settings/get",
15015
+ "codexhost/harness/display-settings/set",
15016
+ "codexhost/harness/inspect",
15017
+ "codexhost/harness/installation",
15018
+ "codexhost/harness/launch-settings/get",
15019
+ "codexhost/harness/launch-settings/set",
15020
+ "codexhost/harness/web-ui/open",
15021
+ "codexhost/harness/accounts/sources",
15022
+ "codexhost/harness/accounts/list",
15023
+ "codexhost/harness/accounts/inspect",
15024
+ "codexhost/harness/credential-imports",
15025
+ "codexhost/harness/session-import/sources",
15026
+ "codexhost/harness/session-import/list",
15027
+ "codexhost/harness/session-import/import",
15028
+ "codexhost/account/list",
15029
+ "codexhost/account/refresh",
15030
+ "codexhost/account/usage/inspect",
15031
+ "codexhost/update/check",
15032
+ "codexhost/update/start",
15033
+ "codexhost/update/status"
15034
+ ]);
15035
+
14619
15036
  // ../../shared-contracts/dist/version.js
14620
15037
  var WORKSPACE_CONTRACT_VERSION = 1;
14621
15038
 
@@ -14669,6 +15086,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14669
15086
  var hostItemIdSchema = opaqueIdSchema.brand();
14670
15087
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14671
15088
 
15089
+ // ../../shared-contracts/dist/manual-compaction.js
15090
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
15091
+ threadId: hostThreadIdSchema,
15092
+ turnId: hostTurnIdSchema
15093
+ });
15094
+
14672
15095
  // ../../shared-contracts/dist/thread-usage.js
14673
15096
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14674
15097
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -14729,6 +15152,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14729
15152
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14730
15153
  var accountCreditsProductUsageSchema = external_exports.object({
14731
15154
  product: external_exports.string().min(1),
15155
+ used: external_exports.number().finite().nonnegative().optional(),
15156
+ // Zero is a real empty cap, not an absent field.
15157
+ limit: external_exports.number().finite().nonnegative().optional(),
15158
+ unit: external_exports.string().min(1).max(32).optional(),
14732
15159
  usagePercent: usagePercentSchema,
14733
15160
  resetsAt: external_exports.string().min(1).optional()
14734
15161
  }).strict();
@@ -14738,6 +15165,10 @@ var accountResetCreditsSchema = external_exports.object({
14738
15165
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14739
15166
  }).strict();
14740
15167
  var accountCreditsSnapshotSchema = external_exports.object({
15168
+ used: external_exports.number().finite().nonnegative().optional(),
15169
+ // Zero is a real empty cap, not an absent field.
15170
+ limit: external_exports.number().finite().nonnegative().optional(),
15171
+ unit: external_exports.string().min(1).max(32).optional(),
14741
15172
  /** Native label when the primary limit is scoped to a model or product group. */
14742
15173
  label: external_exports.string().min(1).optional(),
14743
15174
  usedPercent: usagePercentSchema,
@@ -14757,12 +15188,27 @@ var threadUsageInspectionSchema = external_exports.object({
14757
15188
  }).strict();
14758
15189
 
14759
15190
  // ../../shared-contracts/dist/harness-accounts.js
14760
- var harnessAccountSnapshotSchema = external_exports.object({
15191
+ var accountBalanceSnapshotSchema = external_exports.object({
15192
+ amount: external_exports.number().finite().nonnegative(),
15193
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15194
+ currency: external_exports.string().trim().min(1).max(8),
15195
+ /** Native label when the Harness exposes several Billing Sources. */
15196
+ label: external_exports.string().trim().min(1).max(128).optional()
15197
+ }).strict();
15198
+ var harnessAccountSnapshotObject = external_exports.object({
14761
15199
  email: external_exports.string().trim().min(1).max(320).optional(),
14762
15200
  label: external_exports.string().trim().min(1).max(256).optional(),
14763
15201
  plan: external_exports.string().trim().min(1).max(128).optional(),
14764
- credits: accountCreditsSnapshotSchema
15202
+ credits: accountCreditsSnapshotSchema.optional(),
15203
+ balance: accountBalanceSnapshotSchema.optional()
14765
15204
  }).strict();
15205
+ function requireReportedQuota(schema) {
15206
+ return schema.refine((value) => {
15207
+ const reported = value;
15208
+ return reported.credits !== void 0 || reported.balance !== void 0;
15209
+ }, { message: "Account must report either credits or a balance" });
15210
+ }
15211
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14766
15212
  var harnessAccountIdentityShape = {
14767
15213
  harnessId: harnessIdSchema,
14768
15214
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14773,11 +15219,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14773
15219
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14774
15220
  var harnessAccountInspectResultSchema = external_exports.object({
14775
15221
  ...harnessAccountIdentityShape,
14776
- account: harnessAccountSnapshotSchema.nullable()
15222
+ account: harnessAccountSnapshotSchema.nullable(),
15223
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
15224
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14777
15225
  }).strict();
14778
15226
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14779
15227
  var harnessAccountListResultSchema = external_exports.object({
14780
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
15228
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14781
15229
  }).strict();
14782
15230
 
14783
15231
  // ../../shared-contracts/dist/json-value.js
@@ -14915,6 +15363,8 @@ var harnessModelSchema = external_exports.object({
14915
15363
  ref: harnessModelRefSchema,
14916
15364
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14917
15365
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15366
+ /** Optional opaque selection for this same Model with priority processing enabled. */
15367
+ fastModel: harnessModelRefSchema.optional(),
14918
15368
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14919
15369
  }).strict();
14920
15370
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14947,6 +15397,16 @@ var harnessModelCatalogSchema = external_exports.object({
14947
15397
  });
14948
15398
  }
14949
15399
  refs.add(model.ref.id);
15400
+ if (model.fastModel) {
15401
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15402
+ context.addIssue({
15403
+ code: "custom",
15404
+ message: "Fast Model refs must be distinct and unique",
15405
+ path: ["models", index, "fastModel"]
15406
+ });
15407
+ }
15408
+ refs.add(model.fastModel.id);
15409
+ }
14950
15410
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14951
15411
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14952
15412
  if (supportedThinkingIds.has(optionId)) {
@@ -15066,11 +15526,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15066
15526
  thinkingOptionId: harnessThinkingOptionIdSchema
15067
15527
  }).strict();
15068
15528
  var threadInspectionParamsSchema = external_exports.object({
15069
- threadId: hostThreadIdSchema
15529
+ threadId: hostThreadIdSchema,
15530
+ includeReferenceCapability: external_exports.boolean().optional()
15070
15531
  }).strict();
15071
15532
  var codexThreadInspectionSchema = external_exports.object({
15072
15533
  owner: external_exports.literal("codex"),
15073
- locked: external_exports.literal(true)
15534
+ locked: external_exports.literal(true),
15535
+ supportsThreadReferences: external_exports.literal(true).optional()
15074
15536
  }).strict();
15075
15537
  var externalThreadInspectionSchema = external_exports.object({
15076
15538
  owner: external_exports.literal("external"),
@@ -15196,6 +15658,22 @@ var harnessLaunchSettingsSchema = external_exports.object({
15196
15658
  restartRequired: external_exports.boolean()
15197
15659
  }).strict();
15198
15660
 
15661
+ // ../../shared-contracts/dist/harness-installation.js
15662
+ var harnessInstallationParamsSchema = external_exports.object({
15663
+ harnessId: harnessIdSchema,
15664
+ action: external_exports.enum(["check", "update", "install"])
15665
+ }).strict();
15666
+ var harnessInstallationStateSchema = external_exports.object({
15667
+ currentVersion: external_exports.string().min(1).max(128),
15668
+ latestVersion: external_exports.string().min(1).max(128),
15669
+ updateAvailable: external_exports.boolean(),
15670
+ canUpdate: external_exports.boolean(),
15671
+ // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
15672
+ message: external_exports.string().max(2048).optional(),
15673
+ messageCode: external_exports.string().min(1).max(128).optional(),
15674
+ latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
15675
+ }).strict();
15676
+
15199
15677
  // ../../shared-contracts/dist/codex-accounts.js
15200
15678
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15201
15679
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
@@ -15495,6 +15973,38 @@ var updateStatusResultSchema = external_exports.strictObject({
15495
15973
  status: updateStatusSchema.nullable()
15496
15974
  });
15497
15975
 
15976
+ // ../../shared-contracts/dist/remote-runtime.js
15977
+ var remoteUpdatePhaseSchema = external_exports.enum([
15978
+ "idle",
15979
+ "installing",
15980
+ "restarting",
15981
+ "succeeded",
15982
+ "failed"
15983
+ ]);
15984
+ var runtimeStatusSchema = external_exports.object({
15985
+ runningVersion: external_exports.string().nullable(),
15986
+ installedVersion: external_exports.string().nullable(),
15987
+ restartRequired: external_exports.boolean(),
15988
+ remote: external_exports.boolean(),
15989
+ updateSupported: external_exports.boolean(),
15990
+ update: external_exports.object({
15991
+ phase: remoteUpdatePhaseSchema,
15992
+ targetVersion: external_exports.string().nullable(),
15993
+ error: external_exports.string().nullable()
15994
+ })
15995
+ });
15996
+ var remoteUpdateParamsSchema = external_exports.object({
15997
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
15998
+ }).strict();
15999
+ var remoteSshSetupParamsSchema = external_exports.object({
16000
+ hostname: external_exports.string().min(1).max(1024).refine((value) => !value.startsWith("-") && !/\s/u.test(value)),
16001
+ port: external_exports.number().int().min(1).max(65535).nullable(),
16002
+ identity: external_exports.string().max(4096).nullable(),
16003
+ action: external_exports.enum(["inspect", "install", "update", "repair"]),
16004
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+$/u).nullable()
16005
+ }).strict();
16006
+ var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
16007
+
15498
16008
  // ../../shared-contracts/dist/index.js
15499
16009
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15500
16010
 
@@ -15776,7 +16286,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
15776
16286
  import { spawn, spawnSync } from "node:child_process";
15777
16287
  import { readdir, readFile as readFile2 } from "node:fs/promises";
15778
16288
  import os4 from "node:os";
15779
- import path9 from "node:path";
16289
+ import path10 from "node:path";
15780
16290
  import { Readable, Writable } from "node:stream";
15781
16291
 
15782
16292
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -19929,281 +20439,54 @@ var ClientSideConnection = class {
19929
20439
  * This is useful for async/await style cleanup:
19930
20440
  *
19931
20441
  * @example
19932
- * ```typescript
19933
- * const connection = new ClientSideConnection(client, stream);
19934
- * await connection.closed;
19935
- * console.log('Connection closed - performing cleanup');
19936
- * ```
19937
- */
19938
- get closed() {
19939
- return this.connection.closed;
19940
- }
19941
- };
19942
-
19943
- // dist/grok-slash-commands.js
19944
- var GROK_LIVE_COMMAND_ID_PREFIX = "grok.slash.";
19945
- function isRecord3(value) {
19946
- return typeof value === "object" && value !== null && !Array.isArray(value);
19947
- }
19948
- function parseGrokAvailableCommands(value) {
19949
- if (!Array.isArray(value))
19950
- return [];
19951
- return value.flatMap((entry) => {
19952
- if (!isRecord3(entry))
19953
- return [];
19954
- const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
19955
- if (!name)
19956
- return [];
19957
- return [
19958
- {
19959
- name,
19960
- description: typeof entry.description === "string" ? entry.description : "",
19961
- meta: isRecord3(entry._meta) ? entry._meta : null
19962
- }
19963
- ];
19964
- });
19965
- }
19966
- function isGrokSkill(command) {
19967
- const path12 = command.meta?.path;
19968
- return typeof path12 === "string" && /(^|[\\/])SKILL\.md$/u.test(path12) || typeof command.meta?.qualifiedName === "string";
19969
- }
19970
- function grokLiveCommands(native) {
19971
- return native.map((command) => ({
19972
- name: command.name,
19973
- description: command.description,
19974
- kind: isGrokSkill(command) ? "skill" : "command"
19975
- }));
19976
- }
19977
-
19978
- // dist/command.js
19979
- import path4 from "node:path";
19980
-
19981
- // ../../harness-discovery/dist/environment.js
19982
- import fs from "node:fs";
19983
- import path2 from "node:path";
19984
- function targetPath(platform) {
19985
- return platform === "win32" ? path2.win32 : path2.posix;
19986
- }
19987
- function environmentValue(environment, name) {
19988
- const lowered = name.toLowerCase();
19989
- for (const [key, value] of Object.entries(environment)) {
19990
- if (key.toLowerCase() === lowered)
19991
- return value;
19992
- }
19993
- return void 0;
19994
- }
19995
- function pathDelimiter(platform) {
19996
- return platform === "win32" ? ";" : ":";
19997
- }
19998
- function pathDirectories(environment, platform) {
19999
- return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
20000
- }
20001
- function executableExtensions(command, platform, environment) {
20002
- if (platform !== "win32")
20003
- return [""];
20004
- if (targetPath(platform).extname(command) !== "")
20005
- return [""];
20006
- return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
20007
- }
20008
- function isExecutableFile(filePath, platform) {
20009
- try {
20010
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
20011
- return fs.statSync(filePath).isFile();
20012
- } catch {
20013
- return false;
20014
- }
20015
- }
20016
- function subdirectoryNames(directory) {
20017
- try {
20018
- return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
20019
- } catch {
20020
- return [];
20021
- }
20022
- }
20023
- function newestFirst(names) {
20024
- return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
20025
- }
20026
-
20027
- // ../../harness-discovery/dist/invocation.js
20028
- import path3 from "node:path";
20029
- function commandInvocation(command, arguments_, environment, platform = process.platform) {
20030
- const extension = path3.win32.extname(command).toLowerCase();
20031
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
20032
- return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
20033
- }
20034
- const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
20035
- const commandLine = [command, ...arguments_].map(quote).join(" ");
20036
- return {
20037
- command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
20038
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
20039
- windowsVerbatimArguments: true
20040
- };
20041
- }
20042
-
20043
- // ../../harness-discovery/dist/resolve.js
20044
- import os2 from "node:os";
20045
-
20046
- // ../../harness-discovery/dist/version-managers.js
20047
- function versionManagerBinaryDirectories(context) {
20048
- const { platform, environment, home } = context;
20049
- const list = context.subdirectories ?? subdirectoryNames;
20050
- const pathFlavor = targetPath(platform);
20051
- const value = (name) => environmentValue(environment, name);
20052
- const directories = [];
20053
- const versioned = (root, ...tail) => {
20054
- for (const version2 of newestFirst(list(root))) {
20055
- directories.push(pathFlavor.join(root, version2, ...tail));
20056
- }
20057
- };
20058
- if (platform === "win32") {
20059
- const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
20060
- const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
20061
- versioned(pathFlavor.join(appData, "nvm"));
20062
- versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
20063
- directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
20064
- directories.push(pathFlavor.join(home, ".bun", "bin"));
20065
- const pnpmHome2 = value("PNPM_HOME");
20066
- if (pnpmHome2)
20067
- directories.push(pnpmHome2);
20068
- directories.push(pathFlavor.join(localAppData, "pnpm"));
20069
- return directories;
20070
- }
20071
- versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
20072
- const fnmRoots = [
20073
- value("FNM_DIR"),
20074
- pathFlavor.join(home, ".local", "share", "fnm"),
20075
- pathFlavor.join(home, "Library", "Application Support", "fnm")
20076
- ].filter((root) => root !== void 0);
20077
- for (const root of fnmRoots) {
20078
- versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
20079
- }
20080
- const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
20081
- versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
20082
- directories.push(pathFlavor.join(voltaHome, "bin"));
20083
- const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
20084
- versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
20085
- directories.push(pathFlavor.join(asdfHome, "shims"));
20086
- const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
20087
- versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
20088
- directories.push(pathFlavor.join(nodenvHome, "shims"));
20089
- versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
20090
- directories.push(pathFlavor.join(home, ".bun", "bin"));
20091
- const pnpmHome = value("PNPM_HOME");
20092
- if (pnpmHome)
20093
- directories.push(pnpmHome);
20094
- directories.push(pathFlavor.join(home, "Library", "pnpm"));
20095
- directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
20096
- for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
20097
- for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
20098
- directories.push(pathFlavor.join(prefix, formula, "bin"));
20099
- }
20100
- }
20101
- return directories;
20102
- }
20103
-
20104
- // ../../harness-discovery/dist/resolve.js
20105
- var VERSION_MANAGER_ROOTS = "<version-managers>";
20106
- function installRootExtensions(platform) {
20107
- return platform === "win32" ? [".exe", ".cmd"] : [""];
20108
- }
20109
- function resolveHomeDirectory(input) {
20110
- return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os2.homedir();
20111
- }
20112
- function templateVariables(environment, platform, home) {
20113
- const pathFlavor = targetPath(platform);
20114
- return {
20115
- HOME: home,
20116
- USERPROFILE: home,
20117
- APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
20118
- LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
20119
- };
20120
- }
20121
- function joinTemplate(platform, value) {
20122
- const pathFlavor = targetPath(platform);
20123
- const segments = value.split("/");
20124
- const head = segments[0] ?? "";
20125
- const tail = segments.slice(1);
20126
- if (head === "")
20127
- return pathFlavor.join(pathFlavor.sep, ...tail);
20128
- return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
20442
+ * ```typescript
20443
+ * const connection = new ClientSideConnection(client, stream);
20444
+ * await connection.closed;
20445
+ * console.log('Connection closed - performing cleanup');
20446
+ * ```
20447
+ */
20448
+ get closed() {
20449
+ return this.connection.closed;
20450
+ }
20451
+ };
20452
+
20453
+ // dist/grok-slash-commands.js
20454
+ var GROK_LIVE_COMMAND_ID_PREFIX = "grok.slash.";
20455
+ function isRecord3(value) {
20456
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20129
20457
  }
20130
- function expandInstallRoot(template, environment, platform, home) {
20131
- const variables = templateVariables(environment, platform, home);
20132
- let unresolved = false;
20133
- const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
20134
- const value = variables[name] ?? environmentValue(environment, name);
20135
- if (value === void 0 || value === "") {
20136
- unresolved = true;
20137
- return "";
20138
- }
20139
- return value;
20458
+ function parseGrokAvailableCommands(value) {
20459
+ if (!Array.isArray(value))
20460
+ return [];
20461
+ return value.flatMap((entry) => {
20462
+ if (!isRecord3(entry))
20463
+ return [];
20464
+ const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
20465
+ if (!name)
20466
+ return [];
20467
+ return [
20468
+ {
20469
+ name,
20470
+ description: typeof entry.description === "string" ? entry.description : "",
20471
+ meta: isRecord3(entry._meta) ? entry._meta : null
20472
+ }
20473
+ ];
20140
20474
  });
20141
- return unresolved ? void 0 : joinTemplate(platform, substituted);
20142
- }
20143
- function installRootDirectories(spec, input, dependencies, platform, home) {
20144
- const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
20145
- const directories = [];
20146
- for (const template of templates) {
20147
- if (template === VERSION_MANAGER_ROOTS) {
20148
- directories.push(...versionManagerBinaryDirectories({
20149
- platform,
20150
- environment: input.environment,
20151
- home,
20152
- ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
20153
- }));
20154
- continue;
20155
- }
20156
- const directory = expandInstallRoot(template, input.environment, platform, home);
20157
- if (directory !== void 0)
20158
- directories.push(directory);
20159
- }
20160
- return directories;
20161
20475
  }
20162
- function harnessCandidates(spec, input, dependencies = {}) {
20163
- const platform = input.platform ?? process.platform;
20164
- const pathFlavor = targetPath(platform);
20165
- const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
20166
- const command = configured ?? spec.command;
20167
- if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
20168
- return [{ candidate: command, source: "configured" }];
20169
- }
20170
- const candidates = [];
20171
- const extensions = executableExtensions(command, platform, input.environment);
20172
- for (const directory of pathDirectories(input.environment, platform)) {
20173
- for (const extension of extensions) {
20174
- candidates.push({
20175
- candidate: pathFlavor.join(directory, command + extension),
20176
- source: "path"
20177
- });
20178
- }
20179
- }
20180
- if (configured !== void 0)
20181
- return candidates;
20182
- const home = resolveHomeDirectory(input);
20183
- for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
20184
- for (const extension of installRootExtensions(platform)) {
20185
- candidates.push({
20186
- candidate: pathFlavor.join(directory, spec.command + extension),
20187
- source: "install-root"
20188
- });
20189
- }
20190
- }
20191
- return candidates;
20476
+ function isGrokSkill(command) {
20477
+ const path14 = command.meta?.path;
20478
+ return typeof path14 === "string" && /(^|[\\/])SKILL\.md$/u.test(path14) || typeof command.meta?.qualifiedName === "string";
20192
20479
  }
20193
- function resolveHarnessExecutable(spec, input, dependencies = {}) {
20194
- const platform = input.platform ?? process.platform;
20195
- const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
20196
- const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
20197
- const context = { platform, isExecutable };
20198
- for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
20199
- const executable = runnable(candidate, context);
20200
- if (executable !== void 0 && isExecutable(executable))
20201
- return { executable, source };
20202
- }
20203
- return void 0;
20480
+ function grokLiveCommands(native) {
20481
+ return native.map((command) => ({
20482
+ name: command.name,
20483
+ description: command.description,
20484
+ kind: isGrokSkill(command) ? "skill" : "command"
20485
+ }));
20204
20486
  }
20205
20487
 
20206
20488
  // dist/command.js
20489
+ import path5 from "node:path";
20207
20490
  var GrokExecutableError = class extends Error {
20208
20491
  code = "GROK_NOT_FOUND";
20209
20492
  };
@@ -20232,7 +20515,7 @@ function resolveGrokExecutable(input = {}) {
20232
20515
  });
20233
20516
  if (!resolution)
20234
20517
  throw new GrokExecutableError("Grok CLI is not installed");
20235
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path4.resolve(resolution.executable);
20518
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
20236
20519
  }
20237
20520
  function grokInvocation(command, platform = process.platform, modelId) {
20238
20521
  const arguments_ = ["agent", "--no-leader"];
@@ -20245,11 +20528,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
20245
20528
 
20246
20529
  // dist/grok-fork.js
20247
20530
  import { isDeepStrictEqual } from "node:util";
20248
- import path7 from "node:path";
20531
+ import path8 from "node:path";
20249
20532
 
20250
20533
  // dist/grok-file-change.js
20251
20534
  import { Buffer as Buffer2 } from "node:buffer";
20252
- import path5 from "node:path";
20535
+ import path6 from "node:path";
20253
20536
 
20254
20537
  // ../../../node_modules/diff/libesm/diff/base.js
20255
20538
  var Diff = class {
@@ -20351,16 +20634,16 @@ var Diff = class {
20351
20634
  }
20352
20635
  }
20353
20636
  }
20354
- addToPath(path12, added, removed, oldPosInc, options) {
20355
- const last = path12.lastComponent;
20637
+ addToPath(path14, added, removed, oldPosInc, options) {
20638
+ const last = path14.lastComponent;
20356
20639
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20357
20640
  return {
20358
- oldPos: path12.oldPos + oldPosInc,
20641
+ oldPos: path14.oldPos + oldPosInc,
20359
20642
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20360
20643
  };
20361
20644
  } else {
20362
20645
  return {
20363
- oldPos: path12.oldPos + oldPosInc,
20646
+ oldPos: path14.oldPos + oldPosInc,
20364
20647
  lastComponent: { count: 1, added, removed, previousComponent: last }
20365
20648
  };
20366
20649
  }
@@ -20673,13 +20956,13 @@ function isRecord4(value) {
20673
20956
  return typeof value === "object" && value !== null && !Array.isArray(value);
20674
20957
  }
20675
20958
  function validAbsolutePath(value) {
20676
- return typeof value === "string" && path5.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
20959
+ return typeof value === "string" && path6.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
20677
20960
  }
20678
20961
  function displayPath(nativePath, cwd) {
20679
- const resolvedCwd = path5.resolve(cwd);
20680
- const resolvedPath = path5.resolve(nativePath);
20681
- const relative = path5.relative(resolvedCwd, resolvedPath);
20682
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path5.sep}`);
20962
+ const resolvedCwd = path6.resolve(cwd);
20963
+ const resolvedPath = path6.resolve(nativePath);
20964
+ const relative = path6.relative(resolvedCwd, resolvedPath);
20965
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path6.sep}`);
20683
20966
  const selected = inside ? relative : resolvedPath;
20684
20967
  const normalized = selected.replaceAll("\\", "/");
20685
20968
  if (normalized.length === 0 || normalized === ".")
@@ -20742,7 +21025,7 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
20742
21025
  // dist/local-media-markdown.js
20743
21026
  import { existsSync, statSync } from "node:fs";
20744
21027
  import os3 from "node:os";
20745
- import path6 from "node:path";
21028
+ import path7 from "node:path";
20746
21029
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
20747
21030
  ".aac",
20748
21031
  ".gif",
@@ -20761,14 +21044,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
20761
21044
  ".webp"
20762
21045
  ]);
20763
21046
  function grokMediaResolveRoots(cwd, sessionDirectory) {
20764
- const roots = [path6.resolve(cwd)];
21047
+ const roots = [path7.resolve(cwd)];
20765
21048
  if (sessionDirectory) {
20766
- const session = path6.resolve(sessionDirectory);
20767
- roots.push(session, path6.join(session, "videos"), path6.join(session, "images"));
21049
+ const session = path7.resolve(sessionDirectory);
21050
+ roots.push(session, path7.join(session, "videos"), path7.join(session, "images"));
20768
21051
  }
20769
21052
  const home = process.env.HOME ?? process.env.USERPROFILE ?? os3.homedir();
20770
21053
  if (home)
20771
- roots.push(path6.join(home, "Downloads"));
21054
+ roots.push(path7.join(home, "Downloads"));
20772
21055
  return roots;
20773
21056
  }
20774
21057
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -20869,7 +21152,7 @@ function parseInlineCode(text, start) {
20869
21152
  return { closed: false, content: text.slice(start + 1), end: text.length };
20870
21153
  }
20871
21154
  function mediaMarkdownImage(absolutePath) {
20872
- const name = path6.basename(absolutePath).replaceAll("]", "\\]");
21155
+ const name = path7.basename(absolutePath).replaceAll("]", "\\]");
20873
21156
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
20874
21157
  }
20875
21158
  function parseMarkdownImage(text, start) {
@@ -20994,11 +21277,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
20994
21277
  if (!hasMediaExtension(stripped))
20995
21278
  return null;
20996
21279
  if (isAbsoluteMediaPath(stripped)) {
20997
- const absolute = path6.resolve(stripped);
21280
+ const absolute = path7.resolve(stripped);
20998
21281
  return exists(absolute) ? absolute : null;
20999
21282
  }
21000
21283
  for (const root of roots) {
21001
- const absolute = path6.resolve(root, stripped);
21284
+ const absolute = path7.resolve(root, stripped);
21002
21285
  if (exists(absolute))
21003
21286
  return absolute;
21004
21287
  }
@@ -21020,11 +21303,11 @@ function stripFileUrl(value) {
21020
21303
  }
21021
21304
  }
21022
21305
  function isAbsoluteMediaPath(value) {
21023
- return path6.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21306
+ return path7.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21024
21307
  }
21025
21308
  function hasMediaExtension(value) {
21026
21309
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
21027
- return MEDIA_EXTENSIONS.has(path6.extname(pathname).toLowerCase());
21310
+ return MEDIA_EXTENSIONS.has(path7.extname(pathname).toLowerCase());
21028
21311
  }
21029
21312
  function mediaFileExists(absolutePath) {
21030
21313
  try {
@@ -22033,11 +22316,11 @@ function parseGrokForkResponse(value) {
22033
22316
  }
22034
22317
  function projectRelativePath(value, cwds) {
22035
22318
  const normalized = value.replaceAll("\\", "/");
22036
- if (!path7.isAbsolute(value))
22319
+ if (!path8.isAbsolute(value))
22037
22320
  return normalized;
22038
22321
  for (const cwd of cwds) {
22039
- const relative = path7.relative(path7.resolve(cwd), path7.resolve(value));
22040
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path7.sep}`)) {
22322
+ const relative = path8.relative(path8.resolve(cwd), path8.resolve(value));
22323
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`)) {
22041
22324
  return relative.replaceAll("\\", "/");
22042
22325
  }
22043
22326
  }
@@ -22102,8 +22385,8 @@ async function forkGrokSession(input) {
22102
22385
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
22103
22386
  };
22104
22387
  }
22105
- const sourceCwd = path7.resolve(located.cwd);
22106
- const targetCwd = path7.resolve(input.cwd);
22388
+ const sourceCwd = path8.resolve(located.cwd);
22389
+ const targetCwd = path8.resolve(input.cwd);
22107
22390
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
22108
22391
  if (!source.ok)
22109
22392
  return source;
@@ -22285,7 +22568,7 @@ function parseGrokCompactResult(value, cancelled = false) {
22285
22568
  }
22286
22569
 
22287
22570
  // dist/grok-rewind.js
22288
- import path8 from "node:path";
22571
+ import path9 from "node:path";
22289
22572
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
22290
22573
  function error52(code, message, retryable = false) {
22291
22574
  return { code, message, retryable };
@@ -22358,8 +22641,8 @@ async function rewindGrokLastTurn(input) {
22358
22641
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
22359
22642
  };
22360
22643
  }
22361
- const sourceCwd = path8.resolve(located.cwd);
22362
- const targetCwd = path8.resolve(input.cwd);
22644
+ const sourceCwd = path9.resolve(located.cwd);
22645
+ const targetCwd = path9.resolve(input.cwd);
22363
22646
  if (sourceCwd !== targetCwd) {
22364
22647
  return {
22365
22648
  ok: false,
@@ -22603,13 +22886,13 @@ function transportEvent(update, metadata) {
22603
22886
  function grokHomeDir(options) {
22604
22887
  const environment = { ...process.env, ...options.environment };
22605
22888
  const home = environment.HOME ?? environment.USERPROFILE ?? os4.homedir();
22606
- return environment.GROK_HOME ?? path9.join(home, ".grok");
22889
+ return environment.GROK_HOME ?? path10.join(home, ".grok");
22607
22890
  }
22608
22891
  function grokNativeSessionDirectory(options, sessionId) {
22609
- return path9.join(grokHomeDir(options), "sessions", encodeURIComponent(path9.resolve(options.cwd)), sessionId);
22892
+ return path10.join(grokHomeDir(options), "sessions", encodeURIComponent(path10.resolve(options.cwd)), sessionId);
22610
22893
  }
22611
22894
  function nativeSessionFile(options, sessionId, fileName) {
22612
- return path9.join(grokNativeSessionDirectory(options, sessionId), fileName);
22895
+ return path10.join(grokNativeSessionDirectory(options, sessionId), fileName);
22613
22896
  }
22614
22897
  function nativeHistoryPath(options, sessionId) {
22615
22898
  return nativeSessionFile(options, sessionId, "updates.jsonl");
@@ -22629,7 +22912,7 @@ async function locateGrokNativeSession(options, sessionId) {
22629
22912
  return null;
22630
22913
  let entries;
22631
22914
  try {
22632
- entries = await readdir(path9.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
22915
+ entries = await readdir(path10.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
22633
22916
  } catch (error53) {
22634
22917
  if (isMissingFile(error53))
22635
22918
  return null;
@@ -22643,7 +22926,7 @@ async function locateGrokNativeSession(options, sessionId) {
22643
22926
  continue;
22644
22927
  let summaryRaw;
22645
22928
  try {
22646
- summaryRaw = await readFile2(path9.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
22929
+ summaryRaw = await readFile2(path10.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
22647
22930
  } catch (error53) {
22648
22931
  if (isMissingFile(error53) || isRecord11(error53) && error53.code === "ENOTDIR")
22649
22932
  continue;
@@ -22660,8 +22943,8 @@ async function locateGrokNativeSession(options, sessionId) {
22660
22943
  if (!isRecord11(parsed))
22661
22944
  continue;
22662
22945
  const info = parsed.info;
22663
- const cwd = isRecord11(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path9.resolve(info.cwd) : path9.resolve(decodeURIComponent(entry.name));
22664
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path9.resolve(parsed.source_workspace_dir) : void 0;
22946
+ const cwd = isRecord11(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path10.resolve(info.cwd) : path10.resolve(decodeURIComponent(entry.name));
22947
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path10.resolve(parsed.source_workspace_dir) : void 0;
22665
22948
  matches.push({
22666
22949
  cwd,
22667
22950
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -22671,7 +22954,7 @@ async function locateGrokNativeSession(options, sessionId) {
22671
22954
  }
22672
22955
  async function readGrokNativeHistory(options, sessionId) {
22673
22956
  try {
22674
- return parseNativeHistory(await readFile2(nativeHistoryPath({ ...options, cwd: path9.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
22957
+ return parseNativeHistory(await readFile2(nativeHistoryPath({ ...options, cwd: path10.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
22675
22958
  } catch (error53) {
22676
22959
  if (isMissingFile(error53))
22677
22960
  return [];
@@ -23088,6 +23371,323 @@ var GrokAcpTransport = class {
23088
23371
  }
23089
23372
  };
23090
23373
 
23374
+ // dist/session-import.js
23375
+ import { createReadStream } from "node:fs";
23376
+ import { opendir, readFile as readFile3, stat } from "node:fs/promises";
23377
+ import path11 from "node:path";
23378
+ import { createInterface } from "node:readline";
23379
+
23380
+ // ../../harness-adapter/dist/session-import.js
23381
+ import { lstat } from "node:fs/promises";
23382
+ var SessionImportChangedError = class extends Error {
23383
+ constructor(message = "Native Session changed during discovery; refresh and retry") {
23384
+ super(message);
23385
+ this.name = "SessionImportChangedError";
23386
+ }
23387
+ };
23388
+ function isMissingFileError(error53) {
23389
+ return typeof error53 === "object" && error53 !== null && "code" in error53 && error53.code === "ENOENT";
23390
+ }
23391
+ function sameFileFingerprint(left, right) {
23392
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
23393
+ }
23394
+ var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
23395
+ function isStorageAccessError(error53) {
23396
+ return typeof error53 === "object" && error53 !== null && "code" in error53 && typeof error53.code === "string" && STORAGE_ACCESS_ERRORS.has(error53.code);
23397
+ }
23398
+ async function optionalLstat(file2) {
23399
+ try {
23400
+ return await lstat(file2);
23401
+ } catch (error53) {
23402
+ if (isMissingFileError(error53))
23403
+ return null;
23404
+ throw error53;
23405
+ }
23406
+ }
23407
+ async function readStableFiles(files, read) {
23408
+ const before = await Promise.all(files.map(optionalLstat));
23409
+ const value = await read(before);
23410
+ const after = await Promise.all(files.map(optionalLstat));
23411
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
23412
+ throw new SessionImportChangedError();
23413
+ return value;
23414
+ }
23415
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
23416
+ if (typeof value !== "string")
23417
+ return null;
23418
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23419
+ if (!normalized)
23420
+ return null;
23421
+ if (normalized.length <= maxLength)
23422
+ return normalized;
23423
+ const characters = [...normalized];
23424
+ if (characters.length <= maxLength)
23425
+ return normalized;
23426
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
23427
+ }
23428
+ function sessionImportCandidate(input) {
23429
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
23430
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
23431
+ nativeSessionId: input.nativeSessionId,
23432
+ cwd: input.cwd,
23433
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
23434
+ updatedAt: Math.floor(time3),
23435
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
23436
+ running: typeof input.running === "boolean" ? input.running : null
23437
+ });
23438
+ return parsed.success ? parsed.data : null;
23439
+ }
23440
+ var SessionImportScope = class {
23441
+ #abort = new AbortController();
23442
+ #options;
23443
+ #pending = /* @__PURE__ */ new Set();
23444
+ constructor(options) {
23445
+ this.#options = options;
23446
+ }
23447
+ #closed() {
23448
+ return {
23449
+ ok: false,
23450
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
23451
+ };
23452
+ }
23453
+ read(operation) {
23454
+ const signal = this.#abort.signal;
23455
+ if (signal.aborted)
23456
+ return Promise.resolve(this.#closed());
23457
+ let started;
23458
+ try {
23459
+ started = operation(signal);
23460
+ } catch (error53) {
23461
+ started = Promise.reject(error53 instanceof Error ? error53 : new Error("Session read failed"));
23462
+ }
23463
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
23464
+ ok: false,
23465
+ error: {
23466
+ code: "unavailable",
23467
+ message: this.#options.unavailableMessage,
23468
+ retryable: true
23469
+ }
23470
+ }).finally(() => this.#pending.delete(request));
23471
+ this.#pending.add(request);
23472
+ return request;
23473
+ }
23474
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
23475
+ async resolve(operation) {
23476
+ const result = await this.read(operation);
23477
+ if (!result.ok)
23478
+ return result;
23479
+ return result.value ? { ok: true, value: result.value } : {
23480
+ ok: false,
23481
+ error: {
23482
+ code: "sessionNotFound",
23483
+ message: this.#options.notFoundMessage,
23484
+ retryable: false
23485
+ }
23486
+ };
23487
+ }
23488
+ /** Idempotent. Resolves after every started read has settled. */
23489
+ async close() {
23490
+ this.#abort.abort();
23491
+ await Promise.allSettled(this.#pending);
23492
+ }
23493
+ };
23494
+
23495
+ // dist/session-import.js
23496
+ var MAX_METADATA_BYTES = 4 * 1024 * 1024;
23497
+ var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
23498
+ function isRecord12(value) {
23499
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23500
+ }
23501
+ async function readJson(file2, signal) {
23502
+ return JSON.parse(await readFile3(file2, { encoding: "utf8", signal }));
23503
+ }
23504
+ function processAlive(pid) {
23505
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
23506
+ return false;
23507
+ try {
23508
+ process.kill(pid, 0);
23509
+ return true;
23510
+ } catch (error53) {
23511
+ return isRecord12(error53) && error53.code === "EPERM";
23512
+ }
23513
+ }
23514
+ async function firstUserText(file2, signal) {
23515
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
23516
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
23517
+ try {
23518
+ for await (const line of lines) {
23519
+ signal.throwIfAborted();
23520
+ if (!line.includes("user_message_chunk"))
23521
+ continue;
23522
+ let entry;
23523
+ try {
23524
+ entry = JSON.parse(line);
23525
+ } catch {
23526
+ continue;
23527
+ }
23528
+ const update = isRecord12(entry) && isRecord12(entry.params) ? entry.params.update : null;
23529
+ if (!isRecord12(update) || update.sessionUpdate !== "user_message_chunk")
23530
+ continue;
23531
+ const text = isRecord12(update.content) ? update.content.text : null;
23532
+ return typeof text === "string" ? text : "";
23533
+ }
23534
+ return null;
23535
+ } finally {
23536
+ lines.close();
23537
+ stream.destroy();
23538
+ }
23539
+ }
23540
+ var GrokSessionImport = class {
23541
+ #environment;
23542
+ #scope = new SessionImportScope({
23543
+ closedMessage: "Grok Session import is closed",
23544
+ unavailableMessage: "Grok sessions could not be read; close native clients, check storage access and retry",
23545
+ notFoundMessage: "Grok Session is no longer importable"
23546
+ });
23547
+ constructor(environment) {
23548
+ this.#environment = environment ? { ...environment } : void 0;
23549
+ }
23550
+ listCandidates() {
23551
+ return this.#scope.read(async (signal) => {
23552
+ const active = await this.#activeSessions(signal);
23553
+ const candidates = [];
23554
+ for (const [, directories] of await this.#sessionDirectories(signal)) {
23555
+ if (directories.length !== 1 || !directories[0])
23556
+ continue;
23557
+ try {
23558
+ const candidate = await this.#candidate(directories[0], active, signal);
23559
+ if (candidate)
23560
+ candidates.push(candidate);
23561
+ } catch (error53) {
23562
+ if (!(error53 instanceof SessionImportChangedError))
23563
+ throw error53;
23564
+ }
23565
+ }
23566
+ return candidates;
23567
+ });
23568
+ }
23569
+ resolveCandidate(nativeSessionId) {
23570
+ return this.#scope.resolve(async (signal) => {
23571
+ const directories = (await this.#sessionDirectories(signal)).get(nativeSessionId);
23572
+ if (directories?.length !== 1 || !directories[0])
23573
+ return null;
23574
+ const candidate = await this.#candidate(directories[0], await this.#activeSessions(signal), signal);
23575
+ if (!candidate)
23576
+ return null;
23577
+ return {
23578
+ candidate,
23579
+ nativeRef: nativeSessionRefSchema.parse({
23580
+ harnessId: "grok",
23581
+ nativeSessionId,
23582
+ formatVersion: 1
23583
+ })
23584
+ };
23585
+ });
23586
+ }
23587
+ close() {
23588
+ return this.#scope.close();
23589
+ }
23590
+ #home() {
23591
+ return grokHomeDir(this.#environment ? { environment: this.#environment } : {});
23592
+ }
23593
+ /** IDs a live Grok process currently holds open, from Grok's own registry. */
23594
+ async #activeSessions(signal) {
23595
+ const active = /* @__PURE__ */ new Set();
23596
+ let entries;
23597
+ try {
23598
+ entries = await readJson(path11.join(this.#home(), "active_sessions.json"), signal);
23599
+ } catch (error53) {
23600
+ signal.throwIfAborted();
23601
+ if (isStorageAccessError(error53))
23602
+ throw error53;
23603
+ return active;
23604
+ }
23605
+ if (!Array.isArray(entries))
23606
+ return active;
23607
+ for (const entry of entries) {
23608
+ if (isRecord12(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
23609
+ active.add(entry.session_id);
23610
+ }
23611
+ return active;
23612
+ }
23613
+ /** Session ID to every directory claiming it. Enumerated links are not followed. */
23614
+ async #sessionDirectories(signal) {
23615
+ const root = path11.join(this.#home(), "sessions");
23616
+ const found = /* @__PURE__ */ new Map();
23617
+ const info = await optionalLstat(root);
23618
+ if (!info)
23619
+ return found;
23620
+ if (!info.isDirectory())
23621
+ throw new Error("Grok Session store is not a directory");
23622
+ for await (const workspace of await opendir(root)) {
23623
+ signal.throwIfAborted();
23624
+ if (!workspace.isDirectory())
23625
+ continue;
23626
+ const workspaceDirectory = path11.join(root, workspace.name);
23627
+ const sessions = await opendir(workspaceDirectory).catch((error53) => {
23628
+ if (isMissingFileError(error53))
23629
+ return null;
23630
+ throw error53;
23631
+ });
23632
+ if (!sessions)
23633
+ continue;
23634
+ for await (const session of sessions) {
23635
+ signal.throwIfAborted();
23636
+ if (!session.isDirectory())
23637
+ continue;
23638
+ const directories = found.get(session.name) ?? [];
23639
+ directories.push(path11.join(workspaceDirectory, session.name));
23640
+ found.set(session.name, directories);
23641
+ }
23642
+ }
23643
+ return found;
23644
+ }
23645
+ async #candidate(sessionDirectory, active, signal) {
23646
+ signal.throwIfAborted();
23647
+ const nativeSessionId = path11.basename(sessionDirectory);
23648
+ const files = [
23649
+ path11.join(sessionDirectory, "summary.json"),
23650
+ path11.join(sessionDirectory, "updates.jsonl")
23651
+ ];
23652
+ return readStableFiles(files, async ([summaryInfo, updates]) => {
23653
+ if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
23654
+ return null;
23655
+ try {
23656
+ const summary = await readJson(files[0], signal);
23657
+ if (!isRecord12(summary) || !isRecord12(summary.info) || summary.info.id !== nativeSessionId)
23658
+ return null;
23659
+ if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
23660
+ return null;
23661
+ const nativeCwd = summary.info.cwd;
23662
+ if (typeof nativeCwd !== "string" || !path11.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
23663
+ return null;
23664
+ const cwd = path11.resolve(nativeCwd);
23665
+ if (encodeURIComponent(cwd) !== path11.basename(path11.dirname(sessionDirectory)))
23666
+ return null;
23667
+ if (!(await stat(cwd)).isDirectory())
23668
+ return null;
23669
+ const prompt = await firstUserText(files[1], signal);
23670
+ if (prompt === null)
23671
+ return null;
23672
+ const updatedAt = [summary.last_active_at, summary.updated_at].map((value) => typeof value === "string" ? Date.parse(value) : Number.NaN).find((value) => Number.isFinite(value) && value >= 0);
23673
+ return sessionImportCandidate({
23674
+ nativeSessionId,
23675
+ cwd,
23676
+ title: sessionImportTitle(summary.generated_title) ?? sessionImportTitle(summary.session_summary) ?? sessionImportTitle(prompt),
23677
+ updatedAt: updatedAt ?? updates.mtimeMs,
23678
+ // Grok registers open Sessions with their process. Absence is not proof of idleness.
23679
+ running: active.has(nativeSessionId) ? true : null
23680
+ });
23681
+ } catch (error53) {
23682
+ signal.throwIfAborted();
23683
+ if (isStorageAccessError(error53))
23684
+ throw error53;
23685
+ return null;
23686
+ }
23687
+ });
23688
+ }
23689
+ };
23690
+
23091
23691
  // dist/grok-subagent-lifecycle.js
23092
23692
  function subagentFailure() {
23093
23693
  return {
@@ -23281,7 +23881,7 @@ var GrokSubagentLifecycle = class {
23281
23881
  };
23282
23882
 
23283
23883
  // dist/grok-models.js
23284
- function isRecord12(value) {
23884
+ function isRecord13(value) {
23285
23885
  return typeof value === "object" && value !== null && !Array.isArray(value);
23286
23886
  }
23287
23887
  function nonBlank(value) {
@@ -23293,7 +23893,7 @@ function thinkingOptions(value) {
23293
23893
  const seen = /* @__PURE__ */ new Set();
23294
23894
  const options = [];
23295
23895
  for (const candidate of value) {
23296
- if (!isRecord12(candidate) || !nonBlank(candidate.label))
23896
+ if (!isRecord13(candidate) || !nonBlank(candidate.label))
23297
23897
  continue;
23298
23898
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
23299
23899
  if (!id.success || seen.has(id.data))
@@ -23304,7 +23904,7 @@ function thinkingOptions(value) {
23304
23904
  return options;
23305
23905
  }
23306
23906
  function parseGrokModelState(value) {
23307
- if (!isRecord12(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
23907
+ if (!isRecord13(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
23308
23908
  return null;
23309
23909
  }
23310
23910
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -23315,12 +23915,12 @@ function parseGrokModelState(value) {
23315
23915
  const models = [];
23316
23916
  let currentThinkingOptionId;
23317
23917
  for (const candidate of value.availableModels) {
23318
- if (!isRecord12(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
23918
+ if (!isRecord13(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
23319
23919
  continue;
23320
23920
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
23321
23921
  if (!ref.success)
23322
23922
  continue;
23323
- const metadata = isRecord12(candidate._meta) ? candidate._meta : {};
23923
+ const metadata = isRecord13(candidate._meta) ? candidate._meta : {};
23324
23924
  const options2 = thinkingOptions(metadata.reasoningEfforts);
23325
23925
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
23326
23926
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
@@ -23355,10 +23955,10 @@ function parseGrokModelState(value) {
23355
23955
  };
23356
23956
  }
23357
23957
  function modelStateFromInitialize(response) {
23358
- return parseGrokModelState(isRecord12(response._meta) ? response._meta.modelState : void 0);
23958
+ return parseGrokModelState(isRecord13(response._meta) ? response._meta.modelState : void 0);
23359
23959
  }
23360
23960
  function modelStateFromSessionResponse(response) {
23361
- return parseGrokModelState(isRecord12(response) ? response.models : void 0);
23961
+ return parseGrokModelState(isRecord13(response) ? response.models : void 0);
23362
23962
  }
23363
23963
  function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
23364
23964
  const selectedModel = model;
@@ -23377,12 +23977,12 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
23377
23977
  }
23378
23978
 
23379
23979
  // dist/grok-credits.js
23380
- import { readFile as readFile3 } from "node:fs/promises";
23980
+ import { readFile as readFile4 } from "node:fs/promises";
23381
23981
  import os5 from "node:os";
23382
- import path10 from "node:path";
23982
+ import path12 from "node:path";
23383
23983
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
23384
23984
  var REQUEST_TIMEOUT_MS = 15e3;
23385
- function isRecord13(value) {
23985
+ function isRecord14(value) {
23386
23986
  return typeof value === "object" && value !== null && !Array.isArray(value);
23387
23987
  }
23388
23988
  function finitePercent(value) {
@@ -23391,7 +23991,7 @@ function finitePercent(value) {
23391
23991
  return Math.min(100, Math.max(0, value));
23392
23992
  }
23393
23993
  function nonNegativeCentValue(value) {
23394
- if (!isRecord13(value))
23994
+ if (!isRecord14(value))
23395
23995
  return void 0;
23396
23996
  const amount = value.val === void 0 ? 0 : value.val;
23397
23997
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -23399,7 +23999,7 @@ function nonNegativeCentValue(value) {
23399
23999
  return amount;
23400
24000
  }
23401
24001
  function grokHome(environment) {
23402
- return environment.GROK_HOME ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
24002
+ return environment.GROK_HOME ?? path12.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
23403
24003
  }
23404
24004
  function periodTypeFrom(value) {
23405
24005
  if (typeof value !== "string")
@@ -23415,7 +24015,7 @@ function productUsageFrom(value) {
23415
24015
  if (!Array.isArray(value))
23416
24016
  return void 0;
23417
24017
  const products = value.flatMap((entry) => {
23418
- if (!isRecord13(entry) || typeof entry.product !== "string")
24018
+ if (!isRecord14(entry) || typeof entry.product !== "string")
23419
24019
  return [];
23420
24020
  const usagePercent = finitePercent(entry.usagePercent);
23421
24021
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -23423,10 +24023,10 @@ function productUsageFrom(value) {
23423
24023
  return products.length > 0 ? products : void 0;
23424
24024
  }
23425
24025
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
23426
- if (!isRecord13(value) || !isRecord13(value.config))
24026
+ if (!isRecord14(value) || !isRecord14(value.config))
23427
24027
  return null;
23428
24028
  const config2 = value.config;
23429
- const period = isRecord13(config2.currentPeriod) ? config2.currentPeriod : void 0;
24029
+ const period = isRecord14(config2.currentPeriod) ? config2.currentPeriod : void 0;
23430
24030
  const periodType = periodTypeFrom(period?.type);
23431
24031
  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);
23432
24032
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -23453,11 +24053,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
23453
24053
  };
23454
24054
  }
23455
24055
  function selectAccessToken(auth, now) {
23456
- if (!isRecord13(auth))
24056
+ if (!isRecord14(auth))
23457
24057
  return null;
23458
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord13(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")));
24058
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord14(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
23459
24059
  for (const [, value] of entries) {
23460
- if (!isRecord13(value) || typeof value.key !== "string")
24060
+ if (!isRecord14(value) || typeof value.key !== "string")
23461
24061
  continue;
23462
24062
  if (typeof value.expires_at === "string") {
23463
24063
  const expiresAt = Date.parse(value.expires_at);
@@ -23478,8 +24078,8 @@ async function fetchGrokAccount(input = {}) {
23478
24078
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
23479
24079
  return null;
23480
24080
  const now = input.now ?? /* @__PURE__ */ new Date();
23481
- const authPath = path10.join(grokHome(environment), "auth.json");
23482
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile3(authPath, "utf8");
24081
+ const authPath = path12.join(grokHome(environment), "auth.json");
24082
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile4(authPath, "utf8");
23483
24083
  const token = selectAccessToken(JSON.parse(raw), now);
23484
24084
  if (!token)
23485
24085
  return null;
@@ -23514,7 +24114,7 @@ async function fetchGrokAccount(input = {}) {
23514
24114
  }
23515
24115
  async function fetchGrokCredits(input = {}) {
23516
24116
  const account = await fetchGrokAccount(input);
23517
- if (!account)
24117
+ if (!account?.credits)
23518
24118
  return null;
23519
24119
  const { credits } = account;
23520
24120
  return {
@@ -23528,7 +24128,7 @@ async function fetchGrokCredits(input = {}) {
23528
24128
 
23529
24129
  // dist/grok-usage.js
23530
24130
  var USD_TICKS_PER_DOLLAR = 1e10;
23531
- function isRecord14(value) {
24131
+ function isRecord15(value) {
23532
24132
  return typeof value === "object" && value !== null && !Array.isArray(value);
23533
24133
  }
23534
24134
  function optionalToken(value) {
@@ -23545,7 +24145,7 @@ function combineUsage(base, next) {
23545
24145
  return base === null ? next : parseHostUsage({ ...base, ...next });
23546
24146
  }
23547
24147
  function usageFromNative(value) {
23548
- if (!isRecord14(value))
24148
+ if (!isRecord15(value))
23549
24149
  return null;
23550
24150
  const inputTokens = optionalToken(value.inputTokens);
23551
24151
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -23572,7 +24172,7 @@ function usageFromPrompt(response) {
23572
24172
  return response.usage ? usageFromNative(response.usage) : null;
23573
24173
  }
23574
24174
  function usageFromSignals(value) {
23575
- if (!isRecord14(value))
24175
+ if (!isRecord15(value))
23576
24176
  return null;
23577
24177
  try {
23578
24178
  return parseHostUsage({
@@ -23592,7 +24192,7 @@ var summedUsageFields = [
23592
24192
  "totalTokens"
23593
24193
  ];
23594
24194
  function nativeCostTicks(value) {
23595
- if (!isRecord14(value))
24195
+ if (!isRecord15(value))
23596
24196
  return void 0;
23597
24197
  const ticks = value.costUsdTicks;
23598
24198
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -23669,7 +24269,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
23669
24269
  function usageFromUpdate(update, metadata, contextWindowTokens) {
23670
24270
  try {
23671
24271
  if (update?.sessionUpdate === "usage_update") {
23672
- const cost = isRecord14(update.cost) ? update.cost : null;
24272
+ const cost = isRecord15(update.cost) ? update.cost : null;
23673
24273
  return parseHostUsage({
23674
24274
  contextUsedTokens: update.used,
23675
24275
  contextWindowTokens: update.size,
@@ -24681,6 +25281,7 @@ var GrokAdapter = class {
24681
25281
  commandCatalog = grokCommandCatalog;
24682
25282
  liveCommandCatalog = true;
24683
25283
  harnessId = grokHarnessId;
25284
+ sessionImport;
24684
25285
  subagents = {
24685
25286
  readSnapshot: async (input) => {
24686
25287
  if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
@@ -24728,6 +25329,7 @@ var GrokAdapter = class {
24728
25329
  constructor(options = {}, dependencies) {
24729
25330
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
24730
25331
  this.#environment = options.environment;
25332
+ this.sessionImport = new GrokSessionImport(options.environment);
24731
25333
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
24732
25334
  this.#dependencies = dependencies ?? {
24733
25335
  randomUUID,
@@ -24771,7 +25373,7 @@ var GrokAdapter = class {
24771
25373
  async inspect(input = {}) {
24772
25374
  if (this.#closePromise)
24773
25375
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
24774
- const cwd = path11.resolve(input.cwd ?? process.cwd());
25376
+ const cwd = path13.resolve(input.cwd ?? process.cwd());
24775
25377
  if (!input.refresh) {
24776
25378
  const cached2 = this.#inspectionCache.get(cwd);
24777
25379
  if (cached2)
@@ -24833,7 +25435,7 @@ var GrokAdapter = class {
24833
25435
  }
24834
25436
  };
24835
25437
  }
24836
- const cwd = path11.resolve(input.cwd);
25438
+ const cwd = path13.resolve(input.cwd);
24837
25439
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
24838
25440
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
24839
25441
  return {
@@ -25004,7 +25606,10 @@ var GrokAdapter = class {
25004
25606
  if (!this.#closePromise) {
25005
25607
  this.#accountAbort.abort();
25006
25608
  this.#inspectionCache.clear();
25007
- this.#closePromise = Promise.all([...this.#sessions].map((session) => session.close())).then(() => void 0);
25609
+ this.#closePromise = Promise.all([
25610
+ this.sessionImport.close(),
25611
+ ...[...this.#sessions].map((session) => session.close())
25612
+ ]).then(() => void 0);
25008
25613
  }
25009
25614
  return this.#closePromise;
25010
25615
  }
@@ -25017,13 +25622,51 @@ var GrokAdapter = class {
25017
25622
  }
25018
25623
  };
25019
25624
 
25625
+ // dist/installation.js
25626
+ var GROK_NPM_PACKAGE = "@xai-official/grok";
25627
+ function createGrokInstallation(environment, command) {
25628
+ const run = (args, timeout, extra) => runInstallationCommand(resolveGrokExecutable({ environment, ...command ? { command } : {} }), args, extra ? { ...environment, ...extra } : environment, timeout);
25629
+ let installer = "";
25630
+ return createInstallationManager({
25631
+ async check() {
25632
+ const state = JSON.parse(await run(["update", "--check", "--json"]));
25633
+ if (state.error || typeof state.updateAvailable !== "boolean")
25634
+ throw new Error("Grok update check failed");
25635
+ installer = typeof state.installer === "string" ? state.installer : "";
25636
+ return {
25637
+ currentVersion: installationVersion(state.currentVersion),
25638
+ latestVersion: installationVersion(state.latestVersion),
25639
+ updateAvailable: state.updateAvailable,
25640
+ canUpdate: true
25641
+ };
25642
+ },
25643
+ async update() {
25644
+ if (installer !== "npm") {
25645
+ await run(["update"], 3e5);
25646
+ return;
25647
+ }
25648
+ const existing = environment.npm_config_allow_scripts?.trim();
25649
+ const allowed = existing ? `${existing},${GROK_NPM_PACKAGE}` : GROK_NPM_PACKAGE;
25650
+ await run(["update", "--force-reinstall"], 3e5, {
25651
+ npm_config_allow_scripts: allowed
25652
+ });
25653
+ }
25654
+ });
25655
+ }
25656
+
25020
25657
  // dist/plugin.js
25021
25658
  var GROK_COMMAND_ENV = "CODEXHOST_GROK_COMMAND";
25022
25659
  function createHarnessAdapter(context) {
25023
25660
  const environment = { ...context.environment };
25024
- return new GrokAdapter({
25661
+ return Object.assign(new GrokAdapter({
25025
25662
  ...environment[GROK_COMMAND_ENV] ? { command: environment[GROK_COMMAND_ENV] } : {},
25026
25663
  environment
25664
+ }), {
25665
+ installation: createGrokInstallation(environment, environment[GROK_COMMAND_ENV]),
25666
+ install: createHarnessInstaller(environment, {
25667
+ npm: "@xai-official/grok",
25668
+ allowScripts: "@xai-official/grok"
25669
+ })
25027
25670
  });
25028
25671
  }
25029
25672
  export {