@liberseek/boft-cli-linux-x64 0.7.5 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,9 +5,491 @@ 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
+ }, (error51, stdout, stderr) => {
264
+ if (error51)
265
+ reject(new Error(error51.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 versionFromOutput(output) {
278
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
279
+ }
280
+ function newerInstallationVersion(current, latest) {
281
+ const a = installationVersion(current).replace(/\+.*/, "");
282
+ const b = installationVersion(latest).replace(/\+.*/, "");
283
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
284
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
285
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
286
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
287
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
288
+ }
289
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
290
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
291
+ if (!preA.length || !preB.length)
292
+ return !!preA.length && !preB.length;
293
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
294
+ const x = preA[i];
295
+ const y = preB[i];
296
+ if (x === y)
297
+ continue;
298
+ if (x === void 0 || y === void 0)
299
+ return x === void 0;
300
+ const numericX = /^\d+$/.test(x);
301
+ const numericY = /^\d+$/.test(y);
302
+ if (numericX && numericY) {
303
+ if (BigInt(x) === BigInt(y))
304
+ continue;
305
+ return BigInt(y) > BigInt(x);
306
+ }
307
+ if (numericX !== numericY)
308
+ return numericX;
309
+ return y > x;
310
+ }
311
+ return false;
312
+ }
313
+ function createInstallationManager(options) {
314
+ let checking;
315
+ let updating;
316
+ const check2 = () => checking ??= options.check().finally(() => {
317
+ checking = void 0;
318
+ });
319
+ return (action) => {
320
+ if (updating)
321
+ return updating;
322
+ if (action === "check")
323
+ return check2();
324
+ updating = (async () => {
325
+ const before = await check2();
326
+ if (!before.updateAvailable)
327
+ return before;
328
+ if (!before.canUpdate)
329
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
330
+ await options.update(before);
331
+ const after = await check2();
332
+ if (after.currentVersion === before.currentVersion)
333
+ throw new Error("The Harness version did not change; check the native updater and retry");
334
+ return after;
335
+ })().finally(() => {
336
+ updating = void 0;
337
+ });
338
+ return updating;
339
+ };
340
+ }
341
+ async function fetchInstallationText(url2) {
342
+ const request = async () => {
343
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
344
+ if (!response.ok)
345
+ throw new Error("Could not check the latest Harness version");
346
+ return response.text();
347
+ };
348
+ try {
349
+ return await request();
350
+ } catch (error51) {
351
+ if (error51 instanceof DOMException && (error51.name === "AbortError" || error51.name === "TimeoutError"))
352
+ throw error51;
353
+ return request();
354
+ }
355
+ }
356
+
357
+ // ../../harness-discovery/dist/npm-installation.js
358
+ import { readFile, realpath } from "node:fs/promises";
359
+ import path4 from "node:path";
360
+ function referencesNpmBin(shim, name, bin) {
361
+ if (bin.includes(".."))
362
+ return false;
363
+ const target = `node_modules/${name}/${bin.replace(/^\.\//, "")}`.toLowerCase();
364
+ const text = shim.replaceAll("\\", "/").toLowerCase();
365
+ return text.includes(`%dp0%/${target}"`) || text.includes(`%~dp0/${target}"`);
366
+ }
367
+ async function npmInstallation(command, packages, environment) {
368
+ let selected = await realpath(command);
369
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(selected)) {
370
+ const shim = (await readFile(selected, "utf8")).replaceAll("\\", "/");
371
+ const root = path4.dirname(selected);
372
+ for (const name of packages) {
373
+ const directory2 = path4.join(root, "node_modules", ...name.split("/"));
374
+ const metadata = await readFile(path4.join(directory2, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
375
+ const bins = typeof metadata?.bin === "string" ? [metadata.bin] : Object.values(metadata?.bin ?? {});
376
+ const bin = bins.find((entry) => referencesNpmBin(shim, name, entry));
377
+ if (bin) {
378
+ selected = await realpath(path4.join(directory2, bin));
379
+ break;
380
+ }
381
+ }
382
+ }
383
+ let directory = path4.dirname(selected);
384
+ for (let depth = 0; depth < 8; depth++) {
385
+ const metadata = await readFile(path4.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
386
+ if (metadata?.name && packages.includes(metadata.name)) {
387
+ const name = metadata.name;
388
+ const currentVersion = installationVersion(metadata.version);
389
+ const segments = name.split("/");
390
+ let modules = directory;
391
+ for (let index = 0; index < segments.length; index++)
392
+ modules = path4.dirname(modules);
393
+ const prefix = process.platform === "win32" ? path4.dirname(modules) : path4.dirname(path4.dirname(modules));
394
+ const globalRoot = process.platform === "win32" ? path4.join(prefix, "node_modules") : path4.join(prefix, "lib", "node_modules");
395
+ const env = withNodeRuntimeOnPath(environment);
396
+ const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
397
+ let globalInstall = modules === globalRoot;
398
+ if (process.platform === "win32") {
399
+ const project = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile(path4.join(prefix, file2), "utf8").then(() => true, (error51) => error51.code !== "ENOENT")))).some(Boolean);
400
+ const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
401
+ const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
402
+ if (path4.basename(bin) !== bin || entry.includes(".."))
403
+ return false;
404
+ const target = await realpath(path4.join(directory, entry)).catch(() => "");
405
+ if (target.toLowerCase() !== selected.toLowerCase())
406
+ return false;
407
+ const shim = await readFile(path4.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
408
+ return referencesNpmBin(shim, name, entry);
409
+ }));
410
+ globalInstall = globalInstall && !project && launchers.some(Boolean);
411
+ }
412
+ const canUpdate = globalInstall && !!npm;
413
+ return {
414
+ prefix,
415
+ currentVersion,
416
+ canUpdate,
417
+ latest: async () => {
418
+ const data = JSON.parse(await fetchInstallationText(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`));
419
+ return installationVersion(data.version);
420
+ },
421
+ update: async (version2) => {
422
+ if (!canUpdate || !npm)
423
+ throw new Error("Use the original package manager to update this installation");
424
+ await runInstallationCommand(npm.executable, ["install", "--global", "--prefix", prefix, `${name}@${installationVersion(version2)}`], env, 3e5);
425
+ }
426
+ };
427
+ }
428
+ const parent = path4.dirname(directory);
429
+ if (parent === directory)
430
+ break;
431
+ directory = parent;
432
+ }
433
+ return null;
434
+ }
435
+
436
+ // ../../harness-discovery/dist/installer.js
437
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
438
+ import { tmpdir } from "node:os";
439
+ import { join } from "node:path";
440
+ function createHarnessInstaller(environment, source) {
441
+ return async () => {
442
+ if (!["darwin", "linux", "win32"].includes(process.platform))
443
+ throw new Error("Unsupported installation platform");
444
+ const env = withNodeRuntimeOnPath(environment);
445
+ if ("npm" in source) {
446
+ const npm = resolveHarnessExecutable({
447
+ id: "npm",
448
+ command: "npm",
449
+ installRoots: {
450
+ posix: [
451
+ "~/.npm-global/bin",
452
+ "~/.local/bin",
453
+ VERSION_MANAGER_ROOTS,
454
+ "/opt/homebrew/bin",
455
+ "/usr/local/bin",
456
+ "/usr/bin"
457
+ ],
458
+ windows: [
459
+ "${APPDATA}/npm",
460
+ VERSION_MANAGER_ROOTS,
461
+ "${ProgramFiles}/nodejs",
462
+ "${LOCALAPPDATA}/Programs/nodejs"
463
+ ]
464
+ }
465
+ }, { environment: env });
466
+ if (!npm)
467
+ throw new Error("Install Node.js and npm first");
468
+ await runInstallationCommand(npm.executable, ["install", "--global", source.npm], {
469
+ ...env,
470
+ ...source.allowScripts ? { npm_config_allow_scripts: source.allowScripts } : {}
471
+ }, 6e5);
472
+ return;
473
+ }
474
+ const windows = process.platform === "win32";
475
+ const url2 = windows ? source.windows : source.posix;
476
+ if (new URL(url2).protocol !== "https:")
477
+ throw new Error("Installer requires HTTPS");
478
+ const script = await fetchInstallationText(url2);
479
+ const directory = await mkdtemp(join(tmpdir(), "codexhost-installer-"));
480
+ try {
481
+ const file2 = join(directory, windows ? "install.ps1" : "install.sh");
482
+ await writeFile(file2, script, { mode: 384 });
483
+ await runInstallationCommand(windows ? "powershell.exe" : source.shell ?? "bash", windows ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file2] : [file2], env, 6e5);
484
+ } finally {
485
+ await rm(directory, { recursive: true, force: true });
486
+ }
487
+ };
488
+ }
489
+
8
490
  // dist/kimi-adapter.js
9
- import { readFile as readFile3 } from "node:fs/promises";
10
- import path6 from "node:path";
491
+ import { readFile as readFile5 } from "node:fs/promises";
492
+ import path8 from "node:path";
11
493
  import { isDeepStrictEqual } from "node:util";
12
494
 
13
495
  // ../../../node_modules/zod/v4/classic/external.js
@@ -776,10 +1258,10 @@ function mergeDefs(...defs) {
776
1258
  function cloneDef(schema) {
777
1259
  return mergeDefs(schema._zod.def);
778
1260
  }
779
- function getElementAtPath(obj, path7) {
780
- if (!path7)
1261
+ function getElementAtPath(obj, path9) {
1262
+ if (!path9)
781
1263
  return obj;
782
- return path7.reduce((acc, key) => acc?.[key], obj);
1264
+ return path9.reduce((acc, key) => acc?.[key], obj);
783
1265
  }
784
1266
  function promiseAllObject(promisesObj) {
785
1267
  const keys = Object.keys(promisesObj);
@@ -1188,11 +1670,11 @@ function explicitlyAborted(x, startIndex = 0) {
1188
1670
  }
1189
1671
  return false;
1190
1672
  }
1191
- function prefixIssues(path7, issues) {
1673
+ function prefixIssues(path9, issues) {
1192
1674
  return issues.map((iss) => {
1193
1675
  var _a3;
1194
1676
  (_a3 = iss).path ?? (_a3.path = []);
1195
- iss.path.unshift(path7);
1677
+ iss.path.unshift(path9);
1196
1678
  return iss;
1197
1679
  });
1198
1680
  }
@@ -1339,16 +1821,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1339
1821
  }
1340
1822
  function formatError(error51, mapper = (issue2) => issue2.message) {
1341
1823
  const fieldErrors = { _errors: [] };
1342
- const processError = (error52, path7 = []) => {
1824
+ const processError = (error52, path9 = []) => {
1343
1825
  for (const issue2 of error52.issues) {
1344
1826
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1345
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1827
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1346
1828
  } else if (issue2.code === "invalid_key") {
1347
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1829
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1348
1830
  } else if (issue2.code === "invalid_element") {
1349
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1831
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1350
1832
  } else {
1351
- const fullpath = [...path7, ...issue2.path];
1833
+ const fullpath = [...path9, ...issue2.path];
1352
1834
  if (fullpath.length === 0) {
1353
1835
  fieldErrors._errors.push(mapper(issue2));
1354
1836
  } else {
@@ -1375,17 +1857,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1375
1857
  }
1376
1858
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1377
1859
  const result = { errors: [] };
1378
- const processError = (error52, path7 = []) => {
1860
+ const processError = (error52, path9 = []) => {
1379
1861
  var _a3, _b;
1380
1862
  for (const issue2 of error52.issues) {
1381
1863
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1382
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1864
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1383
1865
  } else if (issue2.code === "invalid_key") {
1384
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1866
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1385
1867
  } else if (issue2.code === "invalid_element") {
1386
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1868
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1387
1869
  } else {
1388
- const fullpath = [...path7, ...issue2.path];
1870
+ const fullpath = [...path9, ...issue2.path];
1389
1871
  if (fullpath.length === 0) {
1390
1872
  result.errors.push(mapper(issue2));
1391
1873
  continue;
@@ -1417,8 +1899,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1417
1899
  }
1418
1900
  function toDotPath(_path) {
1419
1901
  const segs = [];
1420
- const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
- for (const seg of path7) {
1902
+ const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1903
+ for (const seg of path9) {
1422
1904
  if (typeof seg === "number")
1423
1905
  segs.push(`[${seg}]`);
1424
1906
  else if (typeof seg === "symbol")
@@ -14110,13 +14592,13 @@ function resolveRef(ref, ctx) {
14110
14592
  if (!ref.startsWith("#")) {
14111
14593
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14112
14594
  }
14113
- const path7 = ref.slice(1).split("/").filter(Boolean);
14114
- if (path7.length === 0) {
14595
+ const path9 = ref.slice(1).split("/").filter(Boolean);
14596
+ if (path9.length === 0) {
14115
14597
  return ctx.rootSchema;
14116
14598
  }
14117
14599
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14118
- if (path7[0] === defsKey) {
14119
- const key = path7[1];
14600
+ if (path9[0] === defsKey) {
14601
+ const key = path9[1];
14120
14602
  if (!key || !ctx.defs[key]) {
14121
14603
  throw new Error(`Reference not found: ${ref}`);
14122
14604
  }
@@ -14579,6 +15061,123 @@ var credentialImportsParamsSchema = external_exports.object({
14579
15061
  request: credentialImportsRequestSchema
14580
15062
  }).strict();
14581
15063
 
15064
+ // ../../shared-contracts/dist/harness-display-settings.js
15065
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
15066
+ agent: external_exports.string().min(1).max(128),
15067
+ section: external_exports.enum(["main", "more", "auto"])
15068
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
15069
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
15070
+ entries: harnessDisplayEntriesSchema.nullable()
15071
+ });
15072
+ var harnessDisplayGetSchema = external_exports.strictObject({});
15073
+ var harnessDisplaySetSchema = external_exports.strictObject({
15074
+ entries: harnessDisplayEntriesSchema,
15075
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
15076
+ initializeOnly: external_exports.boolean().optional()
15077
+ });
15078
+
15079
+ // ../../shared-contracts/dist/ids.js
15080
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15081
+ message: "Identifier must not be empty or whitespace"
15082
+ });
15083
+ var harnessIdSchema = opaqueIdSchema.brand();
15084
+ var hostThreadIdSchema = opaqueIdSchema.brand();
15085
+ var hostTurnIdSchema = opaqueIdSchema.brand();
15086
+ var hostItemIdSchema = opaqueIdSchema.brand();
15087
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
15088
+
15089
+ // ../../shared-contracts/dist/harness-plugins.js
15090
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15091
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15092
+ var HARNESS_PLUGIN_LIMIT = 128;
15093
+ var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
15094
+ var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15095
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15096
+ var pluginPresentationShape = {
15097
+ id: harnessPluginIdSchema,
15098
+ name: external_exports.string().trim().min(1).max(128),
15099
+ version: external_exports.string().min(1).max(128),
15100
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15101
+ launchCommand: external_exports.literal(true).optional(),
15102
+ links: external_exports.object({
15103
+ documentation: documentationUrlSchema.optional(),
15104
+ installation: documentationUrlSchema.optional()
15105
+ }).strict().optional()
15106
+ };
15107
+ var harnessPluginManifestSchema = external_exports.object({
15108
+ manifestVersion: external_exports.literal(1),
15109
+ ...pluginPresentationShape,
15110
+ adapterApiVersion: external_exports.number().int().positive(),
15111
+ entry: relativeResourceSchema,
15112
+ icon: relativeResourceSchema.optional()
15113
+ }).strict();
15114
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15115
+ var harnessPluginDescriptorSchema = external_exports.object({
15116
+ ...pluginPresentationShape,
15117
+ icon: harnessPluginIconSchema.optional()
15118
+ }).strict();
15119
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15120
+ var harnessPluginListResultSchema = external_exports.object({
15121
+ plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15122
+ }).strict();
15123
+ var harnessPluginConfigurationSchema = external_exports.object({
15124
+ version: external_exports.literal(1),
15125
+ enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15126
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15127
+ message: "Enabled plugin IDs must be unique",
15128
+ path: ["enabled"]
15129
+ });
15130
+
15131
+ // ../../shared-contracts/dist/harness-long-context.js
15132
+ var HARNESS_LONG_CONTEXT_GET_METHOD = "codexhost/harness/long-context/get";
15133
+ var HARNESS_LONG_CONTEXT_SET_METHOD = "codexhost/harness/long-context/set";
15134
+ var harnessLongContextGetSchema = external_exports.object({
15135
+ harnessId: harnessPluginIdSchema
15136
+ }).strict();
15137
+ var harnessLongContextSetSchema = harnessLongContextGetSchema.extend({
15138
+ enabled: external_exports.boolean()
15139
+ });
15140
+ var harnessLongContextSchema = external_exports.object({
15141
+ enabled: external_exports.boolean()
15142
+ }).strict();
15143
+
15144
+ // ../../shared-contracts/dist/console.js
15145
+ var consoleAnnouncementSchema = external_exports.strictObject({
15146
+ title: external_exports.string().trim().min(1).max(200),
15147
+ type: external_exports.enum(["info", "warning", "danger"]),
15148
+ body: external_exports.string().trim().min(1).max(16 * 1024)
15149
+ });
15150
+ var consoleOpenParamsSchema = external_exports.strictObject({});
15151
+ var consoleOpenResultSchema = external_exports.strictObject({
15152
+ /** The console address. */
15153
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
15154
+ });
15155
+ var CONSOLE_HOST_METHODS = Object.freeze([
15156
+ "codexhost/harness/plugins/list",
15157
+ "codexhost/harness/display-settings/get",
15158
+ "codexhost/harness/display-settings/set",
15159
+ "codexhost/harness/inspect",
15160
+ "codexhost/harness/installation",
15161
+ "codexhost/harness/launch-settings/get",
15162
+ "codexhost/harness/launch-settings/set",
15163
+ HARNESS_LONG_CONTEXT_GET_METHOD,
15164
+ HARNESS_LONG_CONTEXT_SET_METHOD,
15165
+ "codexhost/harness/web-ui/open",
15166
+ "codexhost/harness/accounts/sources",
15167
+ "codexhost/harness/accounts/list",
15168
+ "codexhost/harness/accounts/inspect",
15169
+ "codexhost/harness/credential-imports",
15170
+ "codexhost/harness/session-import/sources",
15171
+ "codexhost/harness/session-import/list",
15172
+ "codexhost/harness/session-import/import",
15173
+ "codexhost/account/list",
15174
+ "codexhost/account/refresh",
15175
+ "codexhost/account/usage/inspect",
15176
+ "codexhost/update/check",
15177
+ "codexhost/update/start",
15178
+ "codexhost/update/status"
15179
+ ]);
15180
+
14582
15181
  // ../../shared-contracts/dist/version.js
14583
15182
  var WORKSPACE_CONTRACT_VERSION = 1;
14584
15183
 
@@ -14622,15 +15221,11 @@ var loadedSessionsSchema = external_exports.array(external_exports.strictObject(
14622
15221
  inactiveMs: external_exports.number().nonnegative()
14623
15222
  }));
14624
15223
 
14625
- // ../../shared-contracts/dist/ids.js
14626
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14627
- message: "Identifier must not be empty or whitespace"
15224
+ // ../../shared-contracts/dist/manual-compaction.js
15225
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
15226
+ threadId: hostThreadIdSchema,
15227
+ turnId: hostTurnIdSchema
14628
15228
  });
14629
- var harnessIdSchema = opaqueIdSchema.brand();
14630
- var hostThreadIdSchema = opaqueIdSchema.brand();
14631
- var hostTurnIdSchema = opaqueIdSchema.brand();
14632
- var hostItemIdSchema = opaqueIdSchema.brand();
14633
- var hostInteractionIdSchema = opaqueIdSchema.brand();
14634
15229
 
14635
15230
  // ../../shared-contracts/dist/thread-usage.js
14636
15231
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
@@ -14692,6 +15287,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14692
15287
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14693
15288
  var accountCreditsProductUsageSchema = external_exports.object({
14694
15289
  product: external_exports.string().min(1),
15290
+ used: external_exports.number().finite().nonnegative().optional(),
15291
+ // Zero is a real empty cap, not an absent field.
15292
+ limit: external_exports.number().finite().nonnegative().optional(),
15293
+ unit: external_exports.string().min(1).max(32).optional(),
14695
15294
  usagePercent: usagePercentSchema,
14696
15295
  resetsAt: external_exports.string().min(1).optional()
14697
15296
  }).strict();
@@ -14701,11 +15300,14 @@ var accountResetCreditsSchema = external_exports.object({
14701
15300
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14702
15301
  }).strict();
14703
15302
  var accountCreditsSnapshotSchema = external_exports.object({
15303
+ used: external_exports.number().finite().nonnegative().optional(),
15304
+ // Zero is a real empty cap, not an absent field.
15305
+ limit: external_exports.number().finite().nonnegative().optional(),
15306
+ unit: external_exports.string().trim().min(1).max(32).optional(),
14704
15307
  /** Native label when the primary limit is scoped to a model or product group. */
14705
15308
  label: external_exports.string().min(1).optional(),
14706
15309
  usedPercent: usagePercentSchema.optional(),
14707
15310
  remaining: external_exports.number().finite().optional(),
14708
- unit: external_exports.string().trim().min(1).max(32).optional(),
14709
15311
  resetsAt: external_exports.string().min(1).optional(),
14710
15312
  periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
14711
15313
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
@@ -14736,12 +15338,27 @@ var threadUsageInspectionSchema = external_exports.object({
14736
15338
  }).strict();
14737
15339
 
14738
15340
  // ../../shared-contracts/dist/harness-accounts.js
14739
- var harnessAccountSnapshotSchema = external_exports.object({
15341
+ var accountBalanceSnapshotSchema = external_exports.object({
15342
+ amount: external_exports.number().finite().nonnegative(),
15343
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15344
+ currency: external_exports.string().trim().min(1).max(8),
15345
+ /** Native label when the Harness exposes several Billing Sources. */
15346
+ label: external_exports.string().trim().min(1).max(128).optional()
15347
+ }).strict();
15348
+ var harnessAccountSnapshotObject = external_exports.object({
14740
15349
  email: external_exports.string().trim().min(1).max(320).optional(),
14741
15350
  label: external_exports.string().trim().min(1).max(256).optional(),
14742
15351
  plan: external_exports.string().trim().min(1).max(128).optional(),
14743
- credits: accountCreditsSnapshotSchema
15352
+ credits: accountCreditsSnapshotSchema.optional(),
15353
+ balance: accountBalanceSnapshotSchema.optional()
14744
15354
  }).strict();
15355
+ function requireReportedQuota(schema) {
15356
+ return schema.refine((value) => {
15357
+ const reported = value;
15358
+ return reported.credits !== void 0 || reported.balance !== void 0;
15359
+ }, { message: "Account must report either credits or a balance" });
15360
+ }
15361
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14745
15362
  var harnessAccountIdentityShape = {
14746
15363
  harnessId: harnessIdSchema,
14747
15364
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14752,11 +15369,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14752
15369
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14753
15370
  var harnessAccountInspectResultSchema = external_exports.object({
14754
15371
  ...harnessAccountIdentityShape,
14755
- account: harnessAccountSnapshotSchema.nullable()
15372
+ account: harnessAccountSnapshotSchema.nullable(),
15373
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
15374
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14756
15375
  }).strict();
14757
15376
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14758
15377
  var harnessAccountListResultSchema = external_exports.object({
14759
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
15378
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14760
15379
  }).strict();
14761
15380
 
14762
15381
  // ../../shared-contracts/dist/json-value.js
@@ -14894,6 +15513,8 @@ var harnessModelSchema = external_exports.object({
14894
15513
  ref: harnessModelRefSchema,
14895
15514
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14896
15515
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15516
+ /** Optional opaque selection for this same Model with priority processing enabled. */
15517
+ fastModel: harnessModelRefSchema.optional(),
14897
15518
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14898
15519
  }).strict();
14899
15520
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14926,6 +15547,16 @@ var harnessModelCatalogSchema = external_exports.object({
14926
15547
  });
14927
15548
  }
14928
15549
  refs.add(model.ref.id);
15550
+ if (model.fastModel) {
15551
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15552
+ context.addIssue({
15553
+ code: "custom",
15554
+ message: "Fast Model refs must be distinct and unique",
15555
+ path: ["models", index, "fastModel"]
15556
+ });
15557
+ }
15558
+ refs.add(model.fastModel.id);
15559
+ }
14929
15560
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14930
15561
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14931
15562
  if (supportedThinkingIds.has(optionId)) {
@@ -15048,11 +15679,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15048
15679
  thinkingOptionId: harnessThinkingOptionIdSchema
15049
15680
  }).strict();
15050
15681
  var threadInspectionParamsSchema = external_exports.object({
15051
- threadId: hostThreadIdSchema
15682
+ threadId: hostThreadIdSchema,
15683
+ includeReferenceCapability: external_exports.boolean().optional()
15052
15684
  }).strict();
15053
15685
  var codexThreadInspectionSchema = external_exports.object({
15054
15686
  owner: external_exports.literal("codex"),
15055
- locked: external_exports.literal(true)
15687
+ locked: external_exports.literal(true),
15688
+ supportsThreadReferences: external_exports.literal(true).optional()
15056
15689
  }).strict();
15057
15690
  var externalThreadInspectionSchema = external_exports.object({
15058
15691
  owner: external_exports.literal("external"),
@@ -15117,48 +15750,6 @@ var threadOwnershipListResultSchema = external_exports.object({
15117
15750
  }
15118
15751
  });
15119
15752
 
15120
- // ../../shared-contracts/dist/harness-plugins.js
15121
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15122
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15123
- var HARNESS_PLUGIN_LIMIT = 128;
15124
- var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
15125
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15126
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15127
- var pluginPresentationShape = {
15128
- id: harnessPluginIdSchema,
15129
- name: external_exports.string().trim().min(1).max(128),
15130
- version: external_exports.string().min(1).max(128),
15131
- /** The factory accepts a persisted local entrypoint through its construction context. */
15132
- launchCommand: external_exports.literal(true).optional(),
15133
- links: external_exports.object({
15134
- documentation: documentationUrlSchema.optional(),
15135
- installation: documentationUrlSchema.optional()
15136
- }).strict().optional()
15137
- };
15138
- var harnessPluginManifestSchema = external_exports.object({
15139
- manifestVersion: external_exports.literal(1),
15140
- ...pluginPresentationShape,
15141
- adapterApiVersion: external_exports.number().int().positive(),
15142
- entry: relativeResourceSchema,
15143
- icon: relativeResourceSchema.optional()
15144
- }).strict();
15145
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15146
- var harnessPluginDescriptorSchema = external_exports.object({
15147
- ...pluginPresentationShape,
15148
- icon: harnessPluginIconSchema.optional()
15149
- }).strict();
15150
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
15151
- var harnessPluginListResultSchema = external_exports.object({
15152
- plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15153
- }).strict();
15154
- var harnessPluginConfigurationSchema = external_exports.object({
15155
- version: external_exports.literal(1),
15156
- enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15157
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15158
- message: "Enabled plugin IDs must be unique",
15159
- path: ["enabled"]
15160
- });
15161
-
15162
15753
  // ../../shared-contracts/dist/harness-route.js
15163
15754
  var harnessPluginRouteSchema = external_exports.object({
15164
15755
  harnessId: harnessPluginIdSchema,
@@ -15180,10 +15771,31 @@ var harnessLaunchSettingsSchema = external_exports.object({
15180
15771
  restartRequired: external_exports.boolean()
15181
15772
  }).strict();
15182
15773
 
15774
+ // ../../shared-contracts/dist/harness-installation.js
15775
+ var harnessInstallationParamsSchema = external_exports.object({
15776
+ harnessId: harnessIdSchema,
15777
+ action: external_exports.enum(["check", "update", "install"])
15778
+ }).strict();
15779
+ var harnessInstallationStateSchema = external_exports.object({
15780
+ currentVersion: external_exports.string().min(1).max(128),
15781
+ latestVersion: external_exports.string().min(1).max(128),
15782
+ updateAvailable: external_exports.boolean(),
15783
+ canUpdate: external_exports.boolean(),
15784
+ message: external_exports.string().max(2048).optional()
15785
+ }).strict();
15786
+
15183
15787
  // ../../shared-contracts/dist/codex-accounts.js
15184
15788
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15185
15789
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
15186
15790
  var codexAccountAuthKindSchema = external_exports.enum(["api", "chatgpt"]);
15791
+ var codexAccountSiteUrlPattern = /^https?:\/\/(?:\[[0-9a-fA-F:]+\]|[^/\s:@?#]+)(?::\d{1,5})?(?:[/?#][^\s]*)?$/u;
15792
+ function isCodexAccountSiteUrl(value) {
15793
+ return value.length > 0 && value.length <= 2048 && codexAccountSiteUrlPattern.test(value);
15794
+ }
15795
+ var externalUrlOpenParamsSchema = external_exports.object({
15796
+ url: external_exports.string().max(2048).refine(isCodexAccountSiteUrl, "External URL must be http(s)")
15797
+ }).strict();
15798
+ var externalUrlOpenResultSchema = external_exports.object({}).strict();
15187
15799
  var codexAccountPlanTypeSchema = external_exports.enum([
15188
15800
  "free",
15189
15801
  "go",
@@ -15209,7 +15821,8 @@ var codexAccountSchema = external_exports.object({
15209
15821
  email: external_exports.string().email().max(320).optional(),
15210
15822
  planType: codexAccountPlanTypeSchema.optional(),
15211
15823
  authKind: codexAccountAuthKindSchema.optional(),
15212
- authIdentity: nonBlankTextSchema3.max(256).optional()
15824
+ authIdentity: nonBlankTextSchema3.max(256).optional(),
15825
+ siteUrl: external_exports.string().refine(isCodexAccountSiteUrl, "Account site URL must be http(s)").optional()
15213
15826
  }).strict();
15214
15827
  var codexAccountPhaseSchema = external_exports.enum(["ready", "unavailable"]);
15215
15828
  var codexAccountListResultSchema = external_exports.object({
@@ -19764,318 +20377,91 @@ var ClientSideConnection = class {
19764
20377
  return this.connection.sendNotification(AGENT_METHODS.nes_accept, params);
19765
20378
  }
19766
20379
  /**
19767
- * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
19768
- *
19769
- * Notifies the agent that a NES suggestion was rejected.
19770
- *
19771
- * @experimental
19772
- */
19773
- unstable_rejectNes(params) {
19774
- return this.connection.sendNotification(AGENT_METHODS.nes_reject, params);
19775
- }
19776
- request(method, params, options) {
19777
- const spec = agentRequestSpecsByMethod[method];
19778
- return this.connection.sendRequest(method, params, spec?.mapResponse, options);
19779
- }
19780
- notify(method, params) {
19781
- return this.connection.sendNotification(method, params);
19782
- }
19783
- /**
19784
- * Extension method.
19785
- *
19786
- * @deprecated Use {@link request}.
19787
- */
19788
- extMethod(method, params) {
19789
- return this.request(method, params);
19790
- }
19791
- /**
19792
- * Extension notification.
19793
- *
19794
- * @deprecated Use {@link notify}.
19795
- */
19796
- extNotification(method, params) {
19797
- return this.notify(method, params);
19798
- }
19799
- /**
19800
- * AbortSignal that aborts when the connection closes.
19801
- *
19802
- * This signal can be used to:
19803
- * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
19804
- * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
19805
- * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
19806
- *
19807
- * The connection closes when the underlying stream ends, either normally or due to an error.
19808
- *
19809
- * @example
19810
- * ```typescript
19811
- * const connection = new ClientSideConnection(client, stream);
19812
- *
19813
- * // Listen for closure
19814
- * connection.signal.addEventListener('abort', () => {
19815
- * console.log('Connection closed - performing cleanup');
19816
- * });
19817
- *
19818
- * // Check status
19819
- * if (connection.signal.aborted) {
19820
- * console.log('Connection is already closed');
19821
- * }
19822
- *
19823
- * // Pass to other APIs
19824
- * fetch(url, { signal: connection.signal });
19825
- * ```
19826
- */
19827
- get signal() {
19828
- return this.connection.signal;
19829
- }
19830
- /**
19831
- * Promise that resolves when the connection closes.
19832
- *
19833
- * The connection closes when the underlying stream ends, either normally or due to an error.
19834
- * Once closed, the connection cannot send or receive any more messages.
19835
- *
19836
- * This is useful for async/await style cleanup:
19837
- *
19838
- * @example
19839
- * ```typescript
19840
- * const connection = new ClientSideConnection(client, stream);
19841
- * await connection.closed;
19842
- * console.log('Connection closed - performing cleanup');
19843
- * ```
19844
- */
19845
- get closed() {
19846
- return this.connection.closed;
19847
- }
19848
- };
19849
-
19850
- // dist/command.js
19851
- import path3 from "node:path";
19852
-
19853
- // ../../harness-discovery/dist/environment.js
19854
- import fs from "node:fs";
19855
- import path from "node:path";
19856
- function targetPath(platform) {
19857
- return platform === "win32" ? path.win32 : path.posix;
19858
- }
19859
- function environmentValue(environment, name) {
19860
- const lowered = name.toLowerCase();
19861
- for (const [key, value] of Object.entries(environment)) {
19862
- if (key.toLowerCase() === lowered)
19863
- return value;
19864
- }
19865
- return void 0;
19866
- }
19867
- function pathDelimiter(platform) {
19868
- return platform === "win32" ? ";" : ":";
19869
- }
19870
- function pathDirectories(environment, platform) {
19871
- return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
19872
- }
19873
- function executableExtensions(command, platform, environment) {
19874
- if (platform !== "win32")
19875
- return [""];
19876
- if (targetPath(platform).extname(command) !== "")
19877
- return [""];
19878
- return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
19879
- }
19880
- function isExecutableFile(filePath, platform) {
19881
- try {
19882
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
19883
- return fs.statSync(filePath).isFile();
19884
- } catch {
19885
- return false;
19886
- }
19887
- }
19888
- function subdirectoryNames(directory) {
19889
- try {
19890
- return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
19891
- } catch {
19892
- return [];
19893
- }
19894
- }
19895
- function newestFirst(names) {
19896
- return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
19897
- }
19898
-
19899
- // ../../harness-discovery/dist/invocation.js
19900
- import path2 from "node:path";
19901
- function commandInvocation(command, arguments_, environment, platform = process.platform) {
19902
- const extension = path2.win32.extname(command).toLowerCase();
19903
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
19904
- return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
19905
- }
19906
- const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
19907
- const commandLine = [command, ...arguments_].map(quote).join(" ");
19908
- return {
19909
- command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
19910
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
19911
- windowsVerbatimArguments: true
19912
- };
19913
- }
19914
-
19915
- // ../../harness-discovery/dist/resolve.js
19916
- import os from "node:os";
19917
-
19918
- // ../../harness-discovery/dist/version-managers.js
19919
- function versionManagerBinaryDirectories(context) {
19920
- const { platform, environment, home } = context;
19921
- const list = context.subdirectories ?? subdirectoryNames;
19922
- const pathFlavor = targetPath(platform);
19923
- const value = (name) => environmentValue(environment, name);
19924
- const directories = [];
19925
- const versioned = (root, ...tail) => {
19926
- for (const version2 of newestFirst(list(root))) {
19927
- directories.push(pathFlavor.join(root, version2, ...tail));
19928
- }
19929
- };
19930
- if (platform === "win32") {
19931
- const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
19932
- const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
19933
- versioned(pathFlavor.join(appData, "nvm"));
19934
- versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
19935
- directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
19936
- directories.push(pathFlavor.join(home, ".bun", "bin"));
19937
- const pnpmHome2 = value("PNPM_HOME");
19938
- if (pnpmHome2)
19939
- directories.push(pnpmHome2);
19940
- directories.push(pathFlavor.join(localAppData, "pnpm"));
19941
- return directories;
19942
- }
19943
- versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
19944
- const fnmRoots = [
19945
- value("FNM_DIR"),
19946
- pathFlavor.join(home, ".local", "share", "fnm"),
19947
- pathFlavor.join(home, "Library", "Application Support", "fnm")
19948
- ].filter((root) => root !== void 0);
19949
- for (const root of fnmRoots) {
19950
- versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
19951
- }
19952
- const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
19953
- versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
19954
- directories.push(pathFlavor.join(voltaHome, "bin"));
19955
- const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
19956
- versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
19957
- directories.push(pathFlavor.join(asdfHome, "shims"));
19958
- const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
19959
- versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
19960
- directories.push(pathFlavor.join(nodenvHome, "shims"));
19961
- versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
19962
- directories.push(pathFlavor.join(home, ".bun", "bin"));
19963
- const pnpmHome = value("PNPM_HOME");
19964
- if (pnpmHome)
19965
- directories.push(pnpmHome);
19966
- directories.push(pathFlavor.join(home, "Library", "pnpm"));
19967
- directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
19968
- for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
19969
- for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
19970
- directories.push(pathFlavor.join(prefix, formula, "bin"));
19971
- }
20380
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
20381
+ *
20382
+ * Notifies the agent that a NES suggestion was rejected.
20383
+ *
20384
+ * @experimental
20385
+ */
20386
+ unstable_rejectNes(params) {
20387
+ return this.connection.sendNotification(AGENT_METHODS.nes_reject, params);
19972
20388
  }
19973
- return directories;
19974
- }
19975
-
19976
- // ../../harness-discovery/dist/resolve.js
19977
- var VERSION_MANAGER_ROOTS = "<version-managers>";
19978
- function installRootExtensions(platform) {
19979
- return platform === "win32" ? [".exe", ".cmd"] : [""];
19980
- }
19981
- function resolveHomeDirectory(input) {
19982
- return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
19983
- }
19984
- function templateVariables(environment, platform, home) {
19985
- const pathFlavor = targetPath(platform);
19986
- return {
19987
- HOME: home,
19988
- USERPROFILE: home,
19989
- APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
19990
- LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
19991
- };
19992
- }
19993
- function joinTemplate(platform, value) {
19994
- const pathFlavor = targetPath(platform);
19995
- const segments = value.split("/");
19996
- const head = segments[0] ?? "";
19997
- const tail = segments.slice(1);
19998
- if (head === "")
19999
- return pathFlavor.join(pathFlavor.sep, ...tail);
20000
- return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
20001
- }
20002
- function expandInstallRoot(template, environment, platform, home) {
20003
- const variables = templateVariables(environment, platform, home);
20004
- let unresolved = false;
20005
- const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
20006
- const value = variables[name] ?? environmentValue(environment, name);
20007
- if (value === void 0 || value === "") {
20008
- unresolved = true;
20009
- return "";
20010
- }
20011
- return value;
20012
- });
20013
- return unresolved ? void 0 : joinTemplate(platform, substituted);
20014
- }
20015
- function installRootDirectories(spec, input, dependencies, platform, home) {
20016
- const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
20017
- const directories = [];
20018
- for (const template of templates) {
20019
- if (template === VERSION_MANAGER_ROOTS) {
20020
- directories.push(...versionManagerBinaryDirectories({
20021
- platform,
20022
- environment: input.environment,
20023
- home,
20024
- ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
20025
- }));
20026
- continue;
20027
- }
20028
- const directory = expandInstallRoot(template, input.environment, platform, home);
20029
- if (directory !== void 0)
20030
- directories.push(directory);
20389
+ request(method, params, options) {
20390
+ const spec = agentRequestSpecsByMethod[method];
20391
+ return this.connection.sendRequest(method, params, spec?.mapResponse, options);
20031
20392
  }
20032
- return directories;
20033
- }
20034
- function harnessCandidates(spec, input, dependencies = {}) {
20035
- const platform = input.platform ?? process.platform;
20036
- const pathFlavor = targetPath(platform);
20037
- const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
20038
- const command = configured ?? spec.command;
20039
- if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
20040
- return [{ candidate: command, source: "configured" }];
20393
+ notify(method, params) {
20394
+ return this.connection.sendNotification(method, params);
20041
20395
  }
20042
- const candidates = [];
20043
- const extensions = executableExtensions(command, platform, input.environment);
20044
- for (const directory of pathDirectories(input.environment, platform)) {
20045
- for (const extension of extensions) {
20046
- candidates.push({
20047
- candidate: pathFlavor.join(directory, command + extension),
20048
- source: "path"
20049
- });
20050
- }
20396
+ /**
20397
+ * Extension method.
20398
+ *
20399
+ * @deprecated Use {@link request}.
20400
+ */
20401
+ extMethod(method, params) {
20402
+ return this.request(method, params);
20051
20403
  }
20052
- if (configured !== void 0)
20053
- return candidates;
20054
- const home = resolveHomeDirectory(input);
20055
- for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
20056
- for (const extension of installRootExtensions(platform)) {
20057
- candidates.push({
20058
- candidate: pathFlavor.join(directory, spec.command + extension),
20059
- source: "install-root"
20060
- });
20061
- }
20404
+ /**
20405
+ * Extension notification.
20406
+ *
20407
+ * @deprecated Use {@link notify}.
20408
+ */
20409
+ extNotification(method, params) {
20410
+ return this.notify(method, params);
20062
20411
  }
20063
- return candidates;
20064
- }
20065
- function resolveHarnessExecutable(spec, input, dependencies = {}) {
20066
- const platform = input.platform ?? process.platform;
20067
- const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
20068
- const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
20069
- const context = { platform, isExecutable };
20070
- for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
20071
- const executable = runnable(candidate, context);
20072
- if (executable !== void 0 && isExecutable(executable))
20073
- return { executable, source };
20412
+ /**
20413
+ * AbortSignal that aborts when the connection closes.
20414
+ *
20415
+ * This signal can be used to:
20416
+ * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
20417
+ * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
20418
+ * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
20419
+ *
20420
+ * The connection closes when the underlying stream ends, either normally or due to an error.
20421
+ *
20422
+ * @example
20423
+ * ```typescript
20424
+ * const connection = new ClientSideConnection(client, stream);
20425
+ *
20426
+ * // Listen for closure
20427
+ * connection.signal.addEventListener('abort', () => {
20428
+ * console.log('Connection closed - performing cleanup');
20429
+ * });
20430
+ *
20431
+ * // Check status
20432
+ * if (connection.signal.aborted) {
20433
+ * console.log('Connection is already closed');
20434
+ * }
20435
+ *
20436
+ * // Pass to other APIs
20437
+ * fetch(url, { signal: connection.signal });
20438
+ * ```
20439
+ */
20440
+ get signal() {
20441
+ return this.connection.signal;
20074
20442
  }
20075
- return void 0;
20076
- }
20443
+ /**
20444
+ * Promise that resolves when the connection closes.
20445
+ *
20446
+ * The connection closes when the underlying stream ends, either normally or due to an error.
20447
+ * Once closed, the connection cannot send or receive any more messages.
20448
+ *
20449
+ * This is useful for async/await style cleanup:
20450
+ *
20451
+ * @example
20452
+ * ```typescript
20453
+ * const connection = new ClientSideConnection(client, stream);
20454
+ * await connection.closed;
20455
+ * console.log('Connection closed - performing cleanup');
20456
+ * ```
20457
+ */
20458
+ get closed() {
20459
+ return this.connection.closed;
20460
+ }
20461
+ };
20077
20462
 
20078
20463
  // dist/command.js
20464
+ import path5 from "node:path";
20079
20465
  var KimiExecutableError = class extends Error {
20080
20466
  code = "KIMI_NOT_FOUND";
20081
20467
  };
@@ -20099,7 +20485,7 @@ function resolveKimiExecutable(input = {}) {
20099
20485
  });
20100
20486
  if (!resolution)
20101
20487
  throw new KimiExecutableError("Kimi Code CLI is not installed");
20102
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path3.resolve(resolution.executable);
20488
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
20103
20489
  }
20104
20490
  function kimiInvocation(command, environment = process.env, platform = process.platform) {
20105
20491
  return commandInvocation(command, ["acp"], environment, platform);
@@ -20543,10 +20929,229 @@ var KimiAcpTransport = class {
20543
20929
  }
20544
20930
  };
20545
20931
 
20932
+ // dist/account-identity.js
20933
+ import { randomUUID } from "node:crypto";
20934
+ import { readFile as readFile2, rename, unlink, writeFile as writeFile2 } from "node:fs/promises";
20935
+ import { homedir as homedir2 } from "node:os";
20936
+ import { join as join2 } from "node:path";
20937
+ var KIMI_USAGES_ENDPOINT = "https://api.kimi.com/coding/v1/usages";
20938
+ var KIMI_OAUTH_TOKEN_ENDPOINT = "https://auth.kimi.com/api/oauth/token";
20939
+ var KIMI_CODE_CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
20940
+ var REQUEST_TIMEOUT_MS = 8e3;
20941
+ var REFRESH_SKEW_MS = 6e4;
20942
+ var credentialSchema = external_exports.object({
20943
+ access_token: external_exports.string().min(1),
20944
+ refresh_token: external_exports.string().min(1).optional(),
20945
+ expires_at: external_exports.number().optional(),
20946
+ expires_in: external_exports.number().optional(),
20947
+ scope: external_exports.string().optional(),
20948
+ token_type: external_exports.string().optional()
20949
+ });
20950
+ var refreshResponseSchema = external_exports.object({
20951
+ access_token: external_exports.string().min(1),
20952
+ refresh_token: external_exports.string().min(1).optional(),
20953
+ expires_in: external_exports.number().positive().optional(),
20954
+ scope: external_exports.string().optional(),
20955
+ token_type: external_exports.string().optional()
20956
+ });
20957
+ function kimiHome(environment) {
20958
+ return environment.KIMI_CODE_HOME ?? join2(environment.HOME ?? homedir2(), ".kimi-code");
20959
+ }
20960
+ function credentialPath(environment) {
20961
+ return join2(kimiHome(environment), "credentials", "kimi-code.json");
20962
+ }
20963
+ function oauthTokenUrl(environment) {
20964
+ const host = environment.KIMI_CODE_OAUTH_HOST ?? environment.KIMI_OAUTH_HOST;
20965
+ return host ? `${host.replace(/\/$/u, "")}/api/oauth/token` : KIMI_OAUTH_TOKEN_ENDPOINT;
20966
+ }
20967
+ function isRecord3(value) {
20968
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20969
+ }
20970
+ function quantity(value) {
20971
+ if (typeof value === "number" && Number.isFinite(value))
20972
+ return value;
20973
+ if (typeof value === "string" && value.trim()) {
20974
+ const parsed = Number(value);
20975
+ if (Number.isFinite(parsed))
20976
+ return parsed;
20977
+ }
20978
+ return void 0;
20979
+ }
20980
+ function isFiveHourWindow(window) {
20981
+ if (!isRecord3(window))
20982
+ return false;
20983
+ const duration3 = quantity(window.duration);
20984
+ const unit = String(window.timeUnit ?? "").toLowerCase();
20985
+ return duration3 === 300 && unit.includes("minute");
20986
+ }
20987
+ function usageShare(detail) {
20988
+ if (!isRecord3(detail))
20989
+ return void 0;
20990
+ const limit = quantity(detail.limit);
20991
+ const remaining = quantity(detail.remaining);
20992
+ const used = quantity(detail.used) ?? (limit !== void 0 && remaining !== void 0 ? Math.max(0, limit - remaining) : void 0);
20993
+ if (limit === void 0 || limit <= 0 || used === void 0 || used < 0)
20994
+ return void 0;
20995
+ const resetsAt = typeof detail.resetTime === "string" && detail.resetTime ? detail.resetTime : void 0;
20996
+ return { usedPercent: Math.min(100, used / limit * 100), ...resetsAt ? { resetsAt } : {} };
20997
+ }
20998
+ function membershipPlan(user) {
20999
+ if (!isRecord3(user) || !isRecord3(user.membership) || typeof user.membership.level !== "string")
21000
+ return void 0;
21001
+ return user.membership.level.replace(/^LEVEL_/u, "").trim() || void 0;
21002
+ }
21003
+ function nickname(user) {
21004
+ if (!isRecord3(user) || typeof user.nickname !== "string")
21005
+ return void 0;
21006
+ return user.nickname.trim() || void 0;
21007
+ }
21008
+ function expiresAtMs(expiresAt) {
21009
+ if (expiresAt === void 0 || !Number.isFinite(expiresAt))
21010
+ return void 0;
21011
+ return expiresAt < 1e12 ? expiresAt * 1e3 : expiresAt;
21012
+ }
21013
+ function accessTokenFresh(credentials, now) {
21014
+ const expires = expiresAtMs(credentials.expires_at);
21015
+ return expires === void 0 || expires - REFRESH_SKEW_MS > now;
21016
+ }
21017
+ function projectKimiUsages(payload) {
21018
+ if (!isRecord3(payload))
21019
+ return null;
21020
+ const weekly = usageShare(payload.usage);
21021
+ if (!weekly)
21022
+ return null;
21023
+ const productUsage = (Array.isArray(payload.limits) ? payload.limits : []).flatMap((entry) => {
21024
+ if (!isRecord3(entry))
21025
+ return [];
21026
+ const share = usageShare(entry.detail);
21027
+ if (!share || !isFiveHourWindow(entry.window))
21028
+ return [];
21029
+ return [
21030
+ {
21031
+ product: "Kimi Code · 5-hour window",
21032
+ usagePercent: share.usedPercent,
21033
+ ...share.resetsAt ? { resetsAt: share.resetsAt } : {}
21034
+ }
21035
+ ];
21036
+ });
21037
+ const credits = {
21038
+ usedPercent: weekly.usedPercent,
21039
+ periodType: "weekly",
21040
+ ...weekly.resetsAt ? { resetsAt: weekly.resetsAt } : {},
21041
+ ...productUsage.length ? { productUsage } : {}
21042
+ };
21043
+ const plan = membershipPlan(payload.user);
21044
+ const label = nickname(payload.user);
21045
+ const parsed = harnessAccountSnapshotSchema.safeParse({
21046
+ label: label || "Kimi Code",
21047
+ ...plan ? { plan } : {},
21048
+ credits
21049
+ });
21050
+ return parsed.success ? parsed.data : null;
21051
+ }
21052
+ async function readNativeCredentials(filePath, readAuthFile) {
21053
+ try {
21054
+ const raw = JSON.parse(await readAuthFile(filePath));
21055
+ if (!isRecord3(raw))
21056
+ return void 0;
21057
+ const parsed = credentialSchema.safeParse(raw);
21058
+ return parsed.success ? { raw, credentials: parsed.data } : void 0;
21059
+ } catch {
21060
+ return void 0;
21061
+ }
21062
+ }
21063
+ async function defaultWriteAuthFile(filePath, contents) {
21064
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
21065
+ try {
21066
+ await writeFile2(temporary, contents, { encoding: "utf8", mode: 384, flag: "wx" });
21067
+ await rename(temporary, filePath);
21068
+ } finally {
21069
+ await unlink(temporary).catch(() => void 0);
21070
+ }
21071
+ }
21072
+ async function refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, signal, now) {
21073
+ const refreshToken = stored.credentials.refresh_token;
21074
+ if (!refreshToken)
21075
+ return void 0;
21076
+ const response = await fetchImpl(oauthTokenUrl(environment), {
21077
+ method: "POST",
21078
+ headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
21079
+ body: new URLSearchParams({
21080
+ client_id: KIMI_CODE_CLIENT_ID,
21081
+ grant_type: "refresh_token",
21082
+ refresh_token: refreshToken
21083
+ }),
21084
+ signal
21085
+ });
21086
+ if (!response.ok)
21087
+ return void 0;
21088
+ const parsed = refreshResponseSchema.safeParse(await response.json());
21089
+ if (!parsed.success)
21090
+ return void 0;
21091
+ const expiresIn = parsed.data.expires_in ?? stored.credentials.expires_in ?? 900;
21092
+ const next = {
21093
+ ...stored.raw,
21094
+ access_token: parsed.data.access_token,
21095
+ refresh_token: parsed.data.refresh_token ?? refreshToken,
21096
+ expires_in: expiresIn,
21097
+ expires_at: now / 1e3 + expiresIn,
21098
+ ...parsed.data.scope ? { scope: parsed.data.scope } : {},
21099
+ ...parsed.data.token_type ? { token_type: parsed.data.token_type } : {}
21100
+ };
21101
+ await writeAuthFile(filePath, `${JSON.stringify(next, void 0, 2)}
21102
+ `).catch(() => void 0);
21103
+ stored.raw = next;
21104
+ stored.credentials = {
21105
+ ...stored.credentials,
21106
+ access_token: parsed.data.access_token,
21107
+ refresh_token: parsed.data.refresh_token ?? refreshToken,
21108
+ expires_in: expiresIn,
21109
+ expires_at: now / 1e3 + expiresIn
21110
+ };
21111
+ return parsed.data.access_token;
21112
+ }
21113
+ async function fetchKimiAccount(input = {}) {
21114
+ try {
21115
+ const environment = input.environment ?? process.env;
21116
+ const fromEnv = environment.KIMI_CODE_API_KEY?.trim() || environment.KIMI_API_KEY?.trim();
21117
+ const readAuthFile = input.readAuthFile ?? ((filePath2) => readFile2(filePath2, "utf8"));
21118
+ const writeAuthFile = input.writeAuthFile ?? defaultWriteAuthFile;
21119
+ const fetchImpl = input.fetch ?? fetch;
21120
+ const requestSignal = () => input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
21121
+ const now = input.now ?? Date.now();
21122
+ const filePath = credentialPath(environment);
21123
+ const stored = fromEnv ? void 0 : await readNativeCredentials(filePath, readAuthFile);
21124
+ let token = fromEnv ?? stored?.credentials.access_token;
21125
+ if (!token)
21126
+ return null;
21127
+ if (stored && !accessTokenFresh(stored.credentials, now)) {
21128
+ token = await refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, requestSignal(), now) ?? token;
21129
+ }
21130
+ const requestUsages = (accessToken) => fetchImpl(KIMI_USAGES_ENDPOINT, {
21131
+ method: "GET",
21132
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
21133
+ signal: requestSignal()
21134
+ });
21135
+ let response = await requestUsages(token);
21136
+ if (response.status === 401 && stored?.credentials.refresh_token) {
21137
+ const refreshed = await refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, requestSignal(), now);
21138
+ if (!refreshed)
21139
+ return null;
21140
+ token = refreshed;
21141
+ response = await requestUsages(token);
21142
+ }
21143
+ if (!response.ok)
21144
+ return null;
21145
+ return projectKimiUsages(await response.json());
21146
+ } catch {
21147
+ return null;
21148
+ }
21149
+ }
21150
+
20546
21151
  // dist/history.js
20547
- import { readFile } from "node:fs/promises";
21152
+ import { readFile as readFile3 } from "node:fs/promises";
20548
21153
  import os2 from "node:os";
20549
- import path4 from "node:path";
21154
+ import path6 from "node:path";
20550
21155
 
20551
21156
  // ../../../node_modules/diff/libesm/diff/base.js
20552
21157
  var Diff = class {
@@ -20648,16 +21253,16 @@ var Diff = class {
20648
21253
  }
20649
21254
  }
20650
21255
  }
20651
- addToPath(path7, added, removed, oldPosInc, options) {
20652
- const last = path7.lastComponent;
21256
+ addToPath(path9, added, removed, oldPosInc, options) {
21257
+ const last = path9.lastComponent;
20653
21258
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20654
21259
  return {
20655
- oldPos: path7.oldPos + oldPosInc,
21260
+ oldPos: path9.oldPos + oldPosInc,
20656
21261
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20657
21262
  };
20658
21263
  } else {
20659
21264
  return {
20660
- oldPos: path7.oldPos + oldPosInc,
21265
+ oldPos: path9.oldPos + oldPosInc,
20661
21266
  lastComponent: { count: 1, added, removed, previousComponent: last }
20662
21267
  };
20663
21268
  }
@@ -21789,9 +22394,9 @@ function readKimiThinkingOptions(configOptions) {
21789
22394
  }
21790
22395
 
21791
22396
  // dist/projection.js
21792
- import { randomUUID } from "node:crypto";
22397
+ import { randomUUID as randomUUID2 } from "node:crypto";
21793
22398
  function projectKimiApprovalRequest(turnId, request) {
21794
- const interactionId = hostInteractionIdSchema.parse(randomUUID());
22399
+ const interactionId = hostInteractionIdSchema.parse(randomUUID2());
21795
22400
  const optionIdByActionId = /* @__PURE__ */ new Map();
21796
22401
  const actions = [];
21797
22402
  const description = readAcpToolContentText(request.toolCall.content);
@@ -21835,7 +22440,7 @@ function projectKimiApprovalRequest(turnId, request) {
21835
22440
  return { interaction, optionIdByActionId };
21836
22441
  }
21837
22442
  function projectKimiElicitationRequest(turnId, request) {
21838
- const interactionId = hostInteractionIdSchema.parse(randomUUID());
22443
+ const interactionId = hostInteractionIdSchema.parse(randomUUID2());
21839
22444
  const questions = [];
21840
22445
  const schemaProperties = {};
21841
22446
  const req = request;
@@ -21905,18 +22510,18 @@ function formatElicitationResponse(response, schemaProperties) {
21905
22510
  }
21906
22511
  return { action: "accept", content };
21907
22512
  }
21908
- function isRecord3(value) {
22513
+ function isRecord4(value) {
21909
22514
  return typeof value === "object" && value !== null && !Array.isArray(value);
21910
22515
  }
21911
22516
  function canonicalizeKimiToolName(name, kind, rawInput) {
21912
22517
  const trimmed = name?.trim();
21913
22518
  const lower = trimmed?.toLowerCase() ?? "";
21914
22519
  if (lower.startsWith("write") || lower.startsWith("writ")) {
21915
- const isEdit = isRecord3(rawInput) && ("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
22520
+ const isEdit = isRecord4(rawInput) && ("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
21916
22521
  return isEdit ? "Edit" : "Write";
21917
22522
  }
21918
22523
  if (kind === "edit" || lower.startsWith("edit")) {
21919
- const isWrite = isRecord3(rawInput) && ("content" in rawInput || "text" in rawInput) && !("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
22524
+ const isWrite = isRecord4(rawInput) && ("content" in rawInput || "text" in rawInput) && !("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
21920
22525
  return isWrite ? "Write" : "Edit";
21921
22526
  }
21922
22527
  if (kind === "execute" || lower.startsWith("bash") || lower.startsWith("shell") || lower.startsWith("run")) {
@@ -22125,14 +22730,14 @@ function createKimiNativeCheckpointRef(sessionId, turnId) {
22125
22730
  });
22126
22731
  }
22127
22732
  function getKimiCodeHome(homeDirectory, environment = process.env) {
22128
- return environment.KIMI_CODE_HOME || (homeDirectory ? path4.join(homeDirectory, ".kimi-code") : path4.join(os2.homedir(), ".kimi-code"));
22733
+ return environment.KIMI_CODE_HOME || (homeDirectory ? path6.join(homeDirectory, ".kimi-code") : path6.join(os2.homedir(), ".kimi-code"));
22129
22734
  }
22130
22735
  async function locateKimiSession(sessionId, options = {}) {
22131
- const kimiHome = options.kimiCodeHome || getKimiCodeHome(options.homeDirectory);
22132
- const indexFile = path4.join(kimiHome, "session_index.jsonl");
22736
+ const kimiHome2 = options.kimiCodeHome || getKimiCodeHome(options.homeDirectory);
22737
+ const indexFile = path6.join(kimiHome2, "session_index.jsonl");
22133
22738
  let content;
22134
22739
  try {
22135
- content = await readFile(indexFile, "utf8");
22740
+ content = await readFile3(indexFile, "utf8");
22136
22741
  } catch {
22137
22742
  return null;
22138
22743
  }
@@ -22153,15 +22758,15 @@ async function locateKimiSession(sessionId, options = {}) {
22153
22758
  if (!targetEntry || targetEntry.deleted || !targetEntry.sessionDir) {
22154
22759
  return null;
22155
22760
  }
22156
- const sessionDir = path4.resolve(targetEntry.sessionDir);
22157
- const normalizedKimiHome = path4.resolve(kimiHome);
22158
- const relativeToHome = path4.relative(normalizedKimiHome, sessionDir);
22159
- if (relativeToHome.startsWith("..") || path4.isAbsolute(relativeToHome)) {
22761
+ const sessionDir = path6.resolve(targetEntry.sessionDir);
22762
+ const normalizedKimiHome = path6.resolve(kimiHome2);
22763
+ const relativeToHome = path6.relative(normalizedKimiHome, sessionDir);
22764
+ if (relativeToHome.startsWith("..") || path6.isAbsolute(relativeToHome)) {
22160
22765
  throw new Error(`Session directory ${sessionDir} is outside KIMI_CODE_HOME`);
22161
22766
  }
22162
22767
  let state;
22163
22768
  try {
22164
- const stateContent = await readFile(path4.join(sessionDir, "state.json"), "utf8");
22769
+ const stateContent = await readFile3(path6.join(sessionDir, "state.json"), "utf8");
22165
22770
  state = JSON.parse(stateContent);
22166
22771
  } catch {
22167
22772
  return null;
@@ -22169,7 +22774,7 @@ async function locateKimiSession(sessionId, options = {}) {
22169
22774
  if (state.id !== sessionId) {
22170
22775
  throw new Error(`State JSON session ID mismatch: expected ${sessionId}, found ${state.id}`);
22171
22776
  }
22172
- const mainHomeDir = state.agents?.main?.homedir ? path4.resolve(state.agents.main.homedir) : path4.join(sessionDir, "agents", "main");
22777
+ const mainHomeDir = state.agents?.main?.homedir ? path6.resolve(state.agents.main.homedir) : path6.join(sessionDir, "agents", "main");
22173
22778
  return { sessionDir, mainHomeDir, state };
22174
22779
  }
22175
22780
  async function parseKimiWireLog(wireContent, sessionId, mainHomeDir) {
@@ -22462,14 +23067,14 @@ async function parseKimiWireLog(wireContent, sessionId, mainHomeDir) {
22462
23067
  let newContent = "";
22463
23068
  if (tracked?.key) {
22464
23069
  try {
22465
- oldContent = await readFile(path4.join(mainHomeDir, tracked.key), "utf8");
23070
+ oldContent = await readFile3(path6.join(mainHomeDir, tracked.key), "utf8");
22466
23071
  } catch {
22467
23072
  oldContent = "";
22468
23073
  }
22469
23074
  }
22470
23075
  if (checkpoint?.key) {
22471
23076
  try {
22472
- newContent = await readFile(path4.join(mainHomeDir, checkpoint.key), "utf8");
23077
+ newContent = await readFile3(path6.join(mainHomeDir, checkpoint.key), "utf8");
22473
23078
  } catch {
22474
23079
  newContent = "";
22475
23080
  }
@@ -22542,10 +23147,10 @@ async function readKimiSessionSnapshot(sessionId, options = {}) {
22542
23147
  if (!located) {
22543
23148
  throw new Error(`Kimi native session not found: ${sessionId}`);
22544
23149
  }
22545
- const wirePath = path4.join(located.mainHomeDir, "wire.jsonl");
23150
+ const wirePath = path6.join(located.mainHomeDir, "wire.jsonl");
22546
23151
  let wireContent = "";
22547
23152
  try {
22548
- wireContent = await readFile(wirePath, "utf8");
23153
+ wireContent = await readFile3(wirePath, "utf8");
22549
23154
  } catch (error51) {
22550
23155
  throw new Error(`Failed to read Kimi native history ${wirePath}: ${error51 instanceof Error ? error51.message : String(error51)}`, { cause: error51 });
22551
23156
  }
@@ -22602,9 +23207,9 @@ async function readKimiSessionUsage(sessionId, options = {}) {
22602
23207
  const located = await locateKimiSession(sessionId, options);
22603
23208
  if (!located)
22604
23209
  return null;
22605
- const wirePath = path4.join(located.mainHomeDir, "wire.jsonl");
23210
+ const wirePath = path6.join(located.mainHomeDir, "wire.jsonl");
22606
23211
  try {
22607
- const wireContent = await readFile(wirePath, "utf8");
23212
+ const wireContent = await readFile3(wirePath, "utf8");
22608
23213
  return extractKimiUsageFromWireLog(wireContent, options.contextWindowTokens);
22609
23214
  } catch {
22610
23215
  return null;
@@ -22615,15 +23220,15 @@ async function readKimiSessionUsage(sessionId, options = {}) {
22615
23220
  import { setTimeout as delay } from "node:timers/promises";
22616
23221
 
22617
23222
  // dist/command-history.js
22618
- import { appendFile, readFile as readFile2, writeFile } from "node:fs/promises";
22619
- import path5 from "node:path";
23223
+ import { appendFile, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
23224
+ import path7 from "node:path";
22620
23225
  async function readKimiCommandHistory(sessionId, options) {
22621
23226
  const located = await locateKimiSession(sessionId, options);
22622
23227
  if (!located)
22623
23228
  return [];
22624
23229
  let content;
22625
23230
  try {
22626
- content = await readFile2(path5.join(located.sessionDir, "codexhost-commands.jsonl"), "utf8");
23231
+ content = await readFile4(path7.join(located.sessionDir, "codexhost-commands.jsonl"), "utf8");
22627
23232
  } catch (error51) {
22628
23233
  if (error51.code === "ENOENT")
22629
23234
  return [];
@@ -22653,7 +23258,7 @@ async function appendKimiCommandHistory(turn, options) {
22653
23258
  const located = await locateKimiSession(turn.nativeTurnRef.nativeSessionId, options);
22654
23259
  if (!located)
22655
23260
  throw new Error("Cannot persist Kimi command: native session is missing");
22656
- await appendFile(path5.join(located.sessionDir, "codexhost-commands.jsonl"), `${JSON.stringify(turn)}
23261
+ await appendFile(path7.join(located.sessionDir, "codexhost-commands.jsonl"), `${JSON.stringify(turn)}
22657
23262
  `, "utf8");
22658
23263
  }
22659
23264
  async function copyKimiCommandHistory(turns, sessionId, options) {
@@ -22667,7 +23272,7 @@ async function copyKimiCommandHistory(turns, sessionId, options) {
22667
23272
  nativeTurnRef: { ...turn.nativeTurnRef, nativeSessionId: sessionId },
22668
23273
  ...turn.checkpoint ? { checkpoint: { ...turn.checkpoint, nativeSessionId: sessionId } } : {}
22669
23274
  }));
22670
- await writeFile(path5.join(located.sessionDir, "codexhost-commands.jsonl"), copied.map((turn) => `${JSON.stringify(turn)}
23275
+ await writeFile3(path7.join(located.sessionDir, "codexhost-commands.jsonl"), copied.map((turn) => `${JSON.stringify(turn)}
22671
23276
  `).join(""), "utf8");
22672
23277
  }
22673
23278
 
@@ -23852,6 +24457,11 @@ var KimiAdapter = class {
23852
24457
  this.#options = options;
23853
24458
  this.#deps = dependencies;
23854
24459
  }
24460
+ async inspectAccount() {
24461
+ if (this.#closed)
24462
+ return null;
24463
+ return fetchKimiAccount({ environment: { ...process.env, ...this.#options.environment } });
24464
+ }
23855
24465
  #createTransport(options) {
23856
24466
  return this.#deps.createTransport ? this.#deps.createTransport(options) : new KimiAcpTransport(options);
23857
24467
  }
@@ -23883,11 +24493,11 @@ var KimiAdapter = class {
23883
24493
  this.#inspectionCache = result;
23884
24494
  return result;
23885
24495
  }
23886
- const kimiHome = getKimiCodeHome(this.#options.homeDirectory, environment);
23887
- const configPath = path6.join(kimiHome, "config.toml");
24496
+ const kimiHome2 = getKimiCodeHome(this.#options.homeDirectory, environment);
24497
+ const configPath = path8.join(kimiHome2, "config.toml");
23888
24498
  let nativeConfig = null;
23889
24499
  try {
23890
- const configContent = await readFile3(configPath, "utf8");
24500
+ const configContent = await readFile5(configPath, "utf8");
23891
24501
  nativeConfig = parseKimiConfigToml(configContent);
23892
24502
  } catch {
23893
24503
  nativeConfig = null;
@@ -23997,11 +24607,11 @@ var KimiAdapter = class {
23997
24607
  ...this.#options.closeTimeoutMs ? { closeTimeoutMs: this.#options.closeTimeoutMs } : {},
23998
24608
  onFault: (error51) => session?.handleTransportFault(error51)
23999
24609
  });
24000
- const kimiHome = getKimiCodeHome(this.#options.homeDirectory, environment);
24001
- const configPath = path6.join(kimiHome, "config.toml");
24610
+ const kimiHome2 = getKimiCodeHome(this.#options.homeDirectory, environment);
24611
+ const configPath = path8.join(kimiHome2, "config.toml");
24002
24612
  let nativeConfig = null;
24003
24613
  try {
24004
- const configContent = await readFile3(configPath, "utf8");
24614
+ const configContent = await readFile5(configPath, "utf8");
24005
24615
  nativeConfig = parseKimiConfigToml(configContent);
24006
24616
  } catch {
24007
24617
  nativeConfig = null;
@@ -24058,7 +24668,7 @@ var KimiAdapter = class {
24058
24668
  await transport.close().catch(() => void 0);
24059
24669
  return err2("checkpointNotFound", "Kimi Checkpoint does not belong to the source Native Session");
24060
24670
  }
24061
- if (path6.resolve(cwd) !== path6.resolve(located.state.cwd)) {
24671
+ if (path8.resolve(cwd) !== path8.resolve(located.state.cwd)) {
24062
24672
  await transport.close().catch(() => void 0);
24063
24673
  return err2("unsupported", "Kimi Code cannot fork across different working directories");
24064
24674
  }
@@ -24181,7 +24791,7 @@ var KimiAdapter = class {
24181
24791
  const located = await locateKimiSession(sourceId, historyOptions);
24182
24792
  if (!located)
24183
24793
  return err2("sessionNotFound", "Kimi source session was not found");
24184
- if (path6.resolve(input.cwd) !== path6.resolve(located.state.cwd))
24794
+ if (path8.resolve(input.cwd) !== path8.resolve(located.state.cwd))
24185
24795
  return err2("unsupported", "Kimi cannot roll back into another working directory");
24186
24796
  const source = [...this.#sessions].find((candidate) => candidate.initialState.nativeRef?.nativeSessionId === sourceId);
24187
24797
  if (source) {
@@ -24246,12 +24856,69 @@ var KimiAdapter = class {
24246
24856
  }
24247
24857
  };
24248
24858
 
24859
+ // dist/installation.js
24860
+ import { open, readFile as readFile6 } from "node:fs/promises";
24861
+ import { homedir as homedir3 } from "node:os";
24862
+ import { join as join3 } from "node:path";
24863
+ function createKimiInstallation(environment) {
24864
+ const executable = () => resolveKimiExecutable({ environment });
24865
+ const run = (args, timeout) => runInstallationCommand(executable(), args, { ...environment, KIMI_CODE_NO_AUTO_UPDATE: "1" }, timeout);
24866
+ const nativeUpdaterAvailable = async () => {
24867
+ const file2 = await open(executable(), "r");
24868
+ try {
24869
+ const header = Buffer.alloc(4);
24870
+ await file2.read(header, 0, 4, 0);
24871
+ const magic = header.toString("hex");
24872
+ if (!["cffaedfe", "cefaedfe", "cafebabe", "7f454c46"].includes(magic) && !magic.startsWith("4d5a"))
24873
+ return false;
24874
+ } finally {
24875
+ await file2.close();
24876
+ }
24877
+ return /--manual/.test(await run(["__update_download", "--help"]));
24878
+ };
24879
+ return createInstallationManager({
24880
+ async check() {
24881
+ const currentVersion = versionFromOutput(await run(["--version"]));
24882
+ const home = environment.KIMI_CODE_HOME ?? join3(environment.HOME ?? homedir3(), ".kimi-code");
24883
+ const region = await readFile6(join3(home, "region"), "utf8").catch(() => "");
24884
+ const base = region.trim() === "global" ? "https://code.kimi.ai/kimi-code" : "https://code.kimi.com/kimi-code";
24885
+ const latestVersion = installationVersion(await fetchInstallationText(`${base}/latest`));
24886
+ const npm = await npmInstallation(executable(), ["@moonshot-ai/kimi-code"], environment);
24887
+ const canUpdate = npm ? npm.canUpdate : await nativeUpdaterAvailable();
24888
+ return {
24889
+ currentVersion,
24890
+ latestVersion,
24891
+ updateAvailable: newerInstallationVersion(currentVersion, latestVersion),
24892
+ canUpdate,
24893
+ ...!canUpdate ? { message: "Use the original installer to update this Kimi installation" } : {}
24894
+ };
24895
+ },
24896
+ async update(state) {
24897
+ const npm = await npmInstallation(executable(), ["@moonshot-ai/kimi-code"], environment);
24898
+ if (npm)
24899
+ await npm.update(state.latestVersion);
24900
+ else {
24901
+ if (!await nativeUpdaterAvailable())
24902
+ throw new Error("Kimi native updater is unavailable");
24903
+ await run(["__update_download", state.latestVersion, "--manual"], 3e5);
24904
+ await run(["--version"]);
24905
+ }
24906
+ }
24907
+ });
24908
+ }
24909
+
24249
24910
  // dist/plugin.js
24250
24911
  function createHarnessAdapter(context) {
24251
24912
  const environment = { ...context.environment };
24252
- return new KimiAdapter({
24913
+ return Object.assign(new KimiAdapter({
24253
24914
  ...environment[KIMI_COMMAND_ENV] ? { command: environment[KIMI_COMMAND_ENV] } : {},
24254
24915
  environment
24916
+ }), {
24917
+ installation: createKimiInstallation(environment),
24918
+ install: createHarnessInstaller(environment, {
24919
+ posix: "https://code.kimi.com/kimi-code/install.sh",
24920
+ windows: "https://code.kimi.com/kimi-code/install.ps1"
24921
+ })
24255
24922
  });
24256
24923
  }
24257
24924
  export {