@dotobokuri/fleet-console 1.57.2 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/cli.mjs +30 -5
  2. package/dist/client/assets/{_baseUniq-dvybACFL.js → _baseUniq-DJ4C0UQF.js} +1 -1
  3. package/dist/client/assets/{arc-BM1EQJ5i.js → arc-DkQKttnC.js} +1 -1
  4. package/dist/client/assets/{architectureDiagram-Q4EWVU46-C5NpB_9B.js → architectureDiagram-Q4EWVU46-BpuET3uK.js} +1 -1
  5. package/dist/client/assets/{blockDiagram-DXYQGD6D-BemCHdjP.js → blockDiagram-DXYQGD6D-CatlulZp.js} +1 -1
  6. package/dist/client/assets/{c4Diagram-AHTNJAMY-BB7Qe4id.js → c4Diagram-AHTNJAMY-BPfWevDh.js} +1 -1
  7. package/dist/client/assets/channel-DDcyY5eB.js +1 -0
  8. package/dist/client/assets/{chunk-4BX2VUAB-CqmbYj1h.js → chunk-4BX2VUAB-a7lkla2P.js} +1 -1
  9. package/dist/client/assets/{chunk-4TB4RGXK-DY8csFL8.js → chunk-4TB4RGXK-Bh-20OVN.js} +1 -1
  10. package/dist/client/assets/{chunk-55IACEB6-Bc2JNsBB.js → chunk-55IACEB6-DiPm-_AS.js} +1 -1
  11. package/dist/client/assets/{chunk-EDXVE4YY-B7fkHilr.js → chunk-EDXVE4YY-BcGep4mz.js} +1 -1
  12. package/dist/client/assets/{chunk-FMBD7UC4-CKS1kchI.js → chunk-FMBD7UC4-Cn0A6Wm1.js} +1 -1
  13. package/dist/client/assets/{chunk-OYMX7WX6-BoSMhV9B.js → chunk-OYMX7WX6-DNTIDjw4.js} +1 -1
  14. package/dist/client/assets/{chunk-QZHKN3VN-B6NI5Nv8.js → chunk-QZHKN3VN-cji_BhbG.js} +1 -1
  15. package/dist/client/assets/{chunk-YZCP3GAM-DDwSQ8RI.js → chunk-YZCP3GAM-B6I5kLlB.js} +1 -1
  16. package/dist/client/assets/classDiagram-6PBFFD2Q-CqqUqRwS.js +1 -0
  17. package/dist/client/assets/classDiagram-v2-HSJHXN6E-CqqUqRwS.js +1 -0
  18. package/dist/client/assets/clone-CjMEm_X8.js +1 -0
  19. package/dist/client/assets/{cose-bilkent-S5V4N54A-VjTSxeFA.js → cose-bilkent-S5V4N54A-_Xmui3Dj.js} +1 -1
  20. package/dist/client/assets/{dagre-KV5264BT-BQSQIPKP.js → dagre-KV5264BT-BI_m6tGN.js} +1 -1
  21. package/dist/client/assets/{diagram-5BDNPKRD-C6e_Ovvo.js → diagram-5BDNPKRD-JDBqcRRR.js} +1 -1
  22. package/dist/client/assets/{diagram-G4DWMVQ6-D6vqaIMN.js → diagram-G4DWMVQ6-CdIHKaZT.js} +1 -1
  23. package/dist/client/assets/{diagram-MMDJMWI5-DFxtu5Sa.js → diagram-MMDJMWI5-CULX6wM5.js} +1 -1
  24. package/dist/client/assets/{diagram-TYMM5635-BcYaszXB.js → diagram-TYMM5635-C1JXiI2W.js} +1 -1
  25. package/dist/client/assets/{erDiagram-SMLLAGMA-DLSCg-9y.js → erDiagram-SMLLAGMA-RJI8bZrW.js} +1 -1
  26. package/dist/client/assets/{flowDiagram-DWJPFMVM-_kx-OfzH.js → flowDiagram-DWJPFMVM-CSrF7U0E.js} +1 -1
  27. package/dist/client/assets/{ganttDiagram-T4ZO3ILL-DluEefPv.js → ganttDiagram-T4ZO3ILL-CHp3LObA.js} +1 -1
  28. package/dist/client/assets/{gitGraphDiagram-UUTBAWPF-BDHypYJk.js → gitGraphDiagram-UUTBAWPF-BEeoTjqh.js} +1 -1
  29. package/dist/client/assets/{graph-CHPq19s3.js → graph-DNvMdh3j.js} +1 -1
  30. package/dist/client/assets/index-BG857Idy.css +1 -0
  31. package/dist/client/assets/index-CCNdSGui.js +483 -0
  32. package/dist/client/assets/{infoDiagram-42DDH7IO-BhntKSlv.js → infoDiagram-42DDH7IO-31kh8JMu.js} +1 -1
  33. package/dist/client/assets/{ishikawaDiagram-UXIWVN3A-Vo0lWYeZ.js → ishikawaDiagram-UXIWVN3A-DZgEgolJ.js} +1 -1
  34. package/dist/client/assets/{journeyDiagram-VCZTEJTY-B-jydfQ3.js → journeyDiagram-VCZTEJTY-DfZ3i3Bu.js} +1 -1
  35. package/dist/client/assets/{kanban-definition-6JOO6SKY-CR7_O2tt.js → kanban-definition-6JOO6SKY-giivFfnv.js} +1 -1
  36. package/dist/client/assets/{layout-C7qyIJFE.js → layout-DdVRNrH8.js} +1 -1
  37. package/dist/client/assets/{linear-ClKfz3Xw.js → linear-3cmeYdGh.js} +1 -1
  38. package/dist/client/assets/{mermaid.core-eHgX1dDu.js → mermaid.core-Cjqy_Y5Z.js} +4 -4
  39. package/dist/client/assets/{min-CBcfPH4t.js → min-Cgsd0one.js} +1 -1
  40. package/dist/client/assets/{mindmap-definition-QFDTVHPH-BrjeA0rz.js → mindmap-definition-QFDTVHPH-PfuGubxC.js} +1 -1
  41. package/dist/client/assets/{pieDiagram-DEJITSTG-Bx3gB3ns.js → pieDiagram-DEJITSTG-B9O6H439.js} +1 -1
  42. package/dist/client/assets/{quadrantDiagram-34T5L4WZ-Y_8L8YCa.js → quadrantDiagram-34T5L4WZ-DJH7RQzs.js} +1 -1
  43. package/dist/client/assets/{requirementDiagram-MS252O5E-BByFdhc4.js → requirementDiagram-MS252O5E-BZHTYV2q.js} +1 -1
  44. package/dist/client/assets/{sankeyDiagram-XADWPNL6-Du7m7fuy.js → sankeyDiagram-XADWPNL6-B5aGVyLG.js} +1 -1
  45. package/dist/client/assets/{sequenceDiagram-FGHM5R23-DovViawI.js → sequenceDiagram-FGHM5R23-D2890FYU.js} +1 -1
  46. package/dist/client/assets/{stateDiagram-FHFEXIEX-7fVJHvbx.js → stateDiagram-FHFEXIEX-DWmhZMWZ.js} +1 -1
  47. package/dist/client/assets/stateDiagram-v2-QKLJ7IA2-DoQKtZ4H.js +1 -0
  48. package/dist/client/assets/{timeline-definition-GMOUNBTQ-Dgsxq4-O.js → timeline-definition-GMOUNBTQ-B0pTOfcD.js} +1 -1
  49. package/dist/client/assets/{vennDiagram-DHZGUBPP-D2tu5aMx.js → vennDiagram-DHZGUBPP-D-S4XLnE.js} +1 -1
  50. package/dist/client/assets/{wardley-RL74JXVD-C4IVs_k4.js → wardley-RL74JXVD-ClPA8Fc3.js} +1 -1
  51. package/dist/client/assets/{wardleyDiagram-NUSXRM2D-DCVn_9G_.js → wardleyDiagram-NUSXRM2D-JJgj7CxJ.js} +1 -1
  52. package/dist/client/assets/{xychartDiagram-5P7HB3ND-D1TZkyWh.js → xychartDiagram-5P7HB3ND-BBIy9-Kq.js} +1 -1
  53. package/dist/client/index.html +2 -2
  54. package/dist/fleet-plugins/ledger/routes.mjs +35 -0
  55. package/dist/fleet-plugins/quota/routes.mjs +422 -61
  56. package/dist/fleet-plugins/scuttlebutt/routes.mjs +30 -5
  57. package/dist/fleet-plugins/terminal/routes.mjs +1317 -541
  58. package/dist/fleet.mjs +1541 -674
  59. package/package.json +1 -1
  60. package/dist/client/assets/channel-t207uO3V.js +0 -1
  61. package/dist/client/assets/classDiagram-6PBFFD2Q-Dg0z8qFh.js +0 -1
  62. package/dist/client/assets/classDiagram-v2-HSJHXN6E-Dg0z8qFh.js +0 -1
  63. package/dist/client/assets/clone-B47TzRxK.js +0 -1
  64. package/dist/client/assets/index-D6_LDhkV.css +0 -1
  65. package/dist/client/assets/index-DeiAnv0J.js +0 -483
  66. package/dist/client/assets/stateDiagram-v2-QKLJ7IA2-CQPjJLLI.js +0 -1
package/dist/fleet.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import * as os3 from 'node:os';
3
3
  import os3__default, { tmpdir } from 'node:os';
4
- import * as path23 from 'node:path';
5
- import path23__default, { join, dirname, resolve, relative, sep } from 'node:path';
4
+ import * as path24 from 'node:path';
5
+ import path24__default, { join, dirname, resolve, relative, sep } from 'node:path';
6
6
  import * as fs9 from 'node:fs';
7
7
  import fs9__default, { constants, mkdirSync, mkdtempSync, writeFileSync, rmSync, chmodSync, renameSync, readdirSync, appendFileSync, lstatSync, existsSync, realpathSync, statSync, accessSync, openSync, closeSync, readFileSync } from 'node:fs';
8
8
  import crypto9, { randomUUID, createHash } from 'node:crypto';
@@ -10,7 +10,7 @@ import http from 'node:http';
10
10
  import { execFile, spawn, execFileSync } from 'node:child_process';
11
11
  import { builtinModules, createRequire } from 'node:module';
12
12
  import { fileURLToPath, pathToFileURL } from 'node:url';
13
- import fs7, { appendFile, chmod, mkdtemp, rm, mkdir, readdir, readFile, stat, writeFile, realpath, lstat, rename, unlink } from 'node:fs/promises';
13
+ import fs32, { appendFile, chmod, mkdtemp, rm, mkdir, readdir, readFile, stat, writeFile, realpath, lstat, rename, unlink } from 'node:fs/promises';
14
14
  import { promisify, styleText } from 'node:util';
15
15
  import http2 from 'node:http2';
16
16
  import V2, { stdin, stdout } from 'node:process';
@@ -57,8 +57,8 @@ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__
57
57
  ));
58
58
  function getFleetDataDir(env = process.env) {
59
59
  const override = env[FLEET_DATA_DIR_ENV];
60
- if (override === void 0 || override.trim().length === 0) return path23.join(os3.homedir(), FLEET_DATA_DIR_NAME);
61
- if (!path23.isAbsolute(override)) throw new Error(`${FLEET_DATA_DIR_ENV} must be an absolute path, received: ${override}`);
60
+ if (override === void 0 || override.trim().length === 0) return path24.join(os3.homedir(), FLEET_DATA_DIR_NAME);
61
+ if (!path24.isAbsolute(override)) throw new Error(`${FLEET_DATA_DIR_ENV} must be an absolute path, received: ${override}`);
62
62
  return override;
63
63
  }
64
64
  var FLEET_DATA_DIR_NAME, FLEET_DATA_DIR_ENV;
@@ -109,7 +109,7 @@ function createChildEnv(env, overlay) {
109
109
  return child;
110
110
  }
111
111
  function wrapWindowsShim(resolved, env, platform) {
112
- if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path23__default.extname(resolved).toLowerCase())) {
112
+ if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path24__default.extname(resolved).toLowerCase())) {
113
113
  return { bin: resolved, prefixArgs: [] };
114
114
  }
115
115
  rejectCmdExpansionSensitiveShim(resolved);
@@ -127,13 +127,13 @@ function forceWindowsArgQuoting(value) {
127
127
  return `${value} `;
128
128
  }
