@liberseek/boft-cli-win32-arm64 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,15 +5,413 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
- // dist/pi-credential-imports.js
9
- import { randomUUID } from "node:crypto";
10
- import { execFile } from "node:child_process";
11
- import { promisify } from "node:util";
12
- import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
13
- import { realpath } from "node:fs/promises";
14
- import os2 from "node:os";
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
15
71
  import path3 from "node:path";
16
- import { pathToFileURL } from "node:url";
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/installer.js
358
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
359
+ import { tmpdir } from "node:os";
360
+ import { join } from "node:path";
361
+ function createHarnessInstaller(environment, source) {
362
+ return async () => {
363
+ if (!["darwin", "linux", "win32"].includes(process.platform))
364
+ throw new Error("Unsupported installation platform");
365
+ const env = withNodeRuntimeOnPath(environment);
366
+ if ("npm" in source) {
367
+ const npm = resolveHarnessExecutable({
368
+ id: "npm",
369
+ command: "npm",
370
+ installRoots: {
371
+ posix: [
372
+ "~/.npm-global/bin",
373
+ "~/.local/bin",
374
+ VERSION_MANAGER_ROOTS,
375
+ "/opt/homebrew/bin",
376
+ "/usr/local/bin",
377
+ "/usr/bin"
378
+ ],
379
+ windows: [
380
+ "${APPDATA}/npm",
381
+ VERSION_MANAGER_ROOTS,
382
+ "${ProgramFiles}/nodejs",
383
+ "${LOCALAPPDATA}/Programs/nodejs"
384
+ ]
385
+ }
386
+ }, { environment: env });
387
+ if (!npm)
388
+ throw new Error("Install Node.js and npm first");
389
+ await runInstallationCommand(npm.executable, ["install", "--global", source.npm], {
390
+ ...env,
391
+ ...source.allowScripts ? { npm_config_allow_scripts: source.allowScripts } : {}
392
+ }, 6e5);
393
+ return;
394
+ }
395
+ const windows = process.platform === "win32";
396
+ const url2 = windows ? source.windows : source.posix;
397
+ if (new URL(url2).protocol !== "https:")
398
+ throw new Error("Installer requires HTTPS");
399
+ const script = await fetchInstallationText(url2);
400
+ const directory = await mkdtemp(join(tmpdir(), "codexhost-installer-"));
401
+ try {
402
+ const file2 = join(directory, windows ? "install.ps1" : "install.sh");
403
+ await writeFile(file2, script, { mode: 384 });
404
+ await runInstallationCommand(windows ? "powershell.exe" : source.shell ?? "bash", windows ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file2] : [file2], env, 6e5);
405
+ } finally {
406
+ await rm(directory, { recursive: true, force: true });
407
+ }
408
+ };
409
+ }
410
+
411
+ // dist/account-balance.js
412
+ import { readFile } from "node:fs/promises";
413
+ import { homedir as homedir2 } from "node:os";
414
+ import path4 from "node:path";
17
415
 
18
416
  // ../../../node_modules/zod/v4/classic/external.js
19
417
  var external_exports = {};
@@ -781,10 +1179,10 @@ function mergeDefs(...defs) {
781
1179
  function cloneDef(schema) {
782
1180
  return mergeDefs(schema._zod.def);
783
1181
  }
784
- function getElementAtPath(obj, path10) {
785
- if (!path10)
1182
+ function getElementAtPath(obj, path14) {
1183
+ if (!path14)
786
1184
  return obj;
787
- return path10.reduce((acc, key) => acc?.[key], obj);
1185
+ return path14.reduce((acc, key) => acc?.[key], obj);
788
1186
  }
789
1187
  function promiseAllObject(promisesObj) {
790
1188
  const keys = Object.keys(promisesObj);
@@ -1193,11 +1591,11 @@ function explicitlyAborted(x, startIndex = 0) {
1193
1591
  }
1194
1592
  return false;
1195
1593
  }
1196
- function prefixIssues(path10, issues) {
1594
+ function prefixIssues(path14, issues) {
1197
1595
  return issues.map((iss) => {
1198
1596
  var _a3;
1199
1597
  (_a3 = iss).path ?? (_a3.path = []);
1200
- iss.path.unshift(path10);
1598
+ iss.path.unshift(path14);
1201
1599
  return iss;
1202
1600
  });
1203
1601
  }
@@ -1344,16 +1742,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1344
1742
  }
1345
1743
  function formatError(error51, mapper = (issue2) => issue2.message) {
1346
1744
  const fieldErrors = { _errors: [] };
1347
- const processError = (error52, path10 = []) => {
1745
+ const processError = (error52, path14 = []) => {
1348
1746
  for (const issue2 of error52.issues) {
1349
1747
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1350
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1748
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1351
1749
  } else if (issue2.code === "invalid_key") {
1352
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1750
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1353
1751
  } else if (issue2.code === "invalid_element") {
1354
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1752
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1355
1753
  } else {
1356
- const fullpath = [...path10, ...issue2.path];
1754
+ const fullpath = [...path14, ...issue2.path];
1357
1755
  if (fullpath.length === 0) {
1358
1756
  fieldErrors._errors.push(mapper(issue2));
1359
1757
  } else {
@@ -1380,17 +1778,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1380
1778
  }
1381
1779
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1382
1780
  const result = { errors: [] };
1383
- const processError = (error52, path10 = []) => {
1781
+ const processError = (error52, path14 = []) => {
1384
1782
  var _a3, _b;
1385
1783
  for (const issue2 of error52.issues) {
1386
1784
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1387
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1785
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1388
1786
  } else if (issue2.code === "invalid_key") {
1389
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1787
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1390
1788
  } else if (issue2.code === "invalid_element") {
1391
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1789
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1392
1790
  } else {
1393
- const fullpath = [...path10, ...issue2.path];
1791
+ const fullpath = [...path14, ...issue2.path];
1394
1792
  if (fullpath.length === 0) {
1395
1793
  result.errors.push(mapper(issue2));
1396
1794
  continue;
@@ -1422,8 +1820,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1422
1820
  }
1423
1821
  function toDotPath(_path) {
1424
1822
  const segs = [];
1425
- const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1426
- for (const seg of path10) {
1823
+ const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1824
+ for (const seg of path14) {
1427
1825
  if (typeof seg === "number")
1428
1826
  segs.push(`[${seg}]`);
1429
1827
  else if (typeof seg === "symbol")
@@ -14115,13 +14513,13 @@ function resolveRef(ref, ctx) {
14115
14513
  if (!ref.startsWith("#")) {
14116
14514
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14117
14515
  }
14118
- const path10 = ref.slice(1).split("/").filter(Boolean);
14119
- if (path10.length === 0) {
14516
+ const path14 = ref.slice(1).split("/").filter(Boolean);
14517
+ if (path14.length === 0) {
14120
14518
  return ctx.rootSchema;
14121
14519
  }
14122
14520
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14123
- if (path10[0] === defsKey) {
14124
- const key = path10[1];
14521
+ if (path14[0] === defsKey) {
14522
+ const key = path14[1];
14125
14523
  if (!key || !ctx.defs[key]) {
14126
14524
  throw new Error(`Reference not found: ${ref}`);
14127
14525
  }
@@ -14570,20 +14968,137 @@ var credentialOtherLoginSchema = external_exports.object({
14570
14968
  /** Recognized credential vendor, derived from the OAuth token issuer. Absent when unknown. */
14571
14969
  vendor: external_exports.enum(["openai-codex", "xai"]).optional()
14572
14970
  }).strict();
14573
- var credentialImportsResultSchema = external_exports.object({
14574
- sources: external_exports.array(credentialSourceSchema),
14575
- targets: external_exports.array(external_exports.object({
14576
- harnessId: external_exports.string(),
14577
- providers: external_exports.array(external_exports.enum(["openai-codex", "xai"])),
14578
- imports: external_exports.array(credentialImportRecordSchema),
14579
- others: external_exports.array(credentialOtherLoginSchema).default([])
14580
- }).strict())
14971
+ var credentialImportsResultSchema = external_exports.object({
14972
+ sources: external_exports.array(credentialSourceSchema),
14973
+ targets: external_exports.array(external_exports.object({
14974
+ harnessId: external_exports.string(),
14975
+ providers: external_exports.array(external_exports.enum(["openai-codex", "xai"])),
14976
+ imports: external_exports.array(credentialImportRecordSchema),
14977
+ others: external_exports.array(credentialOtherLoginSchema).default([])
14978
+ }).strict())
14979
+ }).strict();
14980
+ var credentialImportsParamsSchema = external_exports.object({
14981
+ targetHarnessId: external_exports.string().min(1).max(128).optional(),
14982
+ request: credentialImportsRequestSchema
14983
+ }).strict();
14984
+
14985
+ // ../../shared-contracts/dist/harness-display-settings.js
14986
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
14987
+ agent: external_exports.string().min(1).max(128),
14988
+ section: external_exports.enum(["main", "more", "auto"])
14989
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
14990
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
14991
+ entries: harnessDisplayEntriesSchema.nullable()
14992
+ });
14993
+ var harnessDisplayGetSchema = external_exports.strictObject({});
14994
+ var harnessDisplaySetSchema = external_exports.strictObject({
14995
+ entries: harnessDisplayEntriesSchema,
14996
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
14997
+ initializeOnly: external_exports.boolean().optional()
14998
+ });
14999
+
15000
+ // ../../shared-contracts/dist/ids.js
15001
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15002
+ message: "Identifier must not be empty or whitespace"
15003
+ });
15004
+ var harnessIdSchema = opaqueIdSchema.brand();
15005
+ var hostThreadIdSchema = opaqueIdSchema.brand();
15006
+ var hostTurnIdSchema = opaqueIdSchema.brand();
15007
+ var hostItemIdSchema = opaqueIdSchema.brand();
15008
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
15009
+
15010
+ // ../../shared-contracts/dist/harness-plugins.js
15011
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15012
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15013
+ var HARNESS_PLUGIN_LIMIT = 128;
15014
+ 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);
15015
+ 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");
15016
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15017
+ var pluginPresentationShape = {
15018
+ id: harnessPluginIdSchema,
15019
+ name: external_exports.string().trim().min(1).max(128),
15020
+ version: external_exports.string().min(1).max(128),
15021
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15022
+ launchCommand: external_exports.literal(true).optional(),
15023
+ links: external_exports.object({
15024
+ documentation: documentationUrlSchema.optional(),
15025
+ installation: documentationUrlSchema.optional()
15026
+ }).strict().optional()
15027
+ };
15028
+ var harnessPluginManifestSchema = external_exports.object({
15029
+ manifestVersion: external_exports.literal(1),
15030
+ ...pluginPresentationShape,
15031
+ adapterApiVersion: external_exports.number().int().positive(),
15032
+ entry: relativeResourceSchema,
15033
+ icon: relativeResourceSchema.optional()
15034
+ }).strict();
15035
+ 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);
15036
+ var harnessPluginDescriptorSchema = external_exports.object({
15037
+ ...pluginPresentationShape,
15038
+ icon: harnessPluginIconSchema.optional()
15039
+ }).strict();
15040
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15041
+ var harnessPluginListResultSchema = external_exports.object({
15042
+ plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15043
+ }).strict();
15044
+ var harnessPluginConfigurationSchema = external_exports.object({
15045
+ version: external_exports.literal(1),
15046
+ enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15047
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15048
+ message: "Enabled plugin IDs must be unique",
15049
+ path: ["enabled"]
15050
+ });
15051
+
15052
+ // ../../shared-contracts/dist/harness-long-context.js
15053
+ var HARNESS_LONG_CONTEXT_GET_METHOD = "codexhost/harness/long-context/get";
15054
+ var HARNESS_LONG_CONTEXT_SET_METHOD = "codexhost/harness/long-context/set";
15055
+ var harnessLongContextGetSchema = external_exports.object({
15056
+ harnessId: harnessPluginIdSchema
14581
15057
  }).strict();
14582
- var credentialImportsParamsSchema = external_exports.object({
14583
- targetHarnessId: external_exports.string().min(1).max(128).optional(),
14584
- request: credentialImportsRequestSchema
15058
+ var harnessLongContextSetSchema = harnessLongContextGetSchema.extend({
15059
+ enabled: external_exports.boolean()
15060
+ });
15061
+ var harnessLongContextSchema = external_exports.object({
15062
+ enabled: external_exports.boolean()
14585
15063
  }).strict();
14586
15064
 
15065
+ // ../../shared-contracts/dist/console.js
15066
+ var consoleAnnouncementSchema = external_exports.strictObject({
15067
+ title: external_exports.string().trim().min(1).max(200),
15068
+ type: external_exports.enum(["info", "warning", "danger"]),
15069
+ body: external_exports.string().trim().min(1).max(16 * 1024)
15070
+ });
15071
+ var consoleOpenParamsSchema = external_exports.strictObject({});
15072
+ var consoleOpenResultSchema = external_exports.strictObject({
15073
+ /** The console address. */
15074
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
15075
+ });
15076
+ var CONSOLE_HOST_METHODS = Object.freeze([
15077
+ "codexhost/harness/plugins/list",
15078
+ "codexhost/harness/display-settings/get",
15079
+ "codexhost/harness/display-settings/set",
15080
+ "codexhost/harness/inspect",
15081
+ "codexhost/harness/installation",
15082
+ "codexhost/harness/launch-settings/get",
15083
+ "codexhost/harness/launch-settings/set",
15084
+ HARNESS_LONG_CONTEXT_GET_METHOD,
15085
+ HARNESS_LONG_CONTEXT_SET_METHOD,
15086
+ "codexhost/harness/web-ui/open",
15087
+ "codexhost/harness/accounts/sources",
15088
+ "codexhost/harness/accounts/list",
15089
+ "codexhost/harness/accounts/inspect",
15090
+ "codexhost/harness/credential-imports",
15091
+ "codexhost/harness/session-import/sources",
15092
+ "codexhost/harness/session-import/list",
15093
+ "codexhost/harness/session-import/import",
15094
+ "codexhost/account/list",
15095
+ "codexhost/account/refresh",
15096
+ "codexhost/account/usage/inspect",
15097
+ "codexhost/update/check",
15098
+ "codexhost/update/start",
15099
+ "codexhost/update/status"
15100
+ ]);
15101
+
14587
15102
  // ../../shared-contracts/dist/version.js
14588
15103
  var WORKSPACE_CONTRACT_VERSION = 1;
14589
15104
 
@@ -14627,15 +15142,11 @@ var loadedSessionsSchema = external_exports.array(external_exports.strictObject(
14627
15142
  inactiveMs: external_exports.number().nonnegative()
14628
15143
  }));
14629
15144
 
14630
- // ../../shared-contracts/dist/ids.js
14631
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14632
- message: "Identifier must not be empty or whitespace"
15145
+ // ../../shared-contracts/dist/manual-compaction.js
15146
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
15147
+ threadId: hostThreadIdSchema,
15148
+ turnId: hostTurnIdSchema
14633
15149
  });
14634
- var harnessIdSchema = opaqueIdSchema.brand();
14635
- var hostThreadIdSchema = opaqueIdSchema.brand();
14636
- var hostTurnIdSchema = opaqueIdSchema.brand();
14637
- var hostItemIdSchema = opaqueIdSchema.brand();
14638
- var hostInteractionIdSchema = opaqueIdSchema.brand();
14639
15150
 
14640
15151
  // ../../shared-contracts/dist/thread-usage.js
14641
15152
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
@@ -14697,6 +15208,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14697
15208
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14698
15209
  var accountCreditsProductUsageSchema = external_exports.object({
14699
15210
  product: external_exports.string().min(1),
15211
+ used: external_exports.number().finite().nonnegative().optional(),
15212
+ // Zero is a real empty cap, not an absent field.
15213
+ limit: external_exports.number().finite().nonnegative().optional(),
15214
+ unit: external_exports.string().min(1).max(32).optional(),
14700
15215
  usagePercent: usagePercentSchema,
14701
15216
  resetsAt: external_exports.string().min(1).optional()
14702
15217
  }).strict();
@@ -14706,11 +15221,14 @@ var accountResetCreditsSchema = external_exports.object({
14706
15221
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14707
15222
  }).strict();
14708
15223
  var accountCreditsSnapshotSchema = external_exports.object({
15224
+ used: external_exports.number().finite().nonnegative().optional(),
15225
+ // Zero is a real empty cap, not an absent field.
15226
+ limit: external_exports.number().finite().nonnegative().optional(),
15227
+ unit: external_exports.string().trim().min(1).max(32).optional(),
14709
15228
  /** Native label when the primary limit is scoped to a model or product group. */
14710
15229
  label: external_exports.string().min(1).optional(),
14711
15230
  usedPercent: usagePercentSchema.optional(),
14712
15231
  remaining: external_exports.number().finite().optional(),
14713
- unit: external_exports.string().trim().min(1).max(32).optional(),
14714
15232
  resetsAt: external_exports.string().min(1).optional(),
14715
15233
  periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
14716
15234
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
@@ -14741,12 +15259,27 @@ var threadUsageInspectionSchema = external_exports.object({
14741
15259
  }).strict();
14742
15260
 
14743
15261
  // ../../shared-contracts/dist/harness-accounts.js
14744
- var harnessAccountSnapshotSchema = external_exports.object({
15262
+ var accountBalanceSnapshotSchema = external_exports.object({
15263
+ amount: external_exports.number().finite().nonnegative(),
15264
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15265
+ currency: external_exports.string().trim().min(1).max(8),
15266
+ /** Native label when the Harness exposes several Billing Sources. */
15267
+ label: external_exports.string().trim().min(1).max(128).optional()
15268
+ }).strict();
15269
+ var harnessAccountSnapshotObject = external_exports.object({
14745
15270
  email: external_exports.string().trim().min(1).max(320).optional(),
14746
15271
  label: external_exports.string().trim().min(1).max(256).optional(),
14747
15272
  plan: external_exports.string().trim().min(1).max(128).optional(),
14748
- credits: accountCreditsSnapshotSchema
15273
+ credits: accountCreditsSnapshotSchema.optional(),
15274
+ balance: accountBalanceSnapshotSchema.optional()
14749
15275
  }).strict();
15276
+ function requireReportedQuota(schema) {
15277
+ return schema.refine((value) => {
15278
+ const reported = value;
15279
+ return reported.credits !== void 0 || reported.balance !== void 0;
15280
+ }, { message: "Account must report either credits or a balance" });
15281
+ }
15282
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14750
15283
  var harnessAccountIdentityShape = {
14751
15284
  harnessId: harnessIdSchema,
14752
15285
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14757,11 +15290,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14757
15290
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14758
15291
  var harnessAccountInspectResultSchema = external_exports.object({
14759
15292
  ...harnessAccountIdentityShape,
14760
- account: harnessAccountSnapshotSchema.nullable()
15293
+ account: harnessAccountSnapshotSchema.nullable(),
15294
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
15295
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14761
15296
  }).strict();
14762
15297
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14763
15298
  var harnessAccountListResultSchema = external_exports.object({
14764
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
15299
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14765
15300
  }).strict();
14766
15301
 
14767
15302
  // ../../shared-contracts/dist/json-value.js
@@ -14899,6 +15434,8 @@ var harnessModelSchema = external_exports.object({
14899
15434
  ref: harnessModelRefSchema,
14900
15435
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14901
15436
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15437
+ /** Optional opaque selection for this same Model with priority processing enabled. */
15438
+ fastModel: harnessModelRefSchema.optional(),
14902
15439
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14903
15440
  }).strict();
14904
15441
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14931,6 +15468,16 @@ var harnessModelCatalogSchema = external_exports.object({
14931
15468
  });
14932
15469
  }
14933
15470
  refs.add(model.ref.id);
15471
+ if (model.fastModel) {
15472
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15473
+ context.addIssue({
15474
+ code: "custom",
15475
+ message: "Fast Model refs must be distinct and unique",
15476
+ path: ["models", index, "fastModel"]
15477
+ });
15478
+ }
15479
+ refs.add(model.fastModel.id);
15480
+ }
14934
15481
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14935
15482
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14936
15483
  if (supportedThinkingIds.has(optionId)) {
@@ -15053,11 +15600,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15053
15600
  thinkingOptionId: harnessThinkingOptionIdSchema
15054
15601
  }).strict();
15055
15602
  var threadInspectionParamsSchema = external_exports.object({
15056
- threadId: hostThreadIdSchema
15603
+ threadId: hostThreadIdSchema,
15604
+ includeReferenceCapability: external_exports.boolean().optional()
15057
15605
  }).strict();
15058
15606
  var codexThreadInspectionSchema = external_exports.object({
15059
15607
  owner: external_exports.literal("codex"),
15060
- locked: external_exports.literal(true)
15608
+ locked: external_exports.literal(true),
15609
+ supportsThreadReferences: external_exports.literal(true).optional()
15061
15610
  }).strict();
15062
15611
  var externalThreadInspectionSchema = external_exports.object({
15063
15612
  owner: external_exports.literal("external"),
@@ -15122,48 +15671,6 @@ var threadOwnershipListResultSchema = external_exports.object({
15122
15671
  }
15123
15672
  });
15124
15673
 
15125
- // ../../shared-contracts/dist/harness-plugins.js
15126
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15127
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15128
- var HARNESS_PLUGIN_LIMIT = 128;
15129
- 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);
15130
- 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");
15131
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15132
- var pluginPresentationShape = {
15133
- id: harnessPluginIdSchema,
15134
- name: external_exports.string().trim().min(1).max(128),
15135
- version: external_exports.string().min(1).max(128),
15136
- /** The factory accepts a persisted local entrypoint through its construction context. */
15137
- launchCommand: external_exports.literal(true).optional(),
15138
- links: external_exports.object({
15139
- documentation: documentationUrlSchema.optional(),
15140
- installation: documentationUrlSchema.optional()
15141
- }).strict().optional()
15142
- };
15143
- var harnessPluginManifestSchema = external_exports.object({
15144
- manifestVersion: external_exports.literal(1),
15145
- ...pluginPresentationShape,
15146
- adapterApiVersion: external_exports.number().int().positive(),
15147
- entry: relativeResourceSchema,
15148
- icon: relativeResourceSchema.optional()
15149
- }).strict();
15150
- 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);
15151
- var harnessPluginDescriptorSchema = external_exports.object({
15152
- ...pluginPresentationShape,
15153
- icon: harnessPluginIconSchema.optional()
15154
- }).strict();
15155
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
15156
- var harnessPluginListResultSchema = external_exports.object({
15157
- plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15158
- }).strict();
15159
- var harnessPluginConfigurationSchema = external_exports.object({
15160
- version: external_exports.literal(1),
15161
- enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15162
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15163
- message: "Enabled plugin IDs must be unique",
15164
- path: ["enabled"]
15165
- });
15166
-
15167
15674
  // ../../shared-contracts/dist/harness-route.js
15168
15675
  var harnessPluginRouteSchema = external_exports.object({
15169
15676
  harnessId: harnessPluginIdSchema,
@@ -15185,10 +15692,31 @@ var harnessLaunchSettingsSchema = external_exports.object({
15185
15692
  restartRequired: external_exports.boolean()
15186
15693
  }).strict();
15187
15694
 
15695
+ // ../../shared-contracts/dist/harness-installation.js
15696
+ var harnessInstallationParamsSchema = external_exports.object({
15697
+ harnessId: harnessIdSchema,
15698
+ action: external_exports.enum(["check", "update", "install"])
15699
+ }).strict();
15700
+ var harnessInstallationStateSchema = external_exports.object({
15701
+ currentVersion: external_exports.string().min(1).max(128),
15702
+ latestVersion: external_exports.string().min(1).max(128),
15703
+ updateAvailable: external_exports.boolean(),
15704
+ canUpdate: external_exports.boolean(),
15705
+ message: external_exports.string().max(2048).optional()
15706
+ }).strict();
15707
+
15188
15708
  // ../../shared-contracts/dist/codex-accounts.js
15189
15709
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15190
15710
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
15191
15711
  var codexAccountAuthKindSchema = external_exports.enum(["api", "chatgpt"]);
15712
+ var codexAccountSiteUrlPattern = /^https?:\/\/(?:\[[0-9a-fA-F:]+\]|[^/\s:@?#]+)(?::\d{1,5})?(?:[/?#][^\s]*)?$/u;
15713
+ function isCodexAccountSiteUrl(value) {
15714
+ return value.length > 0 && value.length <= 2048 && codexAccountSiteUrlPattern.test(value);
15715
+ }
15716
+ var externalUrlOpenParamsSchema = external_exports.object({
15717
+ url: external_exports.string().max(2048).refine(isCodexAccountSiteUrl, "External URL must be http(s)")
15718
+ }).strict();
15719
+ var externalUrlOpenResultSchema = external_exports.object({}).strict();
15192
15720
  var codexAccountPlanTypeSchema = external_exports.enum([
15193
15721
  "free",
15194
15722
  "go",
@@ -15214,7 +15742,8 @@ var codexAccountSchema = external_exports.object({
15214
15742
  email: external_exports.string().email().max(320).optional(),
15215
15743
  planType: codexAccountPlanTypeSchema.optional(),
15216
15744
  authKind: codexAccountAuthKindSchema.optional(),
15217
- authIdentity: nonBlankTextSchema3.max(256).optional()
15745
+ authIdentity: nonBlankTextSchema3.max(256).optional(),
15746
+ siteUrl: external_exports.string().refine(isCodexAccountSiteUrl, "Account site URL must be http(s)").optional()
15218
15747
  }).strict();
15219
15748
  var codexAccountPhaseSchema = external_exports.enum(["ready", "unavailable"]);
15220
15749
  var codexAccountListResultSchema = external_exports.object({
@@ -15486,234 +16015,167 @@ var updateStartResultSchema = external_exports.strictObject({
15486
16015
  var updateStatusResultSchema = external_exports.strictObject({
15487
16016
  status: updateStatusSchema.nullable()
15488
16017
  });
15489
-
15490
- // ../../shared-contracts/dist/index.js
15491
- var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15492
-
15493
- // ../../harness-discovery/dist/environment.js
15494
- import fs from "node:fs";
15495
- import path from "node:path";
15496
- function targetPath(platform) {
15497
- return platform === "win32" ? path.win32 : path.posix;
15498
- }
15499
- function environmentValue(environment, name) {
15500
- const lowered = name.toLowerCase();
15501
- for (const [key, value] of Object.entries(environment)) {
15502
- if (key.toLowerCase() === lowered)
15503
- return value;
15504
- }
15505
- return void 0;
15506
- }
15507
- function pathDelimiter(platform) {
15508
- return platform === "win32" ? ";" : ":";
15509
- }
15510
- function pathDirectories(environment, platform) {
15511
- return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
15512
- }
15513
- function executableExtensions(command, platform, environment) {
15514
- if (platform !== "win32")
15515
- return [""];
15516
- if (targetPath(platform).extname(command) !== "")
15517
- return [""];
15518
- return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
15519
- }
15520
- function isExecutableFile(filePath, platform) {
15521
- try {
15522
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
15523
- return fs.statSync(filePath).isFile();
15524
- } catch {
15525
- return false;
15526
- }
15527
- }
15528
- function subdirectoryNames(directory) {
15529
- try {
15530
- return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
15531
- } catch {
15532
- return [];
15533
- }
15534
- }
15535
- function newestFirst(names) {
15536
- return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
15537
- }
15538
-
15539
- // ../../harness-discovery/dist/node-runtime.js
15540
- import path2 from "node:path";
15541
- function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
15542
- const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
15543
- const delimiter = platform === "win32" ? ";" : ":";
15544
- const runtimeDirectory = path2.dirname(runtimeExecutable);
15545
- const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
15546
- const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
15547
- if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
15548
- directories.push(runtimeDirectory);
15549
- }
15550
- return { ...environment, [pathKey]: directories.join(delimiter) };
15551
- }
15552
-
15553
- // ../../harness-discovery/dist/resolve.js
15554
- import os from "node:os";
15555
-
15556
- // ../../harness-discovery/dist/version-managers.js
15557
- function versionManagerBinaryDirectories(context) {
15558
- const { platform, environment, home } = context;
15559
- const list = context.subdirectories ?? subdirectoryNames;
15560
- const pathFlavor = targetPath(platform);
15561
- const value = (name) => environmentValue(environment, name);
15562
- const directories = [];
15563
- const versioned = (root, ...tail) => {
15564
- for (const version2 of newestFirst(list(root))) {
15565
- directories.push(pathFlavor.join(root, version2, ...tail));
15566
- }
15567
- };
15568
- if (platform === "win32") {
15569
- const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
15570
- const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
15571
- versioned(pathFlavor.join(appData, "nvm"));
15572
- versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
15573
- directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
15574
- directories.push(pathFlavor.join(home, ".bun", "bin"));
15575
- const pnpmHome2 = value("PNPM_HOME");
15576
- if (pnpmHome2)
15577
- directories.push(pnpmHome2);
15578
- directories.push(pathFlavor.join(localAppData, "pnpm"));
15579
- return directories;
15580
- }
15581
- versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
15582
- const fnmRoots = [
15583
- value("FNM_DIR"),
15584
- pathFlavor.join(home, ".local", "share", "fnm"),
15585
- pathFlavor.join(home, "Library", "Application Support", "fnm")
15586
- ].filter((root) => root !== void 0);
15587
- for (const root of fnmRoots) {
15588
- versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
15589
- }
15590
- const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
15591
- versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
15592
- directories.push(pathFlavor.join(voltaHome, "bin"));
15593
- const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
15594
- versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
15595
- directories.push(pathFlavor.join(asdfHome, "shims"));
15596
- const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
15597
- versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
15598
- directories.push(pathFlavor.join(nodenvHome, "shims"));
15599
- versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
15600
- directories.push(pathFlavor.join(home, ".bun", "bin"));
15601
- const pnpmHome = value("PNPM_HOME");
15602
- if (pnpmHome)
15603
- directories.push(pnpmHome);
15604
- directories.push(pathFlavor.join(home, "Library", "pnpm"));
15605
- directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
15606
- for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
15607
- for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
15608
- directories.push(pathFlavor.join(prefix, formula, "bin"));
15609
- }
15610
- }
15611
- return directories;
15612
- }
15613
-
15614
- // ../../harness-discovery/dist/resolve.js
15615
- var VERSION_MANAGER_ROOTS = "<version-managers>";
15616
- function installRootExtensions(platform) {
15617
- return platform === "win32" ? [".exe", ".cmd"] : [""];
15618
- }
15619
- function resolveHomeDirectory(input) {
15620
- return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
15621
- }
15622
- function templateVariables(environment, platform, home) {
15623
- const pathFlavor = targetPath(platform);
15624
- return {
15625
- HOME: home,
15626
- USERPROFILE: home,
15627
- APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
15628
- LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
15629
- };
15630
- }
15631
- function joinTemplate(platform, value) {
15632
- const pathFlavor = targetPath(platform);
15633
- const segments = value.split("/");
15634
- const head = segments[0] ?? "";
15635
- const tail = segments.slice(1);
15636
- if (head === "")
15637
- return pathFlavor.join(pathFlavor.sep, ...tail);
15638
- return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
15639
- }
15640
- function expandInstallRoot(template, environment, platform, home) {
15641
- const variables = templateVariables(environment, platform, home);
15642
- let unresolved = false;
15643
- const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
15644
- const value = variables[name] ?? environmentValue(environment, name);
15645
- if (value === void 0 || value === "") {
15646
- unresolved = true;
15647
- return "";
15648
- }
15649
- return value;
16018
+
16019
+ // ../../shared-contracts/dist/index.js
16020
+ var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16021
+
16022
+ // dist/account-balance.js
16023
+ var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
16024
+ var SUB2API_USAGE_PATH = "/v1/usage";
16025
+ var REQUEST_TIMEOUT_MS = 1e4;
16026
+ var MAX_PI_ACCOUNTS = 8;
16027
+ function agentDirectory(environment) {
16028
+ const configured = environment.PI_CODING_AGENT_DIR?.trim();
16029
+ if (configured)
16030
+ return configured;
16031
+ return path4.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".pi", "agent");
16032
+ }
16033
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
16034
+ async function deepSeekApiKey(environment) {
16035
+ const auth = record2(JSON.parse(await readFile(path4.join(agentDirectory(environment), "auth.json"), "utf8")));
16036
+ const deepseek = record2(auth.deepseek);
16037
+ if (deepseek.type !== "api_key")
16038
+ return void 0;
16039
+ return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
16040
+ }
16041
+ function projectSub2ApiUsage(payload, providerId) {
16042
+ const data = record2(payload);
16043
+ if (data.isValid === false)
16044
+ return null;
16045
+ if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
16046
+ return null;
16047
+ const currency = typeof data.unit === "string" ? data.unit.trim() : "";
16048
+ if (!/^[A-Z]{3}$/u.test(currency))
16049
+ return null;
16050
+ const wallet = finiteAmount(data.balance);
16051
+ const remaining = finiteAmount(data.remaining);
16052
+ const quotaRemaining = finiteAmount(record2(data.quota).remaining);
16053
+ const amount = wallet ?? remaining ?? quotaRemaining;
16054
+ if (amount === null)
16055
+ return null;
16056
+ const planName = typeof data.planName === "string" ? data.planName.trim() : "";
16057
+ const label = providerId.trim();
16058
+ if (!label || label.length > 128)
16059
+ return null;
16060
+ const parsed = harnessAccountSnapshotSchema.safeParse({
16061
+ label,
16062
+ ...planName ? { plan: planName.slice(0, 128) } : {},
16063
+ balance: { amount, currency, label: planName || label }
15650
16064
  });
15651
- return unresolved ? void 0 : joinTemplate(platform, substituted);
16065
+ return parsed.success ? parsed.data : null;
15652
16066
  }
15653
- function installRootDirectories(spec, input, dependencies, platform, home) {
15654
- const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
15655
- const directories = [];
15656
- for (const template of templates) {
15657
- if (template === VERSION_MANAGER_ROOTS) {
15658
- directories.push(...versionManagerBinaryDirectories({
15659
- platform,
15660
- environment: input.environment,
15661
- home,
15662
- ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
15663
- }));
15664
- continue;
15665
- }
15666
- const directory = expandInstallRoot(template, input.environment, platform, home);
15667
- if (directory !== void 0)
15668
- directories.push(directory);
15669
- }
15670
- return directories;
16067
+ function finiteAmount(value) {
16068
+ const amount = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
16069
+ return Number.isFinite(amount) && amount >= 0 ? amount : null;
15671
16070
  }
15672
- function harnessCandidates(spec, input, dependencies = {}) {
15673
- const platform = input.platform ?? process.platform;
15674
- const pathFlavor = targetPath(platform);
15675
- const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
15676
- const command = configured ?? spec.command;
15677
- if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
15678
- return [{ candidate: command, source: "configured" }];
16071
+ function projectDeepSeekBalance(payload) {
16072
+ const data = record2(payload);
16073
+ if (!Array.isArray(data.balance_infos))
16074
+ return null;
16075
+ const first = record2(data.balance_infos[0]);
16076
+ const amount = finiteAmount(first.total_balance);
16077
+ const currency = typeof first.currency === "string" ? first.currency.trim() : "";
16078
+ if (amount === null || !currency)
16079
+ return null;
16080
+ const parsed = harnessAccountSnapshotSchema.safeParse({
16081
+ label: "DeepSeek",
16082
+ balance: { amount, currency, label: "DeepSeek API" }
16083
+ });
16084
+ return parsed.success ? parsed.data : null;
16085
+ }
16086
+ function usageEndpoint(baseUrl) {
16087
+ let url2;
16088
+ try {
16089
+ url2 = new URL(baseUrl);
16090
+ } catch {
16091
+ return null;
15679
16092
  }
15680
- const candidates = [];
15681
- const extensions = executableExtensions(command, platform, input.environment);
15682
- for (const directory of pathDirectories(input.environment, platform)) {
15683
- for (const extension of extensions) {
15684
- candidates.push({
15685
- candidate: pathFlavor.join(directory, command + extension),
15686
- source: "path"
15687
- });
16093
+ if (url2.protocol !== "https:" && url2.protocol !== "http:" || !url2.hostname)
16094
+ return null;
16095
+ url2.username = "";
16096
+ url2.password = "";
16097
+ url2.pathname = SUB2API_USAGE_PATH;
16098
+ url2.search = "";
16099
+ url2.hash = "";
16100
+ return url2.toString();
16101
+ }
16102
+ async function configuredSub2ApiProviders(environment) {
16103
+ try {
16104
+ const models = record2(JSON.parse(await readFile(path4.join(agentDirectory(environment), "models.json"), "utf8")));
16105
+ const providers = record2(models.providers);
16106
+ const found = [];
16107
+ for (const [id, definition] of Object.entries(providers)) {
16108
+ const provider = record2(definition);
16109
+ const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
16110
+ const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
16111
+ if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
16112
+ continue;
16113
+ found.push({ id, apiKey, baseUrl });
15688
16114
  }
16115
+ return found.sort((left, right) => left.id.localeCompare(right.id));
16116
+ } catch {
16117
+ return [];
15689
16118
  }
15690
- if (configured !== void 0)
15691
- return candidates;
15692
- const home = resolveHomeDirectory(input);
15693
- for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
15694
- for (const extension of installRootExtensions(platform)) {
15695
- candidates.push({
15696
- candidate: pathFlavor.join(directory, spec.command + extension),
15697
- source: "install-root"
15698
- });
15699
- }
16119
+ }
16120
+ async function fetchSub2ApiBalance(provider, fetchImpl, signal) {
16121
+ const endpoint = usageEndpoint(provider.baseUrl);
16122
+ if (!endpoint)
16123
+ return null;
16124
+ const response = await fetchImpl(endpoint, {
16125
+ headers: { Authorization: `Bearer ${provider.apiKey}`, Accept: "application/json" },
16126
+ redirect: "error",
16127
+ signal
16128
+ });
16129
+ if (!response.ok)
16130
+ return null;
16131
+ return projectSub2ApiUsage(await response.json(), provider.id);
16132
+ }
16133
+ async function fetchPiAccounts(input = {}) {
16134
+ try {
16135
+ const environment = input.environment ?? process.env;
16136
+ const fetchImpl = input.fetch ?? fetch;
16137
+ const signal = input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
16138
+ const [providers, deepseek] = await Promise.all([
16139
+ input.readProviders ? input.readProviders() : configuredSub2ApiProviders(environment),
16140
+ fetchPiAccountBalance({ ...input, environment, fetch: fetchImpl, signal })
16141
+ ]);
16142
+ const wallets = await Promise.all(providers.filter((provider) => provider.apiKey.trim() && usageEndpoint(provider.baseUrl)).map((provider) => fetchSub2ApiBalance(provider, fetchImpl, signal).catch(() => null)));
16143
+ return [...wallets, deepseek].filter((account) => account !== null).slice(0, MAX_PI_ACCOUNTS);
16144
+ } catch {
16145
+ return [];
15700
16146
  }
15701
- return candidates;
15702
16147
  }
15703
- function resolveHarnessExecutable(spec, input, dependencies = {}) {
15704
- const platform = input.platform ?? process.platform;
15705
- const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
15706
- const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
15707
- const context = { platform, isExecutable };
15708
- for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
15709
- const executable = runnable(candidate, context);
15710
- if (executable !== void 0 && isExecutable(executable))
15711
- return { executable, source };
16148
+ async function fetchPiAccountBalance(input) {
16149
+ try {
16150
+ const key = await (input.readApiKey ? input.readApiKey() : deepSeekApiKey(input.environment));
16151
+ if (!key)
16152
+ return null;
16153
+ const response = await input.fetch(DEEPSEEK_BALANCE_ENDPOINT, {
16154
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
16155
+ signal: input.signal
16156
+ });
16157
+ if (!response.ok)
16158
+ return null;
16159
+ return projectDeepSeekBalance(await response.json());
16160
+ } catch {
16161
+ return null;
15712
16162
  }
15713
- return void 0;
15714
16163
  }
15715
16164
 
16165
+ // dist/pi-credential-imports.js
16166
+ import { randomUUID } from "node:crypto";
16167
+ import { execFile as execFile2 } from "node:child_process";
16168
+ import { promisify } from "node:util";
16169
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
16170
+ import { realpath } from "node:fs/promises";
16171
+ import os2 from "node:os";
16172
+ import path6 from "node:path";
16173
+ import { pathToFileURL } from "node:url";
16174
+
15716
16175
  // dist/command.js
16176
+ import fs2 from "node:fs";
16177
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
16178
+ import path5 from "node:path";
15717
16179
  var piDiscoverySpec = {
15718
16180
  id: "pi",
15719
16181
  command: "pi",
@@ -15738,6 +16200,34 @@ function resolvePiExecutable(input, dependencies = {}) {
15738
16200
  }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
15739
16201
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
15740
16202
  }
16203
+ function isFilesystemRoot(cwd) {
16204
+ const resolved = path5.resolve(cwd);
16205
+ return resolved === path5.parse(resolved).root;
16206
+ }
16207
+ function writableDirectory(candidate) {
16208
+ if (!candidate || !path5.isAbsolute(candidate) || isFilesystemRoot(candidate))
16209
+ return void 0;
16210
+ try {
16211
+ if (!fs2.statSync(candidate).isDirectory())
16212
+ return void 0;
16213
+ fs2.accessSync(candidate, fs2.constants.R_OK | fs2.constants.W_OK);
16214
+ return candidate;
16215
+ } catch {
16216
+ return void 0;
16217
+ }
16218
+ }
16219
+ function resolvePiInspectCwd(inputCwd, environment = process.env) {
16220
+ if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
16221
+ return path5.resolve(inputCwd);
16222
+ }
16223
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir3(), tmpdir2()];
16224
+ for (const candidate of candidates) {
16225
+ const usable = writableDirectory(candidate);
16226
+ if (usable)
16227
+ return usable;
16228
+ }
16229
+ return inputCwd && inputCwd.length > 0 ? path5.resolve(inputCwd) : process.cwd();
16230
+ }
15741
16231
 
15742
16232
  // dist/pi-credential-imports.js
15743
16233
  var PREFIX = "codexhost-account-";
@@ -15780,6 +16270,15 @@ function describeOauth(credential) {
15780
16270
  ...match ? { vendor: match.vendor } : {}
15781
16271
  };
15782
16272
  }
16273
+ function readPiCodexProviderNames(environment) {
16274
+ const agentDir = environment.PI_CODING_AGENT_DIR ?? path6.join(environment.HOME ?? environment.USERPROFILE ?? os2.homedir(), ".pi/agent");
16275
+ try {
16276
+ const auth = parseAuth(readFileSync(path6.join(agentDir, "auth.json"), "utf8"));
16277
+ return Object.entries(auth).filter(([, credential]) => describeOauth(credential).vendor === "openai-codex").map(([provider]) => provider);
16278
+ } catch {
16279
+ return [];
16280
+ }
16281
+ }
15783
16282
  function writeAuth(filename, content) {
15784
16283
  const temporary = `${filename}.${randomUUID()}.tmp`;
15785
16284
  try {
@@ -15790,8 +16289,8 @@ function writeAuth(filename, content) {
15790
16289
  }
15791
16290
  }
15792
16291
  function removeOwnedFiles(dir) {
15793
- rmSync(path3.join(dir, "index.ts"), { force: true });
15794
- rmSync(path3.join(dir, "import.json"), { force: true });
16292
+ rmSync(path6.join(dir, "index.ts"), { force: true });
16293
+ rmSync(path6.join(dir, "import.json"), { force: true });
15795
16294
  try {
15796
16295
  rmdirSync(dir);
15797
16296
  } catch {
@@ -15799,26 +16298,26 @@ function removeOwnedFiles(dir) {
15799
16298
  }
15800
16299
  async function installation(command, environment, authPath) {
15801
16300
  const executable = await realpath(resolvePiExecutable({ ...command ? { command } : {}, environment }));
15802
- let directory = path3.dirname(executable);
16301
+ let directory = path6.dirname(executable);
15803
16302
  while (true) {
15804
- const manifest = path3.join(directory, "package.json");
16303
+ const manifest = path6.join(directory, "package.json");
15805
16304
  if (existsSync(manifest)) {
15806
16305
  const pkg = JSON.parse(readFileSync(manifest, "utf8"));
15807
16306
  if (pkg.name === "@earendil-works/pi-coding-agent")
15808
16307
  break;
15809
16308
  }
15810
- const parent = path3.dirname(directory);
16309
+ const parent = path6.dirname(directory);
15811
16310
  if (parent === directory)
15812
16311
  throw new Error("Pi credential import requires a supported npm Pi installation");
15813
16312
  directory = parent;
15814
16313
  }
15815
- const storage = await import(pathToFileURL(path3.join(directory, "dist/core/auth-storage.js")).href);
15816
- const ai = path3.join(directory, "node_modules/@earendil-works/pi-ai/dist");
15817
- const all = await import(pathToFileURL(path3.join(ai, "providers/all.js")).href);
16314
+ const storage = await import(pathToFileURL(path6.join(directory, "dist/core/auth-storage.js")).href);
16315
+ const ai = path6.join(directory, "node_modules/@earendil-works/pi-ai/dist");
16316
+ const all = await import(pathToFileURL(path6.join(ai, "providers/all.js")).href);
15818
16317
  const providers = all.getBuiltinProviders();
15819
16318
  const providerModules = {
15820
- "openai-codex": pathToFileURL(path3.join(ai, "providers/openai-codex.js")).href,
15821
- xai: pathToFileURL(path3.join(ai, "providers/xai.js")).href
16319
+ "openai-codex": pathToFileURL(path6.join(ai, "providers/openai-codex.js")).href,
16320
+ xai: pathToFileURL(path6.join(ai, "providers/xai.js")).href
15822
16321
  };
15823
16322
  for (const [id, url2] of Object.entries(providerModules)) {
15824
16323
  const module = await import(url2);
@@ -15831,9 +16330,9 @@ async function installation(command, environment, authPath) {
15831
16330
  providerModules,
15832
16331
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
15833
16332
  async configuredProviderNames() {
15834
- const { stdout } = await promisify(execFile)(process.execPath, [executable, "--offline", "--no-approve", "--list-models"], {
15835
- cwd: existsSync(path3.dirname(authPath)) ? path3.dirname(authPath) : os2.homedir(),
15836
- env: { ...environment, PI_CODING_AGENT_DIR: path3.dirname(authPath), PI_OFFLINE: "1" },
16333
+ const { stdout } = await promisify(execFile2)(process.execPath, [executable, "--offline", "--no-approve", "--list-models"], {
16334
+ cwd: existsSync(path6.dirname(authPath)) ? path6.dirname(authPath) : os2.homedir(),
16335
+ env: { ...environment, PI_CODING_AGENT_DIR: path6.dirname(authPath), PI_OFFLINE: "1" },
15837
16336
  timeout: 15e3,
15838
16337
  maxBuffer: 4 * 1024 * 1024
15839
16338
  });
@@ -15863,26 +16362,26 @@ export default async function (pi) {
15863
16362
  }
15864
16363
  function createPiCredentialImports(options = {}) {
15865
16364
  const env = { ...process.env, ...options.environment };
15866
- const agentDir = env.PI_CODING_AGENT_DIR ?? path3.join(env.HOME ?? os2.homedir(), ".pi/agent");
15867
- const authPath = path3.join(agentDir, "auth.json");
15868
- const extensionsDir = path3.join(agentDir, "extensions");
16365
+ const agentDir = env.PI_CODING_AGENT_DIR ?? path6.join(env.HOME ?? os2.homedir(), ".pi/agent");
16366
+ const authPath = path6.join(agentDir, "auth.json");
16367
+ const extensionsDir = path6.join(agentDir, "extensions");
15869
16368
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
15870
16369
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
15871
- const location = (name) => path3.join(extensionsDir, `${PREFIX}${credentialImportNameSchema.parse(name)}`);
16370
+ const location = (name) => path6.join(extensionsDir, `${PREFIX}${credentialImportNameSchema.parse(name)}`);
15872
16371
  const readRecord = (name) => {
15873
16372
  const dir = location(name);
15874
16373
  if (lstatSync(dir).isSymbolicLink())
15875
16374
  throw new Error("Imported configuration was changed; manage it in Pi");
15876
- const value = JSON.parse(readFileSync(path3.join(dir, "import.json"), "utf8"));
16375
+ const value = JSON.parse(readFileSync(path6.join(dir, "import.json"), "utf8"));
15877
16376
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
15878
16377
  throw new Error("Invalid import metadata");
15879
- const record6 = value.record;
15880
- if (!object2(record6))
16378
+ const record7 = value.record;
16379
+ if (!object2(record7))
15881
16380
  throw new Error("Invalid import metadata");
15882
16381
  value.record = credentialImportRecordSchema.parse({
15883
- name: record6.name,
15884
- source: record6.source,
15885
- importedAt: record6.importedAt
16382
+ name: record7.name,
16383
+ source: record7.source,
16384
+ importedAt: record7.importedAt
15886
16385
  });
15887
16386
  if (value.record.name !== name)
15888
16387
  throw new Error("Import identity mismatch");
@@ -15890,7 +16389,7 @@ function createPiCredentialImports(options = {}) {
15890
16389
  };
15891
16390
  const owned = (meta3, auth) => {
15892
16391
  const credential = auth[meta3.record.name];
15893
- const file2 = path3.join(location(meta3.record.name), "index.ts");
16392
+ const file2 = path6.join(location(meta3.record.name), "index.ts");
15894
16393
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
15895
16394
  };
15896
16395
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -15904,7 +16403,7 @@ function createPiCredentialImports(options = {}) {
15904
16403
  const name = entry.slice(PREFIX.length);
15905
16404
  if (!credentialImportNameSchema.safeParse(name).success)
15906
16405
  continue;
15907
- if (!existsSync(path3.join(location(name), "import.json")))
16406
+ if (!existsSync(path6.join(location(name), "import.json")))
15908
16407
  continue;
15909
16408
  try {
15910
16409
  const meta3 = readRecord(name);
@@ -15925,7 +16424,7 @@ function createPiCredentialImports(options = {}) {
15925
16424
  },
15926
16425
  async listOthers() {
15927
16426
  const auth = readAuth();
15928
- const ours = new Set(ownedRecords(auth).map((record6) => record6.name));
16427
+ const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
15929
16428
  const result = /* @__PURE__ */ new Map();
15930
16429
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
15931
16430
  for (const [provider, credential] of Object.entries(auth)) {
@@ -15938,7 +16437,7 @@ function createPiCredentialImports(options = {}) {
15938
16437
  ...describeOauth(credential)
15939
16438
  });
15940
16439
  }
15941
- const modelsPath = path3.join(agentDir, "models.json");
16440
+ const modelsPath = path6.join(agentDir, "models.json");
15942
16441
  if (existsSync(modelsPath)) {
15943
16442
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
15944
16443
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -15960,7 +16459,7 @@ function createPiCredentialImports(options = {}) {
15960
16459
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
15961
16460
  throw new Error("Provider name already exists; choose another name");
15962
16461
  const owner = randomUUID();
15963
- const record6 = credentialImportRecordSchema.parse({
16462
+ const record7 = credentialImportRecordSchema.parse({
15964
16463
  name,
15965
16464
  source: transfer.source,
15966
16465
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -15972,15 +16471,15 @@ function createPiCredentialImports(options = {}) {
15972
16471
  try {
15973
16472
  sdk.backend.withLock((current) => {
15974
16473
  const auth = parseAuth(current);
15975
- const modelsPath = path3.join(agentDir, "models.json");
16474
+ const modelsPath = path6.join(agentDir, "models.json");
15976
16475
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
15977
- if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path3.join(extensionsDir, `${name}-provider.ts`)))
16476
+ if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path6.join(extensionsDir, `${name}-provider.ts`)))
15978
16477
  throw new Error("Provider name already exists; choose another name");
15979
16478
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
15980
16479
  mkdirSync(dir, { mode: 448 });
15981
16480
  created = true;
15982
- writeFileSync(path3.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record6, extension }), { flag: "wx", mode: 384 });
15983
- writeFileSync(path3.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
16481
+ writeFileSync(path6.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
16482
+ writeFileSync(path6.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
15984
16483
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
15985
16484
  saveAuth(auth);
15986
16485
  committed = true;
@@ -15990,58 +16489,272 @@ function createPiCredentialImports(options = {}) {
15990
16489
  if (created && !committed)
15991
16490
  removeOwnedFiles(dir);
15992
16491
  throw error51;
15993
- }
15994
- },
15995
- async reimport(name, transfer) {
15996
- const sdk = await resolve();
15997
- sdk.backend.withLock((current) => {
15998
- const meta3 = readRecord(name);
15999
- const auth = parseAuth(current);
16000
- if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
16001
- throw new Error("Import ownership or source account changed; refusing replacement");
16002
- const metadataPath = path3.join(location(name), "import.json");
16003
- const previous = readFileSync(metadataPath, "utf8");
16004
- const updated = {
16005
- ...meta3,
16006
- record: { ...meta3.record, importedAt: (/* @__PURE__ */ new Date()).toISOString() }
16007
- };
16008
- writeAuth(metadataPath, JSON.stringify(updated));
16009
- try {
16010
- saveAuth({
16011
- ...auth,
16012
- [name]: { type: "oauth", ...transfer.oauth, codexhostImportId: meta3.owner }
16013
- });
16014
- } catch (error51) {
16015
- writeAuth(metadataPath, previous);
16016
- throw error51;
16017
- }
16018
- return { result: void 0 };
16019
- });
16020
- },
16021
- async remove(name) {
16022
- const sdk = await resolve();
16023
- const meta3 = readRecord(name);
16024
- sdk.backend.withLock((current) => {
16025
- const auth = parseAuth(current);
16026
- if (!owned(meta3, auth))
16027
- throw new Error("Imported configuration was changed; manage it in Pi");
16028
- saveAuth(Object.fromEntries(Object.entries(auth).filter(([key]) => key !== name)));
16029
- removeOwnedFiles(location(name));
16030
- return { result: void 0 };
16031
- });
16492
+ }
16493
+ },
16494
+ async reimport(name, transfer) {
16495
+ const sdk = await resolve();
16496
+ sdk.backend.withLock((current) => {
16497
+ const meta3 = readRecord(name);
16498
+ const auth = parseAuth(current);
16499
+ if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
16500
+ throw new Error("Import ownership or source account changed; refusing replacement");
16501
+ const metadataPath = path6.join(location(name), "import.json");
16502
+ const previous = readFileSync(metadataPath, "utf8");
16503
+ const updated = {
16504
+ ...meta3,
16505
+ record: { ...meta3.record, importedAt: (/* @__PURE__ */ new Date()).toISOString() }
16506
+ };
16507
+ writeAuth(metadataPath, JSON.stringify(updated));
16508
+ try {
16509
+ saveAuth({
16510
+ ...auth,
16511
+ [name]: { type: "oauth", ...transfer.oauth, codexhostImportId: meta3.owner }
16512
+ });
16513
+ } catch (error51) {
16514
+ writeAuth(metadataPath, previous);
16515
+ throw error51;
16516
+ }
16517
+ return { result: void 0 };
16518
+ });
16519
+ },
16520
+ async remove(name) {
16521
+ const sdk = await resolve();
16522
+ const meta3 = readRecord(name);
16523
+ sdk.backend.withLock((current) => {
16524
+ const auth = parseAuth(current);
16525
+ if (!owned(meta3, auth))
16526
+ throw new Error("Imported configuration was changed; manage it in Pi");
16527
+ saveAuth(Object.fromEntries(Object.entries(auth).filter(([key]) => key !== name)));
16528
+ removeOwnedFiles(location(name));
16529
+ return { result: void 0 };
16530
+ });
16531
+ }
16532
+ };
16533
+ }
16534
+
16535
+ // dist/pi-fast-mode.js
16536
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
16537
+ import { mkdir, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
16538
+ import { homedir as homedir4 } from "node:os";
16539
+ import path7 from "node:path";
16540
+
16541
+ // dist/pi-model-catalog.js
16542
+ var PI_MODEL_REF_PREFIX = "pi-model-v1.";
16543
+ var PI_DRAFT_THINKING_OPTION_IDS = [
16544
+ "off",
16545
+ "minimal",
16546
+ "low",
16547
+ "medium",
16548
+ "high",
16549
+ "xhigh",
16550
+ "max"
16551
+ ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16552
+ var PI_THINKING_LABELS = {
16553
+ off: "Off",
16554
+ minimal: "Minimal",
16555
+ low: "Low",
16556
+ medium: "Medium",
16557
+ high: "High",
16558
+ xhigh: "Extra High",
16559
+ max: "Max"
16560
+ };
16561
+ function compareText(left, right) {
16562
+ return left < right ? -1 : left > right ? 1 : 0;
16563
+ }
16564
+ function assertNativePart(value, name) {
16565
+ if (value.trim().length === 0)
16566
+ throw new Error(`Pi ${name} must not be empty`);
16567
+ }
16568
+ function encodePiModelRef(model) {
16569
+ assertNativePart(model.provider, "Model provider");
16570
+ assertNativePart(model.id, "Model id");
16571
+ const encoded = Buffer.from(JSON.stringify(model.fast ? [model.provider, model.id, true] : [model.provider, model.id]), "utf8").toString("base64url");
16572
+ return harnessModelRefSchema.parse({ id: `${PI_MODEL_REF_PREFIX}${encoded}` });
16573
+ }
16574
+ function decodePiModelRef(ref) {
16575
+ const parsedRef = harnessModelRefSchema.parse(ref);
16576
+ if (!parsedRef.id.startsWith(PI_MODEL_REF_PREFIX)) {
16577
+ throw new Error("Model Ref does not belong to PiAdapter");
16578
+ }
16579
+ const encoded = parsedRef.id.slice(PI_MODEL_REF_PREFIX.length);
16580
+ let decoded;
16581
+ try {
16582
+ decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16583
+ } catch {
16584
+ throw new Error("Pi Model Ref is malformed");
16585
+ }
16586
+ if (!Array.isArray(decoded) || decoded.length !== 2 && !(decoded.length === 3 && decoded[2] === true) || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16587
+ throw new Error("Pi Model Ref has an invalid native identity");
16588
+ }
16589
+ const native = {
16590
+ provider: decoded[0],
16591
+ id: decoded[1],
16592
+ ...decoded[2] === true ? { fast: true } : {}
16593
+ };
16594
+ assertNativePart(native.provider, "Model provider");
16595
+ assertNativePart(native.id, "Model id");
16596
+ if (encodePiModelRef(native).id !== parsedRef.id) {
16597
+ throw new Error("Pi Model Ref is not canonical");
16598
+ }
16599
+ return native;
16600
+ }
16601
+ function samePiModel(left, right) {
16602
+ return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16603
+ }
16604
+ function fallbackThinkingLabel(id) {
16605
+ const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16606
+ return label || id;
16607
+ }
16608
+ function normalizePiThinkingOptions(levels) {
16609
+ return levels.map((id) => harnessThinkingOptionSchema.parse({
16610
+ id,
16611
+ label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16612
+ }));
16613
+ }
16614
+ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16615
+ const byRef = /* @__PURE__ */ new Map();
16616
+ for (const native of nativeModels) {
16617
+ const ref = encodePiModelRef(native);
16618
+ const existing = byRef.get(ref.id);
16619
+ if (existing) {
16620
+ if (existing.reasoning !== native.reasoning) {
16621
+ throw new Error("Pi duplicate Model entries disagree on reasoning capability");
16622
+ }
16623
+ continue;
16624
+ }
16625
+ byRef.set(ref.id, {
16626
+ model: {
16627
+ ref,
16628
+ label: `${native.provider} / ${native.id}`
16629
+ },
16630
+ reasoning: native.reasoning
16631
+ });
16632
+ }
16633
+ const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
16634
+ if (defaultModel && !byRef.has(defaultModel.id)) {
16635
+ throw new Error("Pi effective Model is absent from the available Model catalog");
16636
+ }
16637
+ if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16638
+ throw new Error("Pi effective Thinking option is absent from the available option catalog");
16639
+ }
16640
+ if (thinkingLevels && !effectiveThinkingOptionId) {
16641
+ throw new Error("Pi did not report an effective Thinking option");
16642
+ }
16643
+ const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
16644
+ const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16645
+ const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16646
+ const models = [...byRef.values()].map(({ model, reasoning }) => ({
16647
+ ...model,
16648
+ supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16649
+ })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16650
+ const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16651
+ return harnessModelCatalogSchema.parse({
16652
+ models,
16653
+ ...defaultModel ? { defaultModel } : {},
16654
+ thinkingOptions,
16655
+ ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
16656
+ });
16657
+ }
16658
+
16659
+ // dist/pi-fast-mode.js
16660
+ var PI_FAST_COMMAND = "codexhost-fast-mode";
16661
+ var PI_FAST_ACK = "codexhost-fast-mode:";
16662
+ var PI_FAST_EXTENSION = `export default function(pi) {
16663
+ let target;
16664
+ const wrapped = new Set();
16665
+ pi.on("model_select", (_event, ctx) => {
16666
+ if (target && (target.provider !== ctx.model?.provider || target.id !== ctx.model?.id || ctx.model?.api !== "openai-codex-responses")) target = undefined;
16667
+ });
16668
+ pi.on("session_start", (_event, ctx) => {
16669
+ if (typeof ctx.modelRegistry.getProvider !== "function") return;
16670
+ pi.registerCommand("${PI_FAST_COMMAND}", {
16671
+ description: "Codex Host Fast mode",
16672
+ handler: async (args, ctx) => {
16673
+ const [mode, nonce] = args.split(" ");
16674
+ if (!nonce || (mode !== "on" && mode !== "off")) throw new Error("Invalid Fast selection");
16675
+ if (mode === "on") {
16676
+ const model = ctx.model;
16677
+ if (!model || model.api !== "openai-codex-responses") throw new Error("Fast requires the Codex API");
16678
+ const original = ctx.modelRegistry.getProvider(model.provider);
16679
+ if (!original) throw new Error("Codex Provider is unavailable");
16680
+ if (!wrapped.has(model.provider)) {
16681
+ const options = (model, value) => target && model.api === "openai-codex-responses" && target.provider === model.provider && target.id === model.id
16682
+ ? {
16683
+ ...value,
16684
+ serviceTier: "priority",
16685
+ // Pi streamSimple drops serviceTier but preserves onPayload.
16686
+ onPayload: async (payload, requestModel) => {
16687
+ const request = { ...payload, service_tier: "priority" };
16688
+ const replacement = await value?.onPayload?.(request, requestModel);
16689
+ return { ...(replacement === undefined ? request : replacement), service_tier: "priority" };
16690
+ },
16691
+ } : value;
16692
+ pi.registerProvider({
16693
+ ...original,
16694
+ stream: (model, context, value) => original.stream(model, context, options(model, value)),
16695
+ streamSimple: (model, context, value) => original.streamSimple(model, context, options(model, value)),
16696
+ });
16697
+ wrapped.add(model.provider);
16698
+ }
16699
+ target = { provider: model.provider, id: model.id };
16700
+ } else target = undefined;
16701
+ ctx.ui.notify("${PI_FAST_ACK}" + nonce + ":" + mode, "info");
16702
+ },
16703
+ });
16704
+ });
16705
+ }
16706
+ `;
16707
+ async function ensurePiFastExtension(environment) {
16708
+ const digest = createHash("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
16709
+ const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codexhost");
16710
+ const directory = path7.resolve(dataDirectory, "extensions", "pi-codex-fast");
16711
+ const file2 = path7.join(directory, `${digest}.mjs`);
16712
+ if (await readFile2(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
16713
+ return file2;
16714
+ await mkdir(directory, { recursive: true });
16715
+ const temporary = `${file2}.${randomUUID2()}.tmp`;
16716
+ try {
16717
+ await writeFile2(temporary, PI_FAST_EXTENSION, { mode: 384 });
16718
+ try {
16719
+ await rename(temporary, file2);
16720
+ } catch (error51) {
16721
+ if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
16722
+ throw error51;
16032
16723
  }
16724
+ } finally {
16725
+ await rm2(temporary, { force: true });
16726
+ }
16727
+ return file2;
16728
+ }
16729
+ async function piFastModelKeys(models, environment) {
16730
+ try {
16731
+ const codexHome = environment.CODEX_HOME ?? path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codex");
16732
+ const cache = JSON.parse(await readFile2(path7.join(codexHome, "models_cache.json"), "utf8"));
16733
+ if (!cache || typeof cache !== "object" || !("models" in cache) || !Array.isArray(cache.models))
16734
+ return /* @__PURE__ */ new Set();
16735
+ const priority = new Set(cache.models.filter((model) => typeof model?.slug === "string" && Array.isArray(model.service_tiers) && model.service_tiers.some((tier) => tier?.id === "priority")).map((model) => model.slug));
16736
+ const codexProviders = new Set(readPiCodexProviderNames(environment));
16737
+ return new Set(models.filter((model) => model.api === "openai-codex-responses" && codexProviders.has(model.provider) && priority.has(model.id)).map((model) => encodePiModelRef(model).id));
16738
+ } catch {
16739
+ return /* @__PURE__ */ new Set();
16740
+ }
16741
+ }
16742
+ function withPiFast(catalog, supported) {
16743
+ return {
16744
+ ...catalog,
16745
+ models: catalog.models.map((model) => supported.has(model.ref.id) ? { ...model, fastModel: encodePiModelRef({ ...decodePiModelRef(model.ref), fast: true }) } : model)
16033
16746
  };
16034
16747
  }
16035
16748
 
16036
16749
  // dist/pi-empty-session.js
16037
16750
  import { createReadStream } from "node:fs";
16038
16751
  import { createInterface } from "node:readline";
16039
- import { randomUUID as randomUUID2 } from "node:crypto";
16040
- import { link, open as open2, rm } from "node:fs/promises";
16041
- import path4 from "node:path";
16752
+ import { randomUUID as randomUUID3 } from "node:crypto";
16753
+ import { link, open as open2, rm as rm3 } from "node:fs/promises";
16754
+ import path8 from "node:path";
16042
16755
 
16043
16756
  // dist/pi-subagents.js
16044
- import { createHash } from "node:crypto";
16757
+ import { createHash as createHash2 } from "node:crypto";
16045
16758
 
16046
16759
  // dist/pi-subagent-workflow.js
16047
16760
  var PREFIX2 = "pi-subagents-workflow-v1:";
@@ -16055,23 +16768,23 @@ var STATES = {
16055
16768
  rejected: "failed",
16056
16769
  detached: "running"
16057
16770
  };
16058
- function record2(value) {
16771
+ function record3(value) {
16059
16772
  return typeof value === "object" && value !== null && !Array.isArray(value);
16060
16773
  }
16061
16774
  function text(value, limit = 256) {
16062
16775
  return typeof value === "string" && value.length > 0 && value.length <= limit;
16063
16776
  }
16064
16777
  function piWorkflowSummary(result) {
16065
- if (!record2(result) || !record2(result.details) || result.details.mode !== "workflow" || result.details.asyncId !== void 0)
16778
+ if (!record3(result) || !record3(result.details) || result.details.mode !== "workflow" || result.details.asyncId !== void 0)
16066
16779
  return null;
16067
16780
  const details = result.details;
16068
16781
  const summary = details.workflowChildren;
16069
- if (!record2(summary) || summary.version !== 1 || !text(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
16782
+ if (!record3(summary) || summary.version !== 1 || !text(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
16070
16783
  return null;
16071
16784
  const children = [];
16072
16785
  const seen = /* @__PURE__ */ new Set();
16073
16786
  for (const child of summary.children) {
16074
- if (!record2(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
16787
+ if (!record3(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
16075
16788
  return null;
16076
16789
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
16077
16790
  if (child[key] !== void 0 && !text(child[key], 2048))
@@ -16144,7 +16857,7 @@ var STATUS_PREFIX = "PI_SUBAGENT_ASYNC_JSON:";
16144
16857
  var INSPECT_PREFIX = "PI_SUBAGENT_INSPECT_JSON:";
16145
16858
  var ID_PREFIX = "pi-subagents-v1:";
16146
16859
  var MAX_BYTES = 64 * 1024;
16147
- function record3(value) {
16860
+ function record4(value) {
16148
16861
  return typeof value === "object" && value !== null && !Array.isArray(value);
16149
16862
  }
16150
16863
  function token(value) {
@@ -16161,7 +16874,7 @@ var statuses = {
16161
16874
  rejected: "failed"
16162
16875
  };
16163
16876
  function node(value, depth, budget) {
16164
- if (!record3(value) || depth > 8 || ++budget.count > 256 || !token(value.id) || !["subagent", "workflow", "step", "host-step"].includes(String(value.kind)) || typeof value.label !== "string" || value.label.length > 2048 || typeof value.state !== "string" || !Object.hasOwn(statuses, value.state))
16877
+ if (!record4(value) || depth > 8 || ++budget.count > 256 || !token(value.id) || !["subagent", "workflow", "step", "host-step"].includes(String(value.kind)) || typeof value.label !== "string" || value.label.length > 2048 || typeof value.state !== "string" || !Object.hasOwn(statuses, value.state))
16165
16878
  return null;
16166
16879
  const children = [];
16167
16880
  if (value.children !== void 0) {
@@ -16183,14 +16896,14 @@ function node(value, depth, budget) {
16183
16896
  };
16184
16897
  }
16185
16898
  function widget(value, key, prefix) {
16186
- if (!record3(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== key || !Array.isArray(value.widgetLines))
16899
+ if (!record4(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== key || !Array.isArray(value.widgetLines))
16187
16900
  return null;
16188
16901
  const line = value.widgetLines.find((part) => typeof part === "string" && part.startsWith(prefix));
16189
16902
  if (!line || Buffer.byteLength(line) > MAX_BYTES + prefix.length)
16190
16903
  return null;
16191
16904
  try {
16192
16905
  const parsed = JSON.parse(line.slice(prefix.length));
16193
- return record3(parsed) && parsed.version === 1 ? parsed : null;
16906
+ return record4(parsed) && parsed.version === 1 ? parsed : null;
16194
16907
  } catch {
16195
16908
  return null;
16196
16909
  }
@@ -16254,7 +16967,7 @@ function states(run) {
16254
16967
  return result;
16255
16968
  }
16256
16969
  function asyncRunId(toolName, result) {
16257
- if (toolName !== "subagent" || !record3(result) || !record3(result.details))
16970
+ if (toolName !== "subagent" || !record4(result) || !record4(result.details))
16258
16971
  return null;
16259
16972
  const details = result.details;
16260
16973
  return ["single", "parallel", "chain", "workflow"].includes(String(details.mode)) && token(details.asyncId) && typeof details.asyncDir === "string" ? details.asyncId : null;
@@ -16394,15 +17107,15 @@ function parsePiSubagentInspection(value) {
16394
17107
  const parsed = widget(value, "subagent-inspect", INSPECT_PREFIX);
16395
17108
  if (!parsed || parsed.kind !== "pi-subagents.inspect-reply" || !token(parsed.requestId))
16396
17109
  return null;
16397
- if (parsed.error !== void 0 && (!record3(parsed.error) || typeof parsed.error.code !== "string" || typeof parsed.error.message !== "string"))
17110
+ if (parsed.error !== void 0 && (!record4(parsed.error) || typeof parsed.error.code !== "string" || typeof parsed.error.message !== "string"))
16398
17111
  return null;
16399
17112
  for (const field of ["asyncId", "childId", "status", "task", "finalOutput"]) {
16400
17113
  if (parsed[field] !== void 0 && typeof parsed[field] !== "string")
16401
17114
  return null;
16402
17115
  }
16403
- if (parsed.messages !== void 0 && (!Array.isArray(parsed.messages) || parsed.messages.length > 200 || parsed.messages.some((entry) => !record3(entry) || typeof entry.role !== "string" || typeof entry.text !== "string" || !["text", "toolCall", "toolResult"].includes(String(entry.kind)) || entry.name !== void 0 && typeof entry.name !== "string")))
17116
+ if (parsed.messages !== void 0 && (!Array.isArray(parsed.messages) || parsed.messages.length > 200 || parsed.messages.some((entry) => !record4(entry) || typeof entry.role !== "string" || typeof entry.text !== "string" || !["text", "toolCall", "toolResult"].includes(String(entry.kind)) || entry.name !== void 0 && typeof entry.name !== "string")))
16404
17117
  return null;
16405
- if (parsed.truncated !== void 0 && (!record3(parsed.truncated) || typeof parsed.truncated.task !== "boolean" || typeof parsed.truncated.finalOutput !== "boolean" || !Number.isSafeInteger(parsed.truncated.messages) || Number(parsed.truncated.messages) < 0))
17118
+ if (parsed.truncated !== void 0 && (!record4(parsed.truncated) || typeof parsed.truncated.task !== "boolean" || typeof parsed.truncated.finalOutput !== "boolean" || !Number.isSafeInteger(parsed.truncated.messages) || Number(parsed.truncated.messages) < 0))
16406
17119
  return null;
16407
17120
  return parsed;
16408
17121
  }
@@ -16421,7 +17134,7 @@ ${entry.text}`);
16421
17134
  nativeTurnRef: nativeTurnRefSchema.parse({
16422
17135
  harnessId: "pi",
16423
17136
  nativeSessionId: parentSessionId,
16424
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
17137
+ nativeTurnKey: `pi-subagent-${createHash2("sha256").update(id).digest("hex")}`,
16425
17138
  formatVersion: 1
16426
17139
  }),
16427
17140
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
@@ -16429,7 +17142,7 @@ ${entry.text}`);
16429
17142
  item: {
16430
17143
  type: "agentMessage",
16431
17144
  text: text2,
16432
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
17145
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash2("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
16433
17146
  },
16434
17147
  outcome: { status: "succeeded" }
16435
17148
  })),
@@ -16449,120 +17162,6 @@ ${entry.text}`);
16449
17162
  };
16450
17163
  }
16451
17164
 
16452
- // dist/pi-model-catalog.js
16453
- var PI_MODEL_REF_PREFIX = "pi-model-v1.";
16454
- var PI_DRAFT_THINKING_OPTION_IDS = [
16455
- "off",
16456
- "minimal",
16457
- "low",
16458
- "medium",
16459
- "high",
16460
- "xhigh",
16461
- "max"
16462
- ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16463
- var PI_THINKING_LABELS = {
16464
- off: "Off",
16465
- minimal: "Minimal",
16466
- low: "Low",
16467
- medium: "Medium",
16468
- high: "High",
16469
- xhigh: "Extra High",
16470
- max: "Max"
16471
- };
16472
- function compareText(left, right) {
16473
- return left < right ? -1 : left > right ? 1 : 0;
16474
- }
16475
- function assertNativePart(value, name) {
16476
- if (value.trim().length === 0)
16477
- throw new Error(`Pi ${name} must not be empty`);
16478
- }
16479
- function encodePiModelRef(model) {
16480
- assertNativePart(model.provider, "Model provider");
16481
- assertNativePart(model.id, "Model id");
16482
- const encoded = Buffer.from(JSON.stringify([model.provider, model.id]), "utf8").toString("base64url");
16483
- return harnessModelRefSchema.parse({ id: `${PI_MODEL_REF_PREFIX}${encoded}` });
16484
- }
16485
- function decodePiModelRef(ref) {
16486
- const parsedRef = harnessModelRefSchema.parse(ref);
16487
- if (!parsedRef.id.startsWith(PI_MODEL_REF_PREFIX)) {
16488
- throw new Error("Model Ref does not belong to PiAdapter");
16489
- }
16490
- const encoded = parsedRef.id.slice(PI_MODEL_REF_PREFIX.length);
16491
- let decoded;
16492
- try {
16493
- decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16494
- } catch {
16495
- throw new Error("Pi Model Ref is malformed");
16496
- }
16497
- if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16498
- throw new Error("Pi Model Ref has an invalid native identity");
16499
- }
16500
- const native = { provider: decoded[0], id: decoded[1] };
16501
- assertNativePart(native.provider, "Model provider");
16502
- assertNativePart(native.id, "Model id");
16503
- if (encodePiModelRef(native).id !== parsedRef.id) {
16504
- throw new Error("Pi Model Ref is not canonical");
16505
- }
16506
- return native;
16507
- }
16508
- function samePiModel(left, right) {
16509
- return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16510
- }
16511
- function fallbackThinkingLabel(id) {
16512
- const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16513
- return label || id;
16514
- }
16515
- function normalizePiThinkingOptions(levels) {
16516
- return levels.map((id) => harnessThinkingOptionSchema.parse({
16517
- id,
16518
- label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16519
- }));
16520
- }
16521
- function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16522
- const byRef = /* @__PURE__ */ new Map();
16523
- for (const native of nativeModels) {
16524
- const ref = encodePiModelRef(native);
16525
- const existing = byRef.get(ref.id);
16526
- if (existing) {
16527
- if (existing.reasoning !== native.reasoning) {
16528
- throw new Error("Pi duplicate Model entries disagree on reasoning capability");
16529
- }
16530
- continue;
16531
- }
16532
- byRef.set(ref.id, {
16533
- model: {
16534
- ref,
16535
- label: `${native.provider} / ${native.id}`
16536
- },
16537
- reasoning: native.reasoning
16538
- });
16539
- }
16540
- const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
16541
- if (defaultModel && !byRef.has(defaultModel.id)) {
16542
- throw new Error("Pi effective Model is absent from the available Model catalog");
16543
- }
16544
- if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16545
- throw new Error("Pi effective Thinking option is absent from the available option catalog");
16546
- }
16547
- if (thinkingLevels && !effectiveThinkingOptionId) {
16548
- throw new Error("Pi did not report an effective Thinking option");
16549
- }
16550
- const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
16551
- const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16552
- const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16553
- const models = [...byRef.values()].map(({ model, reasoning }) => ({
16554
- ...model,
16555
- supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16556
- })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16557
- const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16558
- return harnessModelCatalogSchema.parse({
16559
- models,
16560
- ...defaultModel ? { defaultModel } : {},
16561
- thinkingOptions,
16562
- ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
16563
- });
16564
- }
16565
-
16566
17165
  // dist/pi-history.js
16567
17166
  var piHarnessId = harnessIdSchema.parse("pi");
16568
17167
  function isRecord(value) {
@@ -16868,7 +17467,7 @@ async function verifyPiSessionCwd(input) {
16868
17467
  async function persistEmptyPiSession(input) {
16869
17468
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
16870
17469
  const destination = state2.sessionFile;
16871
- if (!destination || !path4.isAbsolute(destination) || path4.resolve(destination) === path4.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
17470
+ if (!destination || !path8.isAbsolute(destination) || path8.resolve(destination) === path8.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
16872
17471
  throw new Error("Pi empty Session is not an independent empty native fork");
16873
17472
  await verifyPiSessionCwd({
16874
17473
  sessionFile: sourceSessionFile,
@@ -16892,7 +17491,7 @@ async function persistEmptyPiSession(input) {
16892
17491
  cwd,
16893
17492
  parentSession: sourceSessionFile
16894
17493
  };
16895
- const temporary = path4.join(path4.dirname(destination), `.codexhost-${randomUUID2()}.tmp`);
17494
+ const temporary = path8.join(path8.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
16896
17495
  try {
16897
17496
  const file2 = await open2(temporary, "wx", 384);
16898
17497
  try {
@@ -16903,7 +17502,7 @@ async function persistEmptyPiSession(input) {
16903
17502
  }
16904
17503
  await link(temporary, destination);
16905
17504
  if (process.platform !== "win32") {
16906
- const directory = await open2(path4.dirname(destination), "r");
17505
+ const directory = await open2(path8.dirname(destination), "r");
16907
17506
  try {
16908
17507
  await directory.sync();
16909
17508
  } finally {
@@ -16911,7 +17510,7 @@ async function persistEmptyPiSession(input) {
16911
17510
  }
16912
17511
  }
16913
17512
  } finally {
16914
- await rm(temporary, { force: true });
17513
+ await rm3(temporary, { force: true });
16915
17514
  }
16916
17515
  }
16917
17516
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -17066,16 +17665,16 @@ var Diff = class {
17066
17665
  }
17067
17666
  }
17068
17667
  }
17069
- addToPath(path10, added, removed, oldPosInc, options) {
17070
- const last = path10.lastComponent;
17668
+ addToPath(path14, added, removed, oldPosInc, options) {
17669
+ const last = path14.lastComponent;
17071
17670
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17072
17671
  return {
17073
- oldPos: path10.oldPos + oldPosInc,
17672
+ oldPos: path14.oldPos + oldPosInc,
17074
17673
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17075
17674
  };
17076
17675
  } else {
17077
17676
  return {
17078
- oldPos: path10.oldPos + oldPosInc,
17677
+ oldPos: path14.oldPos + oldPosInc,
17079
17678
  lastComponent: { count: 1, added, removed, previousComponent: last }
17080
17679
  };
17081
17680
  }
@@ -17487,8 +18086,8 @@ function splitLines(text2) {
17487
18086
  }
17488
18087
 
17489
18088
  // dist/pi-adapter.js
17490
- import { randomUUID as randomUUID5 } from "node:crypto";
17491
- import path9 from "node:path";
18089
+ import { randomUUID as randomUUID6 } from "node:crypto";
18090
+ import path13 from "node:path";
17492
18091
 
17493
18092
  // ../../harness-adapter/dist/question.js
17494
18093
  function invalidRequest(message3) {
@@ -17799,16 +18398,16 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17799
18398
  }
17800
18399
 
17801
18400
  // dist/pi-workflow-child-history.js
17802
- import { createHash as createHash2 } from "node:crypto";
18401
+ import { createHash as createHash3 } from "node:crypto";
17803
18402
  import { constants } from "node:fs";
17804
18403
  import { open as open3 } from "node:fs/promises";
17805
- import path5 from "node:path";
17806
- function record4(value) {
18404
+ import path9 from "node:path";
18405
+ function record5(value) {
17807
18406
  return typeof value === "object" && value !== null && !Array.isArray(value);
17808
18407
  }
17809
18408
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
17810
18409
  async function childHistory(file2, parentSessionId, identity) {
17811
- if (!path5.isAbsolute(file2))
18410
+ if (!path9.isAbsolute(file2))
17812
18411
  throw new Error("Pi child Session path is not absolute");
17813
18412
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
17814
18413
  try {
@@ -17821,18 +18420,18 @@ async function childHistory(file2, parentSessionId, identity) {
17821
18420
  throw new Error("Pi child Session exceeds read bounds");
17822
18421
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
17823
18422
  const header = values[0];
17824
- if (!record4(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
18423
+ if (!record5(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
17825
18424
  throw new Error("Unsupported Pi child Session header");
17826
18425
  const entries = [];
17827
18426
  for (const entry of values.slice(1)) {
17828
18427
  const parsed = jsonValueSchema.safeParse(entry);
17829
- if (!parsed.success || !record4(parsed.data) || typeof parsed.data.id !== "string")
18428
+ if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
17830
18429
  throw new Error("Malformed Pi child Session entry");
17831
18430
  entries.push(parsed.data);
17832
18431
  }
17833
18432
  const history = { entries, leafId: String(entries.at(-1)?.id ?? "") || null };
17834
18433
  const snapshot = mapPiSnapshot(history, { sessionId: parentSessionId, model: null });
17835
- const prefix = createHash2("sha256").update(identity).digest("hex");
18434
+ const prefix = createHash3("sha256").update(identity).digest("hex");
17836
18435
  return {
17837
18436
  turns: snapshot.turns.map((turn) => {
17838
18437
  const readonlyTurn = {
@@ -17853,7 +18452,7 @@ async function childHistory(file2, parentSessionId, identity) {
17853
18452
  async function readPiWorkflowChild(history, parentSessionId, address) {
17854
18453
  for (const entry of activePiEntries(history).reverse()) {
17855
18454
  const message3 = entry.message;
17856
- if (!record4(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
18455
+ if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
17857
18456
  continue;
17858
18457
  const summary = piWorkflowSummary(message3);
17859
18458
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -17862,10 +18461,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
17862
18461
  if (!child)
17863
18462
  break;
17864
18463
  const details = message3.details;
17865
- if (!record4(details) || !Array.isArray(details.results))
18464
+ if (!record5(details) || !Array.isArray(details.results))
17866
18465
  break;
17867
- const result = details.results.findLast((candidate) => record4(candidate) && candidate.workflowKey === address.childId);
17868
- if (!record4(result))
18466
+ const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
18467
+ if (!record5(result))
17869
18468
  break;
17870
18469
  const id = piWorkflowSubagentId(address);
17871
18470
  if (typeof result.sessionFile === "string") {
@@ -17911,22 +18510,22 @@ ${output}`,
17911
18510
  // dist/pi-subagent-history.js
17912
18511
  import { constants as constants2 } from "node:fs";
17913
18512
  import { open as open4 } from "node:fs/promises";
17914
- import path6 from "node:path";
17915
- function record5(value) {
18513
+ import path10 from "node:path";
18514
+ function record6(value) {
17916
18515
  return typeof value === "object" && value !== null && !Array.isArray(value);
17917
18516
  }
17918
18517
  function state(value) {
17919
18518
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
17920
18519
  }
17921
18520
  function piSubagentArtifact(value, runId, parentSessionId) {
17922
- if (!record5(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
18521
+ if (!record6(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
17923
18522
  return null;
17924
18523
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
17925
18524
  return null;
17926
18525
  const steps = Array.isArray(value.steps) ? value.steps : [];
17927
18526
  const children = [];
17928
18527
  for (const [index, step] of steps.entries()) {
17929
- if (!record5(step) || typeof step.agent !== "string")
18528
+ if (!record6(step) || typeof step.agent !== "string")
17930
18529
  return null;
17931
18530
  children.push({
17932
18531
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -17959,17 +18558,17 @@ function piSubagentArtifact(value, runId, parentSessionId) {
17959
18558
  async function restorePiSubagents(history, parentSessionId, observer) {
17960
18559
  const receipts = /* @__PURE__ */ new Map();
17961
18560
  for (const entry of activePiEntries(history)) {
17962
- if (!record5(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record5(entry.message.details))
18561
+ if (!record6(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record6(entry.message.details))
17963
18562
  continue;
17964
18563
  const details = entry.message.details;
17965
- if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path6.isAbsolute(details.asyncDir) || path6.basename(details.asyncDir) !== details.asyncId)
18564
+ if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path10.isAbsolute(details.asyncDir) || path10.basename(details.asyncDir) !== details.asyncId)
17966
18565
  continue;
17967
18566
  receipts.set(details.asyncId, details.asyncDir);
17968
18567
  }
17969
18568
  for (const [id, directory] of [...receipts].slice(-128)) {
17970
18569
  let file2;
17971
18570
  try {
17972
- file2 = await open4(path6.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
18571
+ file2 = await open4(path10.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
17973
18572
  const stat2 = await file2.stat();
17974
18573
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
17975
18574
  continue;
@@ -18051,7 +18650,7 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
18051
18650
  import { createReadStream as createReadStream2 } from "node:fs";
18052
18651
  import { opendir, realpath as realpath3, stat } from "node:fs/promises";
18053
18652
  import os3 from "node:os";
18054
- import path7 from "node:path";
18653
+ import path11 from "node:path";
18055
18654
  import { createInterface as createInterface2 } from "node:readline";
18056
18655
  var PiSessionChangedError = class extends Error {
18057
18656
  constructor() {
@@ -18068,7 +18667,7 @@ function missing(error51) {
18068
18667
  return isRecord4(error51) && error51.code === "ENOENT";
18069
18668
  }
18070
18669
  function expandDirectory(value, home) {
18071
- return path7.resolve(value === "~" ? home : value.startsWith(`~${path7.sep}`) || value.startsWith("~/") ? path7.join(home, value.slice(2)) : value);
18670
+ return path11.resolve(value === "~" ? home : value.startsWith(`~${path11.sep}`) || value.startsWith("~/") ? path11.join(home, value.slice(2)) : value);
18072
18671
  }
18073
18672
  function piSessionImportDirectory(environment) {
18074
18673
  const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
@@ -18077,7 +18676,7 @@ function piSessionImportDirectory(environment) {
18077
18676
  return { directory: expandDirectory(custom2, home), flat: true };
18078
18677
  const agent = environment.PI_CODING_AGENT_DIR;
18079
18678
  return {
18080
- directory: path7.join(agent ? expandDirectory(agent, home) : path7.join(home, ".pi", "agent"), "sessions"),
18679
+ directory: path11.join(agent ? expandDirectory(agent, home) : path11.join(home, ".pi", "agent"), "sessions"),
18081
18680
  flat: false
18082
18681
  };
18083
18682
  }
@@ -18095,9 +18694,9 @@ async function sessionFiles(directory, flat, signal) {
18095
18694
  for await (const entry of entries) {
18096
18695
  signal.throwIfAborted();
18097
18696
  if (projectLevel && entry.isDirectory())
18098
- await visit(path7.join(dir, entry.name), false);
18697
+ await visit(path11.join(dir, entry.name), false);
18099
18698
  else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
18100
- files.push(path7.join(dir, entry.name));
18699
+ files.push(path11.join(dir, entry.name));
18101
18700
  }
18102
18701
  }
18103
18702
  };
@@ -18130,7 +18729,7 @@ async function readCandidate(file2, signal) {
18130
18729
  if (!isRecord4(entry))
18131
18730
  return null;
18132
18731
  if (!header) {
18133
- if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path7.isAbsolute(entry.cwd))
18732
+ if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path11.isAbsolute(entry.cwd))
18134
18733
  return null;
18135
18734
  header = entry;
18136
18735
  continue;
@@ -18280,8 +18879,8 @@ var PiSessionImportIndex = class {
18280
18879
 
18281
18880
  // dist/pi-rpc-session.js
18282
18881
  import { spawn, spawnSync } from "node:child_process";
18283
- import { randomUUID as randomUUID4 } from "node:crypto";
18284
- import path8 from "node:path";
18882
+ import { randomUUID as randomUUID5 } from "node:crypto";
18883
+ import path12 from "node:path";
18285
18884
 
18286
18885
  // dist/pi-slash-commands.js
18287
18886
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -18303,15 +18902,15 @@ function parsePiNativeCommands(response) {
18303
18902
  return data.commands.flatMap((entry) => {
18304
18903
  if (typeof entry !== "object" || entry === null)
18305
18904
  return [];
18306
- const record6 = entry;
18307
- const name = typeof record6.name === "string" ? record6.name.trim().replace(/^\//u, "") : "";
18905
+ const record7 = entry;
18906
+ const name = typeof record7.name === "string" ? record7.name.trim().replace(/^\//u, "") : "";
18308
18907
  if (!name)
18309
18908
  return [];
18310
18909
  return [
18311
18910
  {
18312
18911
  name,
18313
- ...typeof record6.description === "string" ? { description: record6.description } : {},
18314
- ...typeof record6.source === "string" ? { source: record6.source } : {}
18912
+ ...typeof record7.description === "string" ? { description: record7.description } : {},
18913
+ ...typeof record7.source === "string" ? { source: record7.source } : {}
18315
18914
  }
18316
18915
  ];
18317
18916
  });
@@ -18399,7 +18998,7 @@ function optionalPiStateContextUsage(value) {
18399
18998
  }
18400
18999
 
18401
19000
  // dist/pi-subagent-rpc.js
18402
- import { randomUUID as randomUUID3 } from "node:crypto";
19001
+ import { randomUUID as randomUUID4 } from "node:crypto";
18403
19002
  var PiSubagentRpc = class {
18404
19003
  send;
18405
19004
  timeoutMs;
@@ -18441,7 +19040,7 @@ var PiSubagentRpc = class {
18441
19040
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
18442
19041
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
18443
19042
  }
18444
- const requestId = randomUUID3();
19043
+ const requestId = randomUUID4();
18445
19044
  const reply = new Promise((resolve, reject) => {
18446
19045
  const timer = setTimeout(() => {
18447
19046
  this.#pending.delete(requestId);
@@ -18587,7 +19186,11 @@ function parseAvailableModels(response) {
18587
19186
  if (!parsed || !isRecord6(model) || typeof model.reasoning !== "boolean") {
18588
19187
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
18589
19188
  }
18590
- return { ...parsed, reasoning: model.reasoning };
19189
+ return {
19190
+ ...parsed,
19191
+ reasoning: model.reasoning,
19192
+ ...typeof model.api === "string" ? { api: model.api } : {}
19193
+ };
18591
19194
  });
18592
19195
  }
18593
19196
  function assistantText(value) {
@@ -18672,13 +19275,14 @@ function piRpcProcessCommand(options, dependencies = {}) {
18672
19275
  const modelArguments = startupModel ? ["--provider", startupModel.provider, "--model", startupModel.id] : [];
18673
19276
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
18674
19277
  const arguments_ = [
19278
+ ...options.fastExtension ? ["--extension", options.fastExtension] : [],
18675
19279
  "--mode",
18676
19280
  "rpc",
18677
19281
  ...modelArguments,
18678
19282
  ...thinkingArguments,
18679
19283
  ...sessionArguments
18680
19284
  ];
18681
- const extension = path8.win32.extname(command).toLowerCase();
19285
+ const extension = path12.win32.extname(command).toLowerCase();
18682
19286
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
18683
19287
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
18684
19288
  }
@@ -18717,6 +19321,8 @@ var PiRpcSession = class {
18717
19321
  #failed = false;
18718
19322
  #pending = /* @__PURE__ */ new Map();
18719
19323
  #state = null;
19324
+ #fast = null;
19325
+ #fastAcknowledgement = null;
18720
19326
  #latestCacheHitRatePercent;
18721
19327
  #manualCompaction = null;
18722
19328
  #stderrTail = "";
@@ -18743,7 +19349,9 @@ var PiRpcSession = class {
18743
19349
  get state() {
18744
19350
  if (!this.#state)
18745
19351
  throw new Error("Pi RPC Session has not started");
18746
- return this.#state;
19352
+ if (this.#fast && (this.#fast.provider !== this.#state.provider || this.#fast.id !== this.#state.modelId))
19353
+ this.#fast = null;
19354
+ return this.#fast ? { ...this.#state, fast: true } : this.#state;
18747
19355
  }
18748
19356
  get stderrTail() {
18749
19357
  return this.#stderrTail;
@@ -18760,8 +19368,10 @@ var PiRpcSession = class {
18760
19368
  async start() {
18761
19369
  if (this.#child || this.#closed)
18762
19370
  throw new Error("Pi RPC Session cannot be started twice");
19371
+ const fastExtension = this.#processAdapter === nodeProcessAdapter ? await ensurePiFastExtension({ ...process.env, ...this.#options.environment }) : void 0;
18763
19372
  const child = this.#processAdapter.spawn({
18764
19373
  cwd: this.#options.cwd,
19374
+ ...fastExtension ? { fastExtension } : {},
18765
19375
  ...this.#options.command ? { command: this.#options.command } : {},
18766
19376
  environment: withNodeRuntimeOnPath({
18767
19377
  ...process.env,
@@ -18908,7 +19518,36 @@ var PiRpcSession = class {
18908
19518
  throw error51;
18909
19519
  }
18910
19520
  }
19521
+ async supportsFastMode() {
19522
+ return (await this.getCommands()).some((command) => command.name === PI_FAST_COMMAND && command.source === "extension");
19523
+ }
19524
+ async selectFastMode(enabled) {
19525
+ if (!enabled && !this.#fast)
19526
+ return this.state;
19527
+ if (!await this.supportsFastMode())
19528
+ throw new Error("Installed Pi does not support the Host Fast extension");
19529
+ const nonce = randomUUID5();
19530
+ const mode = enabled ? "on" : "off";
19531
+ const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
19532
+ this.#fastAcknowledgement = acknowledgement;
19533
+ try {
19534
+ await this.#send("prompt", { message: `/${PI_FAST_COMMAND} ${mode} ${nonce}` });
19535
+ if (!acknowledgement.received)
19536
+ throw new Error("Pi did not confirm the Fast selection");
19537
+ this.#fast = enabled ? { provider: this.state.provider ?? "", id: this.state.modelId ?? "" } : null;
19538
+ return this.state;
19539
+ } catch (error51) {
19540
+ const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi Fast selection could not be confirmed: ${message2(error51)}`);
19541
+ this.#fail(fault);
19542
+ await this.close().catch(() => void 0);
19543
+ throw fault;
19544
+ } finally {
19545
+ this.#fastAcknowledgement = null;
19546
+ }
19547
+ }
18911
19548
  async selectModel(model) {
19549
+ if (this.#fast)
19550
+ await this.selectFastMode(false);
18912
19551
  await this.#send("set_model", { provider: model.provider, modelId: model.id });
18913
19552
  return this.#refreshState("Model");
18914
19553
  }
@@ -18920,7 +19559,7 @@ var PiRpcSession = class {
18920
19559
  async #refreshState(operation) {
18921
19560
  try {
18922
19561
  this.#state = parseSessionState(await this.#send("get_state", {}));
18923
- return this.#state;
19562
+ return this.state;
18924
19563
  } catch (error51) {
18925
19564
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC ${operation} state could not be confirmed: ${message2(error51)}`);
18926
19565
  this.#fail(fault);
@@ -19076,6 +19715,11 @@ var PiRpcSession = class {
19076
19715
  }
19077
19716
  }
19078
19717
  #handle(value) {
19718
+ if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
19719
+ if (this.#fastAcknowledgement?.message === value.message)
19720
+ this.#fastAcknowledgement.received = true;
19721
+ return;
19722
+ }
19079
19723
  if (this.#closed || this.#failed)
19080
19724
  return;
19081
19725
  if (value.type === "response") {
@@ -19198,7 +19842,7 @@ var PiRpcSession = class {
19198
19842
  const active = {
19199
19843
  origin: "autonomous",
19200
19844
  autonomousEvents: events,
19201
- nativeTurnKey: assistantMessageId(value) ?? randomUUID4(),
19845
+ nativeTurnKey: assistantMessageId(value) ?? randomUUID5(),
19202
19846
  nativeCancellationObserved: false,
19203
19847
  text: "",
19204
19848
  assistantMessageId: null,
@@ -19461,7 +20105,7 @@ var PiRpcSession = class {
19461
20105
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19462
20106
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19463
20107
  }
19464
- const messageId = assistantMessageId(value) ?? randomUUID4();
20108
+ const messageId = assistantMessageId(value) ?? randomUUID5();
19465
20109
  active.assistantMessageId = messageId;
19466
20110
  active.sawStreamedMessageText = false;
19467
20111
  active.sawStreamedMessageReasoning = false;
@@ -19522,7 +20166,7 @@ var PiRpcSession = class {
19522
20166
  if (!child?.stdin.writable || this.#closed || this.#failed) {
19523
20167
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
19524
20168
  }
19525
- const id = `codexhost-${randomUUID4()}`;
20169
+ const id = `codexhost-${randomUUID5()}`;
19526
20170
  return new Promise((resolve, reject) => {
19527
20171
  const pending = {
19528
20172
  command: type,
@@ -19697,7 +20341,7 @@ function nativeModelFromState(state2) {
19697
20341
  }
19698
20342
  function effectiveModelFromState(state2) {
19699
20343
  const model = nativeModelFromState(state2);
19700
- return model ? encodePiModelRef(model) : void 0;
20344
+ return model ? encodePiModelRef({ ...model, ...state2.fast ? { fast: true } : {} }) : void 0;
19701
20345
  }
19702
20346
  function harnessStateFromPi(state2, thinkingLevels) {
19703
20347
  const effectiveModel = effectiveModelFromState(state2);
@@ -19783,10 +20427,10 @@ function stripDiffPrefix(pathString) {
19783
20427
  return pathString.startsWith("a/") || pathString.startsWith("b/") ? pathString.slice(2) : pathString;
19784
20428
  }
19785
20429
  function displayPath(nativePath, cwd) {
19786
- const resolvedCwd = path9.resolve(cwd);
19787
- const resolvedPath = path9.isAbsolute(nativePath) ? path9.resolve(nativePath) : path9.resolve(cwd, nativePath);
19788
- const relative = path9.relative(resolvedCwd, resolvedPath);
19789
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`);
20430
+ const resolvedCwd = path13.resolve(cwd);
20431
+ const resolvedPath = path13.isAbsolute(nativePath) ? path13.resolve(nativePath) : path13.resolve(cwd, nativePath);
20432
+ const relative = path13.relative(resolvedCwd, resolvedPath);
20433
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path13.sep}`);
19790
20434
  const selected = inside ? relative : resolvedPath;
19791
20435
  const normalized = selected.replaceAll("\\", "/");
19792
20436
  if (normalized.length === 0 || normalized === ".")
@@ -19985,6 +20629,7 @@ var PiHarnessSession = class {
19985
20629
  #requestedModel;
19986
20630
  #requestedThinkingOptionId;
19987
20631
  #toolOutputLimit;
20632
+ #isFastSupported;
19988
20633
  #acceptingTurn = false;
19989
20634
  #active = null;
19990
20635
  #closePromise = null;
@@ -20006,6 +20651,7 @@ var PiHarnessSession = class {
20006
20651
  this.#requestedModel = options.model;
20007
20652
  this.#requestedThinkingOptionId = options.thinkingOptionId;
20008
20653
  this.#toolOutputLimit = options.toolOutputLimit;
20654
+ this.#isFastSupported = options.isFastSupported;
20009
20655
  this.capabilities = {
20010
20656
  configuration: {
20011
20657
  selectModel: true,
@@ -20034,13 +20680,13 @@ var PiHarnessSession = class {
20034
20680
  return this.#transport?.state.sessionId === id;
20035
20681
  }
20036
20682
  async readSubagentHistory(cwd) {
20037
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20683
+ if (this.#phase !== "open" || path13.resolve(cwd) !== path13.resolve(this.#cwd)) {
20038
20684
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
20039
20685
  }
20040
20686
  return (await this.#ensureTransport()).getEntries();
20041
20687
  }
20042
20688
  async inspectSubagent(id, cwd) {
20043
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20689
+ if (this.#phase !== "open" || path13.resolve(cwd) !== path13.resolve(this.#cwd)) {
20044
20690
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
20045
20691
  }
20046
20692
  const transport = await this.#ensureTransport();
@@ -20286,20 +20932,27 @@ var PiHarnessSession = class {
20286
20932
  error: invalidState("Pi Model selection requires a started Native Session")
20287
20933
  };
20288
20934
  }
20289
- let requested;
20290
- try {
20291
- requested = decodePiModelRef(command.model);
20292
- } catch (error51) {
20293
- return { ok: false, error: normalizedError(error51, "invalidRequest") };
20294
- }
20295
20935
  const previousModel = this.#state.effectiveModel;
20296
20936
  this.#configuring = true;
20297
20937
  try {
20938
+ let requested;
20939
+ try {
20940
+ requested = decodePiModelRef(command.model);
20941
+ if (requested.fast && !await this.#isFastSupported(command.model, transport))
20942
+ throw new Error("Fast is unavailable for this Pi Model");
20943
+ } catch (error51) {
20944
+ return { ok: false, error: normalizedError(error51, "invalidRequest") };
20945
+ }
20298
20946
  let state2;
20299
20947
  let thinkingLevels;
20300
20948
  try {
20301
- state2 = await transport.selectModel(requested);
20949
+ state2 = samePiModel(nativeModelFromState(transport.state), requested) ? transport.state : await transport.selectModel(requested);
20302
20950
  thinkingLevels = await transport.getAvailableThinkingLevels();
20951
+ if (requested.fast || state2.fast) {
20952
+ if (!transport.selectFastMode)
20953
+ throw new Error("Pi Fast extension is unavailable");
20954
+ state2 = await transport.selectFastMode(requested.fast === true);
20955
+ }
20303
20956
  this.#publishTransportState(state2, thinkingLevels);
20304
20957
  } catch (error51) {
20305
20958
  if (error51 instanceof PiRpcFaultError)
@@ -20436,7 +21089,7 @@ var PiHarnessSession = class {
20436
21089
  const transport = this.#transport;
20437
21090
  if (this.#phase === "open" && transport?.getCommands) {
20438
21091
  try {
20439
- this.#liveCommands = piLiveCommandCatalog(piCommandCatalog, await transport.getCommands());
21092
+ this.#liveCommands = piLiveCommandCatalog(piCommandCatalog, (await transport.getCommands()).filter((command) => command.name !== PI_FAST_COMMAND));
20440
21093
  } catch {
20441
21094
  }
20442
21095
  }
@@ -20583,6 +21236,11 @@ var PiHarnessSession = class {
20583
21236
  this.#publishTransportState(state2, thinkingLevels);
20584
21237
  throw new Error("Pi did not activate the requested create Model");
20585
21238
  }
21239
+ if (requested.fast) {
21240
+ if (!await this.#isFastSupported(this.#requestedModel, transport) || !transport.selectFastMode)
21241
+ throw new Error("Fast is unavailable for this Pi Model");
21242
+ state2 = await transport.selectFastMode(true);
21243
+ }
20586
21244
  }
20587
21245
  if (this.#requestedThinkingOptionId) {
20588
21246
  if (!thinkingLevels) {
@@ -20663,7 +21321,7 @@ var PiHarnessSession = class {
20663
21321
  }));
20664
21322
  return;
20665
21323
  }
20666
- const turnId = hostTurnIdSchema.parse(randomUUID5());
21324
+ const turnId = hostTurnIdSchema.parse(randomUUID6());
20667
21325
  let resolveCompletion = () => void 0;
20668
21326
  const completion = new Promise((resolve) => {
20669
21327
  resolveCompletion = resolve;
@@ -20825,7 +21483,7 @@ var PiHarnessSession = class {
20825
21483
  if (active.interactionByNativeId.has(request.requestId)) {
20826
21484
  throw new Error("Pi Interaction started more than once");
20827
21485
  }
20828
- const interactionId = hostInteractionIdSchema.parse(randomUUID5());
21486
+ const interactionId = hostInteractionIdSchema.parse(randomUUID6());
20829
21487
  const question = request.method === "select" ? {
20830
21488
  id: "answer",
20831
21489
  type: "choice",
@@ -21172,7 +21830,7 @@ var PiHarnessSession = class {
21172
21830
  this.#channel.emit({ kind: "event", event });
21173
21831
  }
21174
21832
  #newItemId() {
21175
- return hostItemIdSchema.parse(randomUUID5());
21833
+ return hostItemIdSchema.parse(randomUUID6());
21176
21834
  }
21177
21835
  };
21178
21836
  var PiAdapter = class {
@@ -21263,6 +21921,7 @@ var PiAdapter = class {
21263
21921
  #inspections = /* @__PURE__ */ new Set();
21264
21922
  #sessions = /* @__PURE__ */ new Set();
21265
21923
  #toolOutputLimit;
21924
+ #environment;
21266
21925
  #closePromise = null;
21267
21926
  #thinkingSelectionSupported = null;
21268
21927
  constructor(options = {}, dependencies = {
@@ -21282,10 +21941,21 @@ var PiAdapter = class {
21282
21941
  remove: (name) => updateCatalog(imports.remove(name))
21283
21942
  };
21284
21943
  this.#createTransport = dependencies.createTransport;
21944
+ this.#environment = options.environment ?? process.env;
21285
21945
  this.#importIndex = new PiSessionImportIndex({ ...process.env, ...options.environment });
21286
21946
  this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
21287
21947
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
21288
21948
  }
21949
+ /** Pi itself holds no Account; this reports configured Provider balances. */
21950
+ async inspectAccounts() {
21951
+ if (this.#closePromise)
21952
+ return [];
21953
+ return fetchPiAccounts({ environment: this.#environment });
21954
+ }
21955
+ async inspectAccount() {
21956
+ const accounts = await this.inspectAccounts();
21957
+ return accounts[0] ?? null;
21958
+ }
21289
21959
  #readImport(operation) {
21290
21960
  if (this.#importAbort.signal.aborted)
21291
21961
  return Promise.resolve({ ok: false, error: invalidState("Pi Adapter is closed") });
@@ -21311,7 +21981,7 @@ var PiAdapter = class {
21311
21981
  }
21312
21982
  };
21313
21983
  }
21314
- const cwd = input.cwd ?? process.cwd();
21984
+ const cwd = resolvePiInspectCwd(input.cwd);
21315
21985
  const inFlight = this.#inspectionInFlight.get(cwd);
21316
21986
  if (inFlight)
21317
21987
  return inFlight;
@@ -21345,7 +22015,9 @@ var PiAdapter = class {
21345
22015
  stage = "capabilities";
21346
22016
  const thinkingLevels = await transport.getAvailableThinkingLevels();
21347
22017
  this.#thinkingSelectionSupported = thinkingLevels !== null;
21348
- const catalog = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel);
22018
+ const normalized = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel);
22019
+ const fastModels = await transport.supportsFastMode?.() ? await piFastModelKeys(models, this.#environment) : /* @__PURE__ */ new Set();
22020
+ const catalog = withPiFast(normalized, fastModels);
21349
22021
  await transport.close();
21350
22022
  return {
21351
22023
  status: "ready",
@@ -21382,6 +22054,27 @@ var PiAdapter = class {
21382
22054
  if (this.#closePromise) {
21383
22055
  return { ok: false, error: invalidState("Pi Adapter is closed") };
21384
22056
  }
22057
+ if ("model" in input && input.model) {
22058
+ let model;
22059
+ try {
22060
+ model = decodePiModelRef(input.model);
22061
+ } catch (error51) {
22062
+ return { ok: false, error: normalizedError(error51, "invalidRequest") };
22063
+ }
22064
+ if (model.fast) {
22065
+ if (!this.#isFastSupported(input.model, input.cwd))
22066
+ await this.inspect({ cwd: input.cwd });
22067
+ if (!this.#isFastSupported(input.model, input.cwd) && input.kind !== "resume")
22068
+ return {
22069
+ ok: false,
22070
+ error: {
22071
+ code: "unsupported",
22072
+ message: "Fast is unavailable for this Pi Model",
22073
+ retryable: false
22074
+ }
22075
+ };
22076
+ }
22077
+ }
21385
22078
  if (input.cwd.length === 0) {
21386
22079
  return {
21387
22080
  ok: false,
@@ -21552,6 +22245,11 @@ var PiAdapter = class {
21552
22245
  await transport.verifySessionCwd(input.cwd);
21553
22246
  }
21554
22247
  }
22248
+ if (input.kind === "resume" && input.model && this.#isFastSupported(input.model, input.cwd) && decodePiModelRef(input.model).fast && samePiModel(nativeModelFromState(transport.state), decodePiModelRef(input.model))) {
22249
+ if (!transport.selectFastMode)
22250
+ throw new Error("Pi Fast extension is unavailable");
22251
+ await transport.selectFastMode(true);
22252
+ }
21555
22253
  const startedThinkingLevels = await transport.getAvailableThinkingLevels();
21556
22254
  this.#thinkingSelectionSupported = startedThinkingLevels !== null;
21557
22255
  const initialUsage = await transport.getSessionUsage().catch(() => null);
@@ -21568,6 +22266,9 @@ var PiAdapter = class {
21568
22266
  return { ok: false, error: normalizedError(error51, "nativeFailure") };
21569
22267
  }
21570
22268
  }
22269
+ #isFastSupported(ref, cwd) {
22270
+ return this.#inspectionCache.get(cwd)?.catalog.models.some((model) => model.fastModel?.id === ref.id) ?? false;
22271
+ }
21571
22272
  #trackSession(cwd, options) {
21572
22273
  const environment = options.environment;
21573
22274
  const createTransport = environment ? (input) => this.#createTransport({ ...input, environment }) : this.#createTransport;
@@ -21579,6 +22280,14 @@ var PiAdapter = class {
21579
22280
  ...options.thinkingOptionId ? { thinkingOptionId: options.thinkingOptionId } : {},
21580
22281
  toolOutputLimit: this.#toolOutputLimit,
21581
22282
  supportsThinkingSelection: options.supportsThinkingSelection,
22283
+ isFastSupported: async (ref, transport) => {
22284
+ if (this.#inspectionCache.has(cwd))
22285
+ return this.#isFastSupported(ref, cwd);
22286
+ if (!await transport.supportsFastMode?.())
22287
+ return false;
22288
+ const fastModels = await piFastModelKeys(await transport.getAvailableModels(), environment ?? this.#environment);
22289
+ return fastModels.has(encodePiModelRef({ ...decodePiModelRef(ref), fast: false }).id);
22290
+ },
21582
22291
  ...options.startedTransport ? { startedTransport: options.startedTransport } : {},
21583
22292
  ...options.startedThinkingLevels !== void 0 ? { startedThinkingLevels: options.startedThinkingLevels } : {},
21584
22293
  ...options.initialUsage !== void 0 ? { initialUsage: options.initialUsage } : {}
@@ -21599,13 +22308,42 @@ var PiAdapter = class {
21599
22308
  }
21600
22309
  };
21601
22310
 
22311
+ // dist/installation.js
22312
+ var PI_LATEST_VERSION_URL = "https://pi.dev/api/latest-version";
22313
+ function createPiInstallation(environment, command) {
22314
+ const run = (args, timeout) => runInstallationCommand(resolvePiExecutable({ environment, ...command ? { command } : {} }), args, environment, timeout);
22315
+ return createInstallationManager({
22316
+ async check() {
22317
+ const currentVersion = versionFromOutput(await run(["--version"]));
22318
+ const payload = JSON.parse(await fetchInstallationText(PI_LATEST_VERSION_URL));
22319
+ const latestVersion = installationVersion(payload.version);
22320
+ return {
22321
+ currentVersion,
22322
+ latestVersion,
22323
+ updateAvailable: newerInstallationVersion(currentVersion, latestVersion),
22324
+ canUpdate: true
22325
+ };
22326
+ },
22327
+ async update() {
22328
+ await run(["update"], 3e5);
22329
+ }
22330
+ });
22331
+ }
22332
+
21602
22333
  // dist/plugin.js
21603
22334
  var PI_COMMAND_ENV = "CODEXHOST_PI_COMMAND";
21604
22335
  function createHarnessAdapter(context) {
21605
22336
  const environment = { ...context.environment };
21606
- return new PiAdapter({
22337
+ return Object.assign(new PiAdapter({
21607
22338
  ...environment[PI_COMMAND_ENV] ? { command: environment[PI_COMMAND_ENV] } : {},
21608
22339
  environment
22340
+ }), {
22341
+ installation: createPiInstallation(environment, environment[PI_COMMAND_ENV]),
22342
+ install: createHarnessInstaller(environment, {
22343
+ posix: "https://pi.dev/install.sh",
22344
+ windows: "https://pi.dev/install.ps1",
22345
+ shell: "sh"
22346
+ })
21609
22347
  });
21610
22348
  }
21611
22349
  export {