129
129
  function findOnPath(bin, pathValue, pathExts, platform) {
130
- const pathSeparator = platform === "win32" ? WINDOWS_PATH_SEPARATOR : path23__default.delimiter;
131
- if (hasPathSeparator(bin, platform) || path23__default.isAbsolute(bin)) {
130
+ const pathSeparator = platform === "win32" ? WINDOWS_PATH_SEPARATOR : path24__default.delimiter;
131
+ if (hasPathSeparator(bin, platform) || path24__default.isAbsolute(bin)) {
132
132
  return resolveWithExtensions(bin, pathExts, platform);
133
133
  }
134
134
  for (const entry of pathValue.split(pathSeparator)) {
135
135
  const searchDir = entry.length === 0 ? "." : entry;
136
- const candidate = resolveWithExtensions(path23__default.join(searchDir, bin), pathExts, platform);
136
+ const candidate = resolveWithExtensions(path24__default.join(searchDir, bin), pathExts, platform);
137
137
  if (candidate) {
138
138
  return candidate;
139
139
  }
@@ -141,7 +141,7 @@ function findOnPath(bin, pathValue, pathExts, platform) {
141
141
  return void 0;
142
142
  }
143
143
  function resolveWithExtensions(candidate, pathExts, platform) {
144
- if (platform !== "win32" || path23__default.extname(candidate).length > 0) {
144
+ if (platform !== "win32" || path24__default.extname(candidate).length > 0) {
145
145
  return isAccessibleExecutable(candidate, platform) ? candidate : void 0;
146
146
  }
147
147
  for (const ext of pathExts) {
@@ -1306,7 +1306,7 @@ function formatInstallCommand(packageNames, command2, versionOrChannel) {
1306
1306
  return `${command2} i -g ${packageNames.map((name) => `${name}@${versionOrChannel}`).join(" ")}`;
1307
1307
  }
1308
1308
  function isPathInside(deps, child, parent) {
1309
- const separator = deps.platform === "win32" ? "\\" : path23__default.sep;
1309
+ const separator = deps.platform === "win32" ? "\\" : path24__default.sep;
1310
1310
  return child === parent || child.startsWith(`${parent}${separator}`);
1311
1311
  }
1312
1312
  function normalizeExistingPath(deps, value) {
@@ -1321,10 +1321,10 @@ function normalizePath(deps, value) {
1321
1321
  return deps.platform === "win32" ? resolved.toLowerCase() : resolved;
1322
1322
  }
1323
1323
  function resolvePathForPlatform(platform, value) {
1324
- return platform === "win32" ? path23__default.win32.resolve(value) : path23__default.resolve(value);
1324
+ return platform === "win32" ? path24__default.win32.resolve(value) : path24__default.resolve(value);
1325
1325
  }
1326
1326
  function joinPathForPlatform(platform, ...parts) {
1327
- return platform === "win32" ? path23__default.win32.join(...parts) : path23__default.join(...parts);
1327
+ return platform === "win32" ? path24__default.win32.join(...parts) : path24__default.join(...parts);
1328
1328
  }
1329
1329
  function defaultExecFile(file2, args) {
1330
1330
  return execFileSync(file2, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
@@ -1474,7 +1474,7 @@ function writeCachedLatestVersion(channel, latest) {
1474
1474
  }
1475
1475
  }
1476
1476
  function getUpdateCachePath() {
1477
- return path23__default.join(getFleetDataDir(), UPDATE_CACHE_FILENAME);
1477
+ return path24__default.join(getFleetDataDir(), UPDATE_CACHE_FILENAME);
1478
1478
  }
1479
1479
  var UPDATE_CACHE_TTL_MS, UPDATE_CACHE_FILENAME;
1480
1480
  var init_cache = __esm({
@@ -1549,23 +1549,23 @@ async function stopRunningConsoleBeforeUpdate(io, deps = {}) {
1549
1549
  }
1550
1550
  function resolveSiblingConsoleCliPath(moduleUrl = import.meta.url) {
1551
1551
  try {
1552
- const start = path23__default.dirname(fileURLToPath(moduleUrl));
1552
+ const start = path24__default.dirname(fileURLToPath(moduleUrl));
1553
1553
  let dir = start;
1554
1554
  for (let i = 0; i < 8; i += 1) {
1555
- const packageJsonPath = path23__default.join(dir, "package.json");
1555
+ const packageJsonPath = path24__default.join(dir, "package.json");
1556
1556
  if (fs9__default.existsSync(packageJsonPath)) {
1557
1557
  const pkg = JSON.parse(fs9__default.readFileSync(packageJsonPath, "utf8"));
1558
1558
  if (pkg.name === CONSOLE_PACKAGE_NAME) {
1559
- const candidate = path23__default.join(dir, "dist", "cli.mjs");
1559
+ const candidate = path24__default.join(dir, "dist", "cli.mjs");
1560
1560
  return fs9__default.existsSync(candidate) ? candidate : void 0;
1561
1561
  }
1562
1562
  }
1563
- const parent = path23__default.dirname(dir);
1563
+ const parent = path24__default.dirname(dir);
1564
1564
  if (parent === dir) break;
1565
1565
  dir = parent;
1566
1566
  }
1567
- const sameDir = path23__default.join(start, "cli.mjs");
1568
- if (path23__default.basename(start) === "dist" && fs9__default.existsSync(sameDir)) return sameDir;
1567
+ const sameDir = path24__default.join(start, "cli.mjs");
1568
+ if (path24__default.basename(start) === "dist" && fs9__default.existsSync(sameDir)) return sameDir;
1569
1569
  } catch {
1570
1570
  }
1571
1571
  return void 0;
@@ -1694,7 +1694,7 @@ function getCurrentPackageRoot() {
1694
1694
  const packageJsonPath = requireFromHere.resolve(candidate);
1695
1695
  const pkg = requireFromHere(packageJsonPath);
1696
1696
  if (pkg.name === FLEET_CONSOLE_PACKAGE_NAME3) {
1697
- return realpathSync(path23__default.dirname(packageJsonPath));
1697
+ return realpathSync(path24__default.dirname(packageJsonPath));
1698
1698
  }
1699
1699
  } catch {
1700
1700
  }
@@ -1819,9 +1819,9 @@ function ensureSafeDirectory(dirPath) {
1819
1819
  fs9.chmodSync(dirPath, SECURE_DIR_MODE);
1820
1820
  }
1821
1821
  function assertWithinRoot(root, candidatePath) {
1822
- const resolvedRoot = path23.resolve(root);
1823
- const resolvedCandidate = path23.resolve(candidatePath);
1824
- if (!resolvedCandidate.startsWith(`${resolvedRoot}${path23.sep}`) && resolvedCandidate !== resolvedRoot) {
1822
+ const resolvedRoot = path24.resolve(root);
1823
+ const resolvedCandidate = path24.resolve(candidatePath);
1824
+ if (!resolvedCandidate.startsWith(`${resolvedRoot}${path24.sep}`) && resolvedCandidate !== resolvedRoot) {
1825
1825
  throw new Error(`Path escapes root: ${candidatePath}`);
1826
1826
  }
1827
1827
  }
@@ -1882,7 +1882,7 @@ function cleanupTempFiles(dir, prefix, minAgeMs, now) {
1882
1882
  if (!entry.startsWith(prefix)) {
1883
1883
  continue;
1884
1884
  }
1885
- const tempPath = path23.join(dir, entry);
1885
+ const tempPath = path24.join(dir, entry);
1886
1886
  try {
1887
1887
  const stat5 = fs9.lstatSync(tempPath);
1888
1888
  if (stat5?.isFile() && !stat5.isSymbolicLink() && now - stat5.mtimeMs >= minAgeMs) {
@@ -1988,7 +1988,7 @@ function writeLockOwner(lockDir, ownerFileName, startedAt) {
1988
1988
  hostname: os3.hostname(),
1989
1989
  startedAt
1990
1990
  };
1991
- const ownerPath = path23.join(lockDir, ownerFileName);
1991
+ const ownerPath = path24.join(lockDir, ownerFileName);
1992
1992
  try {
1993
1993
  fs9.writeFileSync(ownerPath, JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
1994
1994
  } catch (error51) {
@@ -1997,7 +1997,7 @@ function writeLockOwner(lockDir, ownerFileName, startedAt) {
1997
1997
  }
1998
1998
  }
1999
1999
  function readLockOwner(lockDir, ownerFileName) {
2000
- const ownerPath = path23.join(lockDir, ownerFileName);
2000
+ const ownerPath = path24.join(lockDir, ownerFileName);
2001
2001
  try {
2002
2002
  return sanitizeLockOwner(JSON.parse(fs9.readFileSync(ownerPath, "utf-8")));
2003
2003
  } catch (error51) {
@@ -2037,10 +2037,10 @@ function isProcessAlive(pid) {
2037
2037
  }
2038
2038
  function sanitizeLockOwner(value) {
2039
2039
  if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
2040
- const record5 = value;
2041
- const pid = record5.pid;
2042
- const hostname5 = record5.hostname;
2043
- const startedAt = record5.startedAt;
2040
+ const record6 = value;
2041
+ const pid = record6.pid;
2042
+ const hostname5 = record6.hostname;
2043
+ const startedAt = record6.startedAt;
2044
2044
  if (!Number.isInteger(pid) || pid <= 0) return null;
2045
2045
  if (typeof hostname5 !== "string" || !hostname5) return null;
2046
2046
  if (!Number.isFinite(startedAt) || startedAt <= 0) return null;
@@ -2055,7 +2055,7 @@ function sleepSync(ms) {
2055
2055
  }
2056
2056
 
2057
2057
  // ../../packages/core-infra/src/auth/auth-storage.ts
2058
- var DEFAULT_AUTH_PATH = path23.join(getFleetDataDir(), "auth.json");
2058
+ var DEFAULT_AUTH_PATH = path24.join(getFleetDataDir(), "auth.json");
2059
2059
  var AUTH_LOCK_OWNER_FILE_NAME = "owner.json";
2060
2060
  var AUTH_LOCK_TIMEOUT_MS = 5e3;
2061
2061
  function readAuthStoreFile(filePath) {
@@ -2130,7 +2130,7 @@ function createAuthService(deps = {}) {
2130
2130
  }
2131
2131
  },
2132
2132
  async setApiKey(providerId, key) {
2133
- const dir = path23.dirname(authPath);
2133
+ const dir = path24.dirname(authPath);
2134
2134
  ensureSafeDirectory(dir);
2135
2135
  withAuthLock(authPath, lockDir, () => {
2136
2136
  const data = fs9.existsSync(authPath) ? readAuthStoreFile(authPath) : {};
@@ -2169,7 +2169,7 @@ function createDurableJsonStore(deps) {
2169
2169
  const sensitivity = deps.sensitivity;
2170
2170
  const mode = sensitivity === "sensitive" ? SECURE_FILE_MODE : 420;
2171
2171
  const minAgeMs = deps.tempCleanupMinAgeMs ?? DEFAULT_TEMP_FILE_MIN_AGE_MS;
2172
- const dir = path23.dirname(deps.filePath);
2172
+ const dir = path24.dirname(deps.filePath);
2173
2173
  return {
2174
2174
  path: deps.filePath,
2175
2175
  load() {
@@ -2269,8 +2269,8 @@ function updateGlobalOptions(store, mutate) {
2269
2269
  }
2270
2270
  function createGlobalOptionsStore(deps = {}) {
2271
2271
  const dataDir = deps.dataDir ?? getFleetDataDir();
2272
- const optionsPath = path23.join(dataDir, GLOBAL_OPTIONS_FILE_NAME);
2273
- const lockDir = path23.join(dataDir, LOCK_DIR_NAME);
2272
+ const optionsPath = path24.join(dataDir, GLOBAL_OPTIONS_FILE_NAME);
2273
+ const lockDir = path24.join(dataDir, LOCK_DIR_NAME);
2274
2274
  const store = createDurableJsonStore({
2275
2275
  filePath: optionsPath,
2276
2276
  lockDir,
@@ -2416,7 +2416,7 @@ function getWorkspaceDirectoryRoot(dataDir) {
2416
2416
  if (!dataDir.trim()) {
2417
2417
  throw new Error("Fleet data directory is required");
2418
2418
  }
2419
- return path23.join(path23.resolve(dataDir), WORKSPACES_DIRECTORY_NAME);
2419
+ return path24.join(path24.resolve(dataDir), WORKSPACES_DIRECTORY_NAME);
2420
2420
  }
2421
2421
  function resolveWorkspaceDirectory(dataDir, cwd) {
2422
2422
  const canonicalCwd = canonicalizeWorkspaceCwd(cwd);
@@ -2424,7 +2424,7 @@ function resolveWorkspaceDirectory(dataDir, cwd) {
2424
2424
  }
2425
2425
  function ensureWorkspaceDirectory(dataDir, cwd) {
2426
2426
  const workspace = resolveWorkspaceDirectory(dataDir, cwd);
2427
- const resolvedDataDir = path23.resolve(dataDir);
2427
+ const resolvedDataDir = path24.resolve(dataDir);
2428
2428
  ensureSafeDirectory(resolvedDataDir);
2429
2429
  ensureSafeDirectory(workspace.root);
2430
2430
  assertWithinRoot(workspace.root, workspace.path);
@@ -2449,11 +2449,11 @@ function ensureWorkspaceDirectory(dataDir, cwd) {
2449
2449
  function buildWorkspaceDirectory(dataDir, name, cwd) {
2450
2450
  assertWorkspaceDirectoryName(name);
2451
2451
  const root = getWorkspaceDirectoryRoot(dataDir);
2452
- const workspacePath = path23.join(root, name);
2452
+ const workspacePath = path24.join(root, name);
2453
2453
  assertWithinRoot(root, workspacePath);
2454
2454
  return {
2455
2455
  cwd,
2456
- identityPath: path23.join(workspacePath, WORKSPACE_IDENTITY_FILE_NAME),
2456
+ identityPath: path24.join(workspacePath, WORKSPACE_IDENTITY_FILE_NAME),
2457
2457
  name,
2458
2458
  path: workspacePath,
2459
2459
  root
@@ -2463,7 +2463,7 @@ function canonicalizeWorkspaceCwd(cwd) {
2463
2463
  if (!cwd.trim()) {
2464
2464
  throw new Error("Workspace cwd is required");
2465
2465
  }
2466
- return fs9.realpathSync.native(path23.resolve(cwd));
2466
+ return fs9.realpathSync.native(path24.resolve(cwd));
2467
2467
  }
2468
2468
  function assertWorkspaceDirectoryName(name) {
2469
2469
  if (!name || !WORKSPACE_NAME_PATTERN.test(name)) {
@@ -2489,8 +2489,8 @@ function readWorkspaceIdentity(identityPath) {
2489
2489
  }
2490
2490
  function isWorkspaceDirectoryIdentity(value) {
2491
2491
  if (typeof value !== "object" || value === null) return false;
2492
- const record5 = value;
2493
- return typeof record5.cwd === "string" && record5.cwd.length > 0;
2492
+ const record6 = value;
2493
+ return typeof record6.cwd === "string" && record6.cwd.length > 0;
2494
2494
  }
2495
2495
 
2496
2496
  // ../../packages/core-infra/src/index.ts
@@ -3265,10 +3265,10 @@ function mergeDefs(...defs) {
3265
3265
  function cloneDef(schema) {
3266
3266
  return mergeDefs(schema._zod.def);
3267
3267
  }
3268
- function getElementAtPath(obj, path57) {
3269
- if (!path57)
3268
+ function getElementAtPath(obj, path58) {
3269
+ if (!path58)
3270
3270
  return obj;
3271
- return path57.reduce((acc, key) => acc?.[key], obj);
3271
+ return path58.reduce((acc, key) => acc?.[key], obj);
3272
3272
  }
3273
3273
  function promiseAllObject(promisesObj) {
3274
3274
  const keys = Object.keys(promisesObj);
@@ -3677,11 +3677,11 @@ function explicitlyAborted(x3, startIndex = 0) {
3677
3677
  }
3678
3678
  return false;
3679
3679
  }
3680
- function prefixIssues(path57, issues) {
3680
+ function prefixIssues(path58, issues) {
3681
3681
  return issues.map((iss) => {
3682
3682
  var _a3;
3683
3683
  (_a3 = iss).path ?? (_a3.path = []);
3684
- iss.path.unshift(path57);
3684
+ iss.path.unshift(path58);
3685
3685
  return iss;
3686
3686
  });
3687
3687
  }
@@ -3828,16 +3828,16 @@ function flattenError(error51, mapper = (issue3) => issue3.message) {
3828
3828
  }
3829
3829
  function formatError(error51, mapper = (issue3) => issue3.message) {
3830
3830
  const fieldErrors = { _errors: [] };
3831
- const processError = (error52, path57 = []) => {
3831
+ const processError = (error52, path58 = []) => {
3832
3832
  for (const issue3 of error52.issues) {
3833
3833
  if (issue3.code === "invalid_union" && issue3.errors.length) {
3834
- issue3.errors.map((issues) => processError({ issues }, [...path57, ...issue3.path]));
3834
+ issue3.errors.map((issues) => processError({ issues }, [...path58, ...issue3.path]));
3835
3835
  } else if (issue3.code === "invalid_key") {
3836
- processError({ issues: issue3.issues }, [...path57, ...issue3.path]);
3836
+ processError({ issues: issue3.issues }, [...path58, ...issue3.path]);
3837
3837
  } else if (issue3.code === "invalid_element") {
3838
- processError({ issues: issue3.issues }, [...path57, ...issue3.path]);
3838
+ processError({ issues: issue3.issues }, [...path58, ...issue3.path]);
3839
3839
  } else {
3840
- const fullpath = [...path57, ...issue3.path];
3840
+ const fullpath = [...path58, ...issue3.path];
3841
3841
  if (fullpath.length === 0) {
3842
3842
  fieldErrors._errors.push(mapper(issue3));
3843
3843
  } else {
@@ -3864,17 +3864,17 @@ function formatError(error51, mapper = (issue3) => issue3.message) {
3864
3864
  }
3865
3865
  function treeifyError(error51, mapper = (issue3) => issue3.message) {
3866
3866
  const result = { errors: [] };
3867
- const processError = (error52, path57 = []) => {
3867
+ const processError = (error52, path58 = []) => {
3868
3868
  var _a3, _b;
3869
3869
  for (const issue3 of error52.issues) {
3870
3870
  if (issue3.code === "invalid_union" && issue3.errors.length) {
3871
- issue3.errors.map((issues) => processError({ issues }, [...path57, ...issue3.path]));
3871
+ issue3.errors.map((issues) => processError({ issues }, [...path58, ...issue3.path]));
3872
3872
  } else if (issue3.code === "invalid_key") {
3873
- processError({ issues: issue3.issues }, [...path57, ...issue3.path]);
3873
+ processError({ issues: issue3.issues }, [...path58, ...issue3.path]);
3874
3874
  } else if (issue3.code === "invalid_element") {
3875
- processError({ issues: issue3.issues }, [...path57, ...issue3.path]);
3875
+ processError({ issues: issue3.issues }, [...path58, ...issue3.path]);
3876
3876
  } else {
3877
- const fullpath = [...path57, ...issue3.path];
3877
+ const fullpath = [...path58, ...issue3.path];
3878
3878
  if (fullpath.length === 0) {
3879
3879
  result.errors.push(mapper(issue3));
3880
3880
  continue;
@@ -3906,8 +3906,8 @@ function treeifyError(error51, mapper = (issue3) => issue3.message) {
3906
3906
  }
3907
3907
  function toDotPath(_path) {
3908
3908
  const segs = [];
3909
- const path57 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3910
- for (const seg of path57) {
3909
+ const path58 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3910
+ for (const seg of path58) {
3911
3911
  if (typeof seg === "number")
3912
3912
  segs.push(`[${seg}]`);
3913
3913
  else if (typeof seg === "symbol")
@@ -16571,13 +16571,13 @@ function resolveRef(ref, ctx) {
16571
16571
  if (!ref.startsWith("#")) {
16572
16572
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
16573
16573
  }
16574
- const path57 = ref.slice(1).split("/").filter(Boolean);
16575
- if (path57.length === 0) {
16574
+ const path58 = ref.slice(1).split("/").filter(Boolean);
16575
+ if (path58.length === 0) {
16576
16576
  return ctx.rootSchema;
16577
16577
  }
16578
16578
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
16579
- if (path57[0] === defsKey) {
16580
- const key = path57[1];
16579
+ if (path58[0] === defsKey) {
16580
+ const key = path58[1];
16581
16581
  if (!key || !ctx.defs[key]) {
16582
16582
  throw new Error(`Reference not found: ${ref}`);
16583
16583
  }
@@ -19979,8 +19979,8 @@ function bootEnumDescriptorProto(init) {
19979
19979
  }
19980
19980
 
19981
19981
  // ../../node_modules/.pnpm/@bufbuild+protobuf@2.13.0/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/message.js
19982
- function messageDesc(file2, path57, ...paths) {
19983
- return paths.reduce((acc, cur) => acc.nestedMessages[cur], file2.messages[path57]);
19982
+ function messageDesc(file2, path58, ...paths) {
19983
+ return paths.reduce((acc, cur) => acc.nestedMessages[cur], file2.messages[path58]);
19984
19984
  }
19985
19985
 
19986
19986
  // ../../node_modules/.pnpm/@bufbuild+protobuf@2.13.0/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/descriptor_pb.js
@@ -21378,11 +21378,11 @@ function fieldMaskFromJson(fieldMask, json3) {
21378
21378
  if (json3 === "") {
21379
21379
  return;
21380
21380
  }
21381
- fieldMask.paths = json3.split(",").map((path57) => {
21382
- if (path57.includes("_")) {
21381
+ fieldMask.paths = json3.split(",").map((path58) => {
21382
+ if (path58.includes("_")) {
21383
21383
  throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
21384
21384
  }
21385
- return protoSnakeCase(path57);
21385
+ return protoSnakeCase(path58);
21386
21386
  });
21387
21387
  }
21388
21388
  function structFromJson(struct, json3, ctx) {
@@ -21744,17 +21744,17 @@ function projectAnthropicUsageEnvelope(value, contextWindow, responseModel) {
21744
21744
  return { changed, value: projectedValue };
21745
21745
  }
21746
21746
  function projectUsageProperty(container, property, contextWindow) {
21747
- const usage3 = container[property];
21748
- if (!isRecord2(usage3)) return { changed: false, value: container };
21747
+ const usage4 = container[property];
21748
+ if (!isRecord2(usage4)) return { changed: false, value: container };
21749
21749
  const coordinates = ANTHROPIC_INPUT_USAGE_FIELDS.map((field) => {
21750
- const tokens = usage3[field];
21750
+ const tokens = usage4[field];
21751
21751
  return typeof tokens === "number" && Number.isFinite(tokens) && tokens >= 0 ? { field, tokens } : void 0;
21752
21752
  }).filter((entry) => entry !== void 0);
21753
21753
  if (coordinates.length === 0) return { changed: false, value: container };
21754
21754
  const total = coordinates.reduce((sum, entry) => sum + entry.tokens, 0);
21755
21755
  const projectedTotal = projectClaudeContextInputTokens(total, contextWindow);
21756
21756
  if (projectedTotal === total) return { changed: false, value: container };
21757
- const projectedUsage = { ...usage3 };
21757
+ const projectedUsage = { ...usage4 };
21758
21758
  const remainderField = coordinates.some((entry) => entry.field === "input_tokens") ? "input_tokens" : coordinates[0].field;
21759
21759
  let assigned = 0;
21760
21760
  for (const entry of coordinates) {
@@ -21901,6 +21901,39 @@ function removeClaudeSkillListingEntries(text, withheld, delisted) {
21901
21901
  function withheldClaudeSkillStub(name, tokens, budget) {
21902
21902
  return `[Fleet AI gateway withheld the "${name}" skill: its body is about ${tokens} tokens, over the ${budget}-token ceiling one skill may take from this model's context window. Read the skill's own files if you need it, or run this work on a model with a larger window.]`;
21903
21903
  }
21904
+ var CLAUDE_WEB_SEARCH_TOOL_NAME = "WebSearch";
21905
+ var ANTHROPIC_WEB_SEARCH_TOOL_NAME = "web_search";
21906
+ var ANTHROPIC_WEB_SEARCH_TOOL_TYPE = "web_search_20250305";
21907
+ function isClaudeWebSearchTool(tool) {
21908
+ return tool.type === ANTHROPIC_WEB_SEARCH_TOOL_TYPE || tool.name === CLAUDE_WEB_SEARCH_TOOL_NAME || tool.name === ANTHROPIC_WEB_SEARCH_TOOL_NAME;
21909
+ }
21910
+ function isClaudeWebSearchToolChoice(choice) {
21911
+ return choice?.type === "tool" && (choice.name === CLAUDE_WEB_SEARCH_TOOL_NAME || choice.name === ANTHROPIC_WEB_SEARCH_TOOL_NAME);
21912
+ }
21913
+ function omitClaudeWebSearchTools(request) {
21914
+ const tools = request.tools;
21915
+ const kept = tools?.filter((tool) => !isClaudeWebSearchTool(tool));
21916
+ const toolsChanged = tools !== void 0 && kept !== void 0 && kept.length !== tools.length;
21917
+ const choice = request.tool_choice;
21918
+ const choiceChanged = isClaudeWebSearchToolChoice(choice);
21919
+ if (!toolsChanged && !choiceChanged) {
21920
+ return { request, changed: false };
21921
+ }
21922
+ const { tools: _tools, tool_choice: _toolChoice, ...rest } = request;
21923
+ return {
21924
+ request: {
21925
+ ...rest,
21926
+ ...toolsChanged ? kept.length === 0 ? {} : { tools: kept } : tools === void 0 ? {} : { tools },
21927
+ ...choiceChanged ? {
21928
+ tool_choice: {
21929
+ type: "auto",
21930
+ ...choice?.disable_parallel_tool_use === void 0 ? {} : { disable_parallel_tool_use: choice.disable_parallel_tool_use }
21931
+ }
21932
+ } : choice === void 0 ? {} : { tool_choice: choice }
21933
+ },
21934
+ changed: true
21935
+ };
21936
+ }
21904
21937
  var benchmarks_default = {
21905
21938
  version: 2,
21906
21939
  sources: {
@@ -22098,7 +22131,7 @@ var benchmarks_default = {
22098
22131
  };
22099
22132
  var models_default = {
22100
22133
  version: 1,
22101
- updatedAt: "2026-08-13T00:00:00Z",
22134
+ updatedAt: "2026-08-14T00:00:00Z",
22102
22135
  providers: {
22103
22136
  codex: {
22104
22137
  name: "Codex",
@@ -22483,13 +22516,37 @@ var models_default = {
22483
22516
  contextWindow: 256e3
22484
22517
  }
22485
22518
  ]
22519
+ },
22520
+ xai: {
22521
+ name: "xAI",
22522
+ defaultModel: "grok-4.6",
22523
+ source: "official Grok CLI 1.0.3 ~/.grok/models_cache.json from GET https://cli-chat-proxy.grok.com/v1/models (observed 2026-08-13)",
22524
+ models: [
22525
+ {
22526
+ modelId: "grok-4.6",
22527
+ name: "Grok-4.6",
22528
+ capabilityClass: "flagship",
22529
+ wire: "responses",
22530
+ contextWindow: 5e5,
22531
+ effort: {
22532
+ supported: true,
22533
+ levels: [
22534
+ "low",
22535
+ "medium",
22536
+ "high",
22537
+ "xhigh"
22538
+ ]
22539
+ },
22540
+ benchmarkKey: "grok-4.6"
22541
+ }
22542
+ ]
22486
22543
  }
22487
22544
  }
22488
22545
  };
22489
22546
  var KIMI_AUTH_PROVIDER_ID = "Claude Code with Moonshot Kimi";
22490
22547
  var KIMI_CODE_API_BASE_URL = "https://api.kimi.com/coding";
22491
22548
  var KIMI_CODE_MODEL = "k3";
22492
- var GATEWAY_PROVIDERS = ["codex", "cursor", "kimi", "opencode"];
22549
+ var GATEWAY_PROVIDERS = ["codex", "xai", "cursor", "opencode", "kimi"];
22493
22550
  var GATEWAY_MODEL_WIRES = ["anthropic", "responses", "chat-completions"];
22494
22551
  var GATEWAY_REASONING_EFFORTS = [
22495
22552
  "low",
@@ -22577,7 +22634,8 @@ var GatewayModelsRegistrySchema = external_exports.object({
22577
22634
  codex: GatewayProviderSchema,
22578
22635
  cursor: GatewayProviderSchema,
22579
22636
  kimi: GatewayProviderSchema,
22580
- opencode: GatewayProviderSchema
22637
+ opencode: GatewayProviderSchema,
22638
+ xai: GatewayProviderSchema
22581
22639
  }).strict()
22582
22640
  }).strict();
22583
22641
  var UNSUPPORTED_GATEWAY_MODEL_EFFORT = Object.freeze({ supported: false });
@@ -22842,8 +22900,8 @@ function validateRegistry(value) {
22842
22900
  if (model.quotaScope && provider !== "cursor") {
22843
22901
  throw new Error(`Gateway quota scope is only supported by Cursor: ${provider}/${model.modelId}`);
22844
22902
  }
22845
- if (model.wire && provider !== "opencode") {
22846
- throw new Error(`Gateway model wire is only supported by OpenCode: ${provider}/${model.modelId}`);
22903
+ if (model.wire && provider !== "opencode" && provider !== "xai") {
22904
+ throw new Error(`Gateway model wire is not supported by provider: ${provider}/${model.modelId}`);
22847
22905
  }
22848
22906
  if (model.effort?.supported) {
22849
22907
  if (new Set(model.effort.levels).size !== model.effort.levels.length) {
@@ -23298,14 +23356,14 @@ function nonNegativeCacheValue(value) {
23298
23356
  }
23299
23357
  return value;
23300
23358
  }
23301
- function anthropicUsageFromCanonical(usage3, advertisedContextWindow, options = {}) {
23359
+ function anthropicUsageFromCanonical(usage4, advertisedContextWindow, options = {}) {
23302
23360
  return toAnthropicCacheAwareUsage(
23303
- usage3?.input_tokens ?? 0,
23304
- usage3?.cached_input_tokens,
23305
- usage3?.cache_write_input_tokens,
23306
- options.forceOutputZero ? 0 : usage3?.output_tokens ?? 0,
23361
+ usage4?.input_tokens ?? 0,
23362
+ usage4?.cached_input_tokens,
23363
+ usage4?.cache_write_input_tokens,
23364
+ options.forceOutputZero ? 0 : usage4?.output_tokens ?? 0,
23307
23365
  advertisedContextWindow,
23308
- usage3?.context_window
23366
+ usage4?.context_window
23309
23367
  );
23310
23368
  }
23311
23369
  async function collectAnthropicMessage(events, fallbackModel, options = {}) {
@@ -25302,7 +25360,7 @@ var execFileAsync = promisify(execFile);
25302
25360
  var MAX_CREDENTIAL_BYTES = 65536;
25303
25361
  var CREDENTIAL_OPEN_FLAGS = process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NONBLOCK;
25304
25362
  async function readBoundedFile(filePath, maxBytes) {
25305
- const handle = await fs7.open(filePath, CREDENTIAL_OPEN_FLAGS);
25363
+ const handle = await fs32.open(filePath, CREDENTIAL_OPEN_FLAGS);
25306
25364
  try {
25307
25365
  const stat22 = await handle.stat();
25308
25366
  if (!stat22.isFile() || stat22.size > maxBytes) return null;
@@ -25378,9 +25436,9 @@ async function resolveClaudeCredentials(deps) {
25378
25436
  } catch {
25379
25437
  }
25380
25438
  }
25381
- const configDir = deps.env.CLAUDE_CONFIG_DIR || path23__default.join(deps.homedir(), ".claude");
25439
+ const configDir = deps.env.CLAUDE_CONFIG_DIR || path24__default.join(deps.homedir(), ".claude");
25382
25440
  try {
25383
- const raw = await deps.readBounded(path23__default.join(configDir, ".credentials.json"), MAX_CREDENTIAL_BYTES);
25441
+ const raw = await deps.readBounded(path24__default.join(configDir, ".credentials.json"), MAX_CREDENTIAL_BYTES);
25384
25442
  return raw === null || raw.length > MAX_CREDENTIAL_BYTES ? null : parseClaudeCredentialJson(raw, "file");
25385
25443
  } catch {
25386
25444
  return null;
@@ -25484,7 +25542,7 @@ function optionalNonEmptyString(value) {
25484
25542
  return typeof value === "string" && value.length > 0 ? value : void 0;
25485
25543
  }
25486
25544
  function codexAuthFilePath(deps) {
25487
- return path23__default.join(deps.env.CODEX_HOME || path23__default.join(deps.homedir(), ".codex"), "auth.json");
25545
+ return path24__default.join(deps.env.CODEX_HOME || path24__default.join(deps.homedir(), ".codex"), "auth.json");
25488
25546
  }
25489
25547
  async function resolveCodexCredentials(deps) {
25490
25548
  try {
@@ -25534,9 +25592,9 @@ function parseResetCredits(payload) {
25534
25592
  for (let index = 0; index < credits.length && index < MAX_CREDIT_ENTRIES; index += 1) {
25535
25593
  const credit = object2(credits[index]);
25536
25594
  if (credit?.status !== "available") continue;
25537
- const expiry = safeTimestamp(credit.expires_at);
25538
- if (expiry !== void 0 && (nextExpiresAt === void 0 || expiry < nextExpiresAt)) {
25539
- nextExpiresAt = expiry;
25595
+ const expiry2 = safeTimestamp(credit.expires_at);
25596
+ if (expiry2 !== void 0 && (nextExpiresAt === void 0 || expiry2 < nextExpiresAt)) {
25597
+ nextExpiresAt = expiry2;
25540
25598
  }
25541
25599
  }
25542
25600
  return {
@@ -25556,7 +25614,7 @@ async function fetchCodexUsage(deps = {}) {
25556
25614
  if (credentials.accountId) headers["ChatGPT-Account-Id"] = credentials.accountId;
25557
25615
  try {
25558
25616
  const fetchImpl = deps.fetch ?? fetch;
25559
- const usage3 = parseCodexUsage(await getJson(fetchImpl, "https://chatgpt.com/backend-api/wham/usage", headers));
25617
+ const usage4 = parseCodexUsage(await getJson(fetchImpl, "https://chatgpt.com/backend-api/wham/usage", headers));
25560
25618
  let credits;
25561
25619
  try {
25562
25620
  credits = parseResetCredits(await getJson(
@@ -25569,8 +25627,8 @@ async function fetchCodexUsage(deps = {}) {
25569
25627
  }
25570
25628
  return {
25571
25629
  status: "ok",
25572
- plan: usage3.plan,
25573
- windows: usage3.windows,
25630
+ plan: usage4.plan,
25631
+ windows: usage4.windows,
25574
25632
  ...credits ? { credits } : {},
25575
25633
  fetchedAt: (deps.now ?? Date.now)()
25576
25634
  };
@@ -25603,12 +25661,12 @@ function parseCursorCredentialJson(raw, method) {
25603
25661
  function cursorAuthFilePath(deps) {
25604
25662
  const home = deps.homedir();
25605
25663
  if (deps.platform === "win32") {
25606
- return path23__default.join(deps.env.APPDATA || path23__default.join(home, "AppData", "Roaming"), "Cursor", "auth.json");
25664
+ return path24__default.join(deps.env.APPDATA || path24__default.join(home, "AppData", "Roaming"), "Cursor", "auth.json");
25607
25665
  }
25608
25666
  if (deps.platform === "darwin") {
25609
- return path23__default.join(home, ".cursor", "auth.json");
25667
+ return path24__default.join(home, ".cursor", "auth.json");
25610
25668
  }
25611
- return path23__default.join(deps.env.XDG_CONFIG_HOME || path23__default.join(home, ".config"), "cursor", "auth.json");
25669
+ return path24__default.join(deps.env.XDG_CONFIG_HOME || path24__default.join(home, ".config"), "cursor", "auth.json");
25612
25670
  }
25613
25671
  async function resolveCursorCredentials(deps) {
25614
25672
  if (deps.platform === "darwin") {
@@ -25684,12 +25742,12 @@ async function fetchCursorUsage(deps = {}) {
25684
25742
  };
25685
25743
  try {
25686
25744
  const fetchImpl = deps.fetch ?? fetch;
25687
- const usage3 = parseCursorUsage(await postJson(
25745
+ const usage4 = parseCursorUsage(await postJson(
25688
25746
  fetchImpl,
25689
25747
  "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
25690
25748
  headers
25691
25749
  ));
25692
- if (usage3.status === "no_subscription") return { status: "no_subscription", method: credentials.method };
25750
+ if (usage4.status === "no_subscription") return { status: "no_subscription", method: credentials.method };
25693
25751
  let plan;
25694
25752
  try {
25695
25753
  const planRoot = object2(await postJson(
@@ -25705,8 +25763,8 @@ async function fetchCursorUsage(deps = {}) {
25705
25763
  status: "ok",
25706
25764
  method: credentials.method,
25707
25765
  ...plan ? { plan } : {},
25708
- ...usage3.cycleDays !== void 0 ? { cycleDays: usage3.cycleDays } : {},
25709
- windows: usage3.windows,
25766
+ ...usage4.cycleDays !== void 0 ? { cycleDays: usage4.cycleDays } : {},
25767
+ windows: usage4.windows,
25710
25768
  fetchedAt: (deps.now ?? Date.now)()
25711
25769
  };
25712
25770
  } catch (error51) {
@@ -25791,16 +25849,16 @@ async function fetchKimiUsage(deps = {}) {
25791
25849
  const apiKey = await deps.authService.getApiKey(KIMI_AUTH_PROVIDER_ID);
25792
25850
  if (!apiKey) return { status: "signed_out" };
25793
25851
  try {
25794
- const usage3 = parseKimiUsage(await getJson(
25852
+ const usage4 = parseKimiUsage(await getJson(
25795
25853
  deps.fetch ?? fetch,
25796
25854
  `${KIMI_CODE_API_BASE_URL}/v1/usages`,
25797
25855
  { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
25798
25856
  ));
25799
- if (usage3.status === "no_subscription") return { status: "no_subscription" };
25857
+ if (usage4.status === "no_subscription") return { status: "no_subscription" };
25800
25858
  return {
25801
25859
  status: "ok",
25802
- ...usage3.plan ? { plan: usage3.plan } : {},
25803
- windows: usage3.windows,
25860
+ ...usage4.plan ? { plan: usage4.plan } : {},
25861
+ windows: usage4.windows,
25804
25862
  fetchedAt: (deps.now ?? Date.now)()
25805
25863
  };
25806
25864
  } catch (error51) {
@@ -25820,7 +25878,7 @@ function resolveOpencodeDataDir(env = process.env, homeDir = os3__default.homedi
25820
25878
  if (override) return expandHome(override, homeDir).replace(/\/+$/, "");
25821
25879
  const xdg = env.XDG_DATA_HOME?.trim();
25822
25880
  if (xdg) return `${expandHome(xdg, homeDir).replace(/\/+$/, "")}/opencode`;
25823
- return path23__default.join(homeDir, ".local", "share", "opencode");
25881
+ return path24__default.join(homeDir, ".local", "share", "opencode");
25824
25882
  }
25825
25883
  function listOpencodeDatabases(dataDir) {
25826
25884
  let names;
@@ -25830,7 +25888,7 @@ function listOpencodeDatabases(dataDir) {
25830
25888
  if (!fs9__default.existsSync(dataDir)) return [];
25831
25889
  throw error51;
25832
25890
  }
25833
- return names.filter((name) => name.startsWith("opencode") && name.endsWith(".db")).sort().map((name) => path23__default.join(dataDir, name));
25891
+ return names.filter((name) => name.startsWith("opencode") && name.endsWith(".db")).sort().map((name) => path24__default.join(dataDir, name));
25834
25892
  }
25835
25893
  async function scanOpencodeGoWindows(deps = {}) {
25836
25894
  const nowMs = (deps.now ?? Date.now)();
@@ -25979,7 +26037,7 @@ function anchoredMonthStart(year, month, anchor) {
25979
26037
  }
25980
26038
  function expandHome(value, homeDir) {
25981
26039
  if (value === "~") return homeDir;
25982
- if (value.startsWith("~/")) return path23__default.join(homeDir, value.slice(2));
26040
+ if (value.startsWith("~/")) return path24__default.join(homeDir, value.slice(2));
25983
26041
  return value;
25984
26042
  }
25985
26043
  var OPENCODE_GO_CHAT_COMPLETIONS_URL = "https://opencode.ai/zen/go/v1/chat/completions";
@@ -26282,7 +26340,7 @@ async function* translateChatCompletionsStream(body2, options, toolSchemas) {
26282
26340
  let createdEmitted = false;
26283
26341
  let textSeen = false;
26284
26342
  let accumulatedText = "";
26285
- let usage3 = null;
26343
+ let usage4 = null;
26286
26344
  let failed = false;
26287
26345
  const toolCalls = /* @__PURE__ */ new Map();
26288
26346
  const MESSAGE_ITEM_ID = "chat_message_0";
@@ -26313,7 +26371,7 @@ async function* translateChatCompletionsStream(body2, options, toolSchemas) {
26313
26371
  };
26314
26372
  }
26315
26373
  if (isRecord5(value.usage)) {
26316
- usage3 = chatUsage(value.usage);
26374
+ usage4 = chatUsage(value.usage);
26317
26375
  }
26318
26376
  const choices = Array.isArray(value.choices) ? value.choices : [];
26319
26377
  for (const choice of choices) {
@@ -26406,7 +26464,7 @@ async function* translateChatCompletionsStream(body2, options, toolSchemas) {
26406
26464
  model: responseModel ?? "",
26407
26465
  // 하류 message_delta는 usage가 필수다. include_usage에도 usage 청크를 주지
26408
26466
  // 않는 백엔드에서는 0-usage로 완결하고, 실제 회계는 provider 콘솔이 맡는다.
26409
- usage: usage3 ?? { input_tokens: 0, output_tokens: 0 }
26467
+ usage: usage4 ?? { input_tokens: 0, output_tokens: 0 }
26410
26468
  }
26411
26469
  };
26412
26470
  }
@@ -27094,6 +27152,273 @@ async function fetchOpencodeUsage(deps = {}) {
27094
27152
  fetchedAt: now()
27095
27153
  };
27096
27154
  }
27155
+ var XAI_OIDC_ISSUER = "https://auth.x.ai";
27156
+ var XAI_CLI_REFRESH_URL = "https://auth.x.ai/oauth2/token";
27157
+ var XAI_CLI_DEFAULT_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
27158
+ var XAI_CLI_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
27159
+ var REFRESH_TIMEOUT_MS = 15e3;
27160
+ var FALLBACK_ACCESS_TOKEN_TTL_MS = 36e5;
27161
+ function xaiCliAuthFilePath(deps) {
27162
+ return path24__default.join(deps.env.GROK_HOME || path24__default.join(deps.homedir(), ".grok"), "auth.json");
27163
+ }
27164
+ function expiry(value) {
27165
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
27166
+ const parsed = typeof value === "number" ? value : Date.parse(value);
27167
+ if (!Number.isFinite(parsed)) return void 0;
27168
+ return parsed < 1e12 ? Math.round(parsed * 1e3) : Math.round(parsed);
27169
+ }
27170
+ function jwtExpiry(token) {
27171
+ const parts = token.split(".");
27172
+ if (parts.length < 2) return void 0;
27173
+ try {
27174
+ const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
27175
+ const record42 = credentialRecord(payload);
27176
+ const exp = record42?.exp;
27177
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return void 0;
27178
+ return Math.round(exp * 1e3);
27179
+ } catch {
27180
+ return void 0;
27181
+ }
27182
+ }
27183
+ function effectiveExpiry(entry, accessToken) {
27184
+ const fromEntry = expiry(entry.expires_at) ?? expiry(entry.expires);
27185
+ const fromJwt = jwtExpiry(accessToken);
27186
+ if (fromEntry !== void 0 && fromJwt !== void 0) return Math.min(fromEntry, fromJwt);
27187
+ return fromEntry ?? fromJwt;
27188
+ }
27189
+ function clientId(entryKey, entry) {
27190
+ const fromEntry = optionalTrimmedString(entry.oidc_client_id);
27191
+ if (fromEntry) return fromEntry;
27192
+ const suffix = optionalTrimmedString(entryKey.split("::").at(-1));
27193
+ return suffix ?? XAI_CLI_DEFAULT_CLIENT_ID;
27194
+ }
27195
+ function refreshToken(entry) {
27196
+ return optionalTrimmedString(entry.refresh_token) ?? optionalTrimmedString(entry.refresh);
27197
+ }
27198
+ async function defaultWriteAuthFile(filePath, contents) {
27199
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
27200
+ try {
27201
+ await fs32.writeFile(tmpPath, contents, { encoding: "utf8", mode: 384 });
27202
+ await fs32.rename(tmpPath, filePath);
27203
+ } catch (error51) {
27204
+ await fs32.unlink(tmpPath).catch(() => void 0);
27205
+ throw error51;
27206
+ }
27207
+ }
27208
+ async function persistRefreshedEntry(deps, filePath, entryKey, expected, patch, writeAuthFile) {
27209
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
27210
+ if (raw === null) return;
27211
+ const auth = credentialRecord(JSON.parse(raw));
27212
+ if (!auth) return;
27213
+ const current = credentialRecord(auth[entryKey]);
27214
+ if (!current) return;
27215
+ if (optionalTrimmedString(current.key) !== expected.accessToken) return;
27216
+ if (expected.refreshToken !== void 0 && refreshToken(current) !== expected.refreshToken) return;
27217
+ auth[entryKey] = { ...current, ...patch };
27218
+ await writeAuthFile(filePath, `${JSON.stringify(auth, null, 2)}
27219
+ `);
27220
+ }
27221
+ async function refreshAccessToken(entryKey, entry, fetchImpl, now) {
27222
+ const token = refreshToken(entry);
27223
+ if (!token) return null;
27224
+ const controller = new AbortController();
27225
+ const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
27226
+ try {
27227
+ const body2 = new URLSearchParams({
27228
+ grant_type: "refresh_token",
27229
+ client_id: clientId(entryKey, entry),
27230
+ refresh_token: token
27231
+ });
27232
+ const response = await fetchImpl(XAI_CLI_REFRESH_URL, {
27233
+ method: "POST",
27234
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
27235
+ body: body2,
27236
+ signal: controller.signal
27237
+ });
27238
+ if (!response.ok) return null;
27239
+ const payload = credentialRecord(await response.json());
27240
+ const accessToken = optionalTrimmedString(payload?.access_token);
27241
+ if (!accessToken) return null;
27242
+ const expiresIn = payload?.expires_in;
27243
+ const expiresAt = typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn > 0 ? now() + Math.round(expiresIn * 1e3) : jwtExpiry(accessToken) ?? now() + FALLBACK_ACCESS_TOKEN_TTL_MS;
27244
+ const rotated = optionalTrimmedString(payload?.refresh_token);
27245
+ return {
27246
+ accessToken,
27247
+ expiresAt,
27248
+ ...rotated === void 0 ? {} : { refreshToken: rotated }
27249
+ };
27250
+ } catch {
27251
+ return null;
27252
+ } finally {
27253
+ clearTimeout(timer);
27254
+ }
27255
+ }
27256
+ async function resolveXaiCliAuth(deps, options = {}) {
27257
+ const now = options.now ?? Date.now;
27258
+ const fetchImpl = options.fetch ?? fetch;
27259
+ const writeAuthFile = options.writeAuthFile ?? defaultWriteAuthFile;
27260
+ const filePath = xaiCliAuthFilePath(deps);
27261
+ try {
27262
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
27263
+ if (raw === null || raw.length > MAX_CREDENTIAL_BYTES) return { status: "signed_out" };
27264
+ const auth = credentialRecord(JSON.parse(raw));
27265
+ if (!auth) return { status: "signed_out" };
27266
+ let sawExpired = false;
27267
+ for (const [entryKey, value] of Object.entries(auth)) {
27268
+ if (!entryKey.startsWith(`${XAI_OIDC_ISSUER}::`)) continue;
27269
+ const entry = credentialRecord(value);
27270
+ const issuer = optionalTrimmedString(entry?.oidc_issuer);
27271
+ const accessToken = optionalTrimmedString(entry?.key);
27272
+ if (!entry || issuer !== XAI_OIDC_ISSUER || !accessToken) continue;
27273
+ const expiresAt = effectiveExpiry(entry, accessToken);
27274
+ const expired2 = expiresAt !== void 0 && expiresAt <= now();
27275
+ const needsRefresh = options.forceRefresh === true || expiresAt !== void 0 && expiresAt - now() <= XAI_CLI_REFRESH_BUFFER_MS;
27276
+ if (needsRefresh) {
27277
+ const refreshed = await refreshAccessToken(entryKey, entry, fetchImpl, now);
27278
+ if (refreshed) {
27279
+ const userId2 = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
27280
+ const patch = {
27281
+ key: refreshed.accessToken,
27282
+ expires_at: new Date(refreshed.expiresAt).toISOString()
27283
+ };
27284
+ if (refreshed.refreshToken !== void 0) patch.refresh_token = refreshed.refreshToken;
27285
+ try {
27286
+ await persistRefreshedEntry(
27287
+ deps,
27288
+ filePath,
27289
+ entryKey,
27290
+ { accessToken, refreshToken: refreshToken(entry) },
27291
+ patch,
27292
+ writeAuthFile
27293
+ );
27294
+ } catch {
27295
+ }
27296
+ return {
27297
+ status: "ok",
27298
+ credentials: {
27299
+ accessToken: refreshed.accessToken,
27300
+ expiresAt: refreshed.expiresAt,
27301
+ ...userId2 === void 0 ? {} : { userId: userId2 }
27302
+ }
27303
+ };
27304
+ }
27305
+ if (options.forceRefresh === true || expired2) {
27306
+ sawExpired = true;
27307
+ continue;
27308
+ }
27309
+ } else if (expired2) {
27310
+ sawExpired = true;
27311
+ continue;
27312
+ }
27313
+ const userId = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
27314
+ return {
27315
+ status: "ok",
27316
+ credentials: {
27317
+ accessToken,
27318
+ ...expiresAt === void 0 ? {} : { expiresAt },
27319
+ ...userId === void 0 ? {} : { userId }
27320
+ }
27321
+ };
27322
+ }
27323
+ return { status: sawExpired ? "expired" : "signed_out" };
27324
+ } catch {
27325
+ return { status: "signed_out" };
27326
+ }
27327
+ }
27328
+ async function resolveXaiCliCredentials(deps, nowOrOptions = Date.now) {
27329
+ const options = typeof nowOrOptions === "function" ? { now: nowOrOptions } : nowOrOptions;
27330
+ const result = await resolveXaiCliAuth(deps, options);
27331
+ return result.status === "ok" ? result.credentials : null;
27332
+ }
27333
+ var XAI_CLI_CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
27334
+ var WEEKLY_PERIOD = "USAGE_PERIOD_TYPE_WEEKLY";
27335
+ function parseXaiCredits(payload) {
27336
+ const root = object2(payload);
27337
+ const config2 = object2(root?.config);
27338
+ const period = object2(config2?.currentPeriod);
27339
+ const periodType = typeof period?.type === "string" ? period.type.trim() : "";
27340
+ if (!config2 || !period || periodType.length === 0) return null;
27341
+ const startsAt = safeTimestamp(period.start);
27342
+ const resetsAt = safeTimestamp(period.end);
27343
+ if (startsAt === void 0 || resetsAt === void 0 || resetsAt <= startsAt) return null;
27344
+ if (periodType !== WEEKLY_PERIOD) return { status: "other" };
27345
+ let usedPercent = 0;
27346
+ if (config2.creditUsagePercent !== void 0) {
27347
+ if (typeof config2.creditUsagePercent !== "number" || !Number.isFinite(config2.creditUsagePercent)) {
27348
+ return null;
27349
+ }
27350
+ usedPercent = percent(config2.creditUsagePercent);
27351
+ }
27352
+ return {
27353
+ status: "weekly",
27354
+ window: {
27355
+ id: "weekly",
27356
+ usedPercent,
27357
+ resetsAt,
27358
+ period: {
27359
+ durationMs: resetsAt - startsAt,
27360
+ durationBasis: "upstream",
27361
+ startsAt,
27362
+ startsAtBasis: "upstream"
27363
+ }
27364
+ }
27365
+ };
27366
+ }
27367
+ function creditsHeaders(credentials) {
27368
+ const headers = {
27369
+ Accept: "application/json",
27370
+ Authorization: `Bearer ${credentials.accessToken}`,
27371
+ "X-XAI-Token-Auth": "xai-grok-cli"
27372
+ };
27373
+ if (credentials.userId) headers["x-userid"] = credentials.userId;
27374
+ return headers;
27375
+ }
27376
+ async function fetchXaiUsage(deps = {}) {
27377
+ const credentialDeps = deps.credentials ?? defaultCredentialDeps;
27378
+ const now = deps.now ?? Date.now;
27379
+ const fetchImpl = deps.fetch ?? fetch;
27380
+ const auth = await resolveXaiCliAuth(credentialDeps, { now, fetch: fetchImpl });
27381
+ if (auth.status !== "ok") return { status: auth.status };
27382
+ const load = (credentials) => getJson(
27383
+ fetchImpl,
27384
+ XAI_CLI_CREDITS_URL,
27385
+ creditsHeaders(credentials)
27386
+ );
27387
+ try {
27388
+ let credentials = auth.credentials;
27389
+ let payload;
27390
+ try {
27391
+ payload = await load(credentials);
27392
+ } catch (error51) {
27393
+ if (!expired(error51)) throw error51;
27394
+ const retried = await resolveXaiCliAuth(credentialDeps, {
27395
+ now,
27396
+ fetch: fetchImpl,
27397
+ forceRefresh: true
27398
+ });
27399
+ if (retried.status !== "ok") return { status: "expired" };
27400
+ credentials = retried.credentials;
27401
+ try {
27402
+ payload = await load(credentials);
27403
+ } catch (retryError) {
27404
+ const result = expired(retryError);
27405
+ if (result) return result;
27406
+ throw retryError;
27407
+ }
27408
+ }
27409
+ const parsed = parseXaiCredits(payload);
27410
+ if (!parsed) throw new Error("Grok returned an unsupported quota response");
27411
+ return {
27412
+ status: "ok",
27413
+ windows: parsed.status === "weekly" ? [parsed.window] : [],
27414
+ fetchedAt: now()
27415
+ };
27416
+ } catch (error51) {
27417
+ const result = expired(error51);
27418
+ if (result) return result;
27419
+ throw error51;
27420
+ }
27421
+ }
27097
27422
  var CACHE_TTL_MS = 12e4;
27098
27423
  var STALE_TTL_MS = 18e5;
27099
27424
  function createAiGatewayQuotaCollectors(deps) {
@@ -27109,7 +27434,8 @@ function createAiGatewayQuotaCollectors(deps) {
27109
27434
  fetchCodex: () => fetchCodexUsage(providerDeps),
27110
27435
  fetchCursor: () => fetchCursorUsage(providerDeps),
27111
27436
  fetchKimi: () => fetchKimiUsage(providerDeps),
27112
- fetchOpencode: () => fetchOpencodeUsage(providerDeps)
27437
+ fetchOpencode: () => fetchOpencodeUsage(providerDeps),
27438
+ fetchXai: () => fetchXaiUsage(providerDeps)
27113
27439
  };
27114
27440
  }
27115
27441
  function isProviderSuccess(value) {
@@ -27122,7 +27448,8 @@ function createQuotaService(deps) {
27122
27448
  codex: deps.fetchCodex,
27123
27449
  cursor: deps.fetchCursor,
27124
27450
  kimi: deps.fetchKimi,
27125
- opencode: deps.fetchOpencode
27451
+ opencode: deps.fetchOpencode,
27452
+ xai: deps.fetchXai ?? (async () => ({ status: "signed_out" }))
27126
27453
  };
27127
27454
  const cache = /* @__PURE__ */ new Map();
27128
27455
  const lastGood = /* @__PURE__ */ new Map();
@@ -27165,12 +27492,13 @@ function createQuotaService(deps) {
27165
27492
  }
27166
27493
  return {
27167
27494
  async getSummary(options = {}) {
27168
- const [claude, codex, cursor, kimi, opencode] = await Promise.all([
27495
+ const [claude, codex, cursor, kimi, opencode, xai] = await Promise.all([
27169
27496
  load("claude", options.force === true || options.forceProvider === "claude"),
27170
27497
  load("codex", options.force === true || options.forceProvider === "codex"),
27171
27498
  load("cursor", options.force === true || options.forceProvider === "cursor"),
27172
27499
  load("kimi", options.force === true || options.forceProvider === "kimi"),
27173
- load("opencode", options.force === true || options.forceProvider === "opencode")
27500
+ load("opencode", options.force === true || options.forceProvider === "opencode"),
27501
+ load("xai", options.force === true || options.forceProvider === "xai")
27174
27502
  ]);
27175
27503
  return {
27176
27504
  providers: {
@@ -27178,12 +27506,439 @@ function createQuotaService(deps) {
27178
27506
  codex: withRisk(codex),
27179
27507
  cursor: withRisk(cursor),
27180
27508
  kimi: withRisk(kimi),
27181
- opencode: withRisk(opencode)
27509
+ opencode: withRisk(opencode),
27510
+ xai: withRisk(xai)
27511
+ }
27512
+ };
27513
+ }
27514
+ };
27515
+ }
27516
+ var XAI_CLI_RESPONSES_URL = "https://cli-chat-proxy.grok.com/v1/responses";
27517
+ var XAI_CLI_CLIENT_VERSION = "1.0.3";
27518
+ var DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES = 64 * 1024 * 1024;
27519
+ var DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS = 3e4;
27520
+ var DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS = 3e4;
27521
+ var XaiResponsesAdapter = class {
27522
+ capabilities = {};
27523
+ fetchImpl;
27524
+ maxBodyBytes;
27525
+ idleTimeoutMs;
27526
+ functionCallTimeoutMs;
27527
+ url;
27528
+ extraHeaders;
27529
+ constructor(options = {}) {
27530
+ this.url = XAI_CLI_RESPONSES_URL;
27531
+ this.extraHeaders = options.headers ?? {};
27532
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
27533
+ this.maxBodyBytes = positiveInteger(
27534
+ options.maxBodyBytes ?? DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES,
27535
+ "maxBodyBytes"
27536
+ );
27537
+ this.idleTimeoutMs = positiveInteger(
27538
+ options.idleTimeoutMs ?? DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS,
27539
+ "idleTimeoutMs"
27540
+ );
27541
+ this.functionCallTimeoutMs = positiveInteger(
27542
+ options.functionCallTimeoutMs ?? DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS,
27543
+ "functionCallTimeoutMs"
27544
+ );
27545
+ }
27546
+ async stream(request, options) {
27547
+ if (options.apiKey.length === 0) {
27548
+ throw new TypeError("apiKey must not be empty");
27549
+ }
27550
+ const controller = new AbortController();
27551
+ const unlinkAbort = linkAbortSignal(options.signal, controller);
27552
+ const payload = forXaiResponsesBackend(request);
27553
+ wireLog("xai-responses.wire.request", { url: this.url, payload });
27554
+ let response;
27555
+ try {
27556
+ response = await this.fetchImpl(this.url, {
27557
+ method: "POST",
27558
+ headers: {
27559
+ accept: "text/event-stream",
27560
+ authorization: `Bearer ${options.apiKey}`,
27561
+ "content-type": "application/json",
27562
+ "x-xai-token-auth": "xai-grok-cli",
27563
+ "x-grok-client-version": XAI_CLI_CLIENT_VERSION,
27564
+ "x-grok-model-override": request.model,
27565
+ ...this.extraHeaders
27566
+ },
27567
+ body: JSON.stringify(payload),
27568
+ signal: controller.signal
27569
+ });
27570
+ } catch (error51) {
27571
+ unlinkAbort();
27572
+ throw error51;
27573
+ }
27574
+ if (!response.ok) {
27575
+ if (process.env.FLEET_AI_GATEWAY_DEBUG === "1") {
27576
+ const roles = payload.input.map((item) => "role" in item ? item.role : item.type);
27577
+ console.error(`[ai-gateway] upstream ${response.status} input roles=${JSON.stringify(roles)} keys=${JSON.stringify(Object.keys(payload))}`);
27578
+ }
27579
+ try {
27580
+ const body2 = await readBoundedBody(response.body, {
27581
+ controller,
27582
+ idleTimeoutMs: this.idleTimeoutMs,
27583
+ maxBodyBytes: this.maxBodyBytes
27584
+ });
27585
+ return {
27586
+ ok: false,
27587
+ status: response.status,
27588
+ headers: response.headers,
27589
+ body: body2
27590
+ };
27591
+ } finally {
27592
+ unlinkAbort();
27593
+ }
27594
+ }
27595
+ return {
27596
+ ok: true,
27597
+ status: response.status,
27598
+ headers: response.headers,
27599
+ events: parseXaiEventStream(response.body, {
27600
+ controller,
27601
+ idleTimeoutMs: this.idleTimeoutMs,
27602
+ maxBodyBytes: this.maxBodyBytes,
27603
+ onClose: unlinkAbort
27604
+ }, this.functionCallTimeoutMs)
27605
+ };
27606
+ }
27607
+ };
27608
+ function forXaiResponsesBackend(request) {
27609
+ const { metadata: _metadata, native_tools: _nativeTools, ...rest } = request;
27610
+ return {
27611
+ ...rest,
27612
+ input: request.input.map((item) => {
27613
+ if (item.type === "function_call_output") {
27614
+ const { is_error: _isError, tool_references: _toolReferences, ...wireItem2 } = item;
27615
+ return wireItem2;
27616
+ }
27617
+ const { reasoning_content: _reasoningContent, ...wireItem } = item;
27618
+ return wireItem;
27619
+ }),
27620
+ ...request.tools === void 0 ? {} : { tools: request.tools.map(({ defer_loading: _deferLoading, ...tool }) => tool) }
27621
+ };
27622
+ }
27623
+ function parseXaiEventStream(body2, options, functionCallTimeoutMs) {
27624
+ return assembleXaiFunctionCalls(
27625
+ parseUpstreamSseStream(
27626
+ body2,
27627
+ { ...options, missingBodyMessage: "Grok CLI streaming response had no body" },
27628
+ parseEventFrame3
27629
+ ),
27630
+ options.controller,
27631
+ functionCallTimeoutMs
27632
+ );
27633
+ }
27634
+ async function* assembleXaiFunctionCalls(source, controller, timeoutMs) {
27635
+ const iterator = source[Symbol.asyncIterator]();
27636
+ const pending = /* @__PURE__ */ new Map();
27637
+ let completedNormally = false;
27638
+ try {
27639
+ while (true) {
27640
+ const deadlineAt = earliestXaiFunctionCallDeadline(pending);
27641
+ const result = deadlineAt === void 0 ? await iterator.next() : await nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs);
27642
+ if (result.done) {
27643
+ if (pending.size > 0) {
27644
+ throw incompleteXaiFunctionCall("stream ended before function call output_item.done");
27645
+ }
27646
+ completedNormally = true;
27647
+ return;
27648
+ }
27649
+ const event = result.value;
27650
+ if (event.type === "response.completed" && pending.size > 0) {
27651
+ throw incompleteXaiFunctionCall("response.completed arrived before function call output_item.done");
27652
+ }
27653
+ if (event.type === "response.output_item.added" && event.item.type === "function_call") {
27654
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
27655
+ pending.set(key, {
27656
+ added: event,
27657
+ // Each call gets a full timeout from its own added event. Waiting uses the
27658
+ // earliest active deadline, so a later parallel call is never shortened by
27659
+ // an earlier call's age.
27660
+ deadlineAt: Date.now() + timeoutMs
27661
+ });
27662
+ continue;
27663
+ }
27664
+ if (event.type === "response.function_call_arguments.done") {
27665
+ const call = pending.get(xaiFunctionCallKey(event.output_index, event.item_id));
27666
+ if (call !== void 0) {
27667
+ call.argumentsDone = event;
27668
+ continue;
27669
+ }
27670
+ }
27671
+ if (event.type === "response.output_item.done" && event.item.type === "function_call") {
27672
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
27673
+ const call = pending.get(key);
27674
+ if (call !== void 0) {
27675
+ pending.delete(key);
27676
+ yield call.added;
27677
+ if (call.argumentsDone !== void 0) {
27678
+ yield call.argumentsDone;
27679
+ } else if (event.item.arguments.length > 0) {
27680
+ yield {
27681
+ type: "response.function_call_arguments.done",
27682
+ item_id: event.item.id,
27683
+ output_index: event.output_index,
27684
+ arguments: event.item.arguments
27685
+ };
27686
+ }
27687
+ yield event;
27688
+ continue;
27689
+ }
27690
+ }
27691
+ yield event;
27692
+ }
27693
+ } finally {
27694
+ if (!completedNormally && !controller.signal.aborted) {
27695
+ controller.abort();
27696
+ }
27697
+ const returned = iterator.return?.();
27698
+ if (returned !== void 0) {
27699
+ await returned.catch(() => void 0);
27700
+ }
27701
+ }
27702
+ }
27703
+ function earliestXaiFunctionCallDeadline(pending) {
27704
+ let earliest;
27705
+ for (const call of pending.values()) {
27706
+ if (earliest === void 0 || call.deadlineAt < earliest) {
27707
+ earliest = call.deadlineAt;
27708
+ }
27709
+ }
27710
+ return earliest;
27711
+ }
27712
+ async function nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs) {
27713
+ const remainingMs = deadlineAt - Date.now();
27714
+ if (remainingMs <= 0) {
27715
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
27716
+ controller.abort(error51);
27717
+ throw error51;
27718
+ }
27719
+ let timeout;
27720
+ const next = iterator.next();
27721
+ void next.catch(() => void 0);
27722
+ try {
27723
+ return await Promise.race([
27724
+ next,
27725
+ new Promise((_, reject) => {
27726
+ timeout = setTimeout(() => {
27727
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
27728
+ controller.abort(error51);
27729
+ reject(error51);
27730
+ }, remainingMs);
27731
+ })
27732
+ ]);
27733
+ } finally {
27734
+ if (timeout !== void 0) {
27735
+ clearTimeout(timeout);
27736
+ }
27737
+ }
27738
+ }
27739
+ function incompleteXaiFunctionCall(reason) {
27740
+ return new UpstreamProtocolError(`Grok CLI ${reason}`);
27741
+ }
27742
+ function xaiFunctionCallKey(outputIndex, itemId) {
27743
+ return `${outputIndex}:${itemId}`;
27744
+ }
27745
+ function parseEventFrame3(frame) {
27746
+ const { event: eventName, data } = parseSseFrameFields(frame);
27747
+ if (data.length === 0 || data === "[DONE]") {
27748
+ return void 0;
27749
+ }
27750
+ let parsed;
27751
+ try {
27752
+ parsed = JSON.parse(data);
27753
+ } catch (error51) {
27754
+ throw new UpstreamProtocolError(
27755
+ `Grok CLI SSE contained invalid JSON: ${error51 instanceof Error ? error51.message : String(error51)}`
27756
+ );
27757
+ }
27758
+ if (isRecord7(parsed) && typeof parsed.type !== "string" && eventName !== void 0) {
27759
+ parsed = { ...parsed, type: eventName };
27760
+ }
27761
+ return canonicalEvent3(parsed);
27762
+ }
27763
+ function canonicalEvent3(value) {
27764
+ if (!isRecord7(value) || typeof value.type !== "string") {
27765
+ throw new UpstreamProtocolError("Grok CLI SSE event was not an object with a type");
27766
+ }
27767
+ switch (value.type) {
27768
+ case "response.created":
27769
+ return { type: value.type, response: responseSnapshot3(value.response) };
27770
+ case "response.content_part.added": {
27771
+ const part = record3(value.part, "response.content_part.added.part");
27772
+ if (part.type !== "output_text") {
27773
+ return void 0;
27774
+ }
27775
+ return {
27776
+ type: value.type,
27777
+ item_id: string32(value.item_id, "item_id"),
27778
+ output_index: number32(value.output_index, "output_index"),
27779
+ content_index: number32(value.content_index, "content_index"),
27780
+ part: {
27781
+ type: "output_text",
27782
+ text: typeof part.text === "string" ? part.text : ""
27182
27783
  }
27183
27784
  };
27184
27785
  }
27786
+ case "response.output_text.delta":
27787
+ return {
27788
+ type: value.type,
27789
+ item_id: string32(value.item_id, "item_id"),
27790
+ output_index: number32(value.output_index, "output_index"),
27791
+ content_index: number32(value.content_index, "content_index"),
27792
+ delta: string32(value.delta, "delta")
27793
+ };
27794
+ case "response.output_text.done":
27795
+ return {
27796
+ type: value.type,
27797
+ item_id: string32(value.item_id, "item_id"),
27798
+ output_index: number32(value.output_index, "output_index"),
27799
+ content_index: number32(value.content_index, "content_index"),
27800
+ text: string32(value.text, "text")
27801
+ };
27802
+ case "response.reasoning_summary_text.delta":
27803
+ case "response.reasoning_text.delta":
27804
+ return {
27805
+ type: "response.reasoning_summary_text.delta",
27806
+ item_id: string32(value.item_id, "item_id"),
27807
+ output_index: number32(value.output_index, "output_index"),
27808
+ delta: string32(value.delta, "delta")
27809
+ };
27810
+ case "response.output_item.added":
27811
+ case "response.output_item.done": {
27812
+ const item = outputItem3(value.item);
27813
+ if (item === void 0) {
27814
+ return void 0;
27815
+ }
27816
+ return {
27817
+ type: value.type,
27818
+ output_index: number32(value.output_index, "output_index"),
27819
+ item
27820
+ };
27821
+ }
27822
+ // Hold argument fragments until the Grok CLI proxy's partial-JSON behavior is observed.
27823
+ // The `.done` event carries the complete argument object, which downstream treats as the
27824
+ // remainder when nothing was streamed ahead of it.
27825
+ case "response.function_call_arguments.delta":
27826
+ return void 0;
27827
+ case "response.function_call_arguments.done":
27828
+ return {
27829
+ type: value.type,
27830
+ item_id: string32(value.item_id, "item_id"),
27831
+ output_index: number32(value.output_index, "output_index"),
27832
+ arguments: string32(value.arguments, "arguments")
27833
+ };
27834
+ case "response.completed":
27835
+ return { type: value.type, response: responseSnapshot3(value.response) };
27836
+ case "response.failed": {
27837
+ const response = record3(value.response, "response.failed.response");
27838
+ return {
27839
+ type: value.type,
27840
+ response: {
27841
+ ...responseSnapshot3(response),
27842
+ error: canonicalError3(response.error)
27843
+ }
27844
+ };
27845
+ }
27846
+ case "error":
27847
+ return { type: "error", error: canonicalError3(value.error ?? value) };
27848
+ default:
27849
+ return void 0;
27850
+ }
27851
+ }
27852
+ function responseSnapshot3(value) {
27853
+ const response = record3(value, "response");
27854
+ return {
27855
+ id: string32(response.id, "response.id"),
27856
+ model: string32(response.model, "response.model"),
27857
+ usage: response.usage === null || response.usage === void 0 ? null : usage3(response.usage)
27858
+ };
27859
+ }
27860
+ function usage3(value) {
27861
+ const parsed = record3(value, "usage");
27862
+ const inputTokens = number32(parsed.input_tokens, "usage.input_tokens");
27863
+ const outputTokens = number32(parsed.output_tokens, "usage.output_tokens");
27864
+ const inputDetails = optionalRecord3(parsed.input_tokens_details, "usage.input_tokens_details");
27865
+ const cachedInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cached_tokens, "usage.input_tokens_details.cached_tokens");
27866
+ const cacheWriteInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cache_write_tokens, "usage.input_tokens_details.cache_write_tokens");
27867
+ const outputDetails = optionalRecord3(parsed.output_tokens_details, "usage.output_tokens_details");
27868
+ const reasoningOutputTokens = outputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(outputDetails.reasoning_tokens, "usage.output_tokens_details.reasoning_tokens");
27869
+ const totalTokens = optionalNonNegativeNumber3(parsed.total_tokens, "usage.total_tokens");
27870
+ return {
27871
+ input_tokens: inputTokens,
27872
+ output_tokens: outputTokens,
27873
+ ...cachedInputTokens === void 0 ? {} : { cached_input_tokens: cachedInputTokens },
27874
+ ...cacheWriteInputTokens === void 0 ? {} : { cache_write_input_tokens: cacheWriteInputTokens },
27875
+ ...reasoningOutputTokens === void 0 ? {} : { reasoning_output_tokens: reasoningOutputTokens },
27876
+ ...totalTokens === void 0 ? {} : { total_tokens: totalTokens }
27185
27877
  };
27186
27878
  }
27879
+ function outputItem3(value) {
27880
+ const item = record3(value, "item");
27881
+ if (item.type === "message") {
27882
+ return {
27883
+ id: string32(item.id, "item.id"),
27884
+ type: "message",
27885
+ role: "assistant"
27886
+ };
27887
+ }
27888
+ if (item.type === "function_call") {
27889
+ const id = string32(item.id, "item.id");
27890
+ return {
27891
+ id,
27892
+ type: "function_call",
27893
+ call_id: typeof item.call_id === "string" ? item.call_id : id,
27894
+ name: string32(item.name, "item.name"),
27895
+ arguments: typeof item.arguments === "string" ? item.arguments : ""
27896
+ };
27897
+ }
27898
+ return void 0;
27899
+ }
27900
+ function canonicalError3(value) {
27901
+ const error51 = record3(value, "error");
27902
+ const message = string32(error51.message, "error.message");
27903
+ const type = typeof error51.type === "string" && error51.type !== "error" ? error51.type : typeof error51.code === "string" ? error51.code : "api_error";
27904
+ return { type, message };
27905
+ }
27906
+ function isRecord7(value) {
27907
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27908
+ }
27909
+ function record3(value, name) {
27910
+ if (!isRecord7(value)) {
27911
+ throw new UpstreamProtocolError(`${name} must be an object`);
27912
+ }
27913
+ return value;
27914
+ }
27915
+ function optionalRecord3(value, name) {
27916
+ if (value === void 0 || value === null) {
27917
+ return void 0;
27918
+ }
27919
+ return record3(value, name);
27920
+ }
27921
+ function string32(value, name) {
27922
+ if (typeof value !== "string") {
27923
+ throw new UpstreamProtocolError(`${name} must be a string`);
27924
+ }
27925
+ return value;
27926
+ }
27927
+ function number32(value, name) {
27928
+ if (typeof value !== "number" || !Number.isFinite(value)) {
27929
+ throw new UpstreamProtocolError(`${name} must be a number`);
27930
+ }
27931
+ return value;
27932
+ }
27933
+ function optionalNonNegativeNumber3(value, name) {
27934
+ if (value === void 0 || value === null) {
27935
+ return void 0;
27936
+ }
27937
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
27938
+ throw new UpstreamProtocolError(`${name} must be a finite nonnegative number`);
27939
+ }
27940
+ return value;
27941
+ }
27187
27942
  var NO_USER_FACING_BLOCK = "Do not tell the user access is blocked, disabled, or denied.";
27188
27943
  var CLIENT_TOOL_RETRY = `${NO_USER_FACING_BLOCK} Silently retry with the matching client bridge tool from the current catalog.`;
27189
27944
  function cursorNativeExecPolicyReplies(exec2, clientTools) {
@@ -27224,38 +27979,38 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27224
27979
  "shell_command",
27225
27980
  "exec_command"
27226
27981
  ]);
27227
- if (isRecord7(exec2.readArgs)) {
27982
+ if (isRecord8(exec2.readArgs)) {
27228
27983
  return [execReply(exec2, "readResult", {
27229
27984
  error: { path: stringValue(exec2.readArgs.path), error: readMessage3 }
27230
27985
  })];
27231
27986
  }
27232
- if (isRecord7(exec2.writeArgs)) {
27987
+ if (isRecord8(exec2.writeArgs)) {
27233
27988
  return [execReply(exec2, "writeResult", {
27234
27989
  rejected: { path: stringValue(exec2.writeArgs.path), reason: mutationMessage }
27235
27990
  })];
27236
27991
  }
27237
- if (isRecord7(exec2.deleteArgs)) {
27992
+ if (isRecord8(exec2.deleteArgs)) {
27238
27993
  return [execReply(exec2, "deleteResult", {
27239
27994
  rejected: { path: stringValue(exec2.deleteArgs.path), reason: mutationMessage }
27240
27995
  })];
27241
27996
  }
27242
- if (isRecord7(exec2.lsArgs)) {
27997
+ if (isRecord8(exec2.lsArgs)) {
27243
27998
  return [execReply(exec2, "lsResult", {
27244
27999
  error: { path: stringValue(exec2.lsArgs.path), error: listMessage }
27245
28000
  })];
27246
28001
  }
27247
- if (isRecord7(exec2.grepArgs)) {
28002
+ if (isRecord8(exec2.grepArgs)) {
27248
28003
  return [execReply(exec2, "grepResult", { error: { error: grepMessage } })];
27249
28004
  }
27250
- if (isRecord7(exec2.shellArgs)) {
28005
+ if (isRecord8(exec2.shellArgs)) {
27251
28006
  return [execReply(exec2, "shellResult", shellFailure(exec2.shellArgs, shellMessage))];
27252
28007
  }
27253
- if (isRecord7(exec2.shellStreamArgs)) {
28008
+ if (isRecord8(exec2.shellStreamArgs)) {
27254
28009
  const args = exec2.shellStreamArgs;
27255
28010
  const cwd = stringValue(args.workingDirectory);
27256
28011
  return [
27257
28012
  execReply(exec2, "shellStream", {
27258
- start: isRecord7(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
28013
+ start: isRecord8(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
27259
28014
  }),
27260
28015
  execReply(exec2, "shellStream", { stderr: { data: shellMessage } }),
27261
28016
  execReply(exec2, "shellStream", { exit: { code: 1, cwd, aborted: true } }),
@@ -27263,7 +28018,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27263
28018
  { execClientControlMessage: { streamClose: { id: numberValue(exec2.id) } } }
27264
28019
  ];
27265
28020
  }
27266
- if (isRecord7(exec2.backgroundShellSpawnArgs)) {
28021
+ if (isRecord8(exec2.backgroundShellSpawnArgs)) {
27267
28022
  const args = exec2.backgroundShellSpawnArgs;
27268
28023
  return [execReply(exec2, "backgroundShellSpawnResult", {
27269
28024
  error: {
@@ -27273,15 +28028,15 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27273
28028
  }
27274
28029
  })];
27275
28030
  }
27276
- if (isRecord7(exec2.writeShellStdinArgs)) {
28031
+ if (isRecord8(exec2.writeShellStdinArgs)) {
27277
28032
  return [execReply(exec2, "writeShellStdinResult", { error: { error: shellMessage } })];
27278
28033
  }
27279
- if (isRecord7(exec2.fetchArgs)) {
28034
+ if (isRecord8(exec2.fetchArgs)) {
27280
28035
  return [execReply(exec2, "fetchResult", {
27281
28036
  error: { url: stringValue(exec2.fetchArgs.url), error: networkMessage }
27282
28037
  })];
27283
28038
  }
27284
- if (isRecord7(exec2.diagnosticsArgs)) {
28039
+ if (isRecord8(exec2.diagnosticsArgs)) {
27285
28040
  return [execReply(exec2, "diagnosticsResult", {
27286
28041
  error: {
27287
28042
  path: stringValue(exec2.diagnosticsArgs.path),
@@ -27289,12 +28044,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27289
28044
  }
27290
28045
  })];
27291
28046
  }
27292
- if (isRecord7(exec2.listMcpResourcesExecArgs)) {
28047
+ if (isRecord8(exec2.listMcpResourcesExecArgs)) {
27293
28048
  return [execReply(exec2, "listMcpResourcesExecResult", {
27294
28049
  error: { error: retryMessage(clientTools, ["ListMcpResources", "list_mcp_resources"]) }
27295
28050
  })];
27296
28051
  }
27297
- if (isRecord7(exec2.readMcpResourceExecArgs)) {
28052
+ if (isRecord8(exec2.readMcpResourceExecArgs)) {
27298
28053
  return [execReply(exec2, "readMcpResourceExecResult", {
27299
28054
  error: {
27300
28055
  uri: stringValue(exec2.readMcpResourceExecArgs.uri),
@@ -27302,12 +28057,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27302
28057
  }
27303
28058
  })];
27304
28059
  }
27305
- if (isRecord7(exec2.recordScreenArgs)) {
28060
+ if (isRecord8(exec2.recordScreenArgs)) {
27306
28061
  return [execReply(exec2, "recordScreenResult", {
27307
28062
  failure: { error: retryMessage(clientTools, ["record_screen", "computer_use"]) }
27308
28063
  })];
27309
28064
  }
27310
- if (isRecord7(exec2.computerUseArgs)) {
28065
+ if (isRecord8(exec2.computerUseArgs)) {
27311
28066
  return [execReply(exec2, "computerUseResult", {
27312
28067
  error: {
27313
28068
  error: retryMessage(clientTools, ["computer_use"]),
@@ -27317,7 +28072,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
27317
28072
  }
27318
28073
  })];
27319
28074
  }
27320
- if (isRecord7(exec2.mcpArgs)) {
28075
+ if (isRecord8(exec2.mcpArgs)) {
27321
28076
  return [execReply(exec2, "mcpResult", {
27322
28077
  error: { error: retryMessage(clientTools, []) }
27323
28078
  })];
@@ -27389,7 +28144,7 @@ function numberValue(value) {
27389
28144
  function stringValue(value) {
27390
28145
  return typeof value === "string" ? value : "";
27391
28146
  }
27392
- function isRecord7(value) {
28147
+ function isRecord8(value) {
27393
28148
  return typeof value === "object" && value !== null && !Array.isArray(value);
27394
28149
  }
27395
28150
  var EXECUTE_HOOK_FIELD_NUMBER = 27;
@@ -27541,14 +28296,14 @@ function isCursorNativeRedirectToolName(name) {
27541
28296
  function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
27542
28297
  const messageId = numberValue2(exec2.id ?? 0);
27543
28298
  const execId = stringValue2(exec2.execId) || `redirect-${messageId}`;
27544
- if (isRecord8(exec2.readArgs)) {
27545
- const path72 = stringValue2(exec2.readArgs.path);
27546
- if (!path72) return null;
28299
+ if (isRecord9(exec2.readArgs)) {
28300
+ const path82 = stringValue2(exec2.readArgs.path);
28301
+ if (!path82) return null;
27547
28302
  if ([exec2.readArgs.offset, exec2.readArgs.limit].some((value) => typeof value === "number" && value < 0)) return null;
27548
28303
  const offset = positiveNumber(exec2.readArgs.offset);
27549
28304
  const limit = positiveNumber(exec2.readArgs.limit);
27550
28305
  if (offset !== void 0 || limit !== void 0) return null;
27551
- const mapped = tools.filter((tool) => matchesLeaf(tool, READ_CANDIDATES)).map((tool) => ({ tool, args: readArguments(tool.inputSchemaValue, path72) })).find((candidate) => candidate.args !== null);
28306
+ const mapped = tools.filter((tool) => matchesLeaf(tool, READ_CANDIDATES)).map((tool) => ({ tool, args: readArguments(tool.inputSchemaValue, path82) })).find((candidate) => candidate.args !== null);
27552
28307
  if (!mapped?.args) return null;
27553
28308
  return redirect(
27554
28309
  exec2,
@@ -27560,14 +28315,14 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
27560
28315
  "readResult",
27561
28316
  "read-direct",
27562
28317
  mapped.args,
27563
- { path: path72 }
28318
+ { path: path82 }
27564
28319
  );
27565
28320
  }
27566
- if (isRecord8(exec2.grepArgs)) {
28321
+ if (isRecord9(exec2.grepArgs)) {
27567
28322
  const grepArgs = exec2.grepArgs;
27568
28323
  const pattern = stringValue2(grepArgs.pattern);
27569
28324
  if (!pattern.trim()) return null;
27570
- const path72 = stringValue2(grepArgs.path) || ".";
28325
+ const path82 = stringValue2(grepArgs.path) || ".";
27571
28326
  const glob = stringValue2(grepArgs.glob);
27572
28327
  const outputMode = normalizedGrepOutputMode(stringValue2(grepArgs.outputMode));
27573
28328
  if (!outputMode) return null;
@@ -27583,7 +28338,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
27583
28338
  if (numericOptions.some((value) => typeof value === "number" && value < 0)) return null;
27584
28339
  const mappingInput = {
27585
28340
  pattern,
27586
- path: path72,
28341
+ path: path82,
27587
28342
  glob,
27588
28343
  outputMode,
27589
28344
  caseInsensitive: grepArgs.caseInsensitive === true,
@@ -27600,7 +28355,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
27600
28355
  const mapped = tools.filter((tool) => matchesLeaf(tool, GREP_CANDIDATES)).map((tool) => ({ tool, args: grepArguments(tool, mappingInput) })).find((candidate) => candidate.args !== null);
27601
28356
  const nativeArgs = {
27602
28357
  pattern,
27603
- path: path72,
28358
+ path: path82,
27604
28359
  outputMode,
27605
28360
  ...glob ? { glob } : {},
27606
28361
  ...positiveNumber(grepArgs.offset) === void 0 ? {} : { offset: String(positiveNumber(grepArgs.offset)) }
@@ -27637,15 +28392,15 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
27637
28392
  nativeArgs
27638
28393
  );
27639
28394
  }
27640
- if (isRecord8(exec2.shellArgs) || isRecord8(exec2.shellStreamArgs)) {
27641
- const argsRecord = isRecord8(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
28395
+ if (isRecord9(exec2.shellArgs) || isRecord9(exec2.shellStreamArgs)) {
28396
+ const argsRecord = isRecord9(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
27642
28397
  const command2 = stringValue2(argsRecord.command);
27643
28398
  if (!command2) return null;
27644
28399
  const cwd = stringValue2(argsRecord.workingDirectory);
27645
28400
  const timeout = positiveNumber(argsRecord.timeout) ?? positiveNumber(argsRecord.hardTimeout);
27646
28401
  const mapped = tools.filter((tool) => matchesLeaf(tool, SHELL_CANDIDATES)).map((tool) => ({ tool, args: shellArguments(tool.inputSchemaValue, command2, cwd || void 0, timeout) })).find((candidate) => candidate.args !== null);
27647
28402
  if (!mapped?.args) return null;
27648
- const stream = isRecord8(exec2.shellStreamArgs);
28403
+ const stream = isRecord9(exec2.shellStreamArgs);
27649
28404
  return redirect(
27650
28405
  exec2,
27651
28406
  mapped.tool,
@@ -27735,9 +28490,9 @@ function cursorNativeRedirectErrorReplies(correlation, error51) {
27735
28490
  }
27736
28491
  }
27737
28492
  }
27738
- function readArguments(schema, path72) {
28493
+ function readArguments(schema, path82) {
27739
28494
  const pathKey = firstSchemaProperty(schema, ["file_path", "path"]);
27740
- return pathKey ? { [pathKey]: path72 } : null;
28495
+ return pathKey ? { [pathKey]: path82 } : null;
27741
28496
  }
27742
28497
  function grepArguments(tool, input) {
27743
28498
  const leaf = normalizedLeaf(tool.clientName);
@@ -27898,7 +28653,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
27898
28653
  output.slice(CURSOR_GREP_RECEIPT_PREFIX.length).trim(),
27899
28654
  "base64url"
27900
28655
  ).toString("utf8"));
27901
- if (!isRecord8(decoded)) throw new Error("receipt is not an object");
28656
+ if (!isRecord9(decoded)) throw new Error("receipt is not an object");
27902
28657
  if (decoded.ok === false && typeof decoded.error === "string") {
27903
28658
  return { ok: false, error: decoded.error };
27904
28659
  }
@@ -27911,7 +28666,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
27911
28666
  if (!Array.isArray(decoded.counts) || !decoded.counts.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && typeof entry[1] === "number" && Number.isSafeInteger(entry[1]) && entry[1] >= 0)) {
27912
28667
  throw new Error("receipt counts are invalid");
27913
28668
  }
27914
- if (!Array.isArray(decoded.matches) || !decoded.matches.every((entry) => isRecord8(entry) && typeof entry.file === "string" && typeof entry.lineNumber === "number" && Number.isSafeInteger(entry.lineNumber) && entry.lineNumber > 0 && typeof entry.content === "string" && typeof entry.contentTruncated === "boolean" && typeof entry.isContextLine === "boolean")) {
28669
+ if (!Array.isArray(decoded.matches) || !decoded.matches.every((entry) => isRecord9(entry) && typeof entry.file === "string" && typeof entry.lineNumber === "number" && Number.isSafeInteger(entry.lineNumber) && entry.lineNumber > 0 && typeof entry.content === "string" && typeof entry.contentTruncated === "boolean" && typeof entry.isContextLine === "boolean")) {
27915
28670
  throw new Error("receipt matches are invalid");
27916
28671
  }
27917
28672
  for (const key of ["totalFiles", "totalLines", "totalMatchedLines"]) {
@@ -27929,7 +28684,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
27929
28684
  }
27930
28685
  }
27931
28686
  function buildGrepReceiptSuccess(args, receipt) {
27932
- const path72 = args.path || ".";
28687
+ const path82 = args.path || ".";
27933
28688
  let result;
27934
28689
  if (receipt.outputMode === "files_with_matches") {
27935
28690
  result = {
@@ -27975,15 +28730,15 @@ function buildGrepReceiptSuccess(args, receipt) {
27975
28730
  }
27976
28731
  return {
27977
28732
  pattern: args.pattern ?? "",
27978
- path: path72,
28733
+ path: path82,
27979
28734
  outputMode: receipt.outputMode,
27980
- workspaceResults: { [path72]: result }
28735
+ workspaceResults: { [path82]: result }
27981
28736
  };
27982
28737
  }
27983
28738
  function buildGrepSuccess(args, output) {
27984
28739
  const outputMode = normalizedGrepOutputMode(args.outputMode) ?? "content";
27985
28740
  const lines = output.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.length > 0 && !line.startsWith("[") && !/^no matches/i.test(line));
27986
- const path72 = args.path || ".";
28741
+ const path82 = args.path || ".";
27987
28742
  let result;
27988
28743
  if (outputMode === "files_with_matches") {
27989
28744
  result = {
@@ -28046,9 +28801,9 @@ function buildGrepSuccess(args, output) {
28046
28801
  }
28047
28802
  return {
28048
28803
  pattern: args.pattern ?? "",
28049
- path: path72,
28804
+ path: path82,
28050
28805
  outputMode,
28051
- workspaceResults: { [path72]: result }
28806
+ workspaceResults: { [path82]: result }
28052
28807
  };
28053
28808
  }
28054
28809
  function parseCallerShellOutput(output, isError) {
@@ -28110,7 +28865,7 @@ function redirect(exec2, tool, providerIdentifier, messageId, execId, execCase,
28110
28865
  }
28111
28866
  function execArgsToolCallId(exec2) {
28112
28867
  for (const value of Object.values(exec2)) {
28113
- if (!isRecord8(value)) continue;
28868
+ if (!isRecord9(value)) continue;
28114
28869
  const toolCallId = stringValue2(value.toolCallId);
28115
28870
  if (toolCallId) return toolCallId;
28116
28871
  }
@@ -28131,7 +28886,7 @@ function firstSchemaProperty(schema, candidates) {
28131
28886
  return candidates.find((candidate) => schemaHasProperty(schema, candidate));
28132
28887
  }
28133
28888
  function schemaHasProperty(schema, name) {
28134
- return isRecord8(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
28889
+ return isRecord9(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
28135
28890
  }
28136
28891
  function execReply2(exec2, resultName, result) {
28137
28892
  return {
@@ -28152,13 +28907,13 @@ function numberOrUndefined(value) {
28152
28907
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
28153
28908
  }
28154
28909
  function positiveNumber(value) {
28155
- const number32 = numberOrUndefined(value);
28156
- return number32 !== void 0 && number32 > 0 ? number32 : void 0;
28910
+ const number42 = numberOrUndefined(value);
28911
+ return number42 !== void 0 && number42 > 0 ? number42 : void 0;
28157
28912
  }
28158
28913
  function stringValue2(value) {
28159
28914
  return typeof value === "string" ? value : "";
28160
28915
  }
28161
- function isRecord8(value) {
28916
+ function isRecord9(value) {
28162
28917
  return typeof value === "object" && value !== null && !Array.isArray(value);
28163
28918
  }
28164
28919
  var cursorAgentDescriptor = [
@@ -28989,18 +29744,18 @@ function decodeCursorServerMessage(payload) {
28989
29744
  const message = fromBinary(AgentServerMessageSchema, payload);
28990
29745
  const unknownExecFields = extractCursorUnknownExecFields(message);
28991
29746
  const json3 = toJson(AgentServerMessageSchema, message);
28992
- if (!isRecord9(json3)) throw new TypeError("Cursor server frame was not a message object");
29747
+ if (!isRecord10(json3)) throw new TypeError("Cursor server frame was not a message object");
28993
29748
  if (unknownExecFields.length > 0) {
28994
29749
  Object.defineProperty(json3, CURSOR_UNKNOWN_EXEC_FIELDS, { value: unknownExecFields });
28995
29750
  }
28996
29751
  return json3;
28997
29752
  }
28998
29753
  function extractCursorUnknownExecFields(message) {
28999
- if (!isRecord9(message) || !isRecord9(message.message)) return [];
29000
- if (message.message.case !== "execServerMessage" || !isRecord9(message.message.value)) return [];
29754
+ if (!isRecord10(message) || !isRecord10(message.message)) return [];
29755
+ if (message.message.case !== "execServerMessage" || !isRecord10(message.message.value)) return [];
29001
29756
  const fields = message.message.value.$unknown;
29002
29757
  if (!Array.isArray(fields)) return [];
29003
- return fields.filter((field) => isRecord9(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
29758
+ return fields.filter((field) => isRecord10(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
29004
29759
  }
29005
29760
  function parseConnectEndStreamError(payload) {
29006
29761
  try {
@@ -29295,7 +30050,7 @@ function cursorToolArgumentBytes(argumentsText) {
29295
30050
  } catch {
29296
30051
  return {};
29297
30052
  }
29298
- if (!isRecord9(parsed)) return {};
30053
+ if (!isRecord10(parsed)) return {};
29299
30054
  return Object.fromEntries(Object.entries(parsed).map(([name, value]) => [
29300
30055
  name,
29301
30056
  Buffer.from(toBinary(ValueSchema, fromJson(ValueSchema, value))).toString("base64")
@@ -30272,7 +31027,7 @@ function createCursorLiveRun(options) {
30272
31027
  let blobFetchBytes = 0;
30273
31028
  let blobFetchMisses = 0;
30274
31029
  let redirectOperationSequence = 0;
30275
- const usage3 = (segment) => {
31030
+ const usage4 = (segment) => {
30276
31031
  const outputTokens = Math.max(
30277
31032
  segment.contextOutputTokens,
30278
31033
  estimateTokens(segment.outputText, model)
@@ -30318,7 +31073,7 @@ function createCursorLiveRun(options) {
30318
31073
  else if (segment.started) {
30319
31074
  segment.queue.push({
30320
31075
  type: "response.completed",
30321
- response: { id: segment.responseId, model, usage: usage3(segment) }
31076
+ response: { id: segment.responseId, model, usage: usage4(segment) }
30322
31077
  });
30323
31078
  }
30324
31079
  report("turn.finish", {
@@ -30385,7 +31140,7 @@ function createCursorLiveRun(options) {
30385
31140
  response: {
30386
31141
  id: activeSegment.responseId,
30387
31142
  model,
30388
- usage: usage3(activeSegment)
31143
+ usage: usage4(activeSegment)
30389
31144
  }
30390
31145
  });
30391
31146
  }
@@ -30575,7 +31330,7 @@ ${argumentsText}`;
30575
31330
  const handleFrame = (frame, replayed = false) => {
30576
31331
  const unknownExecFields = frame[CURSOR_UNKNOWN_EXEC_FIELDS] ?? [];
30577
31332
  lastFrame = describeCursorServerFrame(frame, unknownExecFields);
30578
- const tokenDetails = isRecord9(frame.conversationCheckpointUpdate) && isRecord9(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
31333
+ const tokenDetails = isRecord10(frame.conversationCheckpointUpdate) && isRecord10(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
30579
31334
  const checkpointContextTokens = positiveTokenCount(tokenDetails?.usedTokens);
30580
31335
  const checkpointContextWindow = positiveTokenCount(tokenDetails?.maxTokens);
30581
31336
  if (!replayed) {
@@ -30588,7 +31343,7 @@ ${argumentsText}`;
30588
31343
  ...checkpointContextWindow === void 0 ? {} : { contextWindow: checkpointContextWindow }
30589
31344
  });
30590
31345
  }
30591
- if (isRecord9(frame.conversationCheckpointUpdate)) {
31346
+ if (isRecord10(frame.conversationCheckpointUpdate)) {
30592
31347
  if (checkpointContextTokens !== void 0) {
30593
31348
  wireLog("cursor.wire.checkpoint", {
30594
31349
  model: diagnosticModel,
@@ -30611,7 +31366,7 @@ ${argumentsText}`;
30611
31366
  }
30612
31367
  return;
30613
31368
  }
30614
- if (isRecord9(frame.kvServerMessage)) {
31369
+ if (isRecord10(frame.kvServerMessage)) {
30615
31370
  const kv = kvReply(frame.kvServerMessage, blobs);
30616
31371
  stream.write(encodeCursorClientMessage(kv.message));
30617
31372
  if (kv.fetch) {
@@ -30632,7 +31387,7 @@ ${argumentsText}`;
30632
31387
  });
30633
31388
  return;
30634
31389
  }
30635
- if (isRecord9(frame.interactionQuery)) {
31390
+ if (isRecord10(frame.interactionQuery)) {
30636
31391
  const reply = cursorInteractionQueryReply(frame.interactionQuery);
30637
31392
  stream.write(encodeCursorClientMessage(reply.message));
30638
31393
  report("client.reply", { model: diagnosticModel, reply: reply.replyKind });
@@ -30648,7 +31403,7 @@ ${argumentsText}`;
30648
31403
  }
30649
31404
  return;
30650
31405
  }
30651
- if (isRecord9(frame.error)) {
31406
+ if (isRecord10(frame.error)) {
30652
31407
  if (state === "attached") {
30653
31408
  emit({ type: "error", error: cursorError(frame.error) });
30654
31409
  completeRun("server_error");
@@ -30677,8 +31432,8 @@ ${argumentsText}`;
30677
31432
  return;
30678
31433
  }
30679
31434
  if (state !== "attached") return;
30680
- if (isRecord9(frame.execServerMessage)) {
30681
- if (isRecord9(frame.execServerMessage.requestContextArgs)) {
31435
+ if (isRecord10(frame.execServerMessage)) {
31436
+ if (isRecord10(frame.execServerMessage.requestContextArgs)) {
30682
31437
  stream.write(encodeCursorClientMessage(cursorRequestContextReply(frame.execServerMessage, tools)));
30683
31438
  report("client.reply", { model: diagnosticModel, reply: "exec.requestContext" });
30684
31439
  return;
@@ -30767,10 +31522,10 @@ ${argumentsText}`;
30767
31522
  }
30768
31523
  return;
30769
31524
  }
30770
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
31525
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
30771
31526
  if (update === void 0) return;
30772
31527
  if (isSettledToolUpdate(update)) return;
30773
- if (isRecord9(update.textDelta) && typeof update.textDelta.text === "string") {
31528
+ if (isRecord10(update.textDelta) && typeof update.textDelta.text === "string") {
30774
31529
  activeSegment.outputText += update.textDelta.text;
30775
31530
  emit({
30776
31531
  type: "response.output_text.delta",
@@ -30781,7 +31536,7 @@ ${argumentsText}`;
30781
31536
  });
30782
31537
  return;
30783
31538
  }
30784
- if (isRecord9(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
31539
+ if (isRecord10(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
30785
31540
  activeSegment.outputText += update.thinkingDelta.text;
30786
31541
  emit({
30787
31542
  type: "response.reasoning_summary_text.delta",
@@ -30791,12 +31546,12 @@ ${argumentsText}`;
30791
31546
  });
30792
31547
  return;
30793
31548
  }
30794
- if (isRecord9(update.tokenDelta)) {
31549
+ if (isRecord10(update.tokenDelta)) {
30795
31550
  const tokens = positiveTokenCount(update.tokenDelta.tokens);
30796
31551
  if (tokens !== void 0) activeSegment.contextOutputTokens += tokens;
30797
31552
  return;
30798
31553
  }
30799
- if (isRecord9(update.toolCallStarted)) {
31554
+ if (isRecord10(update.toolCallStarted)) {
30800
31555
  const wireCall = mcpCallFromToolUpdate(update.toolCallStarted);
30801
31556
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
30802
31557
  if (call) {
@@ -30806,7 +31561,7 @@ ${argumentsText}`;
30806
31561
  }
30807
31562
  return;
30808
31563
  }
30809
- if (isRecord9(update.partialToolCall)) {
31564
+ if (isRecord10(update.partialToolCall)) {
30810
31565
  const wireCall = mcpCallFromToolUpdate(update.partialToolCall);
30811
31566
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
30812
31567
  if (!call) return;
@@ -30817,7 +31572,7 @@ ${argumentsText}`;
30817
31572
  rescheduleToolTurnFinish();
30818
31573
  return;
30819
31574
  }
30820
- if (isRecord9(update.toolCallCompleted)) {
31575
+ if (isRecord10(update.toolCallCompleted)) {
30821
31576
  const wireCall = mcpCallFromToolUpdate(update.toolCallCompleted);
30822
31577
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
30823
31578
  if (!call) return;
@@ -30830,7 +31585,7 @@ ${argumentsText}`;
30830
31585
  rescheduleToolTurnFinish();
30831
31586
  return;
30832
31587
  }
30833
- if (isRecord9(update.turnEnded)) completeRun("turn_ended");
31588
+ if (isRecord10(update.turnEnded)) completeRun("turn_ended");
30834
31589
  };
30835
31590
  const eventsFor = (segment) => (async function* () {
30836
31591
  try {
@@ -31040,34 +31795,34 @@ var CURSOR_INTERACTION_QUERY_CASES = [
31040
31795
  ];
31041
31796
  var CURSOR_KV_CASES = ["getBlobArgs", "setBlobArgs"];
31042
31797
  function describeCursorServerFrame(frame, unknownExecFields = []) {
31043
- if (isRecord9(frame.interactionUpdate)) {
31798
+ if (isRecord10(frame.interactionUpdate)) {
31044
31799
  return `interactionUpdate.${cursorNestedRecordCase(
31045
31800
  frame.interactionUpdate,
31046
31801
  CURSOR_INTERACTION_UPDATE_CASES
31047
31802
  )}`;
31048
31803
  }
31049
- if (isRecord9(frame.execServerMessage)) {
31804
+ if (isRecord10(frame.execServerMessage)) {
31050
31805
  const knownCase = cursorNestedRecordCase(frame.execServerMessage, CURSOR_EXEC_CASES);
31051
31806
  return `execServerMessage.${knownCase === "unknown" ? cursorUnknownExecCaseName(unknownExecFields) : knownCase}`;
31052
31807
  }
31053
- if (isRecord9(frame.interactionQuery)) {
31808
+ if (isRecord10(frame.interactionQuery)) {
31054
31809
  return `interactionQuery.${cursorNestedRecordCase(
31055
31810
  frame.interactionQuery,
31056
31811
  CURSOR_INTERACTION_QUERY_CASES
31057
31812
  )}`;
31058
31813
  }
31059
- if (isRecord9(frame.kvServerMessage)) {
31814
+ if (isRecord10(frame.kvServerMessage)) {
31060
31815
  return `kvServerMessage.${cursorNestedRecordCase(frame.kvServerMessage, CURSOR_KV_CASES)}`;
31061
31816
  }
31062
- if (isRecord9(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
31063
- if (isRecord9(frame.error)) return "error";
31817
+ if (isRecord10(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
31818
+ if (isRecord10(frame.error)) return "error";
31064
31819
  return "unknown";
31065
31820
  }
31066
31821
  function isCursorHeartbeatFrame(frame) {
31067
- return isRecord9(frame.interactionUpdate) && isRecord9(frame.interactionUpdate.heartbeat);
31822
+ return isRecord10(frame.interactionUpdate) && isRecord10(frame.interactionUpdate.heartbeat);
31068
31823
  }
31069
31824
  function cursorNestedRecordCase(value, cases) {
31070
- return cases.find((candidate) => isRecord9(value[candidate])) ?? "unknown";
31825
+ return cases.find((candidate) => isRecord10(value[candidate])) ?? "unknown";
31071
31826
  }
31072
31827
  function positiveTokenCount(value) {
31073
31828
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) return void 0;
@@ -31079,8 +31834,8 @@ function cursorInteractionQueryReply(query) {
31079
31834
  const response = (result = {}) => ({
31080
31835
  interactionResponse: { id, ...result }
31081
31836
  });
31082
- if (isRecord9(query.createPlanRequestQuery)) {
31083
- const args = isRecord9(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
31837
+ if (isRecord10(query.createPlanRequestQuery)) {
31838
+ const args = isRecord10(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
31084
31839
  const name = stringValue3(args?.name)?.trim();
31085
31840
  const overview = stringValue3(args?.overview)?.trim();
31086
31841
  const plan = stringValue3(args?.plan)?.trim();
@@ -31096,7 +31851,7 @@ function cursorInteractionQueryReply(query) {
31096
31851
  ` } : {}
31097
31852
  };
31098
31853
  }
31099
- if (isRecord9(query.askQuestionInteractionQuery)) {
31854
+ if (isRecord10(query.askQuestionInteractionQuery)) {
31100
31855
  return {
31101
31856
  message: response({
31102
31857
  askQuestionInteractionResponse: {
@@ -31106,7 +31861,7 @@ function cursorInteractionQueryReply(query) {
31106
31861
  replyKind: "interaction.askQuestion.rejected"
31107
31862
  };
31108
31863
  }
31109
- if (isRecord9(query.switchModeRequestQuery)) {
31864
+ if (isRecord10(query.switchModeRequestQuery)) {
31110
31865
  return {
31111
31866
  message: response({
31112
31867
  switchModeRequestResponse: {
@@ -31116,19 +31871,19 @@ function cursorInteractionQueryReply(query) {
31116
31871
  replyKind: "interaction.switchMode.rejected"
31117
31872
  };
31118
31873
  }
31119
- if (isRecord9(query.webSearchRequestQuery)) {
31874
+ if (isRecord10(query.webSearchRequestQuery)) {
31120
31875
  return {
31121
31876
  message: response({ webSearchRequestResponse: { approved: {} } }),
31122
31877
  replyKind: "interaction.webSearch.approved"
31123
31878
  };
31124
31879
  }
31125
- if (isRecord9(query.exaSearchRequestQuery)) {
31880
+ if (isRecord10(query.exaSearchRequestQuery)) {
31126
31881
  return {
31127
31882
  message: response({ exaSearchRequestResponse: { approved: {} } }),
31128
31883
  replyKind: "interaction.exaSearch.approved"
31129
31884
  };
31130
31885
  }
31131
- if (isRecord9(query.exaFetchRequestQuery)) {
31886
+ if (isRecord10(query.exaFetchRequestQuery)) {
31132
31887
  return {
31133
31888
  message: response({ exaFetchRequestResponse: { approved: {} } }),
31134
31889
  replyKind: "interaction.exaFetch.approved"
@@ -31138,7 +31893,7 @@ function cursorInteractionQueryReply(query) {
31138
31893
  }
31139
31894
  function kvReply(kv, blobs) {
31140
31895
  const id = kv.id ?? 0;
31141
- if (isRecord9(kv.getBlobArgs)) {
31896
+ if (isRecord10(kv.getBlobArgs)) {
31142
31897
  const blobId = typeof kv.getBlobArgs.blobId === "string" ? kv.getBlobArgs.blobId : "";
31143
31898
  const blobData = blobs.get(blobId);
31144
31899
  return {
@@ -31150,7 +31905,7 @@ function kvReply(kv, blobs) {
31150
31905
  }
31151
31906
  };
31152
31907
  }
31153
- if (isRecord9(kv.setBlobArgs)) {
31908
+ if (isRecord10(kv.setBlobArgs)) {
31154
31909
  const blobId = typeof kv.setBlobArgs.blobId === "string" ? kv.setBlobArgs.blobId : "";
31155
31910
  const blobData = typeof kv.setBlobArgs.blobData === "string" ? kv.setBlobArgs.blobData : "";
31156
31911
  if (blobId) blobs.set(blobId, blobData);
@@ -31201,7 +31956,7 @@ function repairCursorArgumentValue(value, schema) {
31201
31956
  return { value: String(value), count: 1 };
31202
31957
  }
31203
31958
  if (Array.isArray(value)) {
31204
- const itemSchema = isRecord9(schema) ? schema.items : void 0;
31959
+ const itemSchema = isRecord10(schema) ? schema.items : void 0;
31205
31960
  if (itemSchema === void 0) return { value, count: 0 };
31206
31961
  let repairedValues;
31207
31962
  let count2 = 0;
@@ -31214,7 +31969,7 @@ function repairCursorArgumentValue(value, schema) {
31214
31969
  });
31215
31970
  return { value: repairedValues ?? value, count: count2 };
31216
31971
  }
31217
- if (!isRecord9(value) || !isRecord9(schema) || !isRecord9(schema.properties)) {
31972
+ if (!isRecord10(value) || !isRecord10(schema) || !isRecord10(schema.properties)) {
31218
31973
  return { value, count: 0 };
31219
31974
  }
31220
31975
  let repairedValue;
@@ -31230,12 +31985,12 @@ function repairCursorArgumentValue(value, schema) {
31230
31985
  return { value: repairedValue ?? value, count };
31231
31986
  }
31232
31987
  function cursorSchemaRequiresString(schema) {
31233
- if (!isRecord9(schema)) return false;
31988
+ if (!isRecord10(schema)) return false;
31234
31989
  if (schema.type === "string") return true;
31235
31990
  return Array.isArray(schema.type) && schema.type.includes("string") && schema.type.every((type) => type === "string" || type === "null");
31236
31991
  }
31237
31992
  function mcpCallFromToolUpdate(value) {
31238
- const toolCall = isRecord9(value.toolCall) ? value.toolCall : void 0;
31993
+ const toolCall = isRecord10(value.toolCall) ? value.toolCall : void 0;
31239
31994
  const args = toolCall ? mcpArgsFromToolCall(toolCall) : void 0;
31240
31995
  if (!args) return null;
31241
31996
  const publicCallId = stringValue3(value.callId);
@@ -31260,7 +32015,7 @@ var CURSOR_TOOL_UPDATE_CASES = [
31260
32015
  function cursorToolUpdateIdentifiers(update) {
31261
32016
  for (const key of CURSOR_TOOL_UPDATE_CASES) {
31262
32017
  const value = update[key];
31263
- if (!isRecord9(value)) continue;
32018
+ if (!isRecord10(value)) continue;
31264
32019
  const call = mcpCallFromToolUpdate(value);
31265
32020
  if (!call) return [];
31266
32021
  return [...new Set(
@@ -31270,9 +32025,9 @@ function cursorToolUpdateIdentifiers(update) {
31270
32025
  return void 0;
31271
32026
  }
31272
32027
  function isCursorClientToolFrame(frame, tools, redirectTools) {
31273
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
32028
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
31274
32029
  if (update !== void 0) return cursorToolUpdateIdentifiers(update) !== void 0;
31275
- const exec2 = isRecord9(frame.execServerMessage) ? frame.execServerMessage : void 0;
32030
+ const exec2 = isRecord10(frame.execServerMessage) ? frame.execServerMessage : void 0;
31276
32031
  if (exec2 === void 0) return false;
31277
32032
  const wireCall = mcpCallFromExecMessage(exec2);
31278
32033
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
@@ -31288,16 +32043,16 @@ function isCursorClientToolFrame(frame, tools, redirectTools) {
31288
32043
  ) !== null;
31289
32044
  }
31290
32045
  function isCursorParkedResidueFrame(frame, parked) {
31291
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
32046
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
31292
32047
  if (update === void 0) return false;
31293
- if (isRecord9(update.tokenDelta)) return true;
32048
+ if (isRecord10(update.tokenDelta)) return true;
31294
32049
  const identifiers = cursorToolUpdateIdentifiers(update);
31295
32050
  if (identifiers === void 0 || identifiers.length === 0 || parked === void 0) return false;
31296
32051
  const sealed = new Set(parked.flatMap((call) => [call.callId, call.toolCallId]));
31297
32052
  return identifiers.some((identifier) => sealed.has(identifier));
31298
32053
  }
31299
32054
  function mcpCallFromExecMessage(value) {
31300
- const args = isRecord9(value.mcpArgs) ? value.mcpArgs : void 0;
32055
+ const args = isRecord10(value.mcpArgs) ? value.mcpArgs : void 0;
31301
32056
  if (!args) return null;
31302
32057
  const toolCallId = stringValue3(args.toolCallId);
31303
32058
  if (!toolCallId) return null;
@@ -31315,14 +32070,14 @@ function mcpCallFromExecMessage(value) {
31315
32070
  };
31316
32071
  }
31317
32072
  function mcpArgsFromToolCall(toolCall) {
31318
- const direct = isRecord9(toolCall.mcpToolCall) ? toolCall.mcpToolCall : void 0;
31319
- if (direct && isRecord9(direct.args)) return direct.args;
31320
- const tool = isRecord9(toolCall.tool) ? toolCall.tool : void 0;
31321
- const nested = tool && isRecord9(tool.mcpToolCall) ? tool.mcpToolCall : void 0;
31322
- return nested && isRecord9(nested.args) ? nested.args : void 0;
32073
+ const direct = isRecord10(toolCall.mcpToolCall) ? toolCall.mcpToolCall : void 0;
32074
+ if (direct && isRecord10(direct.args)) return direct.args;
32075
+ const tool = isRecord10(toolCall.tool) ? toolCall.tool : void 0;
32076
+ const nested = tool && isRecord10(tool.mcpToolCall) ? tool.mcpToolCall : void 0;
32077
+ return nested && isRecord10(nested.args) ? nested.args : void 0;
31323
32078
  }
31324
32079
  function cursorMcpArguments(args) {
31325
- if (!isRecord9(args.args) || Object.keys(args.args).length === 0) return {};
32080
+ if (!isRecord10(args.args) || Object.keys(args.args).length === 0) return {};
31326
32081
  const decoded = {};
31327
32082
  for (const [name, value] of Object.entries(args.args)) {
31328
32083
  if (typeof value !== "string") {
@@ -31397,7 +32152,7 @@ function cursorError(value) {
31397
32152
  message: typeof value.message === "string" ? value.message : "Cursor request failed"
31398
32153
  };
31399
32154
  }
31400
- function isRecord9(value) {
32155
+ function isRecord10(value) {
31401
32156
  return typeof value === "object" && value !== null && !Array.isArray(value);
31402
32157
  }
31403
32158
  var DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES = 4 * 1024 * 1024;
@@ -31431,7 +32186,7 @@ var CURSOR_DIAGNOSTIC_EVENTS = /* @__PURE__ */ new Set([
31431
32186
  "turn.finish"
31432
32187
  ]);
31433
32188
  function createCursorDiagnosticLog(dir, options = {}) {
31434
- const logPath = path23__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
32189
+ const logPath = path24__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
31435
32190
  const backupPath = `${logPath}.1`;
31436
32191
  const maxBytes = positiveInteger2(options.maxBytes) ?? DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES;
31437
32192
  let initialized = false;
@@ -31489,43 +32244,43 @@ function createCursorDiagnosticLog(dir, options = {}) {
31489
32244
  }
31490
32245
  function serializeCursorDiagnosticEvent(event) {
31491
32246
  if (!CURSOR_DIAGNOSTIC_EVENTS.has(event.event)) return null;
31492
- const record32 = {
32247
+ const record42 = {
31493
32248
  timestamp: safeString(event.timestamp, 40),
31494
32249
  runId: safeString(event.runId, 64),
31495
32250
  event: event.event,
31496
32251
  elapsedMs: safeNumber(event.elapsedMs)
31497
32252
  };
31498
- addString(record32, "model", event.model, 128);
31499
- addString(record32, "wireModel", event.wireModel, 128);
31500
- addString(record32, "previousWireModel", event.previousWireModel, 128);
32253
+ addString(record42, "model", event.model, 128);
32254
+ addString(record42, "wireModel", event.wireModel, 128);
32255
+ addString(record42, "previousWireModel", event.previousWireModel, 128);
31501
32256
  if (event.requestedEffort && CURSOR_DIAGNOSTIC_EFFORTS.has(event.requestedEffort)) {
31502
- record32.requestedEffort = event.requestedEffort;
31503
- }
31504
- if (event.turn === "prompt" || event.turn === "tool-continuation") record32.turn = event.turn;
31505
- addNumber(record32, "status", event.status);
31506
- addString(record32, "frame", event.frame, 128);
31507
- addString(record32, "reply", event.reply, 128);
31508
- addNumber(record32, "sequence", event.sequence);
31509
- addNumber(record32, "count", event.count);
31510
- addNumber(record32, "frameCount", event.frameCount);
31511
- addString(record32, "lastFrame", event.lastFrame, 128);
31512
- addNumber(record32, "toolCount", event.toolCount);
31513
- addNumber(record32, "argumentRepairCount", event.argumentRepairCount);
31514
- addNumber(record32, "estimatedInputTokens", event.estimatedInputTokens);
31515
- addNumber(record32, "contextTokens", event.contextTokens);
31516
- addNumber(record32, "contextWindow", event.contextWindow);
31517
- addString(record32, "outcome", event.outcome, 128);
31518
- addNumber(record32, "operationSequence", event.operationSequence);
31519
- addString(record32, "adapter", event.adapter, 32);
31520
- addString(record32, "error", event.error, 128);
31521
- return `${JSON.stringify(record32)}
32257
+ record42.requestedEffort = event.requestedEffort;
32258
+ }
32259
+ if (event.turn === "prompt" || event.turn === "tool-continuation") record42.turn = event.turn;
32260
+ addNumber(record42, "status", event.status);
32261
+ addString(record42, "frame", event.frame, 128);
32262
+ addString(record42, "reply", event.reply, 128);
32263
+ addNumber(record42, "sequence", event.sequence);
32264
+ addNumber(record42, "count", event.count);
32265
+ addNumber(record42, "frameCount", event.frameCount);
32266
+ addString(record42, "lastFrame", event.lastFrame, 128);
32267
+ addNumber(record42, "toolCount", event.toolCount);
32268
+ addNumber(record42, "argumentRepairCount", event.argumentRepairCount);
32269
+ addNumber(record42, "estimatedInputTokens", event.estimatedInputTokens);
32270
+ addNumber(record42, "contextTokens", event.contextTokens);
32271
+ addNumber(record42, "contextWindow", event.contextWindow);
32272
+ addString(record42, "outcome", event.outcome, 128);
32273
+ addNumber(record42, "operationSequence", event.operationSequence);
32274
+ addString(record42, "adapter", event.adapter, 32);
32275
+ addString(record42, "error", event.error, 128);
32276
+ return `${JSON.stringify(record42)}
31522
32277
  `;
31523
32278
  }
31524
- function addString(record32, key, value, maxLength) {
31525
- if (value !== void 0) record32[key] = safeString(value, maxLength);
32279
+ function addString(record42, key, value, maxLength) {
32280
+ if (value !== void 0) record42[key] = safeString(value, maxLength);
31526
32281
  }
31527
- function addNumber(record32, key, value) {
31528
- if (value !== void 0) record32[key] = safeNumber(value);
32282
+ function addNumber(record42, key, value) {
32283
+ if (value !== void 0) record42[key] = safeNumber(value);
31529
32284
  }
31530
32285
  function safeString(value, maxLength) {
31531
32286
  return value.replace(/[\r\n\t]/g, " ").slice(0, maxLength);
@@ -31575,8 +32330,8 @@ function kimiAnthropicHeaders(requestHeaders, apiKey) {
31575
32330
  return headers;
31576
32331
  }
31577
32332
  function normalizeAiGatewaySettings(value) {
31578
- if (!isRecord10(value) || value.version !== 1) return { version: 1 };
31579
- const models = Array.isArray(value.models) ? value.models.filter((entry) => isRecord10(entry) && typeof entry.id === "string" && entry.id.length > 0).flatMap((entry) => {
32333
+ if (!isRecord11(value) || value.version !== 1) return { version: 1 };
32334
+ const models = Array.isArray(value.models) ? value.models.filter((entry) => isRecord11(entry) && typeof entry.id === "string" && entry.id.length > 0).flatMap((entry) => {
31580
32335
  const model = findGatewayModel(entry.id);
31581
32336
  if (!model) return [];
31582
32337
  const efforts = Array.isArray(entry.efforts) ? entry.efforts.filter((level) => typeof level === "string" && level.length > 0) : [];
@@ -31610,7 +32365,7 @@ function sanitizeProviderPriority(value) {
31610
32365
  }
31611
32366
  return cleaned.length > 0 ? cleaned : void 0;
31612
32367
  }
31613
- function isRecord10(value) {
32368
+ function isRecord11(value) {
31614
32369
  return typeof value === "object" && value !== null && !Array.isArray(value);
31615
32370
  }
31616
32371
  function resolveAiGatewaySelection(settings2) {
@@ -31756,6 +32511,10 @@ async function readCursorSubscriptionToken() {
31756
32511
  const credentials = await resolveCursorCredentials(defaultCredentialDeps);
31757
32512
  return credentials?.accessToken ?? null;
31758
32513
  }
32514
+ async function readXaiSubscriptionToken() {
32515
+ const credentials = await resolveXaiCliCredentials(defaultCredentialDeps);
32516
+ return credentials?.accessToken ?? null;
32517
+ }
31759
32518
  async function readCodexSubscriptionAuth() {
31760
32519
  const credentials = await resolveCodexCredentials(defaultCredentialDeps);
31761
32520
  if (!credentials?.accountId) return null;
@@ -31853,6 +32612,10 @@ function createAiGatewayRouter(deps) {
31853
32612
  for (const skill of pruned.withheld) withheldSkills.add(skill.name);
31854
32613
  if (pruned.changed) body2 = { ...body2, messages: [...pruned.messages] };
31855
32614
  }
32615
+ if (target2 && target2.provider !== "kimi") {
32616
+ const omitted = omitClaudeWebSearchTools(body2);
32617
+ if (omitted.changed) body2 = omitted.request;
32618
+ }
31856
32619
  let credential = "";
31857
32620
  let chatgptAccountId = "";
31858
32621
  if (target2?.provider === "cursor") {
@@ -31884,6 +32647,13 @@ function createAiGatewayRouter(deps) {
31884
32647
  return true;
31885
32648
  }
31886
32649
  credential = opencodeApiKey;
32650
+ } else if (target2?.provider === "xai") {
32651
+ const xaiToken = await deps.readXaiToken?.();
32652
+ if (!xaiToken) {
32653
+ writeAnthropicError(res, 401, "authentication_error", "No active Grok CLI sign-in was found. Run `grok login` first.");
32654
+ return true;
32655
+ }
32656
+ credential = xaiToken;
31887
32657
  }
31888
32658
  const controller = new AbortController();
31889
32659
  const abort = () => controller.abort(new Error("client disconnected"));
@@ -31920,7 +32690,7 @@ function createAiGatewayRouter(deps) {
31920
32690
  );
31921
32691
  return true;
31922
32692
  }
31923
- const gateway = deps.gateway ?? (target2.provider === "cursor" ? ownedCursorGateway : target2.provider === "opencode" ? createOpencodeGateway(opencodeGoWire(target2)) : createGatewayFor(target2, chatgptAccountId, deps.originator));
32693
+ const gateway = deps.gateway ?? (target2.provider === "cursor" ? ownedCursorGateway : target2.provider === "opencode" ? createOpencodeGateway(opencodeGoWire(target2)) : target2.provider === "xai" ? new AnthropicMessagesGateway(new XaiResponsesAdapter({ fetch: fetchImpl })) : createGatewayFor(target2, chatgptAccountId, deps.originator));
31924
32694
  const diagnosticsEnabled = target2.provider === "cursor" ? cursorDiagnosticsEnabled() : void 0;
31925
32695
  const modelContextWindow = typeof target2.contextWindow === "number" && Number.isFinite(target2.contextWindow) && target2.contextWindow > 0 ? target2.contextWindow : void 0;
31926
32696
  const upstream = await gateway.stream(body2, {
@@ -32026,11 +32796,11 @@ var LOCK_OWNER_FILE_NAME2 = "owner";
32026
32796
  var TEMP_FILE_PREFIX2 = `${AI_GATEWAY_SETTINGS_FILE_NAME}.`;
32027
32797
  function createAiGatewaySettingsStore(deps = {}) {
32028
32798
  const dataDir = deps.dataDir ?? getFleetDataDir();
32029
- const settingsPath = path23.join(dataDir, AI_GATEWAY_SETTINGS_FILE_NAME);
32030
- const legacyPath = deps.legacyDir === void 0 ? void 0 : path23.join(deps.legacyDir, AI_GATEWAY_SETTINGS_FILE_NAME);
32799
+ const settingsPath = path24.join(dataDir, AI_GATEWAY_SETTINGS_FILE_NAME);
32800
+ const legacyPath = deps.legacyDir === void 0 ? void 0 : path24.join(deps.legacyDir, AI_GATEWAY_SETTINGS_FILE_NAME);
32031
32801
  const store = createDurableJsonStore({
32032
32802
  filePath: settingsPath,
32033
- lockDir: path23.join(dataDir, LOCK_DIR_NAME2),
32803
+ lockDir: path24.join(dataDir, LOCK_DIR_NAME2),
32034
32804
  lockOwnerFileName: LOCK_OWNER_FILE_NAME2,
32035
32805
  sanitize: (value) => normalizeAiGatewaySettings(value),
32036
32806
  sensitivity: "sensitive",
@@ -32360,9 +33130,14 @@ var FLEET_MCP_SERVER_NAME = "fleet";
32360
33130
  function isHostSessionToolAllowed(_toolId, _doctrine) {
32361
33131
  return true;
32362
33132
  }
32363
-
32364
- // ../../packages/fleet-admiral/src/agent-cli/prompt.ts
32365
33133
  var CMD_UNSAFE_PROMPT_PATTERN = /["&<>()@^|%]/;
33134
+ var LAUNCH_PROMPT_FILE_MODE = 384;
33135
+ var LAUNCH_PROMPT_TEMP_DIR_PREFIX = "fleet-quick-launch-";
33136
+ var LAUNCH_PROMPT_FILE_NAME = "prompt.md";
33137
+ var LAUNCH_PROMPT_FILE_INSTRUCTION_PREFIX = "Read and follow the launch prompt file: ";
33138
+ function launchPromptHasCmdUnsafeChars(prompt) {
33139
+ return CMD_UNSAFE_PROMPT_PATTERN.test(prompt);
33140
+ }
32366
33141
  var WINDOWS_CMD_SHIM_COMMAND_LINE_MAX_CHARS = 8191;
32367
33142
  var WINDOWS_CREATE_PROCESS_COMMAND_LINE_MAX_CHARS = 32767;
32368
33143
  var LaunchPromptError = class extends Error {
@@ -32426,6 +33201,12 @@ function assertLaunchCommandLineBudget(options) {
32426
33201
  `The launch command line is ${withoutPrompt} characters before any launch prompt, over the ${limit.maxChars}-character Windows ${boundary} limit. Shortening the prompt cannot help; reduce the launch configuration instead.`
32427
33202
  );
32428
33203
  }
33204
+ if (options.promptIsFixedLength === true) {
33205
+ throw new LaunchPromptError(
33206
+ "launch_command_line_too_long",
33207
+ `The launch command line is ${total} characters, over the ${limit.maxChars}-character Windows ${boundary} limit even after moving the launch prompt into a file. Shortening the prompt cannot help; reduce the launch configuration instead.`
33208
+ );
33209
+ }
32429
33210
  const shortenByChars = total - limit.maxChars;
32430
33211
  throw new LaunchPromptError(
32431
33212
  "prompt_command_line_too_long",
@@ -32439,6 +33220,57 @@ function sanitizeLaunchPrompt(value) {
32439
33220
  const trimmed = normalized.trim();
32440
33221
  return trimmed.length === 0 ? void 0 : trimmed;
32441
33222
  }
33223
+ function formatLaunchPromptFileInstruction(filePath) {
33224
+ return `${LAUNCH_PROMPT_FILE_INSTRUCTION_PREFIX}${filePath}`;
33225
+ }
33226
+ function writeLaunchPromptPointer(body2, onCleanup, cmdWrapped) {
33227
+ const written = writeLaunchPromptFile(body2, onCleanup);
33228
+ try {
33229
+ assertLaunchPromptShimSafe(written.instruction, cmdWrapped ? ["cmd-shim"] : []);
33230
+ } catch (error51) {
33231
+ written.cleanup();
33232
+ if (error51 instanceof LaunchPromptError && error51.code === "prompt_unsafe_for_shim") {
33233
+ throw new LaunchPromptError(
33234
+ "prompt_unsafe_for_shim",
33235
+ 'The launch prompt file path contains a character cmd.exe would reinterpret (" & < > ( ) @ ^ | %) while running the Windows shim. Fleet cannot start this launch from the current Windows temp directory.'
33236
+ );
33237
+ }
33238
+ throw error51;
33239
+ }
33240
+ return written.instruction;
33241
+ }
33242
+ function writeLaunchPromptFile(body2, onCleanup) {
33243
+ const tempRoot = path24__default.resolve(os3__default.tmpdir());
33244
+ mkdirSync(tempRoot, { recursive: true });
33245
+ const tempDir = mkdtempSync(path24__default.join(tempRoot, LAUNCH_PROMPT_TEMP_DIR_PREFIX));
33246
+ const cleanup = () => rmBestEffort(tempDir);
33247
+ try {
33248
+ const filePath = path24__default.join(tempDir, LAUNCH_PROMPT_FILE_NAME);
33249
+ writeFileSync(filePath, body2, { encoding: "utf8", flag: "wx", mode: LAUNCH_PROMPT_FILE_MODE });
33250
+ chmodBestEffort(filePath, LAUNCH_PROMPT_FILE_MODE);
33251
+ onCleanup(cleanup);
33252
+ return {
33253
+ cleanup,
33254
+ filePath,
33255
+ instruction: formatLaunchPromptFileInstruction(filePath)
33256
+ };
33257
+ } catch (error51) {
33258
+ cleanup();
33259
+ throw error51;
33260
+ }
33261
+ }
33262
+ function chmodBestEffort(targetPath, mode) {
33263
+ try {
33264
+ chmodSync(targetPath, mode);
33265
+ } catch {
33266
+ }
33267
+ }
33268
+ function rmBestEffort(targetPath) {
33269
+ try {
33270
+ rmSync(targetPath, { force: true, recursive: true });
33271
+ } catch {
33272
+ }
33273
+ }
32442
33274
 
32443
33275
  // ../../packages/fleet-admiral/src/ai-gateway/auth.ts
32444
33276
  async function validateKimiAuthKey(apiKey) {
@@ -32495,9 +33327,9 @@ function prepareAiGatewayLaunchProfile(profile, options) {
32495
33327
  return { ...profile, env };
32496
33328
  }
32497
33329
  function writeClaudeGatewayModelCache(baseUrl, env, homeDir, exposedModels = GATEWAY_MODELS) {
32498
- const configDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : path23__default.join(homeDir, ".claude");
32499
- const cacheDir = path23__default.join(configDir, "cache");
32500
- const cachePath = path23__default.join(cacheDir, "gateway-models.json");
33330
+ const configDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : path24__default.join(homeDir, ".claude");
33331
+ const cacheDir = path24__default.join(configDir, "cache");
33332
+ const cachePath = path24__default.join(cacheDir, "gateway-models.json");
32501
33333
  const models = buildAnthropicModelList(exposedModels).data.filter((model) => /^(claude|anthropic)/i.test(model.id)).map((model) => ({ id: model.id, display_name: model.display_name }));
32502
33334
  fs9__default.mkdirSync(cacheDir, { recursive: true, mode: 448 });
32503
33335
  writeAtomicSync(cachePath, JSON.stringify({ baseUrl, fetchedAt: Date.now(), models }), { mode: 384 });
@@ -32786,7 +33618,7 @@ async function resolveLoadout(deps) {
32786
33618
  }
32787
33619
 
32788
33620
  // ../../packages/fleet-admiral/src/ai-gateway/quota-snapshot.ts
32789
- function record3(value) {
33621
+ function record4(value) {
32790
33622
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
32791
33623
  }
32792
33624
  var AMOUNT_PATTERN = /^\d{1,15}$/;
@@ -32794,7 +33626,7 @@ var MAX_WINDOW_DURATION_MS2 = 400 * 24 * 36e5;
32794
33626
  var DURATION_BASES = /* @__PURE__ */ new Set(["upstream", "catalog"]);
32795
33627
  var START_BASES = /* @__PURE__ */ new Set(["upstream", "derived"]);
32796
33628
  function toWindowPeriod(value) {
32797
- const period = record3(value);
33629
+ const period = record4(value);
32798
33630
  if (!period) return void 0;
32799
33631
  const durationMs = period.durationMs;
32800
33632
  const durationBasis = period.durationBasis;
@@ -32811,7 +33643,7 @@ function toWindowPeriod(value) {
32811
33643
  };
32812
33644
  }
32813
33645
  function toWindowAmounts(value) {
32814
- const amounts = record3(value);
33646
+ const amounts = record4(value);
32815
33647
  if (!amounts) return void 0;
32816
33648
  const used = amounts.used;
32817
33649
  const limit = amounts.limit;
@@ -32820,14 +33652,14 @@ function toWindowAmounts(value) {
32820
33652
  return { used, limit };
32821
33653
  }
32822
33654
  function parseGatewayQuotaSnapshot(value) {
32823
- const providers = record3(record3(value)?.providers);
33655
+ const providers = record4(record4(value)?.providers);
32824
33656
  if (!providers) return void 0;
32825
33657
  const snapshot = {};
32826
33658
  for (const [id, value2] of Object.entries(providers)) {
32827
- const provider = record3(value2);
33659
+ const provider = record4(value2);
32828
33660
  if (!provider || typeof provider.status !== "string") continue;
32829
33661
  const windows = Array.isArray(provider.windows) ? provider.windows.flatMap((entry) => {
32830
- const window = record3(entry);
33662
+ const window = record4(entry);
32831
33663
  if (!window || typeof window.id !== "string" || typeof window.usedPercent !== "number") return [];
32832
33664
  const period = toWindowPeriod(window.period);
32833
33665
  const amounts = toWindowAmounts(window.amounts);
@@ -32860,7 +33692,6 @@ function createClaudeFamilyCliDefinition(options) {
32860
33692
  async createProfile(profileOptions) {
32861
33693
  const { bin, prefixArgs } = resolveBinary("claude", "CLAUDE_BIN", profileOptions.env);
32862
33694
  const launchPrompt = sanitizeLaunchPrompt(profileOptions.prompt);
32863
- assertLaunchPromptShimSafe(launchPrompt, prefixArgs);
32864
33695
  const commandLineLimit = resolveLaunchCommandLineLimit(prefixArgs);
32865
33696
  const childEnv = createChildEnv(profileOptions.env, {});
32866
33697
  return {
@@ -33026,9 +33857,9 @@ function writePrivateJson(filePath, value, rootBase) {
33026
33857
  function writePrivateFile(filePath, content, rootBase) {
33027
33858
  const resolvedBase = ensureRootBase(rootBase);
33028
33859
  ensurePathWithinRoot(resolvedBase, filePath);
33029
- ensureDirectorySegments(resolvedBase, path23__default.dirname(filePath));
33860
+ ensureDirectorySegments(resolvedBase, path24__default.dirname(filePath));
33030
33861
  writeFileNoFollow(filePath, content);
33031
- chmodBestEffort(filePath, FILE_MODE);
33862
+ chmodBestEffort2(filePath, FILE_MODE);
33032
33863
  }
33033
33864
  function removePrivatePath(targetPath, rootBase) {
33034
33865
  const resolvedBase = assertRootBaseSafe(rootBase);
@@ -33056,7 +33887,7 @@ function cleanupPrivateRoot(rootPath, rootBase) {
33056
33887
  throw error51;
33057
33888
  }
33058
33889
  }
33059
- function chmodBestEffort(targetPath, mode) {
33890
+ function chmodBestEffort2(targetPath, mode) {
33060
33891
  try {
33061
33892
  chmodSync(targetPath, mode);
33062
33893
  } catch (_error) {
@@ -33073,20 +33904,20 @@ function writeFileNoFollow(filePath, content) {
33073
33904
  }
33074
33905
  }
33075
33906
  function ensureRootBase(rootBase) {
33076
- const resolvedBase = path23__default.resolve(rootBase);
33077
- const anchor = findExistingDirectoryAnchor(path23__default.dirname(resolvedBase));
33907
+ const resolvedBase = path24__default.resolve(rootBase);
33908
+ const anchor = findExistingDirectoryAnchor(path24__default.dirname(resolvedBase));
33078
33909
  ensureDirectorySegments(anchor, resolvedBase);
33079
33910
  assertDirectorySafe(resolvedBase, "Plugin root base");
33080
33911
  return resolvedBase;
33081
33912
  }
33082
33913
  function assertRootBaseSafe(rootBase) {
33083
- const resolvedBase = path23__default.resolve(rootBase);
33084
- assertExistingSegmentsSafe(findExistingDirectoryAnchor(path23__default.dirname(resolvedBase)), resolvedBase);
33914
+ const resolvedBase = path24__default.resolve(rootBase);
33915
+ assertExistingSegmentsSafe(findExistingDirectoryAnchor(path24__default.dirname(resolvedBase)), resolvedBase);
33085
33916
  assertDirectorySafe(resolvedBase, "Plugin root base");
33086
33917
  return resolvedBase;
33087
33918
  }
33088
33919
  function findExistingDirectoryAnchor(targetPath) {
33089
- const resolvedTarget = path23__default.resolve(targetPath);
33920
+ const resolvedTarget = path24__default.resolve(targetPath);
33090
33921
  let current = resolvedTarget;
33091
33922
  while (true) {
33092
33923
  try {
@@ -33094,7 +33925,7 @@ function findExistingDirectoryAnchor(targetPath) {
33094
33925
  return current;
33095
33926
  } catch (error51) {
33096
33927
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
33097
- const parent = path23__default.dirname(current);
33928
+ const parent = path24__default.dirname(current);
33098
33929
  if (parent === current) throw error51;
33099
33930
  current = parent;
33100
33931
  continue;
@@ -33113,17 +33944,17 @@ function assertDirectorySafe(dirPath, label) {
33113
33944
  }
33114
33945
  }
33115
33946
  function ensurePathWithinRoot(resolvedBase, candidatePath) {
33116
- const resolvedCandidate = path23__default.resolve(candidatePath);
33117
- const relative = path23__default.relative(resolvedBase, resolvedCandidate);
33118
- if (relative === "" || !relative.startsWith("..") && !path23__default.isAbsolute(relative)) return;
33947
+ const resolvedCandidate = path24__default.resolve(candidatePath);
33948
+ const relative = path24__default.relative(resolvedBase, resolvedCandidate);
33949
+ if (relative === "" || !relative.startsWith("..") && !path24__default.isAbsolute(relative)) return;
33119
33950
  throw new Error(`Plugin path escapes root base: ${candidatePath}`);
33120
33951
  }
33121
33952
  function ensureDirectorySegments(resolvedBase, dirPath) {
33122
- const target2 = path23__default.resolve(dirPath);
33123
- const relative = path23__default.relative(resolvedBase, target2);
33953
+ const target2 = path24__default.resolve(dirPath);
33954
+ const relative = path24__default.relative(resolvedBase, target2);
33124
33955
  let current = resolvedBase;
33125
- for (const segment of relative.split(path23__default.sep).filter(Boolean)) {
33126
- current = path23__default.join(current, segment);
33956
+ for (const segment of relative.split(path24__default.sep).filter(Boolean)) {
33957
+ current = path24__default.join(current, segment);
33127
33958
  try {
33128
33959
  const stat5 = lstatSync(current);
33129
33960
  if (stat5.isSymbolicLink()) {
@@ -33135,7 +33966,7 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
33135
33966
  } catch (error51) {
33136
33967
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
33137
33968
  mkdirSync(current, { mode: DIR_MODE });
33138
- chmodBestEffort(current, DIR_MODE);
33969
+ chmodBestEffort2(current, DIR_MODE);
33139
33970
  } else {
33140
33971
  throw error51;
33141
33972
  }
@@ -33144,11 +33975,11 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
33144
33975
  }
33145
33976
  }
33146
33977
  function assertExistingSegmentsSafe(resolvedBase, targetPath) {
33147
- const target2 = path23__default.resolve(targetPath);
33148
- const relative = path23__default.relative(resolvedBase, target2);
33978
+ const target2 = path24__default.resolve(targetPath);
33979
+ const relative = path24__default.relative(resolvedBase, target2);
33149
33980
  let current = resolvedBase;
33150
- for (const segment of relative.split(path23__default.sep).filter(Boolean)) {
33151
- current = path23__default.join(current, segment);
33981
+ for (const segment of relative.split(path24__default.sep).filter(Boolean)) {
33982
+ current = path24__default.join(current, segment);
33152
33983
  const stat5 = lstatSync(current);
33153
33984
  if (stat5.isSymbolicLink()) {
33154
33985
  throw new Error(`Plugin path segment is a symlink: ${current}`);
@@ -33160,13 +33991,13 @@ function assertExistingSegmentsSafe(resolvedBase, targetPath) {
33160
33991
  }
33161
33992
  }
33162
33993
  function assertExistingParentSegmentsSafe(resolvedBase, targetPath) {
33163
- assertExistingSegmentsSafe(resolvedBase, path23__default.dirname(targetPath));
33994
+ assertExistingSegmentsSafe(resolvedBase, path24__default.dirname(targetPath));
33164
33995
  }
33165
33996
  function assertSegmentRealpathWithinRoot(resolvedBase, segmentPath) {
33166
33997
  const baseRealpath = realpathSync(resolvedBase);
33167
33998
  const segmentRealpath = realpathSync(segmentPath);
33168
- const relative = path23__default.relative(baseRealpath, segmentRealpath);
33169
- if (relative === "" || !relative.startsWith("..") && !path23__default.isAbsolute(relative)) return;
33999
+ const relative = path24__default.relative(baseRealpath, segmentRealpath);
34000
+ if (relative === "" || !relative.startsWith("..") && !path24__default.isAbsolute(relative)) return;
33170
34001
  throw new Error(`Plugin path segment escapes root base: ${segmentPath}`);
33171
34002
  }
33172
34003
 
@@ -33186,18 +34017,18 @@ function renderAssetPluginRoot(pluginRoot, bundle, options) {
33186
34017
  options.doctrine ?? resolveDoctrineFromCliId(options.cliId);
33187
34018
  renderEmbeddedSkillAssets(pluginRoot);
33188
34019
  const workflowGuardScriptPath = writeWorkflowGuardScript(pluginRoot);
33189
- writePrivateJson(path23__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
34020
+ writePrivateJson(path24__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
33190
34021
  renderGatewayAgentAssets(pluginRoot, options);
33191
34022
  }
33192
34023
  function renderGatewayAgentAssets(pluginRoot, options) {
33193
34024
  for (const file2 of buildGatewayAgentFiles(options.gatewayDelegationModels ?? [], options.gatewayEffortExposure)) {
33194
- writePrivateFile(path23__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
34025
+ writePrivateFile(path24__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
33195
34026
  }
33196
34027
  }
33197
34028
  function writeWorkflowGuardScript(pluginRoot) {
33198
34029
  const asset = EMBEDDED_AGENT_CLI_HOOK_ASSETS.find((entry) => entry.relativePath === "workflow-guard.mjs");
33199
34030
  if (!asset) throw new Error("Missing embedded workflow-guard hook asset");
33200
- const scriptPath = path23__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
34031
+ const scriptPath = path24__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
33201
34032
  writePrivateFile(scriptPath, asset.content, pluginRoot);
33202
34033
  return scriptPath;
33203
34034
  }
@@ -33256,7 +34087,7 @@ function claudeCommandHook(hookExec) {
33256
34087
  }
33257
34088
  function renderEmbeddedSkillAssets(pluginRoot, doctrine) {
33258
34089
  for (const asset of selectSkillAssetsForDoctrine()) {
33259
- writePrivateFile(path23__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
34090
+ writePrivateFile(path24__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
33260
34091
  }
33261
34092
  }
33262
34093
  function selectSkillAssetsForDoctrine(_doctrine) {
@@ -33333,7 +34164,7 @@ function resolveRenderablePluginBundles(fleetRoot, options) {
33333
34164
  function homeMarketplaceTarget(fleetRoot) {
33334
34165
  return {
33335
34166
  name: FLEET_MARKETPLACE_NAME,
33336
- root: path23__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
34167
+ root: path24__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
33337
34168
  };
33338
34169
  }
33339
34170
  function groupRenderableBundlesByMarketplace(bundles) {
@@ -33349,17 +34180,17 @@ function groupRenderableBundlesByMarketplace(bundles) {
33349
34180
  return groups;
33350
34181
  }
33351
34182
  function renderPluginRoot(pluginRoot, bundle, options) {
33352
- const parentRoot = path23__default.dirname(pluginRoot);
34183
+ const parentRoot = path24__default.dirname(pluginRoot);
33353
34184
  ensurePrivateDir(parentRoot, parentRoot);
33354
34185
  const stageParent = createStagingDir(parentRoot);
33355
- const stagedPluginRoot = path23__default.join(stageParent, path23__default.basename(pluginRoot));
34186
+ const stagedPluginRoot = path24__default.join(stageParent, path24__default.basename(pluginRoot));
33356
34187
  try {
33357
34188
  ensurePrivateDir(stagedPluginRoot, stagedPluginRoot);
33358
- writePrivateJson(path23__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
34189
+ writePrivateJson(path24__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
33359
34190
  switch (bundle.source) {
33360
34191
  case "asset":
33361
- ensurePrivateDir(path23__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
33362
- ensurePrivateDir(path23__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
34192
+ ensurePrivateDir(path24__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
34193
+ ensurePrivateDir(path24__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
33363
34194
  renderAssetPluginRoot(stagedPluginRoot, bundle, options);
33364
34195
  break;
33365
34196
  }
@@ -33374,11 +34205,11 @@ function renderMarketplaceRoot(target2, bundles) {
33374
34205
  ensurePrivateDir(marketplaceRoot, marketplaceRoot);
33375
34206
  const stagedRoot = createStagingDir(marketplaceRoot);
33376
34207
  try {
33377
- writePrivateJson(path23__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
34208
+ writePrivateJson(path24__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
33378
34209
  pruneMarketplaceRoot(target2);
33379
34210
  pruneStalePluginDirs(target2, bundles);
33380
34211
  for (const entry of readdirSync(stagedRoot)) {
33381
- renameSync(path23__default.join(stagedRoot, entry), path23__default.join(marketplaceRoot, entry));
34212
+ renameSync(path24__default.join(stagedRoot, entry), path24__default.join(marketplaceRoot, entry));
33382
34213
  }
33383
34214
  } finally {
33384
34215
  cleanupPrivateRoot(stagedRoot, marketplaceRoot);
@@ -33386,11 +34217,11 @@ function renderMarketplaceRoot(target2, bundles) {
33386
34217
  }
33387
34218
  function pruneMarketplaceRoot(target2) {
33388
34219
  for (const entry of MARKETPLACE_PRUNE_ENTRIES) {
33389
- removePrivatePath(path23__default.join(target2.root, entry), target2.root);
34220
+ removePrivatePath(path24__default.join(target2.root, entry), target2.root);
33390
34221
  }
33391
34222
  }
33392
34223
  function pruneStalePluginDirs(target2, bundles) {
33393
- const pluginsDir = path23__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
34224
+ const pluginsDir = path24__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
33394
34225
  if (!existsSync(pluginsDir)) return;
33395
34226
  const activeDirectoryNames = /* @__PURE__ */ new Set();
33396
34227
  for (const bundle of bundles) {
@@ -33404,11 +34235,11 @@ function pruneStalePluginDirs(target2, bundles) {
33404
34235
  }
33405
34236
  for (const entry of readdirSync(pluginsDir)) {
33406
34237
  if (activeDirectoryNames.has(entry)) continue;
33407
- removePrivatePath(path23__default.join(pluginsDir, entry), target2.root);
34238
+ removePrivatePath(path24__default.join(pluginsDir, entry), target2.root);
33408
34239
  }
33409
34240
  }
33410
34241
  function createStagingDir(rootPath) {
33411
- const stageRoot = mkdtempSync(path23__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
34242
+ const stageRoot = mkdtempSync(path24__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
33412
34243
  return stageRoot;
33413
34244
  }
33414
34245
  function claudeMarketplace(target2, bundles) {
@@ -33430,7 +34261,7 @@ function claudeMarketplace(target2, bundles) {
33430
34261
  };
33431
34262
  }
33432
34263
  function pluginRootForTarget(target2, bundle) {
33433
- return path23__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
34264
+ return path24__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
33434
34265
  }
33435
34266
  function marketplacePluginPath(target2, bundle) {
33436
34267
  return `./${PLUGIN_BUNDLES_DIR_NAME}/${bundle.directoryName}`;
@@ -33461,6 +34292,22 @@ async function injectAgentCliProfile(profile, options) {
33461
34292
  const tempCleanups = [];
33462
34293
  try {
33463
34294
  const systemPromptFile = systemPromptMode === "off" ? void 0 : writeSystemPromptFile(profile.id, options.buildSystemPrompt(), (cleanup2) => tempCleanups.push(cleanup2));
34295
+ let promptArgs = [...profile.promptArgs ?? []];
34296
+ let deliveredViaFile = false;
34297
+ const cmdWrapped = profile.commandLineLimit?.via === "cmd-shim";
34298
+ const windowsLaunch = profile.commandLineLimit !== void 0;
34299
+ const convertPromptToFile = (body2) => {
34300
+ promptArgs = [writeLaunchPromptPointer(
34301
+ body2,
34302
+ (cleanupFn) => tempCleanups.push(cleanupFn),
34303
+ cmdWrapped
34304
+ )];
34305
+ deliveredViaFile = true;
34306
+ };
34307
+ if (promptArgs.length > 0 && windowsLaunch) {
34308
+ const body2 = takeLaunchPromptBody(promptArgs);
34309
+ if (launchPromptHasCmdUnsafeChars(body2)) convertPromptToFile(body2);
34310
+ }
33464
34311
  const plugin = await createAgentCliPlugin({
33465
34312
  cliId: profile.id,
33466
34313
  doctrine,
@@ -33497,26 +34344,39 @@ async function injectAgentCliProfile(profile, options) {
33497
34344
  systemPromptFile
33498
34345
  };
33499
34346
  const injectedArgs = buildAgentCliArgs(capability2.builderId, context);
33500
- const mergedArgs = mergeAgentCliArgs(profile, capability2.builderId, context, injectedArgs);
34347
+ const mergeArgs = (nextPromptArgs) => mergeAgentCliArgs(
34348
+ { ...profile, promptArgs: nextPromptArgs },
34349
+ capability2.builderId,
34350
+ context,
34351
+ injectedArgs
34352
+ );
34353
+ const argsWithoutPrompt = mergeArgs([]);
34354
+ const checkBudget = () => assertLaunchCommandLineBudget({
34355
+ args: mergeArgs(promptArgs),
34356
+ argsWithoutPrompt,
34357
+ bin: profile.bin,
34358
+ limit: profile.commandLineLimit,
34359
+ promptIsFixedLength: deliveredViaFile
34360
+ });
33501
34361
  try {
33502
- assertLaunchCommandLineBudget({
33503
- args: mergedArgs,
33504
- argsWithoutPrompt: mergeAgentCliArgs(
33505
- { ...profile, promptArgs: [] },
33506
- capability2.builderId,
33507
- context,
33508
- injectedArgs
33509
- ),
33510
- bin: profile.bin,
33511
- limit: profile.commandLineLimit
33512
- });
34362
+ checkBudget();
33513
34363
  } catch (error51) {
33514
- cleanup();
33515
- throw error51;
34364
+ const canMoveToFile = !deliveredViaFile && windowsLaunch && promptArgs.length === 1 && error51 instanceof LaunchPromptError && error51.code === "prompt_command_line_too_long";
34365
+ if (!canMoveToFile) {
34366
+ cleanup();
34367
+ throw error51;
34368
+ }
34369
+ convertPromptToFile(takeLaunchPromptBody(promptArgs));
34370
+ try {
34371
+ checkBudget();
34372
+ } catch (retryError) {
34373
+ cleanup();
34374
+ throw retryError;
34375
+ }
33516
34376
  }
33517
34377
  return {
33518
34378
  ...profile,
33519
- args: mergedArgs,
34379
+ args: mergeArgs(promptArgs),
33520
34380
  // 위치 인자는 이미 args 끝에 합쳐졌으므로 비운다. 남겨 두면 하류가 한 번 더 붙일 수 있다.
33521
34381
  promptArgs: [],
33522
34382
  cleanup
@@ -33542,21 +34402,27 @@ function buildAgentCliMcpServerConfigs(endpoints, tokens) {
33542
34402
  };
33543
34403
  });
33544
34404
  }
34405
+ function takeLaunchPromptBody(promptArgs) {
34406
+ if (promptArgs.length !== 1) {
34407
+ throw new Error(`Launch prompt file conversion expects a single positional prompt, got ${promptArgs.length}`);
34408
+ }
34409
+ return promptArgs[0];
34410
+ }
33545
34411
  function writeSystemPromptFile(cliId, systemPrompt, onCleanup) {
33546
- const tempDir = mkdtempSync(path23__default.join(os3__default.tmpdir(), `fleet-${cliId}-`));
33547
- onCleanup(() => rmBestEffort(tempDir));
33548
- const filePath = path23__default.join(tempDir, "system-prompt.md");
34412
+ const tempDir = mkdtempSync(path24__default.join(os3__default.tmpdir(), `fleet-${cliId}-`));
34413
+ onCleanup(() => rmBestEffort2(tempDir));
34414
+ const filePath = path24__default.join(tempDir, "system-prompt.md");
33549
34415
  writeFileSync(filePath, systemPrompt, { encoding: "utf8", flag: "wx", mode: SYSTEM_PROMPT_FILE_MODE });
33550
- chmodBestEffort2(filePath, SYSTEM_PROMPT_FILE_MODE);
34416
+ chmodBestEffort3(filePath, SYSTEM_PROMPT_FILE_MODE);
33551
34417
  return filePath;
33552
34418
  }
33553
- function chmodBestEffort2(targetPath, mode) {
34419
+ function chmodBestEffort3(targetPath, mode) {
33554
34420
  try {
33555
34421
  chmodSync(targetPath, mode);
33556
34422
  } catch {
33557
34423
  }
33558
34424
  }
33559
- function rmBestEffort(targetPath) {
34425
+ function rmBestEffort2(targetPath) {
33560
34426
  try {
33561
34427
  rmSync(targetPath, { force: true, recursive: true });
33562
34428
  } catch {
@@ -33637,7 +34503,7 @@ async function createFleetGatewayAgentRuntimeLifecycle(deps) {
33637
34503
  var MARKETPLACE_LOCK_DIR_SUFFIX = ".lock";
33638
34504
  function withFleetMarketplaceLock(target2, fn) {
33639
34505
  const lockDir = `${target2}${MARKETPLACE_LOCK_DIR_SUFFIX}`;
33640
- mkdirSync(path23__default.dirname(lockDir), { recursive: true });
34506
+ mkdirSync(path24__default.dirname(lockDir), { recursive: true });
33641
34507
  return withDirectoryLock({ lockDir }, fn);
33642
34508
  }
33643
34509
 
@@ -33744,7 +34610,7 @@ async function cleanupResources(profileCleanups, gatewayServer, runtime) {
33744
34610
  if (cleanupError !== void 0) throw cleanupError;
33745
34611
  }
33746
34612
  async function startGatewayHttpServer(deps) {
33747
- const diagnostics = createCursorDiagnosticLog(path23__default.join(getFleetDataDir(), "fleet-cli", "ai-gateway"));
34613
+ const diagnostics = createCursorDiagnosticLog(path24__default.join(getFleetDataDir(), "fleet-cli", "ai-gateway"));
33748
34614
  const router = createAiGatewayRouter({
33749
34615
  readAiGatewaySettings: () => deps.store.read(),
33750
34616
  readKimiApiKey: () => deps.authService.getApiKey(KIMI_AUTH_PROVIDER_ID),
@@ -33753,6 +34619,7 @@ async function startGatewayHttpServer(deps) {
33753
34619
  // 자격증명 조달은 호스트 결정이다 — thin 런처도 export된 기본 reader를 명시 주입한다.
33754
34620
  readAuth: () => readCodexSubscriptionAuth(),
33755
34621
  readCursorToken: () => readCursorSubscriptionToken(),
34622
+ readXaiToken: () => readXaiSubscriptionToken(),
33756
34623
  readModelOverride: () => process.env[AI_GATEWAY_MODEL_ENV],
33757
34624
  cursorDiagnostics: diagnostics.write
33758
34625
  });
@@ -34064,18 +34931,18 @@ Always read \`schema/wiki-schema.md\` directly before composing or revising entr
34064
34931
  `;
34065
34932
  async function ensureWorkspaceSchema(paths) {
34066
34933
  await mkdir(paths.schemaDir, { recursive: true });
34067
- await writeDefaultFileIfMissing(path23__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME), DEFAULT_WORKSPACE_SCHEMA_AGENTS);
34068
- await writeDefaultFileIfMissing(path23__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME), DEFAULT_WORKSPACE_WIKI_SCHEMA);
34934
+ await writeDefaultFileIfMissing(path24__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME), DEFAULT_WORKSPACE_SCHEMA_AGENTS);
34935
+ await writeDefaultFileIfMissing(path24__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME), DEFAULT_WORKSPACE_WIKI_SCHEMA);
34069
34936
  await writeDefaultFileIfMissing(buildTemplatePath(paths, "prd"), DEFAULT_TEMPLATE_PRD);
34070
34937
  return readWorkspaceSchemaSummary(paths);
34071
34938
  }
34072
34939
  async function ensureWorkspaceDoctrine(paths) {
34073
34940
  await mkdir(paths.root, { recursive: true });
34074
- await writeDefaultFileIfMissing(path23__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
34941
+ await writeDefaultFileIfMissing(path24__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
34075
34942
  }
34076
34943
  async function readWorkspaceSchemaSummary(paths) {
34077
- const agentsPath = path23__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
34078
- const wikiSchemaPath = path23__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME);
34944
+ const agentsPath = path24__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
34945
+ const wikiSchemaPath = path24__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME);
34079
34946
  const wikiSchemaContent = await tryReadSchemaFile(paths, wikiSchemaPath);
34080
34947
  const templates = await scanTemplates(paths);
34081
34948
  if (wikiSchemaContent === null) {
@@ -34114,7 +34981,7 @@ async function scanTemplates(paths) {
34114
34981
  if (!entry.name.startsWith(WORKSPACE_TEMPLATE_PREFIX) || !entry.name.endsWith(WORKSPACE_TEMPLATE_SUFFIX)) continue;
34115
34982
  const id = entry.name.slice(WORKSPACE_TEMPLATE_PREFIX.length, -WORKSPACE_TEMPLATE_SUFFIX.length);
34116
34983
  if (!TEMPLATE_ID_PATTERN.test(id)) continue;
34117
- const filePath = path23__default.join(paths.schemaDir, entry.name);
34984
+ const filePath = path24__default.join(paths.schemaDir, entry.name);
34118
34985
  try {
34119
34986
  const parsed = parseTemplateMarkdown(await readFile(filePath, "utf8"));
34120
34987
  templates.push({
@@ -34146,7 +35013,7 @@ async function readSchemaCatalog(paths) {
34146
35013
  }
34147
35014
  async function readSchemaDocument(paths, resource, templateId) {
34148
35015
  const ref = resource === "schema" ? "schema/wiki-schema.md" : schemaTemplateRef(templateId ?? "");
34149
- const absolute = path23__default.resolve(paths.root, ref);
35016
+ const absolute = path24__default.resolve(paths.root, ref);
34150
35017
  await assertContainedSchemaFile(paths, absolute, false);
34151
35018
  return { ref, content: await readFile(absolute, "utf8") };
34152
35019
  }
@@ -34171,10 +35038,10 @@ async function validateSchemaTemplateCreate(paths, templateId, markdown) {
34171
35038
  if (folded.has(key)) throw new Error(`schema template contains duplicate ## section: ${section2}`);
34172
35039
  folded.add(key);
34173
35040
  }
34174
- const absolute = path23__default.resolve(paths.root, ref);
35041
+ const absolute = path24__default.resolve(paths.root, ref);
34175
35042
  await assertContainedSchemaFile(paths, absolute, true);
34176
35043
  const entries = await readdir(paths.schemaDir).catch(() => []);
34177
- const basename = path23__default.basename(absolute).toLocaleLowerCase("en-US");
35044
+ const basename = path24__default.basename(absolute).toLocaleLowerCase("en-US");
34178
35045
  if (entries.some((entry) => entry.toLocaleLowerCase("en-US") === basename)) throw new Error("schema template target already exists");
34179
35046
  return absolute;
34180
35047
  }
@@ -34182,13 +35049,13 @@ function assertTemplateId(id) {
34182
35049
  if (!TEMPLATE_ID_PATTERN.test(id)) throw new Error("template_id must match /^[a-z][a-z0-9-]{0,63}$/");
34183
35050
  }
34184
35051
  async function assertContainedSchemaFile(paths, absolute, allowMissing) {
34185
- const schemaReal = await realpath(paths.schemaDir).catch(() => path23__default.resolve(paths.schemaDir));
34186
- const parentReal = await realpath(path23__default.dirname(absolute)).catch(() => path23__default.resolve(path23__default.dirname(absolute)));
35052
+ const schemaReal = await realpath(paths.schemaDir).catch(() => path24__default.resolve(paths.schemaDir));
35053
+ const parentReal = await realpath(path24__default.dirname(absolute)).catch(() => path24__default.resolve(path24__default.dirname(absolute)));
34187
35054
  if (parentReal !== schemaReal) throw new Error("schema resource escapes schema directory");
34188
- const relative = path23__default.relative(paths.root, absolute);
35055
+ const relative = path24__default.relative(paths.root, absolute);
34189
35056
  let cursor = paths.root;
34190
- for (const part of relative.split(path23__default.sep)) {
34191
- cursor = path23__default.join(cursor, part);
35057
+ for (const part of relative.split(path24__default.sep)) {
35058
+ cursor = path24__default.join(cursor, part);
34192
35059
  try {
34193
35060
  if ((await lstat(cursor)).isSymbolicLink()) throw new Error("schema resource path contains symlink");
34194
35061
  } catch (error51) {
@@ -34216,7 +35083,7 @@ async function validateTemplateCompliance(paths, templateId, body2) {
34216
35083
  }
34217
35084
  }
34218
35085
  function inferTemplateIdFromTarget(target2, knownTemplateIds) {
34219
- const basename = path23__default.basename(target2, ".md");
35086
+ const basename = path24__default.basename(target2, ".md");
34220
35087
  const ids = knownTemplateIds ?? DEFAULT_TEMPLATE_IDS;
34221
35088
  const sorted = [...ids].sort((a, b) => b.length - a.length);
34222
35089
  for (const id of sorted) {
@@ -34248,7 +35115,7 @@ function extractSchemaSummary(content) {
34248
35115
  return lines.find((line) => line.length > 0 && !line.startsWith("#")) ?? "Workspace schema is present.";
34249
35116
  }
34250
35117
  function buildTemplatePath(paths, id) {
34251
- return path23__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
35118
+ return path24__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
34252
35119
  }
34253
35120
  function parseTemplateMarkdown(content) {
34254
35121
  const normalized = content.replace(/\r\n/g, "\n");
@@ -34353,18 +35220,18 @@ function isAlreadyExistsError(error51) {
34353
35220
 
34354
35221
  // ../../packages/fleet-wiki/src/paths.ts
34355
35222
  function resolveMemoryPaths(cwd) {
34356
- return createMemoryPaths(path23__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
35223
+ return createMemoryPaths(path24__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
34357
35224
  }
34358
35225
  function createMemoryPaths(root) {
34359
35226
  return {
34360
35227
  root,
34361
- rawDir: path23__default.join(root, RAW_DIRNAME),
34362
- wikiDir: path23__default.join(root, WIKI_DIRNAME),
34363
- schemaDir: path23__default.join(root, SCHEMA_DIRNAME),
34364
- queueDir: path23__default.join(root, QUEUE_DIRNAME),
34365
- archiveDir: path23__default.join(root, ARCHIVE_DIRNAME),
34366
- conflictsDir: path23__default.join(root, CONFLICTS_DIRNAME),
34367
- indexFile: path23__default.join(root, INDEX_FILENAME)
35228
+ rawDir: path24__default.join(root, RAW_DIRNAME),
35229
+ wikiDir: path24__default.join(root, WIKI_DIRNAME),
35230
+ schemaDir: path24__default.join(root, SCHEMA_DIRNAME),
35231
+ queueDir: path24__default.join(root, QUEUE_DIRNAME),
35232
+ archiveDir: path24__default.join(root, ARCHIVE_DIRNAME),
35233
+ conflictsDir: path24__default.join(root, CONFLICTS_DIRNAME),
35234
+ indexFile: path24__default.join(root, INDEX_FILENAME)
34368
35235
  };
34369
35236
  }
34370
35237
  function resolveToolMemoryPaths(ctx) {
@@ -34382,10 +35249,10 @@ async function ensureMemoryRoot(paths) {
34382
35249
  await ensureWorkspaceDoctrine(paths);
34383
35250
  }
34384
35251
  function getIndexMarkdownFile(paths) {
34385
- return path23__default.join(paths.wikiDir, INDEX_MD_FILENAME);
35252
+ return path24__default.join(paths.wikiDir, INDEX_MD_FILENAME);
34386
35253
  }
34387
35254
  function getLogFile(paths) {
34388
- return path23__default.join(paths.root, LOG_MD_FILENAME);
35255
+ return path24__default.join(paths.root, LOG_MD_FILENAME);
34389
35256
  }
34390
35257
 
34391
35258
  // ../../packages/fleet-wiki/src/conflicts.ts
@@ -34397,7 +35264,7 @@ async function createConflict(input, paths) {
34397
35264
  await ensureMemoryRoot(paths);
34398
35265
  const now = input.now ?? /* @__PURE__ */ new Date();
34399
35266
  const conflictId = buildConflictId(now, input.wikiId, input.reason, input.proposed);
34400
- const conflictDir = path23__default.join(paths.conflictsDir, conflictId);
35267
+ const conflictDir = path24__default.join(paths.conflictsDir, conflictId);
34401
35268
  await mkdir(conflictDir, { recursive: true });
34402
35269
  const meta3 = {
34403
35270
  id: conflictId,
@@ -34417,13 +35284,13 @@ async function createConflict(input, paths) {
34417
35284
  currentHash: input.currentHash,
34418
35285
  warnings: input.warnings
34419
35286
  };
34420
- await writeJsonFile(path23__default.join(conflictDir, CONFLICT_META_FILENAME), meta3, paths);
34421
- await writePatchFile(path23__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME), input.proposed, paths);
35287
+ await writeJsonFile(path24__default.join(conflictDir, CONFLICT_META_FILENAME), meta3, paths);
35288
+ await writePatchFile(path24__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME), input.proposed, paths);
34422
35289
  if (input.current !== void 0) {
34423
- await writePatchFile(path23__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
35290
+ await writePatchFile(path24__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
34424
35291
  }
34425
35292
  if (input.rawSource !== void 0) {
34426
- await writePatchFile(path23__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
35293
+ await writePatchFile(path24__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
34427
35294
  }
34428
35295
  return {
34429
35296
  meta: meta3,
@@ -34437,7 +35304,7 @@ async function listConflicts(paths) {
34437
35304
  const metas = [];
34438
35305
  for (const id of ids) {
34439
35306
  try {
34440
- metas.push(await readJsonFile2(path23__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
35307
+ metas.push(await readJsonFile2(path24__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
34441
35308
  } catch {
34442
35309
  continue;
34443
35310
  }
@@ -34446,13 +35313,13 @@ async function listConflicts(paths) {
34446
35313
  }
34447
35314
  async function readConflict(conflictId, paths) {
34448
35315
  const conflictDir = resolveConflictDir(conflictId, paths);
34449
- const meta3 = await readJsonFile2(path23__default.join(conflictDir, CONFLICT_META_FILENAME));
34450
- const currentPath = path23__default.join(conflictDir, CONFLICT_CURRENT_FILENAME);
34451
- const rawSourcePath = path23__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME);
35316
+ const meta3 = await readJsonFile2(path24__default.join(conflictDir, CONFLICT_META_FILENAME));
35317
+ const currentPath = path24__default.join(conflictDir, CONFLICT_CURRENT_FILENAME);
35318
+ const rawSourcePath = path24__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME);
34452
35319
  return {
34453
35320
  meta: meta3,
34454
35321
  current: await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0,
34455
- proposed: await readPatchFile(path23__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
35322
+ proposed: await readPatchFile(path24__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
34456
35323
  rawSource: await pathExists(rawSourcePath) ? await readPatchFile(rawSourcePath) : void 0
34457
35324
  };
34458
35325
  }
@@ -34471,9 +35338,9 @@ function sanitizeConflictToken(value) {
34471
35338
  return value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "unknown";
34472
35339
  }
34473
35340
  function resolveConflictDir(conflictId, paths) {
34474
- const conflictDir = path23__default.resolve(paths.conflictsDir, conflictId);
34475
- const relative = path23__default.relative(paths.conflictsDir, conflictDir);
34476
- if (!relative || relative.startsWith("..") || path23__default.isAbsolute(relative)) {
35341
+ const conflictDir = path24__default.resolve(paths.conflictsDir, conflictId);
35342
+ const relative = path24__default.relative(paths.conflictsDir, conflictDir);
35343
+ if (!relative || relative.startsWith("..") || path24__default.isAbsolute(relative)) {
34477
35344
  throw new Error(`[fleet-wiki] conflict id escapes conflicts/: ${conflictId}`);
34478
35345
  }
34479
35346
  return conflictDir;
@@ -34637,11 +35504,11 @@ async function validatePatch(patch, paths) {
34637
35504
  if (!target2 || !summary || !proposer || !created) throw new Error("patch frontmatter is incomplete");
34638
35505
  if (summary.length > 120) throw new Error("patch summary exceeds 120 chars");
34639
35506
  assertCanonicalPatchTarget(target2);
34640
- const absoluteTarget = path23__default.resolve(paths.root, target2);
34641
- if (!absoluteTarget.startsWith(`${paths.root}${path23__default.sep}`) && absoluteTarget !== paths.root) {
35507
+ const absoluteTarget = path24__default.resolve(paths.root, target2);
35508
+ if (!absoluteTarget.startsWith(`${paths.root}${path24__default.sep}`) && absoluteTarget !== paths.root) {
34642
35509
  throw new Error("patch target escapes wiki root");
34643
35510
  }
34644
- if (!absoluteTarget.startsWith(`${paths.wikiDir}${path23__default.sep}`)) throw new Error("wiki patch must target wiki/");
35511
+ if (!absoluteTarget.startsWith(`${paths.wikiDir}${path24__default.sep}`)) throw new Error("wiki patch must target wiki/");
34645
35512
  assertNoSymlinkPathComponents(target2, paths);
34646
35513
  if (op === "create_wiki" && await pathExists(absoluteTarget)) {
34647
35514
  throw new Error(
@@ -34662,19 +35529,19 @@ async function applyPatch(patch, paths) {
34662
35529
  async function enqueuePatch(patch, paths, metaOverrides) {
34663
35530
  await ensureMemoryRoot(paths);
34664
35531
  const patchId = buildPatchId(patch.frontmatter.created, patch.frontmatter.summary, patch.frontmatter.target, patch.body);
34665
- const queueDir = path23__default.join(paths.queueDir, patchId);
35532
+ const queueDir = path24__default.join(paths.queueDir, patchId);
34666
35533
  if (await pathExists(queueDir)) {
34667
35534
  throw new Error(`[fleet-wiki] patch id collision: ${patchId} - this should never happen with target+body hashing`);
34668
35535
  }
34669
35536
  await mkdir(queueDir, { recursive: true });
34670
- await writePatchFile(path23__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
35537
+ await writePatchFile(path24__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
34671
35538
  const meta3 = {
34672
35539
  id: patchId,
34673
35540
  status: "pending",
34674
35541
  createdAt: patch.frontmatter.created,
34675
35542
  ...metaOverrides
34676
35543
  };
34677
- await writeJsonFile(path23__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
35544
+ await writeJsonFile(path24__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
34678
35545
  await appendLog(paths, "patch enqueued", {
34679
35546
  patch_id: patchId,
34680
35547
  patch_set_id: meta3.patch_set_id ?? null,
@@ -34692,7 +35559,7 @@ async function listQueue(paths) {
34692
35559
  for (const id of ids) {
34693
35560
  if (id === "_sets") continue;
34694
35561
  try {
34695
- const meta3 = await readJsonFile2(path23__default.join(paths.queueDir, id, PATCH_META_FILENAME));
35562
+ const meta3 = await readJsonFile2(path24__default.join(paths.queueDir, id, PATCH_META_FILENAME));
34696
35563
  results.push({ id, meta: meta3 });
34697
35564
  } catch {
34698
35565
  continue;
@@ -34717,17 +35584,17 @@ async function resolveQueueSelection(id, paths) {
34717
35584
  }
34718
35585
  async function showQueue(id, paths) {
34719
35586
  const selection = await resolveQueueSelection(id, paths);
34720
- const queueDir = path23__default.join(paths.queueDir, selection.id);
34721
- const patch = await parsePatch(await readPatchFile(path23__default.join(queueDir, PATCH_FILENAME)));
34722
- const meta3 = await readJsonFile2(path23__default.join(queueDir, PATCH_META_FILENAME));
35587
+ const queueDir = path24__default.join(paths.queueDir, selection.id);
35588
+ const patch = await parsePatch(await readPatchFile(path24__default.join(queueDir, PATCH_FILENAME)));
35589
+ const meta3 = await readJsonFile2(path24__default.join(queueDir, PATCH_META_FILENAME));
34723
35590
  return { patch, meta: meta3 };
34724
35591
  }
34725
35592
  async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
34726
35593
  assertSafeQueueId(id);
34727
35594
  return withPatchEditLock(paths, id, async () => {
34728
- const queueDir = path23__default.join(paths.queueDir, id);
35595
+ const queueDir = path24__default.join(paths.queueDir, id);
34729
35596
  if (expectedPatchHash !== void 0) {
34730
- const currentMarkdown = await readPatchFile(path23__default.join(queueDir, PATCH_FILENAME));
35597
+ const currentMarkdown = await readPatchFile(path24__default.join(queueDir, PATCH_FILENAME));
34731
35598
  const currentHash = computeContentHash(currentMarkdown);
34732
35599
  if (currentHash !== expectedPatchHash) {
34733
35600
  throw new Error(`[fleet-wiki] wiki_patch_edit stale base_patch_hash: expected ${currentHash}, got ${expectedPatchHash}`);
@@ -34736,8 +35603,8 @@ async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
34736
35603
  const patchMarkdown = serializePatch(patch);
34737
35604
  const patchHash = computeContentHash(patchMarkdown);
34738
35605
  const nextMeta = { ...meta3, lastEditHash: patchHash };
34739
- await writePatchFile(path23__default.join(queueDir, PATCH_FILENAME), patchMarkdown, paths);
34740
- await writeJsonFile(path23__default.join(queueDir, PATCH_META_FILENAME), nextMeta, paths);
35606
+ await writePatchFile(path24__default.join(queueDir, PATCH_FILENAME), patchMarkdown, paths);
35607
+ await writeJsonFile(path24__default.join(queueDir, PATCH_META_FILENAME), nextMeta, paths);
34741
35608
  return patchHash;
34742
35609
  });
34743
35610
  }
@@ -34761,8 +35628,8 @@ async function approvePatch(id, paths) {
34761
35628
  rawSourceRef: meta3.rawSourceRef,
34762
35629
  warnings: meta3.warnings
34763
35630
  });
34764
- const queueDir = path23__default.join(paths.queueDir, id);
34765
- await writeJsonFile(path23__default.join(queueDir, PATCH_META_FILENAME), {
35631
+ const queueDir = path24__default.join(paths.queueDir, id);
35632
+ await writeJsonFile(path24__default.join(queueDir, PATCH_META_FILENAME), {
34766
35633
  ...meta3,
34767
35634
  conflictId
34768
35635
  }, paths);
@@ -34798,7 +35665,7 @@ async function approvePatchSet(patchSetId, paths) {
34798
35665
  const failed = [];
34799
35666
  const missing = [];
34800
35667
  for (const patchId of patchSet.patchIds) {
34801
- const queueDir = path23__default.join(paths.queueDir, patchId);
35668
+ const queueDir = path24__default.join(paths.queueDir, patchId);
34802
35669
  if (!await pathExists(queueDir)) {
34803
35670
  missing.push(patchId);
34804
35671
  continue;
@@ -34864,7 +35731,7 @@ ${patch.body}`;
34864
35731
  }
34865
35732
  async function normalizeWikiEntryPatch(entry, target2, paths) {
34866
35733
  assertSafeEntryId(entry.id);
34867
- if (entry.id !== path23__default.basename(target2, ".md")) {
35734
+ if (entry.id !== path24__default.basename(target2, ".md")) {
34868
35735
  throw new Error("wiki patch body id must match target filename");
34869
35736
  }
34870
35737
  const inlineRawSourceRef = extractInlineRawSourceRef(entry.body);
@@ -34907,9 +35774,9 @@ function buildPatchId(createdAt, summary, target2, body2) {
34907
35774
  }
34908
35775
  async function validatePatchBase(patch, meta3, paths) {
34909
35776
  if (patch.frontmatter.op !== "update_wiki" || !meta3?.baseVersion && !meta3?.baseHash) return;
34910
- const wikiId = path23__default.basename(patch.frontmatter.target, ".md");
35777
+ const wikiId = path24__default.basename(patch.frontmatter.target, ".md");
34911
35778
  const currentEntry = await readWikiEntry(wikiId, paths);
34912
- const currentPath = path23__default.join(paths.root, patch.frontmatter.target);
35779
+ const currentPath = path24__default.join(paths.root, patch.frontmatter.target);
34913
35780
  const currentMarkdown = await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0;
34914
35781
  if (meta3.baseVersion !== void 0 && currentEntry?.version !== meta3.baseVersion) {
34915
35782
  throw new Error(
@@ -34968,17 +35835,17 @@ function assertCanonicalPatchTarget(target2) {
34968
35835
  if (target2.endsWith("/")) {
34969
35836
  throw new Error("patch target must not end with a slash");
34970
35837
  }
34971
- if (target2.startsWith("/") || path23__default.posix.isAbsolute(target2) || path23__default.win32.isAbsolute(target2)) {
35838
+ if (target2.startsWith("/") || path24__default.posix.isAbsolute(target2) || path24__default.win32.isAbsolute(target2)) {
34972
35839
  throw new Error("patch target must be relative");
34973
35840
  }
34974
- if (path23__default.posix.normalize(target2) !== target2) {
35841
+ if (path24__default.posix.normalize(target2) !== target2) {
34975
35842
  throw new Error("patch target must not contain dot segments or redundant separators");
34976
35843
  }
34977
35844
  }
34978
35845
  function canonicalApprovalLockKey(paths, target2) {
34979
35846
  const wikiRoot = realpathSync(paths.wikiDir);
34980
- const relativeTarget = path23__default.posix.relative("wiki", target2);
34981
- const targetPath = path23__default.join(wikiRoot, ...relativeTarget.split("/"));
35847
+ const relativeTarget = path24__default.posix.relative("wiki", target2);
35848
+ const targetPath = path24__default.join(wikiRoot, ...relativeTarget.split("/"));
34982
35849
  return `${wikiRoot}\0${targetPath}`.toLowerCase();
34983
35850
  }
34984
35851
  function canonicalPatchEditLockKey(paths, patchId) {
@@ -34994,7 +35861,7 @@ function assertNoSymlinkPathComponents(target2, paths) {
34994
35861
  throw error51;
34995
35862
  }
34996
35863
  for (const part of parts) {
34997
- current = path23__default.join(current, part);
35864
+ current = path24__default.join(current, part);
34998
35865
  try {
34999
35866
  if (lstatSync(current).isSymbolicLink()) {
35000
35867
  throw new Error("patch target must not include symlink path components");
@@ -35009,8 +35876,8 @@ function assertSafeRawSourceRef(rawSourceRef, paths) {
35009
35876
  if (!rawSourceRef.startsWith("raw/")) {
35010
35877
  throw new Error("raw source provenance must point into raw/");
35011
35878
  }
35012
- const absoluteRef = path23__default.resolve(paths.root, rawSourceRef);
35013
- if (!absoluteRef.startsWith(`${paths.rawDir}${path23__default.sep}`)) {
35879
+ const absoluteRef = path24__default.resolve(paths.root, rawSourceRef);
35880
+ if (!absoluteRef.startsWith(`${paths.rawDir}${path24__default.sep}`)) {
35014
35881
  throw new Error("raw source provenance must point into raw/");
35015
35882
  }
35016
35883
  }
@@ -35026,14 +35893,14 @@ function classifyPatchConflict(error51) {
35026
35893
  }
35027
35894
  async function recordPatchConflict(patch, paths, reason, options) {
35028
35895
  const now = /* @__PURE__ */ new Date();
35029
- const targetPath = path23__default.join(paths.root, patch.frontmatter.target);
35896
+ const targetPath = path24__default.join(paths.root, patch.frontmatter.target);
35030
35897
  const current = await pathExists(targetPath) ? await readPatchFile(targetPath) : void 0;
35031
35898
  const currentEntry = current ? parseStoredWikiEntry(current) : void 0;
35032
35899
  const proposedEntry = parsePatchBodyEntry(patch.body);
35033
- const record5 = await createConflict({
35900
+ const record6 = await createConflict({
35034
35901
  reason,
35035
35902
  target: patch.frontmatter.target,
35036
- wikiId: proposedEntry?.id ?? path23__default.basename(patch.frontmatter.target, ".md"),
35903
+ wikiId: proposedEntry?.id ?? path24__default.basename(patch.frontmatter.target, ".md"),
35037
35904
  title: proposedEntry?.title,
35038
35905
  proposer: patch.frontmatter.proposer,
35039
35906
  rawSourceRef: options?.rawSourceRef,
@@ -35049,14 +35916,14 @@ async function recordPatchConflict(patch, paths, reason, options) {
35049
35916
  now
35050
35917
  }, paths);
35051
35918
  await appendLog(paths, "conflict detected", {
35052
- conflict_id: record5.meta.id,
35919
+ conflict_id: record6.meta.id,
35053
35920
  patch_id: options?.patchId ?? null,
35054
35921
  raw_source_ref: options?.rawSourceRef ?? null,
35055
35922
  reason,
35056
35923
  target: patch.frontmatter.target,
35057
- wiki_id: record5.meta.wikiId
35924
+ wiki_id: record6.meta.wikiId
35058
35925
  }, now);
35059
- return record5.meta.id;
35926
+ return record6.meta.id;
35060
35927
  }
35061
35928
  function parsePatchBodyEntry(content) {
35062
35929
  try {
@@ -35145,11 +36012,11 @@ function parseInlineArray(value) {
35145
36012
  return inner.split(",").map((item) => decodeFrontmatter(item.trim().replace(/^"(.*)"$/, "$1")));
35146
36013
  }
35147
36014
  async function archiveQueueEntry(id, paths, meta3) {
35148
- const fromDir = path23__default.join(paths.queueDir, id);
35149
- const toDir = path23__default.join(paths.archiveDir, id);
36015
+ const fromDir = path24__default.join(paths.queueDir, id);
36016
+ const toDir = path24__default.join(paths.archiveDir, id);
35150
36017
  await removePath(toDir);
35151
36018
  await movePath(fromDir, toDir);
35152
- await writeJsonFile(path23__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
36019
+ await writeJsonFile(path24__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
35153
36020
  }
35154
36021
  function buildQueueIdHelp(prefix, availableIds) {
35155
36022
  if (availableIds.length === 0) {
@@ -35181,15 +36048,15 @@ var PATCH_SET_DIRNAME = "_sets";
35181
36048
  var PATCH_SET_META_FILENAME = PATCH_META_FILENAME;
35182
36049
  function getPatchSetDir(paths, patchSetId) {
35183
36050
  assertSafePatchSetId(patchSetId);
35184
- const patchSetDir = path23__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId);
35185
- const relative = path23__default.relative(path23__default.join(paths.queueDir, PATCH_SET_DIRNAME), patchSetDir);
35186
- if (!relative || relative.startsWith("..") || path23__default.isAbsolute(relative)) {
36051
+ const patchSetDir = path24__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId);
36052
+ const relative = path24__default.relative(path24__default.join(paths.queueDir, PATCH_SET_DIRNAME), patchSetDir);
36053
+ if (!relative || relative.startsWith("..") || path24__default.isAbsolute(relative)) {
35187
36054
  throw new Error(`[fleet-wiki] patch set id escapes queue/_sets: ${patchSetId}`);
35188
36055
  }
35189
36056
  return patchSetDir;
35190
36057
  }
35191
36058
  function getPatchSetMetaFile(paths, patchSetId) {
35192
- return path23__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
36059
+ return path24__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
35193
36060
  }
35194
36061
  function buildPatchSetId(createdAt, sourceRef) {
35195
36062
  const compact = createdAt.replace(/[:.]/g, "-");
@@ -35248,17 +36115,17 @@ async function readWikiEntry(id, paths) {
35248
36115
  const index = await loadIndex(paths);
35249
36116
  const indexed = index[id];
35250
36117
  if (indexed) {
35251
- const resolved = path23__default.resolve(paths.root, indexed.path);
35252
- const rel = path23__default.relative(paths.wikiDir, resolved);
35253
- if (!rel || rel.startsWith("..") || path23__default.isAbsolute(rel)) return null;
36118
+ const resolved = path24__default.resolve(paths.root, indexed.path);
36119
+ const rel = path24__default.relative(paths.wikiDir, resolved);
36120
+ if (!rel || rel.startsWith("..") || path24__default.isAbsolute(rel)) return null;
35254
36121
  return readMarkdownFile(resolved);
35255
36122
  }
35256
- const fallbackPath = path23__default.join(paths.wikiDir, `${id}.md`);
36123
+ const fallbackPath = path24__default.join(paths.wikiDir, `${id}.md`);
35257
36124
  if (await pathExists(fallbackPath)) {
35258
36125
  return readMarkdownFile(fallbackPath);
35259
36126
  }
35260
36127
  const records = await listWikiRecords(paths);
35261
- const match = records.find((record5) => record5.entry.id === id);
36128
+ const match = records.find((record6) => record6.entry.id === id);
35262
36129
  return match ? match.entry : null;
35263
36130
  }
35264
36131
  async function resolveWikiEntryPath(id, paths) {
@@ -35270,37 +36137,37 @@ async function resolveWikiEntryPath(id, paths) {
35270
36137
  const index = await loadIndex(paths);
35271
36138
  const indexed = index[id];
35272
36139
  if (indexed) {
35273
- const resolved = path23__default.resolve(paths.root, indexed.path);
35274
- const rel = path23__default.relative(paths.wikiDir, resolved);
35275
- if (rel && !rel.startsWith("..") && !path23__default.isAbsolute(rel) && await pathExists(resolved)) {
35276
- return path23__default.relative(paths.root, resolved).replaceAll(path23__default.sep, "/");
36140
+ const resolved = path24__default.resolve(paths.root, indexed.path);
36141
+ const rel = path24__default.relative(paths.wikiDir, resolved);
36142
+ if (rel && !rel.startsWith("..") && !path24__default.isAbsolute(rel) && await pathExists(resolved)) {
36143
+ return path24__default.relative(paths.root, resolved).replaceAll(path24__default.sep, "/");
35277
36144
  }
35278
36145
  }
35279
- const fallbackPath = path23__default.join(paths.wikiDir, `${id}.md`);
36146
+ const fallbackPath = path24__default.join(paths.wikiDir, `${id}.md`);
35280
36147
  if (await pathExists(fallbackPath)) {
35281
- return path23__default.relative(paths.root, fallbackPath).replaceAll(path23__default.sep, "/");
36148
+ return path24__default.relative(paths.root, fallbackPath).replaceAll(path24__default.sep, "/");
35282
36149
  }
35283
36150
  const records = await listWikiRecords(paths);
35284
- const match = records.find((record5) => record5.entry.id === id);
36151
+ const match = records.find((record6) => record6.entry.id === id);
35285
36152
  return match ? match.path : null;
35286
36153
  }
35287
36154
  async function writeWikiEntryAtTarget(entry, target2, paths) {
35288
36155
  await ensureMemoryRoot(paths);
35289
36156
  assertSafeEntryId(entry.id);
35290
- const absoluteTarget = path23__default.resolve(paths.root, target2);
35291
- const relativeTarget = path23__default.relative(paths.wikiDir, absoluteTarget);
35292
- if (!relativeTarget || relativeTarget.startsWith("..") || path23__default.isAbsolute(relativeTarget)) {
36157
+ const absoluteTarget = path24__default.resolve(paths.root, target2);
36158
+ const relativeTarget = path24__default.relative(paths.wikiDir, absoluteTarget);
36159
+ if (!relativeTarget || relativeTarget.startsWith("..") || path24__default.isAbsolute(relativeTarget)) {
35293
36160
  throw new Error(`[fleet-wiki] wiki target escapes wiki/: ${target2}`);
35294
36161
  }
35295
36162
  if (!absoluteTarget.endsWith(".md")) {
35296
36163
  throw new Error(`[fleet-wiki] wiki target must end with .md: ${target2}`);
35297
36164
  }
35298
- if (path23__default.basename(absoluteTarget, ".md") !== entry.id) {
36165
+ if (path24__default.basename(absoluteTarget, ".md") !== entry.id) {
35299
36166
  throw new Error("wiki patch body id must match target filename");
35300
36167
  }
35301
- await mkdir(path23__default.dirname(absoluteTarget), { recursive: true });
36168
+ await mkdir(path24__default.dirname(absoluteTarget), { recursive: true });
35302
36169
  await writeAtomic(absoluteTarget, serializeWikiEntry(entry), paths);
35303
- return path23__default.join("wiki", relativeTarget).replaceAll(path23__default.sep, "/");
36170
+ return path24__default.join("wiki", relativeTarget).replaceAll(path24__default.sep, "/");
35304
36171
  }
35305
36172
  async function writeRawSourceEntry(entry, paths) {
35306
36173
  await ensureMemoryRoot(paths);
@@ -35319,11 +36186,11 @@ async function writeRawSourceEntry(entry, paths) {
35319
36186
  },
35320
36187
  entry.content
35321
36188
  );
35322
- await writeAtomic(path23__default.join(paths.root, relativePath2), content, paths);
36189
+ await writeAtomic(path24__default.join(paths.root, relativePath2), content, paths);
35323
36190
  return relativePath2;
35324
36191
  }
35325
36192
  async function readRawSourceEntry(rawSourceRef, paths) {
35326
- const absolutePath = path23__default.resolve(paths.root, rawSourceRef);
36193
+ const absolutePath = path24__default.resolve(paths.root, rawSourceRef);
35327
36194
  assertWithinRawDir(absolutePath, paths);
35328
36195
  const parsed = parseMarkdown(await readFile(absolutePath, "utf8"));
35329
36196
  return {
@@ -35514,8 +36381,8 @@ function computeContentHash(content) {
35514
36381
  return crypto9.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 8);
35515
36382
  }
35516
36383
  function assertWithinRawDir(absolutePath, paths) {
35517
- const relative = path23__default.relative(paths.rawDir, absolutePath);
35518
- if (!relative || relative.startsWith("..") || path23__default.isAbsolute(relative)) {
36384
+ const relative = path24__default.relative(paths.rawDir, absolutePath);
36385
+ if (!relative || relative.startsWith("..") || path24__default.isAbsolute(relative)) {
35519
36386
  throw new Error(`[fleet-wiki] raw source ref escapes raw/: ${absolutePath}`);
35520
36387
  }
35521
36388
  }
@@ -35571,7 +36438,7 @@ function parseWikiEntry(content) {
35571
36438
  async function listWikiRecords(paths) {
35572
36439
  return listMarkdownEntriesRecursive(paths.wikiDir, paths, (content, filePath) => ({
35573
36440
  entry: parseWikiEntry(content),
35574
- path: path23__default.relative(paths.root, filePath).replaceAll(path23__default.sep, "/")
36441
+ path: path24__default.relative(paths.root, filePath).replaceAll(path24__default.sep, "/")
35575
36442
  }));
35576
36443
  }
35577
36444
  async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
@@ -35584,7 +36451,7 @@ async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
35584
36451
  }
35585
36452
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
35586
36453
  for (const entry of sortedEntries) {
35587
- const filePath = path23__default.join(dirPath, entry.name);
36454
+ const filePath = path24__default.join(dirPath, entry.name);
35588
36455
  if (entry.isDirectory()) {
35589
36456
  items.push(...await listMarkdownEntriesRecursive(filePath, paths, parser));
35590
36457
  continue;
@@ -35719,8 +36586,8 @@ async function writeJsonAtomic(filePath, value, paths) {
35719
36586
  }
35720
36587
  async function writeAtomic(filePath, content, paths) {
35721
36588
  await ensureMemoryRoot(paths);
35722
- const tempPath = path23__default.join(
35723
- path23__default.dirname(filePath),
36589
+ const tempPath = path24__default.join(
36590
+ path24__default.dirname(filePath),
35724
36591
  `.tmp-${process.pid}-${Date.now()}-${crypto9.randomUUID()}-${os3__default.hostname()}`
35725
36592
  );
35726
36593
  await writeFile(tempPath, content, "utf8");
@@ -35801,7 +36668,7 @@ function extractLegacyMarkdownWikiLinks(body2, wikiDir, basePath) {
35801
36668
  }
35802
36669
  function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
35803
36670
  if (!target2 || target2.startsWith("#")) return null;
35804
- if (path23__default.isAbsolute(target2)) return null;
36671
+ if (path24__default.isAbsolute(target2)) return null;
35805
36672
  if (/^[a-z][a-z0-9+.-]*:/i.test(target2)) return null;
35806
36673
  const withoutFragment = target2.split("#", 1)[0]?.split("?", 1)[0] ?? "";
35807
36674
  if (!withoutFragment.endsWith(".md")) return null;
@@ -35811,12 +36678,12 @@ function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
35811
36678
  } catch {
35812
36679
  return null;
35813
36680
  }
35814
- const resolved = path23__default.resolve(path23__default.dirname(basePath), decodedTarget);
35815
- const relative = path23__default.relative(wikiDir, resolved);
35816
- if (!relative || relative.startsWith("..") || path23__default.isAbsolute(relative)) return null;
36681
+ const resolved = path24__default.resolve(path24__default.dirname(basePath), decodedTarget);
36682
+ const relative = path24__default.relative(wikiDir, resolved);
36683
+ if (!relative || relative.startsWith("..") || path24__default.isAbsolute(relative)) return null;
35817
36684
  return {
35818
36685
  target: target2,
35819
- entryId: path23__default.basename(relative, ".md")
36686
+ entryId: path24__default.basename(relative, ".md")
35820
36687
  };
35821
36688
  }
35822
36689
  var FLEET_WIKI_ENTRY_BEGIN = "<<<FLEET_WIKI_ENTRY_BEGIN";
@@ -35883,7 +36750,7 @@ async function enhancedSearch(paths, options) {
35883
36750
  for (const entry of entries) {
35884
36751
  if (!index[entry.id]) {
35885
36752
  index[entry.id] = {
35886
- path: path23__default.join("wiki", `${entry.id}.md`),
36753
+ path: path24__default.join("wiki", `${entry.id}.md`),
35887
36754
  title: entry.title,
35888
36755
  tags: entry.tags,
35889
36756
  updated: entry.updated
@@ -36019,7 +36886,7 @@ function toEnhancedHit(entry, signals) {
36019
36886
  score: enhancedScore,
36020
36887
  reason: signals.legacyReason ?? "body",
36021
36888
  excerpt,
36022
- path: path23__default.join("wiki", `${entry.id}.md`),
36889
+ path: path24__default.join("wiki", `${entry.id}.md`),
36023
36890
  tags: entry.tags,
36024
36891
  updated: entry.updated,
36025
36892
  version: entry.version,
@@ -36215,7 +37082,7 @@ function toRankedHit(entry, reason, detail, graphBoost, backlinksById) {
36215
37082
  score: basePriority * 100 + statusPriority * 10 + graphScore + (detail.tagBoost ?? 0),
36216
37083
  reason,
36217
37084
  excerpt,
36218
- path: path23__default.join("wiki", `${entry.id}.md`),
37085
+ path: path24__default.join("wiki", `${entry.id}.md`),
36219
37086
  tags: entry.tags,
36220
37087
  updated: entry.updated,
36221
37088
  version: entry.version,
@@ -37757,8 +38624,8 @@ function CreateObject(types, value) {
37757
38624
  }
37758
38625
  function FromUnionKey(types, value) {
37759
38626
  const flattened = Flatten(types);
37760
- const record5 = TryBuildRecord(flattened, value);
37761
- return IsSchema(record5) ? record5 : CreateObject(flattened, value);
38627
+ const record6 = TryBuildRecord(flattened, value);
38628
+ return IsSchema(record6) ? record6 : CreateObject(flattened, value);
37762
38629
  }
37763
38630
 
37764
38631
  // ../../node_modules/.pnpm/typebox@1.1.34/node_modules/typebox/build/type/engine/record/from_key.mjs
@@ -40981,13 +41848,13 @@ async function readClaims(entryId, paths) {
40981
41848
  }
40982
41849
  }
40983
41850
  function getClaimsDir(paths) {
40984
- return path23__default.join(paths.wikiDir, CLAIMS_DIRNAME);
41851
+ return path24__default.join(paths.wikiDir, CLAIMS_DIRNAME);
40985
41852
  }
40986
41853
  function getClaimsFile(paths, entryId) {
40987
41854
  assertSafeEntryId(entryId);
40988
- const claimsFile = path23__default.join(getClaimsDir(paths), `${entryId}.json`);
40989
- const relative = path23__default.relative(getClaimsDir(paths), claimsFile);
40990
- if (!relative || relative.startsWith("..") || path23__default.isAbsolute(relative)) {
41855
+ const claimsFile = path24__default.join(getClaimsDir(paths), `${entryId}.json`);
41856
+ const relative = path24__default.relative(getClaimsDir(paths), claimsFile);
41857
+ if (!relative || relative.startsWith("..") || path24__default.isAbsolute(relative)) {
40991
41858
  throw new Error(`[fleet-wiki] claims sidecar escapes wiki/.claims: ${entryId}`);
40992
41859
  }
40993
41860
  return claimsFile;
@@ -41078,7 +41945,7 @@ function assertSafeClaimRawRef(ref) {
41078
41945
  if (!ref.startsWith("raw/")) {
41079
41946
  throw new Error(`claim sourceRef must point into raw/: ${ref}`);
41080
41947
  }
41081
- if (ref.includes("..") || path23__default.isAbsolute(ref)) {
41948
+ if (ref.includes("..") || path24__default.isAbsolute(ref)) {
41082
41949
  throw new Error(`claim sourceRef escapes raw/: ${ref}`);
41083
41950
  }
41084
41951
  }
@@ -41156,22 +42023,22 @@ async function runDryDock(paths, options = {}) {
41156
42023
  }
41157
42024
  for (const fileName of await listFileNames(paths.rawDir)) {
41158
42025
  if (!fileName.endsWith(".md")) continue;
41159
- const filePath = path23__default.join(paths.rawDir, fileName);
42026
+ const filePath = path24__default.join(paths.rawDir, fileName);
41160
42027
  issues.push(...safetyIssues(await readPatchFile(filePath), filePath));
41161
42028
  }
41162
42029
  for (const queueId of await listDirectoryNames(paths.queueDir)) {
41163
42030
  if (queueId === PATCH_SET_DIRNAME) continue;
41164
- const queueDir = path23__default.join(paths.queueDir, queueId);
42031
+ const queueDir = path24__default.join(paths.queueDir, queueId);
41165
42032
  try {
41166
- const patchContent = await readPatchFile(path23__default.join(queueDir, PATCH_FILENAME));
41167
- issues.push(...safetyIssues(patchContent, path23__default.join(queueDir, PATCH_FILENAME)));
41168
- await readJsonFile2(path23__default.join(queueDir, PATCH_META_FILENAME));
42033
+ const patchContent = await readPatchFile(path24__default.join(queueDir, PATCH_FILENAME));
42034
+ issues.push(...safetyIssues(patchContent, path24__default.join(queueDir, PATCH_FILENAME)));
42035
+ await readJsonFile2(path24__default.join(queueDir, PATCH_META_FILENAME));
41169
42036
  } catch {
41170
42037
  issues.push(issue2("malformed_queue", "error", "\uC190\uC0C1\uB41C queue \uC5D4\uD2B8\uB9AC", queueDir));
41171
42038
  }
41172
42039
  }
41173
- for (const patchSetId of await listDirectoryNames(path23__default.join(paths.queueDir, PATCH_SET_DIRNAME))) {
41174
- const patchSetMetaFile = path23__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId, PATCH_META_FILENAME);
42040
+ for (const patchSetId of await listDirectoryNames(path24__default.join(paths.queueDir, PATCH_SET_DIRNAME))) {
42041
+ const patchSetMetaFile = path24__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId, PATCH_META_FILENAME);
41175
42042
  let patchSet;
41176
42043
  try {
41177
42044
  patchSet = await readPatchSet(paths, patchSetId);
@@ -41180,8 +42047,8 @@ async function runDryDock(paths, options = {}) {
41180
42047
  continue;
41181
42048
  }
41182
42049
  for (const patchId of patchSet.patchIds) {
41183
- const queueMetaFile = path23__default.join(paths.queueDir, patchId, PATCH_META_FILENAME);
41184
- const archiveMetaFile = path23__default.join(paths.archiveDir, patchId, PATCH_META_FILENAME);
42050
+ const queueMetaFile = path24__default.join(paths.queueDir, patchId, PATCH_META_FILENAME);
42051
+ const archiveMetaFile = path24__default.join(paths.archiveDir, patchId, PATCH_META_FILENAME);
41185
42052
  if (!await pathExists(queueMetaFile) && !await pathExists(archiveMetaFile)) {
41186
42053
  issues.push(
41187
42054
  issue2(
@@ -41218,7 +42085,7 @@ async function runDryDock(paths, options = {}) {
41218
42085
  "conflict_unresolved",
41219
42086
  "warning",
41220
42087
  `\uBBF8\uD574\uACB0 conflict: ${conflict.reason} (${conflict.target})`,
41221
- path23__default.join(paths.conflictsDir, conflict.id, "meta.json")
42088
+ path24__default.join(paths.conflictsDir, conflict.id, "meta.json")
41222
42089
  )
41223
42090
  );
41224
42091
  }
@@ -41231,7 +42098,7 @@ async function runDryDock(paths, options = {}) {
41231
42098
  "unresolved_conflict",
41232
42099
  "warning",
41233
42100
  "\uC190\uC0C1\uB41C conflict \uC5D4\uD2B8\uB9AC",
41234
- path23__default.join(paths.conflictsDir, conflictId, "meta.json")
42101
+ path24__default.join(paths.conflictsDir, conflictId, "meta.json")
41235
42102
  )
41236
42103
  );
41237
42104
  }
@@ -41288,8 +42155,8 @@ async function claimIssues(paths, wikiIds) {
41288
42155
  const claimsDir = getClaimsDir(paths);
41289
42156
  for (const fileName of await listFileNames(claimsDir)) {
41290
42157
  if (!fileName.endsWith(".json")) continue;
41291
- const filePath = path23__default.join(claimsDir, fileName);
41292
- const entryIdFromFile = path23__default.basename(fileName, ".json");
42158
+ const filePath = path24__default.join(claimsDir, fileName);
42159
+ const entryIdFromFile = path24__default.basename(fileName, ".json");
41293
42160
  let raw;
41294
42161
  try {
41295
42162
  raw = await readJsonFile2(filePath);
@@ -41368,7 +42235,7 @@ function toSemanticEntry(filePath, frontmatter, body2) {
41368
42235
  async function schemaIssues(paths) {
41369
42236
  const issues = [];
41370
42237
  const schema = await readWorkspaceSchemaSummary(paths);
41371
- const agentsPath = path23__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
42238
+ const agentsPath = path24__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
41372
42239
  if (!await pathExists(schema.wikiSchemaPath)) {
41373
42240
  issues.push(issue2("schema_missing", "warning", `Workspace schema file is missing: schema/${WORKSPACE_SCHEMA_FILENAME}`, schema.wikiSchemaPath));
41374
42241
  } else {
@@ -41755,7 +42622,7 @@ async function listWikiMarkdownFiles(dirPath) {
41755
42622
  const files = [];
41756
42623
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
41757
42624
  for (const entry of sortedEntries) {
41758
- const filePath = path23__default.join(dirPath, entry.name);
42625
+ const filePath = path24__default.join(dirPath, entry.name);
41759
42626
  if (entry.isDirectory()) {
41760
42627
  files.push(...await listWikiMarkdownFiles(filePath));
41761
42628
  continue;
@@ -41979,7 +42846,7 @@ async function resolveCompileSource(input, paths, now) {
41979
42846
  }
41980
42847
  async function buildCompileProposals(input, paths, now, resolvedSource) {
41981
42848
  const sourceTarget = `wiki/sources/${resolvedSource.sourcePageId}.md`;
41982
- const sourceExists = await pathExists(path23__default.join(paths.root, sourceTarget));
42849
+ const sourceExists = await pathExists(path24__default.join(paths.root, sourceTarget));
41983
42850
  const existingEntries = await listWiki(paths);
41984
42851
  const sourcePageTitle = resolvedSource.sourceTitle?.trim() || `Source ${resolvedSource.sourcePageId}`;
41985
42852
  const existingSourceEntry = existingEntries.find((entry) => entry.id === resolvedSource.sourcePageId);
@@ -42001,7 +42868,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
42001
42868
  target: sourceTarget,
42002
42869
  summary: truncateSummary(`Compile source page ${sourcePageTitle}`),
42003
42870
  entry: sourceEntry,
42004
- baseHash: sourceExists ? computeContentHash(await readPatchFile(path23__default.join(paths.root, sourceTarget))) : void 0,
42871
+ baseHash: sourceExists ? computeContentHash(await readPatchFile(path24__default.join(paths.root, sourceTarget))) : void 0,
42005
42872
  baseVersion: existingSourceEntry?.version
42006
42873
  }];
42007
42874
  const relatedCandidates = await discoverRelatedEntryCandidates(paths, resolvedSource.sourceContent, resolvedSource.sourceTitle);
@@ -42021,7 +42888,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
42021
42888
  rawSourceRefs: mergeRawSourceRefs(existing.rawSourceRefs, existing.rawSourceRef, { ref: resolvedSource.rawSourceRef }),
42022
42889
  body: appendSourceCompileNote(existing.body, resolvedSource.sourcePageId, resolvedSource.rawSourceRef)
42023
42890
  },
42024
- baseHash: computeContentHash(await readPatchFile(path23__default.join(paths.wikiDir, `${existing.id}.md`))),
42891
+ baseHash: computeContentHash(await readPatchFile(path24__default.join(paths.wikiDir, `${existing.id}.md`))),
42025
42892
  baseVersion: existing.version
42026
42893
  });
42027
42894
  }
@@ -42195,7 +43062,7 @@ async function planIngest(input, paths, now) {
42195
43062
  const target2 = `wiki/${input.id}.md`;
42196
43063
  const proposer = input.proposer ?? "tool:wiki_ingest";
42197
43064
  const currentEntry = await readWikiEntry(input.id, paths);
42198
- const currentMarkdown = currentEntry ? await readPatchFile(path23__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
43065
+ const currentMarkdown = currentEntry ? await readPatchFile(path24__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
42199
43066
  const currentHash = currentMarkdown ? computeContentHash(currentMarkdown) : void 0;
42200
43067
  const rawSource = buildRawSourceEntry(input, now);
42201
43068
  await ensureWorkspaceSchema(paths);
@@ -42390,7 +43257,7 @@ async function stageIngestPlan(plan, paths) {
42390
43257
  })
42391
43258
  };
42392
43259
  if (plan.kind === "conflict") {
42393
- const record5 = await createConflict({
43260
+ const record6 = await createConflict({
42394
43261
  reason: plan.conflict.reason,
42395
43262
  target: `wiki/${entry.id}.md`,
42396
43263
  wikiId: entry.id,
@@ -42408,17 +43275,17 @@ async function stageIngestPlan(plan, paths) {
42408
43275
  warnings: plan.warnings
42409
43276
  }, paths);
42410
43277
  await appendLog(paths, "conflict detected", {
42411
- conflict_id: record5.meta.id,
43278
+ conflict_id: record6.meta.id,
42412
43279
  patch_id: null,
42413
43280
  raw_source_ref: rawSourceRef,
42414
43281
  reason: plan.conflict.reason,
42415
- target: record5.meta.target,
42416
- wiki_id: record5.meta.wikiId
43282
+ target: record6.meta.target,
43283
+ wiki_id: record6.meta.wikiId
42417
43284
  });
42418
43285
  return {
42419
43286
  ok: false,
42420
43287
  mode: plan.mode,
42421
- conflict_id: record5.meta.id,
43288
+ conflict_id: record6.meta.id,
42422
43289
  raw_source_ref: rawSourceRef,
42423
43290
  warnings: plan.warnings
42424
43291
  };
@@ -42874,11 +43741,11 @@ async function editQueuedPatch(input, paths) {
42874
43741
  };
42875
43742
  }
42876
43743
  async function readQueuedPatchSnapshot(paths, patchId) {
42877
- const queueDir = path23__default.join(paths.queueDir, patchId);
42878
- const markdown = await readPatchFile(path23__default.join(queueDir, PATCH_FILENAME));
43744
+ const queueDir = path24__default.join(paths.queueDir, patchId);
43745
+ const markdown = await readPatchFile(path24__default.join(queueDir, PATCH_FILENAME));
42879
43746
  return {
42880
43747
  patch: await parsePatch(markdown),
42881
- meta: await readJsonFile2(path23__default.join(queueDir, PATCH_META_FILENAME)),
43748
+ meta: await readJsonFile2(path24__default.join(queueDir, PATCH_META_FILENAME)),
42882
43749
  patchHash: computeContentHash(markdown)
42883
43750
  };
42884
43751
  }
@@ -42964,11 +43831,11 @@ function applyBodyReplacement(entry, replaceInput) {
42964
43831
  }
42965
43832
  function parseBodyReplace(value) {
42966
43833
  if (value === void 0 || value === null) return void 0;
42967
- const record5 = value;
43834
+ const record6 = value;
42968
43835
  return {
42969
- find: String(record5.find ?? ""),
42970
- replace: String(record5.replace ?? ""),
42971
- expected_occurrences: typeof record5.expected_occurrences === "number" ? record5.expected_occurrences : void 0
43836
+ find: String(record6.find ?? ""),
43837
+ replace: String(record6.replace ?? ""),
43838
+ expected_occurrences: typeof record6.expected_occurrences === "number" ? record6.expected_occurrences : void 0
42972
43839
  };
42973
43840
  }
42974
43841
  function stringParam(value) {
@@ -43640,7 +44507,7 @@ ${input.answer ?? ""}`)}`;
43640
44507
  assertSafeEntryId(targetId);
43641
44508
  const subdir = input.targetType === "synthesis" ? "synthesis" : "queries";
43642
44509
  const target2 = `wiki/${subdir}/${targetId}.md`;
43643
- const absoluteTarget = path23__default.join(paths.root, target2);
44510
+ const absoluteTarget = path24__default.join(paths.root, target2);
43644
44511
  const exists = await pathExists(absoluteTarget);
43645
44512
  const existingEntry = exists ? await readWikiEntry(targetId, paths) : null;
43646
44513
  if (exists && !existingEntry) {
@@ -43722,7 +44589,7 @@ function assertSafeRawRef(rawRef) {
43722
44589
  if (!rawRef.startsWith("raw/")) {
43723
44590
  throw new Error(`[fleet-wiki] wiki_query raw source ref must point into raw/: ${rawRef}`);
43724
44591
  }
43725
- if (rawRef.includes("..") || path23__default.isAbsolute(rawRef)) {
44592
+ if (rawRef.includes("..") || path24__default.isAbsolute(rawRef)) {
43726
44593
  throw new Error(`[fleet-wiki] wiki_query raw source ref escapes raw/: ${rawRef}`);
43727
44594
  }
43728
44595
  }
@@ -44291,15 +45158,15 @@ function buildWikiResolveSpec(resolver) {
44291
45158
  ]
44292
45159
  }, resolver);
44293
45160
  }
44294
- function buildWikiToolSpec(config2, usage3, resolver) {
45161
+ function buildWikiToolSpec(config2, usage4, resolver) {
44295
45162
  return {
44296
45163
  id: config2.name,
44297
45164
  tag: config2.name,
44298
45165
  title: config2.label,
44299
45166
  description: config2.description,
44300
45167
  promptSnippet: config2.promptSnippet,
44301
- whenToUse: usage3.whenToUse,
44302
- whenNotToUse: usage3.whenNotToUse,
45168
+ whenToUse: usage4.whenToUse,
45169
+ whenNotToUse: usage4.whenNotToUse,
44303
45170
  usageGuidelines: config2.promptGuidelines,
44304
45171
  parameters: config2.parameters,
44305
45172
  execute: async (args, ctx) => {
@@ -44328,16 +45195,16 @@ function createResolver(deps, hooks) {
44328
45195
  } };
44329
45196
  }
44330
45197
  function resolveLocked(workspace, hooks) {
44331
- const destination = path23__default.join(workspace.path, "knowledge");
44332
- const source = path23__default.join(workspace.cwd, ".fleet", "knowledge");
44333
- const markerPath = path23__default.join(workspace.path, MARKER_NAME);
45198
+ const destination = path24__default.join(workspace.path, "knowledge");
45199
+ const source = path24__default.join(workspace.cwd, ".fleet", "knowledge");
45200
+ const markerPath = path24__default.join(workspace.path, MARKER_NAME);
44334
45201
  const destinationState = inspectTree(destination, true);
44335
45202
  if (destinationState === "content") return createMemoryPaths(destination);
44336
45203
  if (destinationState === "unsafe") throw new Error("Unsafe Fleet Wiki destination state");
44337
45204
  const marker = readMarker(markerPath);
44338
45205
  const stagingEntries = inspectReservedControlState(workspace.path);
44339
45206
  if (marker) {
44340
- const staging2 = path23__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
45207
+ const staging2 = path24__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
44341
45208
  const stagingState = inspectTree(staging2);
44342
45209
  if (stagingState === "content") {
44343
45210
  removeEmptyDirectories(destination);
@@ -44352,7 +45219,7 @@ function resolveLocked(workspace, hooks) {
44352
45219
  if (sourceState !== "content") return createMemoryPaths(destination);
44353
45220
  removeEmptyDirectories(destination);
44354
45221
  const transactionId = randomUUID();
44355
- const staging = path23__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
45222
+ const staging = path24__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
44356
45223
  copyTree(source, staging, hooks);
44357
45224
  if (inspectTree(staging) !== "content") throw new Error("Invalid Fleet Wiki migration staging result");
44358
45225
  syncDirectory(staging);
@@ -44380,7 +45247,7 @@ function inspectTree(target2, regularRootIsContent = false, treeRoot = target2)
44380
45247
  if (nodeKind === "file") return regularRootIsContent ? "content" : "unsafe";
44381
45248
  let content = false;
44382
45249
  for (const entry of fs9.readdirSync(target2, { withFileTypes: true })) {
44383
- const entryPath = path23__default.join(target2, entry.name);
45250
+ const entryPath = path24__default.join(target2, entry.name);
44384
45251
  if (entry.isSymbolicLink()) {
44385
45252
  if (readSafeFileSymlink(treeRoot, entryPath) === null) return "unsafe";
44386
45253
  content = true;
@@ -44412,15 +45279,15 @@ function readMarker(markerPath) {
44412
45279
  throw new Error("Invalid Fleet Wiki migration marker");
44413
45280
  }
44414
45281
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Fleet Wiki migration marker");
44415
- const record5 = value;
44416
- if (record5.version !== 1 || record5.outcome !== "copied" || typeof record5.transactionId !== "string" || !/^[0-9a-f-]{36}$/i.test(record5.transactionId) || typeof record5.completedAt !== "string") throw new Error("Invalid Fleet Wiki migration marker");
44417
- return record5;
45282
+ const record6 = value;
45283
+ if (record6.version !== 1 || record6.outcome !== "copied" || typeof record6.transactionId !== "string" || !/^[0-9a-f-]{36}$/i.test(record6.transactionId) || typeof record6.completedAt !== "string") throw new Error("Invalid Fleet Wiki migration marker");
45284
+ return record6;
44418
45285
  }
44419
45286
  function copyTree(source, destination, hooks, sourceRoot = source) {
44420
45287
  fs9.mkdirSync(destination, { recursive: true });
44421
45288
  for (const entry of fs9.readdirSync(source, { withFileTypes: true })) {
44422
- const from = path23__default.join(source, entry.name);
44423
- const to = path23__default.join(destination, entry.name);
45289
+ const from = path24__default.join(source, entry.name);
45290
+ const to = path24__default.join(destination, entry.name);
44424
45291
  const stat5 = fs9.lstatSync(from);
44425
45292
  if (stat5.isSymbolicLink()) {
44426
45293
  const target2 = readSafeFileSymlink(sourceRoot, from);
@@ -44440,9 +45307,9 @@ function copyTree(source, destination, hooks, sourceRoot = source) {
44440
45307
  }
44441
45308
  function readSafeFileSymlink(treeRoot, linkPath) {
44442
45309
  const target2 = fs9.readlinkSync(linkPath);
44443
- if (path23__default.posix.isAbsolute(target2) || path23__default.win32.isAbsolute(target2)) return null;
44444
- const lexicalRoot = path23__default.resolve(treeRoot);
44445
- const lexicalTarget = path23__default.resolve(path23__default.dirname(linkPath), target2);
45310
+ if (path24__default.posix.isAbsolute(target2) || path24__default.win32.isAbsolute(target2)) return null;
45311
+ const lexicalRoot = path24__default.resolve(treeRoot);
45312
+ const lexicalTarget = path24__default.resolve(path24__default.dirname(linkPath), target2);
44446
45313
  if (!isWithinRoot(lexicalRoot, lexicalTarget)) return null;
44447
45314
  let canonicalRoot;
44448
45315
  let canonicalTarget;
@@ -44459,8 +45326,8 @@ function readSafeFileSymlink(treeRoot, linkPath) {
44459
45326
  return target2;
44460
45327
  }
44461
45328
  function isWithinRoot(root, target2) {
44462
- const relative = path23__default.relative(root, target2);
44463
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path23__default.sep}`) && !path23__default.isAbsolute(relative);
45329
+ const relative = path24__default.relative(root, target2);
45330
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path24__default.sep}`) && !path24__default.isAbsolute(relative);
44464
45331
  }
44465
45332
  function classifyWikiWorkspaceNodeForTest(stat5) {
44466
45333
  if (stat5.isSymbolicLink()) return "unsafe";
@@ -44475,13 +45342,13 @@ function removeEmptyDirectories(target2) {
44475
45342
  if (state === "empty") fs9.rmSync(target2, { recursive: true, force: false });
44476
45343
  }
44477
45344
  function removePriorStaging(workspacePath, stagingEntries) {
44478
- for (const name of stagingEntries) fs9.rmSync(path23__default.join(workspacePath, name), { recursive: true, force: false });
45345
+ for (const name of stagingEntries) fs9.rmSync(path24__default.join(workspacePath, name), { recursive: true, force: false });
44479
45346
  }
44480
45347
  function inspectReservedControlState(workspacePath) {
44481
45348
  const stagingEntries = [];
44482
45349
  for (const entry of fs9.readdirSync(workspacePath, { withFileTypes: true })) {
44483
45350
  if (entry.name.startsWith(`${MARKER_NAME}.`)) {
44484
- const residuePath = path23__default.join(workspacePath, entry.name);
45351
+ const residuePath = path24__default.join(workspacePath, entry.name);
44485
45352
  const residue = fs9.lstatSync(residuePath);
44486
45353
  if (MARKER_TEMP_REGEXP.test(entry.name) && residue.isFile() && !residue.isSymbolicLink()) {
44487
45354
  fs9.unlinkSync(residuePath);
@@ -44491,7 +45358,7 @@ function inspectReservedControlState(workspacePath) {
44491
45358
  }
44492
45359
  if (!entry.name.startsWith(STAGING_PREFIX)) continue;
44493
45360
  if (!/^[0-9a-f-]{36}$/i.test(entry.name.slice(STAGING_PREFIX.length)) || entry.isSymbolicLink() || !entry.isDirectory()) throw new Error("Unsafe Fleet Wiki migration staging state");
44494
- if (inspectTree(path23__default.join(workspacePath, entry.name)) === "unsafe") throw new Error("Unsafe Fleet Wiki migration staging state");
45361
+ if (inspectTree(path24__default.join(workspacePath, entry.name)) === "unsafe") throw new Error("Unsafe Fleet Wiki migration staging state");
44495
45362
  stagingEntries.push(entry.name);
44496
45363
  }
44497
45364
  return stagingEntries;
@@ -44680,7 +45547,7 @@ async function createFleetCliRuntime(options = {}) {
44680
45547
  const wikiWorkspaceResolver = createWikiWorkspaceResolver({
44681
45548
  ensureWorkspace: (cwd) => ensureWorkspaceDirectory(dataDir, cwd),
44682
45549
  withMigrationLock: (workspace, operation) => withDirectoryLock(
44683
- { lockDir: path23__default.join(workspace.path, "knowledge.migration.lock") },
45550
+ { lockDir: path24__default.join(workspace.path, "knowledge.migration.lock") },
44684
45551
  operation
44685
45552
  )
44686
45553
  });
@@ -44735,7 +45602,7 @@ function applyStoredWireLog(store, dataDir) {
44735
45602
  }
44736
45603
  function applyWireLog(stored, dataDir) {
44737
45604
  setWireLogTarget(stored === void 0 ? void 0 : stored ? {
44738
- path: path23__default.join(dataDir, "logs", "fleet-cli-gateway-wire.jsonl"),
45605
+ path: path24__default.join(dataDir, "logs", "fleet-cli-gateway-wire.jsonl"),
44739
45606
  maxBytes: DEFAULT_WIRE_LOG_MAX_BYTES
44740
45607
  } : null);
44741
45608
  }
@@ -45791,7 +46658,7 @@ function createConsoleLock(deps = {}) {
45791
46658
  }
45792
46659
  function assertLockModes(lockFile) {
45793
46660
  if (typeof process.getuid !== "function") return;
45794
- const dir = path23__default.dirname(lockFile);
46661
+ const dir = path24__default.dirname(lockFile);
45795
46662
  const dirMode = fsImpl.statSync(dir).mode & 511;
45796
46663
  const fileMode = fsImpl.statSync(lockFile).mode & 511;
45797
46664
  if (dirMode !== LOCK_DIR_MODE) {
@@ -45848,26 +46715,26 @@ function isDesktopDevelopmentEnvironment(env) {
45848
46715
  return env[DESKTOP_DEVELOPMENT_ENV] === "1";
45849
46716
  }
45850
46717
  function resolveCanonicalStableConsolePaths(input) {
45851
- const dir = input.consoleDirOverride ?? path23__default.join(input.tmpDir, `${LOCK_DIR_NAME3}-${input.uid}-stable`);
45852
- const dataDir = input.consoleDirOverride ?? path23__default.join(input.fleetDataDir, CONSOLE_DATA_DIR_NAME);
46718
+ const dir = input.consoleDirOverride ?? path24__default.join(input.tmpDir, `${LOCK_DIR_NAME3}-${input.uid}-stable`);
46719
+ const dataDir = input.consoleDirOverride ?? path24__default.join(input.fleetDataDir, CONSOLE_DATA_DIR_NAME);
45853
46720
  return {
45854
46721
  dir,
45855
- lockFile: path23__default.join(dir, LOCK_FILE_NAME),
46722
+ lockFile: path24__default.join(dir, LOCK_FILE_NAME),
45856
46723
  dataDir,
45857
- stateFile: path23__default.join(dataDir, CONSOLE_STATE_FILE_NAME),
45858
- settingsFile: path23__default.join(dataDir, CONSOLE_SETTINGS_FILE_NAME),
45859
- capturesDir: path23__default.join(dataDir, CONSOLE_CAPTURES_DIR_NAME)
46724
+ stateFile: path24__default.join(dataDir, CONSOLE_STATE_FILE_NAME),
46725
+ settingsFile: path24__default.join(dataDir, CONSOLE_SETTINGS_FILE_NAME),
46726
+ capturesDir: path24__default.join(dataDir, CONSOLE_CAPTURES_DIR_NAME)
45860
46727
  };
45861
46728
  }
45862
46729
  function resolveCanonicalLocalConsolePaths(input) {
45863
- const dir = path23__default.join(path23__default.resolve(input.packageRoot, "..", ".."), ".fleet", CONSOLE_DATA_DIR_NAME);
46730
+ const dir = path24__default.join(path24__default.resolve(input.packageRoot, "..", ".."), ".fleet", CONSOLE_DATA_DIR_NAME);
45864
46731
  return {
45865
46732
  dir,
45866
- lockFile: path23__default.join(dir, LOCK_FILE_NAME),
46733
+ lockFile: path24__default.join(dir, LOCK_FILE_NAME),
45867
46734
  dataDir: dir,
45868
- stateFile: path23__default.join(dir, CONSOLE_STATE_FILE_NAME),
45869
- settingsFile: path23__default.join(dir, CONSOLE_SETTINGS_FILE_NAME),
45870
- capturesDir: path23__default.join(dir, CONSOLE_CAPTURES_DIR_NAME)
46735
+ stateFile: path24__default.join(dir, CONSOLE_STATE_FILE_NAME),
46736
+ settingsFile: path24__default.join(dir, CONSOLE_SETTINGS_FILE_NAME),
46737
+ capturesDir: path24__default.join(dir, CONSOLE_CAPTURES_DIR_NAME)
45871
46738
  };
45872
46739
  }
45873
46740
  function isDesktopResourceRootMarkerValid(content) {
@@ -45893,17 +46760,17 @@ function isDesktopDevelopmentEnvironment2(env = process.env) {
45893
46760
  return isDesktopDevelopmentEnvironment(env);
45894
46761
  }
45895
46762
  function validateDesktopResourceRoot(root, expectedPackageRoot = resolveDesktopProtocolPackageRoot()) {
45896
- if (!path23__default.isAbsolute(root)) throw new Error("desktop_resource_root_not_absolute");
46763
+ if (!path24__default.isAbsolute(root)) throw new Error("desktop_resource_root_not_absolute");
45897
46764
  const resolvedRoot = fs9__default.realpathSync(root);
45898
46765
  const expectedRoot = fs9__default.realpathSync(expectedPackageRoot);
45899
46766
  if (resolvedRoot !== expectedRoot) throw new Error("desktop_resource_root_invalid");
45900
- const markerPath = path23__default.join(resolvedRoot, DESKTOP_RESOURCE_ROOT_MARKER);
46767
+ const markerPath = path24__default.join(resolvedRoot, DESKTOP_RESOURCE_ROOT_MARKER);
45901
46768
  const marker = fs9__default.readFileSync(markerPath, "utf8");
45902
46769
  if (!isDesktopResourceRootMarkerValid(marker)) throw new Error("desktop_resource_root_marker_invalid");
45903
46770
  return resolvedRoot;
45904
46771
  }
45905
46772
  function validateDesktopDevelopmentResourceRoot(root) {
45906
- if (!path23__default.isAbsolute(root)) throw new Error("desktop_resource_root_not_absolute");
46773
+ if (!path24__default.isAbsolute(root)) throw new Error("desktop_resource_root_not_absolute");
45907
46774
  let resolvedRoot;
45908
46775
  try {
45909
46776
  resolvedRoot = fs9__default.realpathSync(root);
@@ -45918,7 +46785,7 @@ function resolveDesktopProtocolPackageRoot() {
45918
46785
  const requireFromHere = createRequire(import.meta.url);
45919
46786
  for (const candidate of ["../package.json", "../../package.json"]) {
45920
46787
  try {
45921
- return path23__default.dirname(requireFromHere.resolve(candidate));
46788
+ return path24__default.dirname(requireFromHere.resolve(candidate));
45922
46789
  } catch (error51) {
45923
46790
  if (error51.code !== "MODULE_NOT_FOUND") throw error51;
45924
46791
  }
@@ -45933,15 +46800,15 @@ function readFleetConsoleRelease(env = process.env) {
45933
46800
  if (desktop) return readReleaseAt(desktop.resourceRoot, readPackageChannel(desktop.resourceRoot));
45934
46801
  const requireFromHere = createRequire(import.meta.url);
45935
46802
  const packageJsonPath = resolvePackageJsonPath(requireFromHere);
45936
- const packageRoot = path23__default.dirname(packageJsonPath);
46803
+ const packageRoot = path24__default.dirname(packageJsonPath);
45937
46804
  return readReleaseAt(packageRoot, readPackageChannel(packageRoot, requireFromHere), requireFromHere);
45938
46805
  }
45939
46806
  function readPackageChannel(packageRoot, requireFromHere = createRequire(import.meta.url)) {
45940
- const pkg = requireFromHere(path23__default.join(packageRoot, "package.json"));
46807
+ const pkg = requireFromHere(path24__default.join(packageRoot, "package.json"));
45941
46808
  return pkg.private === true ? "local" : "stable";
45942
46809
  }
45943
46810
  function readReleaseAt(packageRoot, channel, requireFromHere = createRequire(import.meta.url)) {
45944
- const packageJsonPath = path23__default.join(packageRoot, "package.json");
46811
+ const packageJsonPath = path24__default.join(packageRoot, "package.json");
45945
46812
  const pkg = requireFromHere(packageJsonPath);
45946
46813
  return { channel, version: pkg.version ?? "", packageRoot };
45947
46814
  }
@@ -45969,14 +46836,14 @@ function readConsoleDirOverride(env) {
45969
46836
  function createConsolePaths(deps = {}) {
45970
46837
  const env = deps.env ?? process.env;
45971
46838
  const base = readConsoleDirOverride(env) ?? defaultConsoleBaseDir(deps);
45972
- return { dir: base, lockFile: path23__default.join(base, "console.lock") };
46839
+ return { dir: base, lockFile: path24__default.join(base, "console.lock") };
45973
46840
  }
45974
46841
  function createConsoleDataPaths(deps = {}) {
45975
46842
  const dir = defaultConsoleDataBaseDir(deps);
45976
46843
  return {
45977
46844
  dir,
45978
- stateFile: path23__default.join(dir, CONSOLE_STATE_FILE_NAME2),
45979
- settingsFile: path23__default.join(dir, CONSOLE_SETTINGS_FILE_NAME2)
46845
+ stateFile: path24__default.join(dir, CONSOLE_STATE_FILE_NAME2),
46846
+ settingsFile: path24__default.join(dir, CONSOLE_SETTINGS_FILE_NAME2)
45980
46847
  };
45981
46848
  }
45982
46849
  function defaultConsoleBaseDir(deps) {
@@ -45995,7 +46862,7 @@ function defaultConsoleBaseDir(deps) {
45995
46862
  }
45996
46863
  function defaultConsoleDataBaseDir(deps) {
45997
46864
  if (deps.fleetDataDir !== void 0) {
45998
- return path23__default.join(deps.fleetDataDir, CONSOLE_DATA_DIR_NAME2);
46865
+ return path24__default.join(deps.fleetDataDir, CONSOLE_DATA_DIR_NAME2);
45999
46866
  }
46000
46867
  const env = deps.env ?? process.env;
46001
46868
  const override = readConsoleDirOverride(env);
@@ -46015,7 +46882,7 @@ function defaultConsoleDataBaseDir(deps) {
46015
46882
  }).dataDir;
46016
46883
  }
46017
46884
  function localConsoleDir(packageRoot) {
46018
- return path23__default.join(path23__default.resolve(packageRoot, "..", ".."), ".fleet", CONSOLE_RUNTIME_DIR_NAME);
46885
+ return path24__default.join(path24__default.resolve(packageRoot, "..", ".."), ".fleet", CONSOLE_RUNTIME_DIR_NAME);
46019
46886
  }
46020
46887
 
46021
46888
  // sdk/operations/launch-variants.ts
@@ -46024,12 +46891,12 @@ function readLaunchVariantGroups(value) {
46024
46891
  return value.map(readLaunchVariantGroup).filter((group) => group !== null);
46025
46892
  }
46026
46893
  function readLaunchVariantGroup(value) {
46027
- if (!isRecord11(value) || typeof value.id !== "string" || typeof value.label !== "string" || !Array.isArray(value.rows)) return null;
46894
+ if (!isRecord12(value) || typeof value.id !== "string" || typeof value.label !== "string" || !Array.isArray(value.rows)) return null;
46028
46895
  const rows = value.rows.map(readLaunchVariantRow).filter((row) => row !== null);
46029
46896
  return rows.length > 0 ? { id: value.id, label: value.label, rows } : null;
46030
46897
  }
46031
46898
  function readLaunchVariantRow(value) {
46032
- if (!isRecord11(value) || typeof value.id !== "string" || typeof value.label !== "string") return null;
46899
+ if (!isRecord12(value) || typeof value.id !== "string" || typeof value.label !== "string") return null;
46033
46900
  const launch = readLaunchPayload(value.launch);
46034
46901
  if (!launch) return null;
46035
46902
  const chips = Array.isArray(value.chips) ? value.chips.map(readLaunchVariantChip).filter((chip) => chip !== null) : [];
@@ -46048,7 +46915,7 @@ function readLaunchVariantRow(value) {
46048
46915
  };
46049
46916
  }
46050
46917
  function readLaunchVariantChip(value) {
46051
- if (!isRecord11(value) || typeof value.id !== "string" || typeof value.label !== "string") return null;
46918
+ if (!isRecord12(value) || typeof value.id !== "string" || typeof value.label !== "string") return null;
46052
46919
  const launch = readLaunchPayload(value.launch);
46053
46920
  return launch ? { id: value.id, label: value.label, launch } : null;
46054
46921
  }
@@ -46058,11 +46925,11 @@ function readLaunchPayload(value) {
46058
46925
  return Object.keys(launch).length > 0 ? launch : null;
46059
46926
  }
46060
46927
  function isPlainRecord(value) {
46061
- if (!isRecord11(value)) return false;
46928
+ if (!isRecord12(value)) return false;
46062
46929
  const prototype = Object.getPrototypeOf(value);
46063
46930
  return prototype === Object.prototype || prototype === null;
46064
46931
  }
46065
- function isRecord11(value) {
46932
+ function isRecord12(value) {
46066
46933
  return typeof value === "object" && value !== null && !Array.isArray(value);
46067
46934
  }
46068
46935
 
@@ -46221,7 +47088,7 @@ function effectiveRemoteAccessAdvertisedTuple(settings2) {
46221
47088
  }
46222
47089
  var REMOTE_BIND_HOST = /^(?:\d{1,3}(?:\.\d{1,3}){3}|[A-Za-z0-9](?:[A-Za-z0-9._-]{0,252}[A-Za-z0-9])?)$/u;
46223
47090
  function sanitizeRemoteAccessSettings(value) {
46224
- if (!isRecord12(value) || "bindHost" in value) return void 0;
47091
+ if (!isRecord13(value) || "bindHost" in value) return void 0;
46225
47092
  if (typeof value.enabled !== "boolean") return void 0;
46226
47093
  const listenAddress = value.listenAddress === "" ? "" : isValidRemoteBindHost(value.listenAddress) ? canonicalizeRemoteBindHost(value.listenAddress) : null;
46227
47094
  const advertisedHost = value.advertisedHost === "" ? "" : isValidRemoteAdvertisedHost(value.advertisedHost) ? canonicalizeRemoteBindHost(value.advertisedHost) : null;
@@ -46269,7 +47136,7 @@ function createConsoleSettingsStore(deps = {}) {
46269
47136
  const readFile7 = deps.readFile ?? ((file2) => fs9__default.readFileSync(file2, "utf8"));
46270
47137
  const base = createStore({
46271
47138
  filePath: paths.settingsFile,
46272
- lockDir: path23__default.join(paths.dir, SETTINGS_LOCK_DIR_NAME),
47139
+ lockDir: path24__default.join(paths.dir, SETTINGS_LOCK_DIR_NAME),
46273
47140
  lockOwnerFileName: SETTINGS_LOCK_OWNER_FILE_NAME,
46274
47141
  now: deps.now,
46275
47142
  sanitize: sanitizeConsoleSettingsData,
@@ -46303,7 +47170,7 @@ function createConsoleSettingsStore(deps = {}) {
46303
47170
  };
46304
47171
  }
46305
47172
  function sanitizeConsoleSettingsData(value) {
46306
- if (!isRecord12(value)) return emptyConsoleSettingsData();
47173
+ if (!isRecord13(value)) return emptyConsoleSettingsData();
46307
47174
  if (value.version !== SETTINGS_VERSION) return emptyConsoleSettingsData();
46308
47175
  const general = readConsoleGeneralSettings(value.general);
46309
47176
  const plugins = readConsolePluginSettings(value.plugins);
@@ -46318,7 +47185,7 @@ function emptyConsoleSettingsData() {
46318
47185
  }
46319
47186
  function sanitizeUiFontSettings(value) {
46320
47187
  if (isConsoleUiFontId(value)) return { source: "builtin", id: value, size: DEFAULT_UI_FONT_SETTINGS.size };
46321
- if (!isRecord12(value) || !isValidUiFontSize(value.size)) return void 0;
47188
+ if (!isRecord13(value) || !isValidUiFontSize(value.size)) return void 0;
46322
47189
  if (value.source === "builtin" && isConsoleUiFontId(value.id)) {
46323
47190
  return { source: "builtin", id: value.id, size: value.size };
46324
47191
  }
@@ -46339,12 +47206,12 @@ function sanitizeSeenFeatureTours(value) {
46339
47206
  return [...seen];
46340
47207
  }
46341
47208
  function isUiFontSettings(value) {
46342
- if (!isRecord12(value) || !isValidUiFontSize(value.size)) return false;
47209
+ if (!isRecord13(value) || !isValidUiFontSize(value.size)) return false;
46343
47210
  if (value.source === "builtin") return isConsoleUiFontId(value.id);
46344
47211
  return value.source === "system" && typeof value.familyName === "string" && value.familyName.length > 0 && value.familyName === sanitizeSystemFontFamily(value.familyName);
46345
47212
  }
46346
47213
  function readConsoleGeneralSettings(value) {
46347
- if (!isRecord12(value)) return null;
47214
+ if (!isRecord13(value)) return null;
46348
47215
  const consolePortMode = value.consolePortMode === "dynamic" || value.consolePortMode === "static" ? value.consolePortMode : void 0;
46349
47216
  const consoleStaticPort = isValidConsoleStaticPort(value.consoleStaticPort) ? value.consoleStaticPort : void 0;
46350
47217
  const language = value.language === "auto" || value.language === "en" || value.language === "ko" ? value.language : void 0;
@@ -46363,11 +47230,11 @@ function readConsoleGeneralSettings(value) {
46363
47230
  };
46364
47231
  }
46365
47232
  function readConsolePluginSettings(value) {
46366
- if (!isRecord12(value)) return null;
47233
+ if (!isRecord13(value)) return null;
46367
47234
  const result = {};
46368
47235
  for (const [key, entry] of Object.entries(value)) {
46369
47236
  if (!PLUGIN_ID_PATTERN.test(key)) continue;
46370
- if (!isRecord12(entry)) continue;
47237
+ if (!isRecord13(entry)) continue;
46371
47238
  result[key] = entry;
46372
47239
  }
46373
47240
  return result;
@@ -46376,13 +47243,13 @@ function isValidRemoteAdvertisedHost(value) {
46376
47243
  return isValidRemoteBindHost(value);
46377
47244
  }
46378
47245
  function sanitizeRemotePortSetting(value) {
46379
- if (!isRecord12(value) || value.mode !== "auto" && value.mode !== "custom" || !isBindablePort(value.value)) return null;
47246
+ if (!isRecord13(value) || value.mode !== "auto" && value.mode !== "custom" || !isBindablePort(value.value)) return null;
46380
47247
  if (value.mode === "auto" && (value.value < REMOTE_AUTO_PORT_MIN || value.value > REMOTE_AUTO_PORT_MAX)) return null;
46381
47248
  return { mode: value.mode, value: value.value };
46382
47249
  }
46383
47250
  function sanitizeAcknowledgment(value) {
46384
47251
  if (value === null) return null;
46385
- if (!isRecord12(value) || value.version !== 1 || !isValidRemoteBindHost(value.listenAddress) || !isValidRemoteAdvertisedHost(value.advertisedHost) || !isBindablePort(value.listenPort) || !isBindablePort(value.advertisedPort)) return null;
47252
+ if (!isRecord13(value) || value.version !== 1 || !isValidRemoteBindHost(value.listenAddress) || !isValidRemoteAdvertisedHost(value.advertisedHost) || !isBindablePort(value.listenPort) || !isBindablePort(value.advertisedPort)) return null;
46386
47253
  return { version: 1, listenAddress: canonicalizeRemoteBindHost(value.listenAddress), listenPort: value.listenPort, advertisedHost: canonicalizeRemoteBindHost(value.advertisedHost), advertisedPort: value.advertisedPort };
46387
47254
  }
46388
47255
  function acknowledgmentMatches(settings2, acknowledgment) {
@@ -46405,24 +47272,24 @@ function readRawSettings(file2, readFile7) {
46405
47272
  }
46406
47273
  }
46407
47274
  function currentRemoteAccessNeedsMigration(raw) {
46408
- return isRecord12(raw) && raw.version === 1 && isRecord12(raw.general) && isRecord12(raw.general.remoteAccess) && !("bindHost" in raw.general.remoteAccess) && typeof raw.general.remoteAccess.publicEndpointEnabled !== "boolean";
47275
+ return isRecord13(raw) && raw.version === 1 && isRecord13(raw.general) && isRecord13(raw.general.remoteAccess) && !("bindHost" in raw.general.remoteAccess) && typeof raw.general.remoteAccess.publicEndpointEnabled !== "boolean";
46409
47276
  }
46410
47277
  function readLegacyRemoteAccess(raw, consoleDir, readFile7, randomInt) {
46411
- if (!isRecord12(raw) || raw.version !== 1 || !isRecord12(raw.general) || !isRecord12(raw.general.remoteAccess)) return null;
47278
+ if (!isRecord13(raw) || raw.version !== 1 || !isRecord13(raw.general) || !isRecord13(raw.general.remoteAccess)) return null;
46412
47279
  const legacy = raw.general.remoteAccess;
46413
47280
  if (!isValidRemoteBindHost(legacy.bindHost)) return null;
46414
47281
  const host = canonicalizeRemoteBindHost(legacy.bindHost);
46415
47282
  let port = null;
46416
47283
  try {
46417
- const endpoint = JSON.parse(readFile7(path23__default.join(consoleDir, "remote", "listener.json")));
46418
- if (isRecord12(endpoint) && endpoint.version === 1 && isBindablePort(endpoint.port)) port = endpoint.port;
47284
+ const endpoint = JSON.parse(readFile7(path24__default.join(consoleDir, "remote", "listener.json")));
47285
+ if (isRecord13(endpoint) && endpoint.version === 1 && isBindablePort(endpoint.port)) port = endpoint.port;
46419
47286
  } catch {
46420
47287
  }
46421
47288
  const listenPort = port === null ? { mode: "auto", value: randomAutoPort(randomInt) } : { mode: "custom", value: port };
46422
47289
  const advertisedPort = port === null ? { mode: "auto", value: randomAutoPort(randomInt) } : { mode: "custom", value: port };
46423
47290
  return { enabled: legacy.enabled === true, publicEndpointEnabled: false, listenAddress: host, advertisedHost: host, listenPort, advertisedPort, acknowledgment: null };
46424
47291
  }
46425
- function isRecord12(value) {
47292
+ function isRecord13(value) {
46426
47293
  return typeof value === "object" && value !== null && !Array.isArray(value);
46427
47294
  }
46428
47295
  function isValidConsoleStaticPort(value) {
@@ -46549,7 +47416,7 @@ async function mutateGlobalSettings(req, res, deps) {
46549
47416
  deps.writeJson(res, 200, response);
46550
47417
  }
46551
47418
  function isValidRemoteAccessInput(value) {
46552
- if (!isRecord12(value) || "bindHost" in value || typeof value.enabled !== "boolean" || typeof value.publicEndpointEnabled !== "boolean") return false;
47419
+ if (!isRecord13(value) || "bindHost" in value || typeof value.enabled !== "boolean" || typeof value.publicEndpointEnabled !== "boolean") return false;
46553
47420
  const validListenAddress = value.listenAddress === "" || isValidRemoteBindHost(value.listenAddress);
46554
47421
  const validAdvertisedHost = value.advertisedHost === "" || isValidRemoteAdvertisedHost(value.advertisedHost);
46555
47422
  if (!validListenAddress || !validAdvertisedHost) return false;
@@ -46563,16 +47430,16 @@ function isValidRemoteAccessInput(value) {
46563
47430
  return value.listenAddress !== "" && value.advertisedHost !== "" && acknowledgmentMatches({ listenAddress: value.listenAddress, advertisedHost: value.advertisedHost, listenPort, advertisedPort }, acknowledgment);
46564
47431
  }
46565
47432
  function normalizeRemoteAccessInput(value) {
46566
- const record5 = value;
46567
- const publicEndpointEnabled = record5.publicEndpointEnabled === true;
47433
+ const record6 = value;
47434
+ const publicEndpointEnabled = record6.publicEndpointEnabled === true;
46568
47435
  return {
46569
- enabled: record5.enabled === true,
47436
+ enabled: record6.enabled === true,
46570
47437
  publicEndpointEnabled,
46571
- listenAddress: record5.listenAddress === "" ? "" : canonicalizeRemoteBindHost(record5.listenAddress),
46572
- advertisedHost: record5.advertisedHost === "" ? "" : canonicalizeRemoteBindHost(record5.advertisedHost),
46573
- listenPort: sanitizeRemotePortSetting(record5.listenPort),
46574
- advertisedPort: sanitizeRemotePortSetting(record5.advertisedPort),
46575
- acknowledgment: publicEndpointEnabled ? sanitizeAcknowledgment(record5.acknowledgment) : null
47438
+ listenAddress: record6.listenAddress === "" ? "" : canonicalizeRemoteBindHost(record6.listenAddress),
47439
+ advertisedHost: record6.advertisedHost === "" ? "" : canonicalizeRemoteBindHost(record6.advertisedHost),
47440
+ listenPort: sanitizeRemotePortSetting(record6.listenPort),
47441
+ advertisedPort: sanitizeRemotePortSetting(record6.advertisedPort),
47442
+ acknowledgment: publicEndpointEnabled ? sanitizeAcknowledgment(record6.acknowledgment) : null
46576
47443
  };
46577
47444
  }
46578
47445
  function withRemoteAccessVisibility(state, req, deps) {
@@ -46658,7 +47525,7 @@ function createPluginSettingsRouter(deps) {
46658
47525
  return true;
46659
47526
  }
46660
47527
  const body2 = await deps.readJsonBody(req);
46661
- if (!isRecord12(body2)) {
47528
+ if (!isRecord13(body2)) {
46662
47529
  deps.writeJson(res, 400, { error: "invalid_json" });
46663
47530
  return true;
46664
47531
  }
@@ -46706,7 +47573,7 @@ function createSanitizedOpDto(node, options = {}) {
46706
47573
  };
46707
47574
  }
46708
47575
  function isResumableProviderSession(value) {
46709
- if (!isRecord13(value)) return false;
47576
+ if (!isRecord14(value)) return false;
46710
47577
  return value.provider === "claude" && typeof value.sessionId === "string" && value.sessionId.length > 0;
46711
47578
  }
46712
47579
  function sanitizeRecord(value, sensitiveFields) {
@@ -46719,10 +47586,10 @@ function sanitizeRecord(value, sensitiveFields) {
46719
47586
  }
46720
47587
  function sanitizeValue(value, sensitiveFields) {
46721
47588
  if (Array.isArray(value)) return value.map((item) => sanitizeValue(item, sensitiveFields));
46722
- if (!isRecord13(value)) return value;
47589
+ if (!isRecord14(value)) return value;
46723
47590
  return sanitizeRecord(value, sensitiveFields);
46724
47591
  }
46725
- function isRecord13(value) {
47592
+ function isRecord14(value) {
46726
47593
  return typeof value === "object" && value !== null && !Array.isArray(value);
46727
47594
  }
46728
47595
  function createOperationStore(deps = {}) {
@@ -46973,8 +47840,8 @@ async function handleCollection(req, res, deps) {
46973
47840
  pluginId: body2.pluginId,
46974
47841
  title: body2.title,
46975
47842
  ...typeof body2.accent === "string" ? { accent: body2.accent } : {},
46976
- payload: isRecord13(body2.payload) ? body2.payload : {},
46977
- geometry: isRecord13(body2.geometry) ? readGeometry(body2.geometry) : null
47843
+ payload: isRecord14(body2.payload) ? body2.payload : {},
47844
+ geometry: isRecord14(body2.geometry) ? readGeometry(body2.geometry) : null
46978
47845
  });
46979
47846
  deps.persist();
46980
47847
  deps.writeJson(res, 201, { operation: sanitizeOperationNode(node, deps) });
@@ -47020,8 +47887,8 @@ async function handleItem(req, res, id, deps) {
47020
47887
  ...typeof body2.title === "string" ? { title: body2.title } : {},
47021
47888
  ...typeof body2.accent === "string" || body2.accent === null ? { accent: body2.accent } : {},
47022
47889
  ...typeof body2.groupId === "string" || body2.groupId === null ? { groupId: body2.groupId } : {},
47023
- ...isRecord13(body2.payload) ? { payload: body2.payload } : {},
47024
- ...isRecord13(body2.geometry) || body2.geometry === null ? { geometry: body2.geometry === null ? null : readGeometry(body2.geometry) } : {}
47890
+ ...isRecord14(body2.payload) ? { payload: body2.payload } : {},
47891
+ ...isRecord14(body2.geometry) || body2.geometry === null ? { geometry: body2.geometry === null ? null : readGeometry(body2.geometry) } : {}
47025
47892
  });
47026
47893
  if (!node) {
47027
47894
  deps.writeJson(res, 404, { error: "operation_not_found" });
@@ -47474,15 +48341,15 @@ var FILE_MODE2 = 384;
47474
48341
  function createRemoteStorage(consoleDir, deps = {}) {
47475
48342
  const fileSystem = deps.fileSystem ?? fs9__default;
47476
48343
  const ensureDirectory = deps.ensureDirectory ?? ensureSafeDirectory;
47477
- const directory = path23__default.join(consoleDir, REMOTE_DIR);
48344
+ const directory = path24__default.join(consoleDir, REMOTE_DIR);
47478
48345
  return {
47479
- path: (file2) => path23__default.join(directory, file2),
48346
+ path: (file2) => path24__default.join(directory, file2),
47480
48347
  /**
47481
48348
  * temp+rename으로 갈아 끼운다. 쓰는 도중에 끊겨도 반쯤 쓰인 파일이 자리를 차지하지 않는다.
47482
48349
  * 파일은 만들어질 때부터 0600이어야 한다 — 나중에 고치면 그사이에 열린 파일이 있다.
47483
48350
  */
47484
48351
  write(file2, content) {
47485
- const target2 = path23__default.join(directory, file2);
48352
+ const target2 = path24__default.join(directory, file2);
47486
48353
  const temporary = `${target2}.tmp`;
47487
48354
  ensureDirectory(directory);
47488
48355
  fileSystem.writeFileSync(temporary, content, { encoding: "utf8", mode: FILE_MODE2 });
@@ -48598,10 +49465,10 @@ var CoworkStore = class {
48598
49465
  }
48599
49466
  const now = (/* @__PURE__ */ new Date()).toISOString();
48600
49467
  const id = crypto9.randomUUID();
48601
- const record5 = { id, workspaceId, entryId, state: "idle", revision: 0, draft: body2, baseDraft: body2, baseHash, baseVersion, selection: null, annotations: [], ...identity2, targetPath, createdAt: now, updatedAt: now };
48602
- this.sessions.set(this.key(workspaceId, id), record5);
49468
+ const record6 = { id, workspaceId, entryId, state: "idle", revision: 0, draft: body2, baseDraft: body2, baseHash, baseVersion, selection: null, annotations: [], ...identity2, targetPath, createdAt: now, updatedAt: now };
49469
+ this.sessions.set(this.key(workspaceId, id), record6);
48603
49470
  this.writers.set(`${workspaceId}:${entryId}`, id);
48604
- return record5;
49471
+ return record6;
48605
49472
  }
48606
49473
  async get(workspaceId, sessionId) {
48607
49474
  return this.sessions.get(this.key(workspaceId, sessionId)) ?? null;
@@ -48667,9 +49534,9 @@ var CoworkStore = class {
48667
49534
  }
48668
49535
  return dir;
48669
49536
  }
48670
- release(record5) {
48671
- this.writers.delete(`${record5.workspaceId}:${record5.entryId}`);
48672
- const key = this.key(record5.workspaceId, record5.id);
49537
+ release(record6) {
49538
+ this.writers.delete(`${record6.workspaceId}:${record6.entryId}`);
49539
+ const key = this.key(record6.workspaceId, record6.id);
48673
49540
  const dir = this.scratchDirs.get(key);
48674
49541
  this.scratchDirs.delete(key);
48675
49542
  if (dir) void rm(dir, { recursive: true, force: true }).catch(() => void 0);
@@ -49002,9 +49869,9 @@ function claudeGatewayModelCache(options) {
49002
49869
 
49003
49870
  // ../../packages/core-agent/src/claude/config-dir.ts
49004
49871
  async function createIsolatedClaudeConfigDir(tempRoot = tmpdir()) {
49005
- const root = await mkdtemp(path23__default.join(tempRoot, "core-agent-claude-"));
49006
- const cachePath = path23__default.join(root, CLAUDE_GATEWAY_MODEL_CACHE_RELPATH);
49007
- await mkdir(path23__default.dirname(cachePath), { recursive: true, mode: 448 });
49872
+ const root = await mkdtemp(path24__default.join(tempRoot, "core-agent-claude-"));
49873
+ const cachePath = path24__default.join(root, CLAUDE_GATEWAY_MODEL_CACHE_RELPATH);
49874
+ await mkdir(path24__default.dirname(cachePath), { recursive: true, mode: 448 });
49008
49875
  let disposed = false;
49009
49876
  return {
49010
49877
  path: root,
@@ -49328,9 +50195,9 @@ var CoworkGatewayClient = class extends EventEmitter {
49328
50195
  publish(event, toolNames, finish) {
49329
50196
  const type = event.type;
49330
50197
  if (type === "stream_event") {
49331
- const inner = record4(event.event);
50198
+ const inner = record5(event.event);
49332
50199
  if (inner.type !== "content_block_delta") return;
49333
- const delta = record4(inner.delta);
50200
+ const delta = record5(inner.delta);
49334
50201
  if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
49335
50202
  this.emit("messageChunk", delta.text);
49336
50203
  }
@@ -49360,9 +50227,9 @@ var CoworkGatewayClient = class extends EventEmitter {
49360
50227
  };
49361
50228
  function toServedMcpServers(values) {
49362
50229
  return values.flatMap((value) => {
49363
- const server = record4(value);
50230
+ const server = record5(value);
49364
50231
  if (typeof server.name !== "string" || typeof server.url !== "string") return [];
49365
- const headers = Array.isArray(server.headers) ? server.headers.map(record4).flatMap((header) => typeof header.name === "string" && typeof header.value === "string" ? [{ name: header.name, value: header.value }] : []) : [];
50232
+ const headers = Array.isArray(server.headers) ? server.headers.map(record5).flatMap((header) => typeof header.name === "string" && typeof header.value === "string" ? [{ name: header.name, value: header.value }] : []) : [];
49366
50233
  return [{
49367
50234
  name: server.name,
49368
50235
  url: server.url,
@@ -49372,10 +50239,10 @@ function toServedMcpServers(values) {
49372
50239
  });
49373
50240
  }
49374
50241
  function blocks(message) {
49375
- const content = record4(message).content;
49376
- return Array.isArray(content) ? content.map(record4) : [];
50242
+ const content = record5(message).content;
50243
+ return Array.isArray(content) ? content.map(record5) : [];
49377
50244
  }
49378
- function record4(value) {
50245
+ function record5(value) {
49379
50246
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
49380
50247
  }
49381
50248
  function workspaceHash(canonicalCwd) {
@@ -49385,7 +50252,7 @@ async function canonicalizeTheaterPath(cwd) {
49385
50252
  return canonicalizeTheaterPathSync(cwd);
49386
50253
  }
49387
50254
  function canonicalizeTheaterPathSync(cwd) {
49388
- const resolved = path23__default.resolve(cwd);
50255
+ const resolved = path24__default.resolve(cwd);
49389
50256
  try {
49390
50257
  return fs9__default.realpathSync.native(resolved);
49391
50258
  } catch {
@@ -49393,7 +50260,7 @@ function canonicalizeTheaterPathSync(cwd) {
49393
50260
  }
49394
50261
  }
49395
50262
  function theaterLabel(cwd) {
49396
- return path23__default.basename(cwd) || cwd;
50263
+ return path24__default.basename(cwd) || cwd;
49397
50264
  }
49398
50265
  var TheaterFolderListError = class extends Error {
49399
50266
  code;
@@ -49426,14 +50293,14 @@ async function listTheaterFolders(requestedPath, deps = {}) {
49426
50293
  }
49427
50294
  function normalizeFolderBrowserPath(value, platform = process.platform) {
49428
50295
  if (typeof value !== "string" || value.length === 0 || value.includes("\0")) throw new TheaterFolderListError("invalid_path");
49429
- if (isWindowsAmbiguousPath(value, platform) || !path23__default.isAbsolute(value)) throw new TheaterFolderListError("invalid_path");
49430
- return path23__default.resolve(value);
50296
+ if (isWindowsAmbiguousPath(value, platform) || !path24__default.isAbsolute(value)) throw new TheaterFolderListError("invalid_path");
50297
+ return path24__default.resolve(value);
49431
50298
  }
49432
50299
  function normalizeListPath(requestedPath, platform, deps) {
49433
50300
  if (requestedPath === null || requestedPath === void 0) {
49434
50301
  const home = deps.homedir?.() ?? os3__default.homedir();
49435
50302
  const start = home || deps.cwd?.() || process.cwd();
49436
- return path23__default.resolve(start);
50303
+ return path24__default.resolve(start);
49437
50304
  }
49438
50305
  return normalizeFolderBrowserPath(requestedPath, platform);
49439
50306
  }
@@ -49484,7 +50351,7 @@ async function openDirectory(targetPath, opendir) {
49484
50351
  }
49485
50352
  async function toTheaterFolderEntry(targetPath, dirent, stat5) {
49486
50353
  if (!dirent.isDirectory() && !dirent.isSymbolicLink()) return null;
49487
- const entryPath = path23__default.join(targetPath, dirent.name);
50354
+ const entryPath = path24__default.join(targetPath, dirent.name);
49488
50355
  if (dirent.isDirectory()) return { name: dirent.name, path: entryPath, kind: "dir", accessible: true };
49489
50356
  const accessible = await statSymlinkDirectory(entryPath, stat5);
49490
50357
  if (accessible === null) return null;
@@ -49504,10 +50371,10 @@ function mapFolderListFsError(error51) {
49504
50371
  return new TheaterFolderListError("invalid_path");
49505
50372
  }
49506
50373
  function parentPath(targetPath, platform) {
49507
- const parsed = path23__default.parse(targetPath);
49508
- const resolved = path23__default.resolve(targetPath);
49509
- if (resolved === path23__default.resolve(parsed.root)) return null;
49510
- const parent = path23__default.dirname(resolved);
50374
+ const parsed = path24__default.parse(targetPath);
50375
+ const resolved = path24__default.resolve(targetPath);
50376
+ if (resolved === path24__default.resolve(parsed.root)) return null;
50377
+ const parent = path24__default.dirname(resolved);
49511
50378
  if (platform === "win32" && parent === resolved) return null;
49512
50379
  return parent;
49513
50380
  }
@@ -49547,8 +50414,8 @@ function createFolderGrantStore(deps = {}) {
49547
50414
  }
49548
50415
  function validateAbsoluteDirectory(cwd, statSync4 = fs9__default.statSync) {
49549
50416
  if (typeof cwd !== "string" || cwd.length === 0 || cwd.includes("\0")) throw new Error("invalid_folder");
49550
- if (isWindowsAmbiguousGrantPath(cwd) || !path23__default.isAbsolute(cwd)) throw new Error("invalid_folder");
49551
- const normalized = path23__default.resolve(cwd);
50417
+ if (isWindowsAmbiguousGrantPath(cwd) || !path24__default.isAbsolute(cwd)) throw new Error("invalid_folder");
50418
+ const normalized = path24__default.resolve(cwd);
49552
50419
  if (!statSync4(normalized).isDirectory()) throw new Error("invalid_folder");
49553
50420
  return normalized;
49554
50421
  }
@@ -49560,7 +50427,7 @@ var TheaterRegistry = class {
49560
50427
  #items = /* @__PURE__ */ new Map();
49561
50428
  #mruId = null;
49562
50429
  async register(cwd) {
49563
- const resolved = path23__default.resolve(cwd);
50430
+ const resolved = path24__default.resolve(cwd);
49564
50431
  const real = await canonicalizeTheaterPath(resolved);
49565
50432
  const id = workspaceHash(real);
49566
50433
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -49635,7 +50502,7 @@ var WorkspaceRegistry = class {
49635
50502
  #items = /* @__PURE__ */ new Map();
49636
50503
  #mruId = null;
49637
50504
  async register(cwdInput, lastOpenedAt) {
49638
- const cwd = path23__default.resolve(cwdInput);
50505
+ const cwd = path24__default.resolve(cwdInput);
49639
50506
  const real = await canonicalizeTheaterPath(cwd);
49640
50507
  const id = workspaceHash(real);
49641
50508
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -49647,7 +50514,7 @@ var WorkspaceRegistry = class {
49647
50514
  id,
49648
50515
  cwd,
49649
50516
  realpath: real,
49650
- label: path23__default.basename(cwd),
50517
+ label: path24__default.basename(cwd),
49651
50518
  registeredAt: existing?.registeredAt ?? now,
49652
50519
  // 복원 경로는 durable lastOpenedAt을 그대로 보존해 재시작 후에도 워크스페이스 최근성
49653
50520
  // 순서(MRU·listRegistrations 동순위 처리)가 durable 상태와 일치하게 한다. 일반 등록은 now.
@@ -50273,7 +51140,7 @@ function createConsoleDurableStateStore(deps = {}) {
50273
51140
  const createStore = deps.createStore ?? createDurableJsonStore;
50274
51141
  return createStore({
50275
51142
  filePath: paths.stateFile,
50276
- lockDir: path23__default.join(paths.dir, STATE_LOCK_DIR_NAME),
51143
+ lockDir: path24__default.join(paths.dir, STATE_LOCK_DIR_NAME),
50277
51144
  lockOwnerFileName: STATE_LOCK_OWNER_FILE_NAME,
50278
51145
  now: deps.now,
50279
51146
  sanitize: sanitizeDurableConsoleState,
@@ -50282,7 +51149,7 @@ function createConsoleDurableStateStore(deps = {}) {
50282
51149
  });
50283
51150
  }
50284
51151
  function sanitizeDurableConsoleState(value) {
50285
- if (!isRecord14(value)) return emptyDurableConsoleState();
51152
+ if (!isRecord15(value)) return emptyDurableConsoleState();
50286
51153
  const upgraded = migrateToCurrentVersion(value);
50287
51154
  if (upgraded.version !== STATE_VERSION) return emptyDurableConsoleState();
50288
51155
  return {
@@ -50321,13 +51188,13 @@ function migrateV2ToV3(v2) {
50321
51188
  };
50322
51189
  }
50323
51190
  function migrateV1Operation(value) {
50324
- if (!isRecord14(value)) return null;
51191
+ if (!isRecord15(value)) return null;
50325
51192
  const sessionId = readNonEmptyString(value.sessionId);
50326
51193
  const theaterId = readNonEmptyString(value.theaterId);
50327
51194
  const cwd = readNonEmptyString(value.cwd);
50328
51195
  const createdAt = readFiniteNumber2(value.createdAt);
50329
51196
  if (!sessionId || !theaterId || !cwd || createdAt === null) return null;
50330
- const title = readOptionalString(value.label) ?? (path23__default.basename(cwd) || cwd);
51197
+ const title = readOptionalString(value.label) ?? (path24__default.basename(cwd) || cwd);
50331
51198
  const payload = { cwd };
50332
51199
  const cliId = readOptionalString(value.cliId);
50333
51200
  const cliLabel = readOptionalString(value.cliLabel);
@@ -50335,7 +51202,7 @@ function migrateV1Operation(value) {
50335
51202
  if (cliId) payload.cliId = cliId;
50336
51203
  if (cliLabel) payload.cliLabel = cliLabel;
50337
51204
  if (labelSource) payload.labelSource = labelSource;
50338
- if (isRecord14(value.providerSession)) payload.providerSession = value.providerSession;
51205
+ if (isRecord15(value.providerSession)) payload.providerSession = value.providerSession;
50339
51206
  return {
50340
51207
  id: sessionId,
50341
51208
  theaterId,
@@ -50366,7 +51233,7 @@ function readOperations(value) {
50366
51233
  return nodes;
50367
51234
  }
50368
51235
  function sanitizeTheaterRegistration(value) {
50369
- if (!isRecord14(value)) return null;
51236
+ if (!isRecord15(value)) return null;
50370
51237
  const id = readNonEmptyString(value.id);
50371
51238
  const theaterPath = readNonEmptyString(value.path);
50372
51239
  const realpath3 = readNonEmptyString(value.realpath);
@@ -50386,7 +51253,7 @@ function sanitizeTheaterRegistration(value) {
50386
51253
  };
50387
51254
  }
50388
51255
  function sanitizeOperationNode2(value) {
50389
- if (!isRecord14(value)) return null;
51256
+ if (!isRecord15(value)) return null;
50390
51257
  const id = readNonEmptyString(value.id);
50391
51258
  const theaterId = readNonEmptyString(value.theaterId);
50392
51259
  const type = readNonEmptyString(value.type);
@@ -50410,7 +51277,7 @@ function sanitizeOperationNode2(value) {
50410
51277
  };
50411
51278
  }
50412
51279
  function sanitizeOperationTimestamps(value) {
50413
- if (!isRecord14(value)) return null;
51280
+ if (!isRecord15(value)) return null;
50414
51281
  const createdAt = readFiniteNumber2(value.createdAt);
50415
51282
  const updatedAt = readFiniteNumber2(value.updatedAt);
50416
51283
  if (createdAt === null || updatedAt === null) return null;
@@ -50418,7 +51285,7 @@ function sanitizeOperationTimestamps(value) {
50418
51285
  }
50419
51286
  function sanitizeOperationGeometry(value) {
50420
51287
  if (value === null || value === void 0) return null;
50421
- if (!isRecord14(value)) return null;
51288
+ if (!isRecord15(value)) return null;
50422
51289
  const x3 = readFiniteNumber2(value.x);
50423
51290
  const y = readFiniteNumber2(value.y);
50424
51291
  const width = readFiniteNumber2(value.width);
@@ -50427,7 +51294,7 @@ function sanitizeOperationGeometry(value) {
50427
51294
  if (x3 === null || y === null || width === null || height === null || zIndex === null) return null;
50428
51295
  return { x: x3, y, width, height, zIndex };
50429
51296
  }
50430
- function isRecord14(value) {
51297
+ function isRecord15(value) {
50431
51298
  return typeof value === "object" && value !== null && !Array.isArray(value);
50432
51299
  }
50433
51300
  function readNonEmptyString(value) {
@@ -50437,7 +51304,7 @@ function readOptionalString(value) {
50437
51304
  return typeof value === "string" && value.length > 0 ? value : void 0;
50438
51305
  }
50439
51306
  function readRecord(value) {
50440
- return isRecord14(value) ? value : {};
51307
+ return isRecord15(value) ? value : {};
50441
51308
  }
50442
51309
  function remapTerminalPluginId(pluginId) {
50443
51310
  return pluginId === "agent" || pluginId === "shell" ? "terminal" : pluginId;
@@ -50471,7 +51338,7 @@ function readOperationGroups(value) {
50471
51338
  return groups;
50472
51339
  }
50473
51340
  function sanitizeOperationGroup(value) {
50474
- if (!isRecord14(value)) return null;
51341
+ if (!isRecord15(value)) return null;
50475
51342
  const id = readNonEmptyString(value.id);
50476
51343
  const theaterId = readNonEmptyString(value.theaterId);
50477
51344
  const rawName = readNonEmptyString(value.name);
@@ -50493,7 +51360,7 @@ function readDeletionTombstones(value) {
50493
51360
  return tombstones;
50494
51361
  }
50495
51362
  function sanitizeDeletionTombstone(value) {
50496
- if (!isRecord14(value)) return null;
51363
+ if (!isRecord15(value)) return null;
50497
51364
  const deletionId = readNonEmptyString(value.deletionId);
50498
51365
  const targetId = readNonEmptyString(value.targetId);
50499
51366
  const deletedAt = readFiniteNumber2(value.deletedAt);
@@ -50598,8 +51465,8 @@ function migrateLegacyCaptures(deps) {
50598
51465
  }
50599
51466
  }
50600
51467
  function migrateLegacyCapturesStrict(deps) {
50601
- if (!path23__default.isAbsolute(deps.consoleDataDir)) return;
50602
- const capturesDir = path23__default.join(deps.consoleDataDir, LEGACY_CAPTURES_DIR_NAME);
51468
+ if (!path24__default.isAbsolute(deps.consoleDataDir)) return;
51469
+ const capturesDir = path24__default.join(deps.consoleDataDir, LEGACY_CAPTURES_DIR_NAME);
50603
51470
  if (!fs9__default.existsSync(capturesDir)) return;
50604
51471
  let migrated = false;
50605
51472
  let retained = false;
@@ -50643,7 +51510,7 @@ function processCaptureFile(deps, capturesDir, operationId, entry) {
50643
51510
  const operation = deps.operations.get(operationId);
50644
51511
  if (operation) {
50645
51512
  if (hasProviderSession(operation.payload)) return { migrated: false, retained: false };
50646
- const filePath = path23__default.join(capturesDir, entry);
51513
+ const filePath = path24__default.join(capturesDir, entry);
50647
51514
  const parsed = JSON.parse(fs9__default.readFileSync(filePath, "utf8"));
50648
51515
  const providerSession = sanitizeProviderSession(parsed);
50649
51516
  if (!providerSession) return { migrated: false, retained: false };
@@ -50676,7 +51543,7 @@ function sanitizeProviderSession(value) {
50676
51543
  };
50677
51544
  }
50678
51545
  function isSafeCaptureId(value) {
50679
- return value.length > 0 && path23__default.basename(value) === value && !value.includes(path23__default.sep) && !value.includes(path23__default.posix.sep);
51546
+ return value.length > 0 && path24__default.basename(value) === value && !value.includes(path24__default.sep) && !value.includes(path24__default.posix.sep);
50680
51547
  }
50681
51548
  var ENDPOINT_FILE = "listener.json";
50682
51549
  var STORE_VERSION2 = 2;
@@ -50970,7 +51837,7 @@ function createRemoteHostStore(consoleDir, deps = {}) {
50970
51837
  try {
50971
51838
  const parsed = JSON.parse(readFile7(storage.path(HOSTS_FILE)));
50972
51839
  if (parsed?.version !== STORE_VERSION3 || !Array.isArray(parsed.hosts)) return [];
50973
- return parsed.hosts.filter(isRecord15).slice(0, MAX_HOSTS);
51840
+ return parsed.hosts.filter(isRecord16).slice(0, MAX_HOSTS);
50974
51841
  } catch {
50975
51842
  return [];
50976
51843
  }
@@ -50986,7 +51853,7 @@ function createRemoteHostStore(consoleDir, deps = {}) {
50986
51853
  findByOrigin: (origin) => hosts.find((entry) => entry.origin === origin) ?? null,
50987
51854
  remember(link) {
50988
51855
  const existing = hosts.find((entry) => entry.origin === link.origin);
50989
- const record5 = {
51856
+ const record6 = {
50990
51857
  id: existing?.id ?? randomId(),
50991
51858
  // 이름은 사용자가 고쳐 부를 수 있으므로, 이미 고쳐 부른 이름을 링크가 덮어쓰지 않는다.
50992
51859
  label: existing?.label ?? link.label,
@@ -50998,10 +51865,10 @@ function createRemoteHostStore(consoleDir, deps = {}) {
50998
51865
  addedAt: existing?.addedAt ?? now(),
50999
51866
  lastOpenedAt: existing?.lastOpenedAt ?? null
51000
51867
  };
51001
- hosts = [record5, ...hosts.filter((entry) => entry.origin !== link.origin)].slice(0, MAX_HOSTS);
51002
- pending.set(record5.origin, { token: link.token, expiresAt: now() + HANDOFF_TTL_MS });
51868
+ hosts = [record6, ...hosts.filter((entry) => entry.origin !== link.origin)].slice(0, MAX_HOSTS);
51869
+ pending.set(record6.origin, { token: link.token, expiresAt: now() + HANDOFF_TTL_MS });
51003
51870
  write();
51004
- return record5;
51871
+ return record6;
51005
51872
  },
51006
51873
  rename(id, label) {
51007
51874
  const cleaned = sanitizeAccessLabel(label);
@@ -51033,7 +51900,7 @@ function createRemoteHostStore(consoleDir, deps = {}) {
51033
51900
  }
51034
51901
  };
51035
51902
  }
51036
- function isRecord15(value) {
51903
+ function isRecord16(value) {
51037
51904
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
51038
51905
  const entry = value;
51039
51906
  return typeof entry.id === "string" && entry.id.length > 0 && typeof entry.label === "string" && typeof entry.origin === "string" && entry.origin.startsWith("https://") && typeof entry.hostname === "string" && entry.hostname.length > 0 && typeof entry.port === "number" && Number.isSafeInteger(entry.port) && typeof entry.fingerprint === "string" && /^[0-9A-F]{64}$/u.test(entry.fingerprint) && typeof entry.addedAt === "number" && (entry.lastOpenedAt === null || typeof entry.lastOpenedAt === "number");
@@ -51289,10 +52156,10 @@ var SHIM_NAMED_EXPORTS = {
51289
52156
 
51290
52157
  // core/host/plugin-host/plugin-host.ts
51291
52158
  function discoverFleetPlugins(options = {}) {
51292
- const builtInSourceRoot = options.builtInSourceRoot ?? (options.cwd ? path23__default.resolve(options.cwd, "runtime/fleet-plugins") : null);
52159
+ const builtInSourceRoot = options.builtInSourceRoot ?? (options.cwd ? path24__default.resolve(options.cwd, "runtime/fleet-plugins") : null);
51293
52160
  const roots = [
51294
52161
  ...builtInSourceRoot ? [{ root: builtInSourceRoot, builtInDistRoot: options.builtInDistRoot ?? null, external: false }] : [],
51295
- { root: path23__default.join(options.homeDir ?? os3__default.homedir(), ".fleet", "plugins"), builtInDistRoot: null, external: true }
52162
+ { root: path24__default.join(options.homeDir ?? os3__default.homedir(), ".fleet", "plugins"), builtInDistRoot: null, external: true }
51296
52163
  ];
51297
52164
  const sourcePlugins = roots.flatMap((root) => discoverPluginRoot(root.root, root.builtInDistRoot, root.external));
51298
52165
  const sourcePluginIds = new Set(sourcePlugins.map((plugin) => plugin.manifest.id));
@@ -51300,7 +52167,7 @@ function discoverFleetPlugins(options = {}) {
51300
52167
  return [...sourcePlugins, ...distPlugins];
51301
52168
  }
51302
52169
  function parseFleetPluginManifest(value) {
51303
- if (!isRecord16(value)) return null;
52170
+ if (!isRecord17(value)) return null;
51304
52171
  const id = readPluginId(value.id);
51305
52172
  if (!id) return null;
51306
52173
  return {
@@ -51318,8 +52185,8 @@ function discoverPluginRoot(root, builtInDistRoot, external) {
51318
52185
  const plugins = [];
51319
52186
  for (const entry of entries) {
51320
52187
  if (!entry.isDirectory() || entry.name === "shared") continue;
51321
- const pluginRoot = path23__default.join(root, entry.name);
51322
- const manifestPath = path23__default.join(pluginRoot, "plugin.json");
52188
+ const pluginRoot = path24__default.join(root, entry.name);
52189
+ const manifestPath = path24__default.join(pluginRoot, "plugin.json");
51323
52190
  if (!fs9__default.existsSync(manifestPath)) continue;
51324
52191
  const manifest = readManifest(manifestPath);
51325
52192
  if (!manifest) continue;
@@ -51337,8 +52204,8 @@ function discoverDistPluginRoot(root) {
51337
52204
  const plugins = [];
51338
52205
  for (const entry of entries) {
51339
52206
  if (!entry.isDirectory() || entry.name === "shared") continue;
51340
- const pluginRoot = path23__default.join(root, entry.name);
51341
- const manifestPath = path23__default.join(pluginRoot, "plugin.json");
52207
+ const pluginRoot = path24__default.join(root, entry.name);
52208
+ const manifestPath = path24__default.join(pluginRoot, "plugin.json");
51342
52209
  const manifest = fs9__default.existsSync(manifestPath) ? readManifest(manifestPath) : readDistPluginManifest(entry.name);
51343
52210
  if (!manifest) continue;
51344
52211
  const clientEntry = resolveOptionalManifestEntry(pluginRoot, manifest.client, "client");
@@ -51365,10 +52232,10 @@ function resolveRoutesEntry(pluginRoot, manifest, builtInDistRoot) {
51365
52232
  if (manifestRoute2 === false) return false;
51366
52233
  if (manifestRoute2) return manifestRoute2;
51367
52234
  }
51368
- const manifestRoute = path23__default.join(pluginRoot, "routes.ts");
52235
+ const manifestRoute = path24__default.join(pluginRoot, "routes.ts");
51369
52236
  if (fs9__default.existsSync(manifestRoute)) return manifestRoute;
51370
52237
  if (!builtInDistRoot) return null;
51371
- const builtRoute = path23__default.join(builtInDistRoot, manifest.id, "routes.mjs");
52238
+ const builtRoute = path24__default.join(builtInDistRoot, manifest.id, "routes.mjs");
51372
52239
  return fs9__default.existsSync(builtRoute) ? builtRoute : null;
51373
52240
  }
51374
52241
  function resolveDistRoutesEntry(pluginRoot, manifest) {
@@ -51382,7 +52249,7 @@ function resolveOptionalManifestEntry(pluginRoot, entryPath, label) {
51382
52249
  console.warn(`[fleet-console] Plugin ${label} entry skipped: unsafe relative path ${entryPath}`);
51383
52250
  return false;
51384
52251
  }
51385
- const candidate = path23__default.resolve(pluginRoot, entryPath);
52252
+ const candidate = path24__default.resolve(pluginRoot, entryPath);
51386
52253
  if (!fs9__default.existsSync(candidate)) return null;
51387
52254
  const rootRealpath = fs9__default.realpathSync.native(pluginRoot);
51388
52255
  const entryRealpath = fs9__default.realpathSync.native(candidate);
@@ -51400,14 +52267,14 @@ function readDistPluginManifest(id) {
51400
52267
  return pluginId ? { id: pluginId, routes: "routes.mjs" } : null;
51401
52268
  }
51402
52269
  function isSafeRelativeEntry(entryPath) {
51403
- if (path23__default.isAbsolute(entryPath)) return false;
52270
+ if (path24__default.isAbsolute(entryPath)) return false;
51404
52271
  return entryPath.split(/[\\/]+/u).every((segment) => segment !== "..");
51405
52272
  }
51406
52273
  function isSubpath(root, candidate) {
51407
- const relative = path23__default.relative(root, candidate);
51408
- return relative === "" || !relative.startsWith("..") && !path23__default.isAbsolute(relative);
52274
+ const relative = path24__default.relative(root, candidate);
52275
+ return relative === "" || !relative.startsWith("..") && !path24__default.isAbsolute(relative);
51409
52276
  }
51410
- function isRecord16(value) {
52277
+ function isRecord17(value) {
51411
52278
  return typeof value === "object" && value !== null && !Array.isArray(value);
51412
52279
  }
51413
52280
  var SHIM_DEFINITIONS = [
@@ -51532,7 +52399,7 @@ var PLUGIN_HOST_PACKAGE_EXTERNALS = [
51532
52399
  "@anthropic-ai/claude-agent-sdk"
51533
52400
  ];
51534
52401
  function createHostPackageExternalsPlugin(consoleNodeModules) {
51535
- const requireFromConsole = consoleNodeModules ? createRequire(path23__default.join(path23__default.dirname(consoleNodeModules), "package.json")) : null;
52402
+ const requireFromConsole = consoleNodeModules ? createRequire(path24__default.join(path24__default.dirname(consoleNodeModules), "package.json")) : null;
51536
52403
  return {
51537
52404
  name: "fleet-console-plugin-host-package-externals",
51538
52405
  setup(build) {
@@ -51552,7 +52419,7 @@ var PLUGIN_BUNDLE_DIR_PREFIX = "fleet-console-plugin-";
51552
52419
  var PLUGIN_BUNDLE_OWNER_FILE = ".fleet-console-plugin-owner.json";
51553
52420
  var PLUGIN_BUNDLE_PID_PATTERN = /^fleet-console-plugin-(\d+)-/u;
51554
52421
  var MAX_PLUGIN_BUNDLE_OWNER_PID = 2147483647;
51555
- var __dirname$1 = path23__default.dirname(fileURLToPath(import.meta.url));
52422
+ var __dirname$1 = path24__default.dirname(fileURLToPath(import.meta.url));
51556
52423
  function createFleetPluginHost(deps) {
51557
52424
  const plugins = filterDiscoveredPlugins(discoverFleetPlugins(deps));
51558
52425
  const sensitiveFieldsByPluginId = new Map(plugins.map((plugin) => [plugin.manifest.id, plugin.manifest.sensitiveFields ?? []]));
@@ -51744,15 +52611,15 @@ async function importPluginModule(entry, bundleCacheDir, generatedBundleDirs) {
51744
52611
  return await import(pathToFileURL(entry).href);
51745
52612
  }
51746
52613
  async function writeTemporaryPluginBundle(entry, source, digest, bundleCacheDir, generatedBundleDirs) {
51747
- const cacheRoot = bundleCacheDir ?? path23__default.join(resolvePluginBundleNodeModules(entry), ".cache");
52614
+ const cacheRoot = bundleCacheDir ?? path24__default.join(resolvePluginBundleNodeModules(entry), ".cache");
51748
52615
  await mkdir(cacheRoot, { recursive: true });
51749
- const dir = path23__default.join(cacheRoot, `${PLUGIN_BUNDLE_DIR_PREFIX}${process.pid}-${digest}`);
52616
+ const dir = path24__default.join(cacheRoot, `${PLUGIN_BUNDLE_DIR_PREFIX}${process.pid}-${digest}`);
51750
52617
  await mkdir(dir, { recursive: true });
51751
52618
  if (bundleCacheDir) {
51752
52619
  generatedBundleDirs.add(dir);
51753
52620
  await writePluginBundleOwner(dir, process.pid);
51754
52621
  }
51755
- const file2 = path23__default.join(dir, "routes.mjs");
52622
+ const file2 = path24__default.join(dir, "routes.mjs");
51756
52623
  await writeFile(file2, source, "utf8");
51757
52624
  return file2;
51758
52625
  }
@@ -51763,7 +52630,7 @@ async function removeStalePluginBundleDirs(bundleCacheDir, isProcessAlive2, remo
51763
52630
  const entries = await readdir(bundleCacheDir, { withFileTypes: true });
51764
52631
  for (const entry of entries) {
51765
52632
  if (!entry.name.startsWith(PLUGIN_BUNDLE_DIR_PREFIX)) continue;
51766
- const entryPath = path23__default.join(bundleCacheDir, entry.name);
52633
+ const entryPath = path24__default.join(bundleCacheDir, entry.name);
51767
52634
  const ownerPid = await readPluginBundleOwnerPid(entryPath, entry.name);
51768
52635
  if (ownerPid !== null && isProcessAlive2(ownerPid)) continue;
51769
52636
  try {
@@ -51780,11 +52647,11 @@ async function removePluginBundleDir(dir) {
51780
52647
  await rm(dir, { recursive: true, force: true });
51781
52648
  }
51782
52649
  async function writePluginBundleOwner(dir, pid) {
51783
- await writeFile(path23__default.join(dir, PLUGIN_BUNDLE_OWNER_FILE), JSON.stringify({ pid }), "utf8");
52650
+ await writeFile(path24__default.join(dir, PLUGIN_BUNDLE_OWNER_FILE), JSON.stringify({ pid }), "utf8");
51784
52651
  }
51785
52652
  async function readPluginBundleOwnerPid(dir, name) {
51786
52653
  try {
51787
- const parsed = JSON.parse(await readFile(path23__default.join(dir, PLUGIN_BUNDLE_OWNER_FILE), "utf8"));
52654
+ const parsed = JSON.parse(await readFile(path24__default.join(dir, PLUGIN_BUNDLE_OWNER_FILE), "utf8"));
51788
52655
  if (isPluginBundleOwnerPid(parsed.pid)) return parsed.pid;
51789
52656
  } catch {
51790
52657
  }
@@ -51805,30 +52672,30 @@ function isPluginBundleOwnerPid(value) {
51805
52672
  }
51806
52673
  function resolvePluginBundleNodeModules(entry) {
51807
52674
  const packageNodeModules = resolveConsolePackageNodeModules();
51808
- let dir = path23__default.dirname(entry);
52675
+ let dir = path24__default.dirname(entry);
51809
52676
  let fallback = packageNodeModules;
51810
52677
  while (true) {
51811
- const workspaceConsoleNodeModules = path23__default.join(dir, "runtime", "fleet-console", "node_modules");
52678
+ const workspaceConsoleNodeModules = path24__default.join(dir, "runtime", "fleet-console", "node_modules");
51812
52679
  if (hasFleetConsoleSdk(workspaceConsoleNodeModules)) return workspaceConsoleNodeModules;
51813
- const candidate = path23__default.join(dir, "node_modules");
52680
+ const candidate = path24__default.join(dir, "node_modules");
51814
52681
  if (hasFleetConsoleSdk(candidate)) return candidate;
51815
52682
  if (fallback === null && existsSync(candidate)) fallback = candidate;
51816
- const parent = path23__default.dirname(dir);
51817
- if (parent === dir) return fallback ?? path23__default.join(path23__default.dirname(entry), "node_modules");
52683
+ const parent = path24__default.dirname(dir);
52684
+ if (parent === dir) return fallback ?? path24__default.join(path24__default.dirname(entry), "node_modules");
51818
52685
  dir = parent;
51819
52686
  }
51820
52687
  }
51821
52688
  function resolveConsolePackageNodeModules() {
51822
52689
  for (const candidate of [
51823
- path23__default.resolve(__dirname$1, "..", "node_modules"),
51824
- path23__default.resolve(__dirname$1, "..", "..", "..", "node_modules")
52690
+ path24__default.resolve(__dirname$1, "..", "node_modules"),
52691
+ path24__default.resolve(__dirname$1, "..", "..", "..", "node_modules")
51825
52692
  ]) {
51826
52693
  if (hasFleetConsoleSdk(candidate)) return candidate;
51827
52694
  }
51828
52695
  return null;
51829
52696
  }
51830
52697
  function hasFleetConsoleSdk(nodeModules) {
51831
- return existsSync(path23__default.join(nodeModules, "@fleet-console", "sdk"));
52698
+ return existsSync(path24__default.join(nodeModules, "@fleet-console", "sdk"));
51832
52699
  }
51833
52700
  function resolveRegister(mod) {
51834
52701
  if (mod.register) return mod.register;
@@ -52277,7 +53144,7 @@ var MIME_TYPES = {
52277
53144
  ".woff2": "font/woff2"
52278
53145
  };
52279
53146
  function createStaticConsoleHandler(packageRoot, deps) {
52280
- const consoleRoot = path23__default.join(packageRoot, "dist", "client");
53147
+ const consoleRoot = path24__default.join(packageRoot, "dist", "client");
52281
53148
  return (req, res, pathname) => tryServeStaticConsole(req, res, pathname, consoleRoot, deps?.getActiveTheme);
52282
53149
  }
52283
53150
  function tryServeStaticConsole(req, res, pathname, consoleRoot, getActiveTheme) {
@@ -52293,7 +53160,7 @@ function tryServeStaticConsole(req, res, pathname, consoleRoot, getActiveTheme)
52293
53160
  res.end(JSON.stringify({ error: "Not found" }));
52294
53161
  return true;
52295
53162
  }
52296
- const absolutePath = path23__default.resolve(consoleRoot, relativePath2);
53163
+ const absolutePath = path24__default.resolve(consoleRoot, relativePath2);
52297
53164
  if (!absolutePath.startsWith(consoleRoot)) {
52298
53165
  res.writeHead(404, withSecurityHeaders2({ "Content-Type": "application/json" }));
52299
53166
  res.end(JSON.stringify({ error: "Not found" }));
@@ -52301,7 +53168,7 @@ function tryServeStaticConsole(req, res, pathname, consoleRoot, getActiveTheme)
52301
53168
  }
52302
53169
  try {
52303
53170
  const data = fs9__default.readFileSync(absolutePath);
52304
- const contentType = MIME_TYPES[path23__default.extname(absolutePath)] ?? "application/octet-stream";
53171
+ const contentType = MIME_TYPES[path24__default.extname(absolutePath)] ?? "application/octet-stream";
52305
53172
  res.writeHead(200, withSecurityHeaders2({ "Content-Type": contentType }));
52306
53173
  if (req.method === "HEAD") {
52307
53174
  res.end();
@@ -52321,7 +53188,7 @@ function tryServeStaticConsole(req, res, pathname, consoleRoot, getActiveTheme)
52321
53188
  }
52322
53189
  function serveFallbackIndex(req, res, consoleRoot, getActiveTheme) {
52323
53190
  try {
52324
- const data = fs9__default.readFileSync(path23__default.join(consoleRoot, "index.html"));
53191
+ const data = fs9__default.readFileSync(path24__default.join(consoleRoot, "index.html"));
52325
53192
  res.writeHead(200, withSecurityHeaders2({ "Content-Type": MIME_TYPES[".html"] }));
52326
53193
  if (req.method === "HEAD") {
52327
53194
  res.end();
@@ -52355,7 +53222,7 @@ function resolveConsolePath(pathname) {
52355
53222
  }
52356
53223
  if (withoutPrefix === "") return "index.html";
52357
53224
  if (withoutPrefix.includes("\0")) return null;
52358
- if (!path23__default.extname(withoutPrefix)) return "index.html";
53225
+ if (!path24__default.extname(withoutPrefix)) return "index.html";
52359
53226
  return withoutPrefix;
52360
53227
  }
52361
53228
 
@@ -52388,10 +53255,10 @@ function createConsoleUpdateApplyService(deps = {}) {
52388
53255
  if (isManagedRuntimePackageRoot(request.currentPackageRoot)) throw new Error("managed_runtime_update_requires_relaunch");
52389
53256
  const packageManager = await preflightInstall(request.currentPackageRoot);
52390
53257
  const stamp = `${now()}-${processPid}`;
52391
- const workerPath = path23__default.join(tmpDir, `${WORKER_FILE_PREFIX}${stamp}${WORKER_FILE_SUFFIX}`);
53258
+ const workerPath = path24__default.join(tmpDir, `${WORKER_FILE_PREFIX}${stamp}${WORKER_FILE_SUFFIX}`);
52392
53259
  makeDir(request.dataDir, { recursive: true, mode: 448 });
52393
- const statusFile = path23__default.join(request.dataDir, `${WORKER_FILE_PREFIX}${stamp}${STATUS_FILE_SUFFIX}`);
52394
- const logFile = path23__default.join(request.dataDir, `${WORKER_FILE_PREFIX}${stamp}${LOG_FILE_SUFFIX}`);
53260
+ const statusFile = path24__default.join(request.dataDir, `${WORKER_FILE_PREFIX}${stamp}${STATUS_FILE_SUFFIX}`);
53261
+ const logFile = path24__default.join(request.dataDir, `${WORKER_FILE_PREFIX}${stamp}${LOG_FILE_SUFFIX}`);
52395
53262
  const script = emitConsoleUpdateWorkerScript({
52396
53263
  currentEndpoint: request.currentEndpoint,
52397
53264
  currentPackageRoot: request.currentPackageRoot,
@@ -52689,9 +53556,9 @@ function sanitizeError(error) {
52689
53556
  `;
52690
53557
  }
52691
53558
  function isManagedRuntimePackageRoot(packageRoot) {
52692
- if (path23__default.basename(packageRoot) !== "latest" || path23__default.basename(path23__default.dirname(packageRoot)) !== "console") return false;
53559
+ if (path24__default.basename(packageRoot) !== "latest" || path24__default.basename(path24__default.dirname(packageRoot)) !== "console") return false;
52693
53560
  try {
52694
- return isDesktopResourceRootMarkerValid(fs9__default.readFileSync(path23__default.join(packageRoot, DESKTOP_RESOURCE_ROOT_MARKER), "utf8"));
53561
+ return isDesktopResourceRootMarkerValid(fs9__default.readFileSync(path24__default.join(packageRoot, DESKTOP_RESOURCE_ROOT_MARKER), "utf8"));
52695
53562
  } catch {
52696
53563
  return false;
52697
53564
  }
@@ -52747,7 +53614,7 @@ function resolveDefaultServerModulePath() {
52747
53614
  if (sourcePath.endsWith(".ts")) {
52748
53615
  return sourcePath.replace(/update-apply\.ts$/, "cli.ts");
52749
53616
  }
52750
- return path23__default.join(path23__default.dirname(sourcePath), "cli.mjs");
53617
+ return path24__default.join(path24__default.dirname(sourcePath), "cli.mjs");
52751
53618
  }
52752
53619
 
52753
53620
  // core/host/update-check.ts
@@ -53121,7 +53988,7 @@ function createConsoleServer(deps = {}) {
53121
53988
  return { cwd: workspace.cwd, path: workspace.path };
53122
53989
  },
53123
53990
  withMigrationLock: (workspace, operation) => withDirectoryLock({
53124
- lockDir: path23__default.join(workspace.path, "knowledge.migration.lock")
53991
+ lockDir: path24__default.join(workspace.path, "knowledge.migration.lock")
53125
53992
  }, operation)
53126
53993
  });
53127
53994
  const codex = createCodexGateway({
@@ -53268,7 +54135,7 @@ function createConsoleServer(deps = {}) {
53268
54135
  },
53269
54136
  paths: {
53270
54137
  fleetDataDir,
53271
- pluginDataDir: (pluginId) => path23__default.join(durablePaths.dir, "plugins", pluginId),
54138
+ pluginDataDir: (pluginId) => path24__default.join(durablePaths.dir, "plugins", pluginId),
53272
54139
  resolveTheaterPath: (theaterId) => theaters.get(theaterId)?.realpath ?? null,
53273
54140
  canonicalizeTheaterPath: canonicalizeTheaterPathSync,
53274
54141
  workspaceHash
@@ -53298,7 +54165,7 @@ function createConsoleServer(deps = {}) {
53298
54165
  const pluginHost = createFleetPluginHost({
53299
54166
  ...resolveBuiltInPluginDiscoveryRoots(release.packageRoot),
53300
54167
  homeDir: deps.pluginHomeDir,
53301
- bundleCacheDir: path23__default.join(durablePaths.dir, "plugin-cache"),
54168
+ bundleCacheDir: path24__default.join(durablePaths.dir, "plugin-cache"),
53302
54169
  routes: routeRegistry,
53303
54170
  upgrades: upgradeRegistry,
53304
54171
  host: pluginHostCapabilities
@@ -54887,11 +55754,11 @@ function errorCodeOf(error51) {
54887
55754
  }
54888
55755
  var REMOTE_PORT_UNAVAILABLE = "FLEET_REMOTE_PORT_UNAVAILABLE";
54889
55756
  function resolveBuiltInPluginDiscoveryRoots(packageRoot) {
54890
- const packageRootRepo = path23__default.resolve(packageRoot, "..", "..");
54891
- const sourceRoot = path23__default.join(packageRootRepo, "runtime", "fleet-plugins");
55757
+ const packageRootRepo = path24__default.resolve(packageRoot, "..", "..");
55758
+ const sourceRoot = path24__default.join(packageRootRepo, "runtime", "fleet-plugins");
54892
55759
  return {
54893
55760
  ...fs9__default.existsSync(sourceRoot) ? { builtInSourceRoot: sourceRoot } : {},
54894
- builtInDistRoot: path23__default.join(packageRoot, "dist", "fleet-plugins")
55761
+ builtInDistRoot: path24__default.join(packageRoot, "dist", "fleet-plugins")
54895
55762
  };
54896
55763
  }
54897
55764
  function createUpgradeListener(deps) {
@@ -55079,14 +55946,14 @@ async function readPluginStorageJson(dataDir, pluginId, key) {
55079
55946
  }
55080
55947
  async function writePluginStorageJson(dataDir, pluginId, key, value) {
55081
55948
  const file2 = resolvePluginStorageFile(dataDir, pluginId, key);
55082
- await fs9__default.promises.mkdir(path23__default.dirname(file2), { recursive: true });
55949
+ await fs9__default.promises.mkdir(path24__default.dirname(file2), { recursive: true });
55083
55950
  await fs9__default.promises.writeFile(file2, JSON.stringify(value), "utf8");
55084
55951
  }
55085
55952
  function resolvePluginStorageFile(dataDir, pluginId, key) {
55086
55953
  if (!/^[a-z0-9][a-z0-9._-]*$/i.test(pluginId) || !/^[a-z0-9][a-z0-9._-]*$/i.test(key)) {
55087
55954
  throw new Error("invalid_plugin_storage_key");
55088
55955
  }
55089
- return path23__default.join(dataDir, "plugins", pluginId, `${key}.json`);
55956
+ return path24__default.join(dataDir, "plugins", pluginId, `${key}.json`);
55090
55957
  }
55091
55958
  function isNodeError(error51) {
55092
55959
  return error51 instanceof Error && "code" in error51;