@dotobokuri/fleet-console 1.57.2 → 1.58.1

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 +1361 -552
  58. package/dist/fleet.mjs +1585 -685
  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
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import * as path18 from 'node:path';
3
- import path18__default, { posix, dirname } from 'node:path';
2
+ import * as path19 from 'node:path';
3
+ import path19__default, { posix, dirname } from 'node:path';
4
4
  import * as fs9 from 'node:fs';
5
5
  import fs9__default, { constants, existsSync, readFileSync, mkdirSync, rmSync, renameSync, appendFileSync, mkdtempSync, writeFileSync, statSync, chmodSync, readdirSync, closeSync, fstatSync, lstatSync, accessSync, realpathSync, openSync, promises } from 'node:fs';
6
6
  import * as os3 from 'node:os';
7
7
  import os3__default, { tmpdir } from 'node:os';
8
8
  import { execFile } from 'node:child_process';
9
- import fs7, { appendFile, chmod, open, mkdtemp, mkdir, rm, writeFile, rename, stat, readFile, readdir, realpath, lstat, unlink } from 'node:fs/promises';
9
+ import fs32, { appendFile, chmod, open, mkdtemp, mkdir, rm, writeFile, rename, stat, readFile, readdir, realpath, lstat, unlink } from 'node:fs/promises';
10
10
  import { promisify } from 'node:util';
11
11
  import crypto5, { randomUUID, createHash } from 'node:crypto';
12
12
  import http2 from 'node:http2';
@@ -26,33 +26,33 @@ var __export = (target2, all) => {
26
26
  function definePlugin(definition) {
27
27
  return definition;
28
28
  }
29
- function registerRouter(ctx, path42, handler, catalog) {
29
+ function registerRouter(ctx, path43, handler, catalog) {
30
30
  if (catalog) {
31
- ctx.registerRouter(normalizePath(path42), handler, catalog);
31
+ ctx.registerRouter(normalizePath(path43), handler, catalog);
32
32
  return;
33
33
  }
34
- ctx.registerRouter(normalizePath(path42), handler);
34
+ ctx.registerRouter(normalizePath(path43), handler);
35
35
  }
36
- function registerWsHandler(ctx, path42, handler, catalog) {
36
+ function registerWsHandler(ctx, path43, handler, catalog) {
37
37
  if (catalog) {
38
- ctx.registerWsHandler(normalizePath(path42), handler, catalog);
38
+ ctx.registerWsHandler(normalizePath(path43), handler, catalog);
39
39
  return;
40
40
  }
41
- ctx.registerWsHandler(normalizePath(path42), handler);
41
+ ctx.registerWsHandler(normalizePath(path43), handler);
42
42
  }
43
43
  function registerLaunchCatalog(ctx, provider) {
44
44
  return ctx.host.operations.registerLaunchCatalog(ctx.pluginId, provider);
45
45
  }
46
- function normalizePath(path42) {
47
- if (path42.length === 0 || path42 === "/") return "/";
48
- return path42;
46
+ function normalizePath(path43) {
47
+ if (path43.length === 0 || path43 === "/") return "/";
48
+ return path43;
49
49
  }
50
50
  var FLEET_DATA_DIR_NAME = ".fleet";
51
51
  var FLEET_DATA_DIR_ENV = "FLEET_DATA_DIR";
52
52
  function getFleetDataDir(env = process.env) {
53
53
  const override = env[FLEET_DATA_DIR_ENV];
54
- if (override === void 0 || override.trim().length === 0) return path18.join(os3.homedir(), FLEET_DATA_DIR_NAME);
55
- if (!path18.isAbsolute(override)) throw new Error(`${FLEET_DATA_DIR_ENV} must be an absolute path, received: ${override}`);
54
+ if (override === void 0 || override.trim().length === 0) return path19.join(os3.homedir(), FLEET_DATA_DIR_NAME);
55
+ if (!path19.isAbsolute(override)) throw new Error(`${FLEET_DATA_DIR_ENV} must be an absolute path, received: ${override}`);
56
56
  return override;
57
57
  }
58
58
  var SECURE_DIR_MODE = 448;
@@ -85,9 +85,9 @@ function ensureSafeDirectory(dirPath) {
85
85
  fs9.chmodSync(dirPath, SECURE_DIR_MODE);
86
86
  }
87
87
  function assertWithinRoot(root, candidatePath) {
88
- const resolvedRoot = path18.resolve(root);
89
- const resolvedCandidate = path18.resolve(candidatePath);
90
- if (!resolvedCandidate.startsWith(`${resolvedRoot}${path18.sep}`) && resolvedCandidate !== resolvedRoot) {
88
+ const resolvedRoot = path19.resolve(root);
89
+ const resolvedCandidate = path19.resolve(candidatePath);
90
+ if (!resolvedCandidate.startsWith(`${resolvedRoot}${path19.sep}`) && resolvedCandidate !== resolvedRoot) {
91
91
  throw new Error(`Path escapes root: ${candidatePath}`);
92
92
  }
93
93
  }
@@ -148,7 +148,7 @@ function cleanupTempFiles(dir, prefix, minAgeMs, now) {
148
148
  if (!entry.startsWith(prefix)) {
149
149
  continue;
150
150
  }
151
- const tempPath = path18.join(dir, entry);
151
+ const tempPath = path19.join(dir, entry);
152
152
  try {
153
153
  const stat4 = fs9.lstatSync(tempPath);
154
154
  if (stat4?.isFile() && !stat4.isSymbolicLink() && now - stat4.mtimeMs >= minAgeMs) {
@@ -254,7 +254,7 @@ function writeLockOwner(lockDir, ownerFileName, startedAt) {
254
254
  hostname: os3.hostname(),
255
255
  startedAt
256
256
  };
257
- const ownerPath = path18.join(lockDir, ownerFileName);
257
+ const ownerPath = path19.join(lockDir, ownerFileName);
258
258
  try {
259
259
  fs9.writeFileSync(ownerPath, JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
260
260
  } catch (error51) {
@@ -263,7 +263,7 @@ function writeLockOwner(lockDir, ownerFileName, startedAt) {
263
263
  }
264
264
  }
265
265
  function readLockOwner(lockDir, ownerFileName) {
266
- const ownerPath = path18.join(lockDir, ownerFileName);
266
+ const ownerPath = path19.join(lockDir, ownerFileName);
267
267
  try {
268
268
  return sanitizeLockOwner(JSON.parse(fs9.readFileSync(ownerPath, "utf-8")));
269
269
  } catch (error51) {
@@ -303,10 +303,10 @@ function isProcessAlive(pid) {
303
303
  }
304
304
  function sanitizeLockOwner(value) {
305
305
  if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
306
- const record6 = value;
307
- const pid = record6.pid;
308
- const hostname5 = record6.hostname;
309
- const startedAt = record6.startedAt;
306
+ const record7 = value;
307
+ const pid = record7.pid;
308
+ const hostname5 = record7.hostname;
309
+ const startedAt = record7.startedAt;
310
310
  if (!Number.isInteger(pid) || pid <= 0) return null;
311
311
  if (typeof hostname5 !== "string" || !hostname5) return null;
312
312
  if (!Number.isFinite(startedAt) || startedAt <= 0) return null;
@@ -321,7 +321,7 @@ function sleepSync(ms) {
321
321
  }
322
322
 
323
323
  // ../../packages/core-infra/src/auth/auth-storage.ts
324
- var DEFAULT_AUTH_PATH = path18.join(getFleetDataDir(), "auth.json");
324
+ var DEFAULT_AUTH_PATH = path19.join(getFleetDataDir(), "auth.json");
325
325
  var AUTH_LOCK_OWNER_FILE_NAME = "owner.json";
326
326
  var AUTH_LOCK_TIMEOUT_MS = 5e3;
327
327
  function readAuthStoreFile(filePath) {
@@ -396,7 +396,7 @@ function createAuthService(deps = {}) {
396
396
  }
397
397
  },
398
398
  async setApiKey(providerId, key) {
399
- const dir = path18.dirname(authPath);
399
+ const dir = path19.dirname(authPath);
400
400
  ensureSafeDirectory(dir);
401
401
  withAuthLock(authPath, lockDir, () => {
402
402
  const data = fs9.existsSync(authPath) ? readAuthStoreFile(authPath) : {};
@@ -432,7 +432,7 @@ function createDurableJsonStore(deps) {
432
432
  const sensitivity = deps.sensitivity;
433
433
  const mode = sensitivity === "sensitive" ? SECURE_FILE_MODE : 420;
434
434
  const minAgeMs = deps.tempCleanupMinAgeMs ?? DEFAULT_TEMP_FILE_MIN_AGE_MS;
435
- const dir = path18.dirname(deps.filePath);
435
+ const dir = path19.dirname(deps.filePath);
436
436
  return {
437
437
  path: deps.filePath,
438
438
  load() {
@@ -532,8 +532,8 @@ function updateGlobalOptions(store, mutate) {
532
532
  }
533
533
  function createGlobalOptionsStore(deps = {}) {
534
534
  const dataDir = deps.dataDir ?? getFleetDataDir();
535
- const optionsPath = path18.join(dataDir, GLOBAL_OPTIONS_FILE_NAME);
536
- const lockDir = path18.join(dataDir, LOCK_DIR_NAME);
535
+ const optionsPath = path19.join(dataDir, GLOBAL_OPTIONS_FILE_NAME);
536
+ const lockDir = path19.join(dataDir, LOCK_DIR_NAME);
537
537
  const store = createDurableJsonStore({
538
538
  filePath: optionsPath,
539
539
  lockDir,
@@ -676,7 +676,7 @@ function getWorkspaceDirectoryRoot(dataDir) {
676
676
  if (!dataDir.trim()) {
677
677
  throw new Error("Fleet data directory is required");
678
678
  }
679
- return path18.join(path18.resolve(dataDir), WORKSPACES_DIRECTORY_NAME);
679
+ return path19.join(path19.resolve(dataDir), WORKSPACES_DIRECTORY_NAME);
680
680
  }
681
681
  function resolveWorkspaceDirectory(dataDir, cwd) {
682
682
  const canonicalCwd = canonicalizeWorkspaceCwd(cwd);
@@ -684,7 +684,7 @@ function resolveWorkspaceDirectory(dataDir, cwd) {
684
684
  }
685
685
  function ensureWorkspaceDirectory(dataDir, cwd) {
686
686
  const workspace = resolveWorkspaceDirectory(dataDir, cwd);
687
- const resolvedDataDir = path18.resolve(dataDir);
687
+ const resolvedDataDir = path19.resolve(dataDir);
688
688
  ensureSafeDirectory(resolvedDataDir);
689
689
  ensureSafeDirectory(workspace.root);
690
690
  assertWithinRoot(workspace.root, workspace.path);
@@ -709,11 +709,11 @@ function ensureWorkspaceDirectory(dataDir, cwd) {
709
709
  function buildWorkspaceDirectory(dataDir, name, cwd) {
710
710
  assertWorkspaceDirectoryName(name);
711
711
  const root = getWorkspaceDirectoryRoot(dataDir);
712
- const workspacePath = path18.join(root, name);
712
+ const workspacePath = path19.join(root, name);
713
713
  assertWithinRoot(root, workspacePath);
714
714
  return {
715
715
  cwd,
716
- identityPath: path18.join(workspacePath, WORKSPACE_IDENTITY_FILE_NAME),
716
+ identityPath: path19.join(workspacePath, WORKSPACE_IDENTITY_FILE_NAME),
717
717
  name,
718
718
  path: workspacePath,
719
719
  root
@@ -723,7 +723,7 @@ function canonicalizeWorkspaceCwd(cwd) {
723
723
  if (!cwd.trim()) {
724
724
  throw new Error("Workspace cwd is required");
725
725
  }
726
- return fs9.realpathSync.native(path18.resolve(cwd));
726
+ return fs9.realpathSync.native(path19.resolve(cwd));
727
727
  }
728
728
  function assertWorkspaceDirectoryName(name) {
729
729
  if (!name || !WORKSPACE_NAME_PATTERN.test(name)) {
@@ -749,8 +749,8 @@ function readWorkspaceIdentity(identityPath) {
749
749
  }
750
750
  function isWorkspaceDirectoryIdentity(value) {
751
751
  if (typeof value !== "object" || value === null) return false;
752
- const record6 = value;
753
- return typeof record6.cwd === "string" && record6.cwd.length > 0;
752
+ const record7 = value;
753
+ return typeof record7.cwd === "string" && record7.cwd.length > 0;
754
754
  }
755
755
 
756
756
  // ../../packages/core-infra/src/index.ts
@@ -1008,9 +1008,14 @@ function isHostSessionToolAllowed(_toolId, _doctrine) {
1008
1008
 
1009
1009
  // ../../packages/fleet-admiral/src/agent-cli/types.ts
1010
1010
  var MAX_LAUNCH_PROMPT_CHARS = 16e3;
1011
-
1012
- // ../../packages/fleet-admiral/src/agent-cli/prompt.ts
1013
1011
  var CMD_UNSAFE_PROMPT_PATTERN = /["&<>()@^|%]/;
1012
+ var LAUNCH_PROMPT_FILE_MODE = 384;
1013
+ var LAUNCH_PROMPT_TEMP_DIR_PREFIX = "fleet-quick-launch-";
1014
+ var LAUNCH_PROMPT_FILE_NAME = "prompt.md";
1015
+ var LAUNCH_PROMPT_FILE_INSTRUCTION_PREFIX = "Read and follow the launch prompt file: ";
1016
+ function launchPromptHasCmdUnsafeChars(prompt) {
1017
+ return CMD_UNSAFE_PROMPT_PATTERN.test(prompt);
1018
+ }
1014
1019
  var WINDOWS_CMD_SHIM_COMMAND_LINE_MAX_CHARS = 8191;
1015
1020
  var WINDOWS_CREATE_PROCESS_COMMAND_LINE_MAX_CHARS = 32767;
1016
1021
  var LaunchPromptError = class extends Error {
@@ -1074,6 +1079,12 @@ function assertLaunchCommandLineBudget(options) {
1074
1079
  `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.`
1075
1080
  );
1076
1081
  }
1082
+ if (options.promptIsFixedLength === true) {
1083
+ throw new LaunchPromptError(
1084
+ "launch_command_line_too_long",
1085
+ `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.`
1086
+ );
1087
+ }
1077
1088
  const shortenByChars = total - limit.maxChars;
1078
1089
  throw new LaunchPromptError(
1079
1090
  "prompt_command_line_too_long",
@@ -1087,6 +1098,57 @@ function sanitizeLaunchPrompt(value) {
1087
1098
  const trimmed = normalized.trim();
1088
1099
  return trimmed.length === 0 ? void 0 : trimmed;
1089
1100
  }
1101
+ function formatLaunchPromptFileInstruction(filePath) {
1102
+ return `${LAUNCH_PROMPT_FILE_INSTRUCTION_PREFIX}${filePath}`;
1103
+ }
1104
+ function writeLaunchPromptPointer(body, onCleanup, cmdWrapped) {
1105
+ const written = writeLaunchPromptFile(body, onCleanup);
1106
+ try {
1107
+ assertLaunchPromptShimSafe(written.instruction, cmdWrapped ? ["cmd-shim"] : []);
1108
+ } catch (error51) {
1109
+ written.cleanup();
1110
+ if (error51 instanceof LaunchPromptError && error51.code === "prompt_unsafe_for_shim") {
1111
+ throw new LaunchPromptError(
1112
+ "prompt_unsafe_for_shim",
1113
+ '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.'
1114
+ );
1115
+ }
1116
+ throw error51;
1117
+ }
1118
+ return written.instruction;
1119
+ }
1120
+ function writeLaunchPromptFile(body, onCleanup) {
1121
+ const tempRoot = path19__default.resolve(os3__default.tmpdir());
1122
+ mkdirSync(tempRoot, { recursive: true });
1123
+ const tempDir = mkdtempSync(path19__default.join(tempRoot, LAUNCH_PROMPT_TEMP_DIR_PREFIX));
1124
+ const cleanup = () => rmBestEffort(tempDir);
1125
+ try {
1126
+ const filePath = path19__default.join(tempDir, LAUNCH_PROMPT_FILE_NAME);
1127
+ writeFileSync(filePath, body, { encoding: "utf8", flag: "wx", mode: LAUNCH_PROMPT_FILE_MODE });
1128
+ chmodBestEffort(filePath, LAUNCH_PROMPT_FILE_MODE);
1129
+ onCleanup(cleanup);
1130
+ return {
1131
+ cleanup,
1132
+ filePath,
1133
+ instruction: formatLaunchPromptFileInstruction(filePath)
1134
+ };
1135
+ } catch (error51) {
1136
+ cleanup();
1137
+ throw error51;
1138
+ }
1139
+ }
1140
+ function chmodBestEffort(targetPath, mode) {
1141
+ try {
1142
+ chmodSync(targetPath, mode);
1143
+ } catch {
1144
+ }
1145
+ }
1146
+ function rmBestEffort(targetPath) {
1147
+ try {
1148
+ rmSync(targetPath, { force: true, recursive: true });
1149
+ } catch {
1150
+ }
1151
+ }
1090
1152
 
1091
1153
  // ../../node_modules/.pnpm/zod@4.4.1/node_modules/zod/v4/classic/external.js
1092
1154
  var external_exports = {};
@@ -1850,10 +1912,10 @@ function mergeDefs(...defs) {
1850
1912
  function cloneDef(schema) {
1851
1913
  return mergeDefs(schema._zod.def);
1852
1914
  }
1853
- function getElementAtPath(obj, path42) {
1854
- if (!path42)
1915
+ function getElementAtPath(obj, path43) {
1916
+ if (!path43)
1855
1917
  return obj;
1856
- return path42.reduce((acc, key) => acc?.[key], obj);
1918
+ return path43.reduce((acc, key) => acc?.[key], obj);
1857
1919
  }
1858
1920
  function promiseAllObject(promisesObj) {
1859
1921
  const keys = Object.keys(promisesObj);
@@ -2262,11 +2324,11 @@ function explicitlyAborted(x, startIndex = 0) {
2262
2324
  }
2263
2325
  return false;
2264
2326
  }
2265
- function prefixIssues(path42, issues) {
2327
+ function prefixIssues(path43, issues) {
2266
2328
  return issues.map((iss) => {
2267
2329
  var _a3;
2268
2330
  (_a3 = iss).path ?? (_a3.path = []);
2269
- iss.path.unshift(path42);
2331
+ iss.path.unshift(path43);
2270
2332
  return iss;
2271
2333
  });
2272
2334
  }
@@ -2413,16 +2475,16 @@ function flattenError(error51, mapper = (issue3) => issue3.message) {
2413
2475
  }
2414
2476
  function formatError(error51, mapper = (issue3) => issue3.message) {
2415
2477
  const fieldErrors = { _errors: [] };
2416
- const processError = (error52, path42 = []) => {
2478
+ const processError = (error52, path43 = []) => {
2417
2479
  for (const issue3 of error52.issues) {
2418
2480
  if (issue3.code === "invalid_union" && issue3.errors.length) {
2419
- issue3.errors.map((issues) => processError({ issues }, [...path42, ...issue3.path]));
2481
+ issue3.errors.map((issues) => processError({ issues }, [...path43, ...issue3.path]));
2420
2482
  } else if (issue3.code === "invalid_key") {
2421
- processError({ issues: issue3.issues }, [...path42, ...issue3.path]);
2483
+ processError({ issues: issue3.issues }, [...path43, ...issue3.path]);
2422
2484
  } else if (issue3.code === "invalid_element") {
2423
- processError({ issues: issue3.issues }, [...path42, ...issue3.path]);
2485
+ processError({ issues: issue3.issues }, [...path43, ...issue3.path]);
2424
2486
  } else {
2425
- const fullpath = [...path42, ...issue3.path];
2487
+ const fullpath = [...path43, ...issue3.path];
2426
2488
  if (fullpath.length === 0) {
2427
2489
  fieldErrors._errors.push(mapper(issue3));
2428
2490
  } else {
@@ -2449,17 +2511,17 @@ function formatError(error51, mapper = (issue3) => issue3.message) {
2449
2511
  }
2450
2512
  function treeifyError(error51, mapper = (issue3) => issue3.message) {
2451
2513
  const result = { errors: [] };
2452
- const processError = (error52, path42 = []) => {
2514
+ const processError = (error52, path43 = []) => {
2453
2515
  var _a3, _b;
2454
2516
  for (const issue3 of error52.issues) {
2455
2517
  if (issue3.code === "invalid_union" && issue3.errors.length) {
2456
- issue3.errors.map((issues) => processError({ issues }, [...path42, ...issue3.path]));
2518
+ issue3.errors.map((issues) => processError({ issues }, [...path43, ...issue3.path]));
2457
2519
  } else if (issue3.code === "invalid_key") {
2458
- processError({ issues: issue3.issues }, [...path42, ...issue3.path]);
2520
+ processError({ issues: issue3.issues }, [...path43, ...issue3.path]);
2459
2521
  } else if (issue3.code === "invalid_element") {
2460
- processError({ issues: issue3.issues }, [...path42, ...issue3.path]);
2522
+ processError({ issues: issue3.issues }, [...path43, ...issue3.path]);
2461
2523
  } else {
2462
- const fullpath = [...path42, ...issue3.path];
2524
+ const fullpath = [...path43, ...issue3.path];
2463
2525
  if (fullpath.length === 0) {
2464
2526
  result.errors.push(mapper(issue3));
2465
2527
  continue;
@@ -2491,8 +2553,8 @@ function treeifyError(error51, mapper = (issue3) => issue3.message) {
2491
2553
  }
2492
2554
  function toDotPath(_path) {
2493
2555
  const segs = [];
2494
- const path42 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2495
- for (const seg of path42) {
2556
+ const path43 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2557
+ for (const seg of path43) {
2496
2558
  if (typeof seg === "number")
2497
2559
  segs.push(`[${seg}]`);
2498
2560
  else if (typeof seg === "symbol")
@@ -15156,13 +15218,13 @@ function resolveRef(ref, ctx) {
15156
15218
  if (!ref.startsWith("#")) {
15157
15219
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
15158
15220
  }
15159
- const path42 = ref.slice(1).split("/").filter(Boolean);
15160
- if (path42.length === 0) {
15221
+ const path43 = ref.slice(1).split("/").filter(Boolean);
15222
+ if (path43.length === 0) {
15161
15223
  return ctx.rootSchema;
15162
15224
  }
15163
15225
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
15164
- if (path42[0] === defsKey) {
15165
- const key = path42[1];
15226
+ if (path43[0] === defsKey) {
15227
+ const key = path43[1];
15166
15228
  if (!key || !ctx.defs[key]) {
15167
15229
  throw new Error(`Reference not found: ${ref}`);
15168
15230
  }
@@ -18564,8 +18626,8 @@ function bootEnumDescriptorProto(init) {
18564
18626
  }
18565
18627
 
18566
18628
  // ../../node_modules/.pnpm/@bufbuild+protobuf@2.13.0/node_modules/@bufbuild/protobuf/dist/esm/codegenv2/message.js
18567
- function messageDesc(file2, path42, ...paths) {
18568
- return paths.reduce((acc, cur) => acc.nestedMessages[cur], file2.messages[path42]);
18629
+ function messageDesc(file2, path43, ...paths) {
18630
+ return paths.reduce((acc, cur) => acc.nestedMessages[cur], file2.messages[path43]);
18569
18631
  }
18570
18632
 
18571
18633
  // ../../node_modules/.pnpm/@bufbuild+protobuf@2.13.0/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/descriptor_pb.js
@@ -19963,11 +20025,11 @@ function fieldMaskFromJson(fieldMask, json2) {
19963
20025
  if (json2 === "") {
19964
20026
  return;
19965
20027
  }
19966
- fieldMask.paths = json2.split(",").map((path42) => {
19967
- if (path42.includes("_")) {
20028
+ fieldMask.paths = json2.split(",").map((path43) => {
20029
+ if (path43.includes("_")) {
19968
20030
  throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
19969
20031
  }
19970
- return protoSnakeCase(path42);
20032
+ return protoSnakeCase(path43);
19971
20033
  });
19972
20034
  }
19973
20035
  function structFromJson(struct, json2, ctx) {
@@ -20329,17 +20391,17 @@ function projectAnthropicUsageEnvelope(value, contextWindow, responseModel) {
20329
20391
  return { changed, value: projectedValue };
20330
20392
  }
20331
20393
  function projectUsageProperty(container, property, contextWindow) {
20332
- const usage3 = container[property];
20333
- if (!isRecord2(usage3)) return { changed: false, value: container };
20394
+ const usage4 = container[property];
20395
+ if (!isRecord2(usage4)) return { changed: false, value: container };
20334
20396
  const coordinates = ANTHROPIC_INPUT_USAGE_FIELDS.map((field) => {
20335
- const tokens = usage3[field];
20397
+ const tokens = usage4[field];
20336
20398
  return typeof tokens === "number" && Number.isFinite(tokens) && tokens >= 0 ? { field, tokens } : void 0;
20337
20399
  }).filter((entry) => entry !== void 0);
20338
20400
  if (coordinates.length === 0) return { changed: false, value: container };
20339
20401
  const total = coordinates.reduce((sum, entry) => sum + entry.tokens, 0);
20340
20402
  const projectedTotal = projectClaudeContextInputTokens(total, contextWindow);
20341
20403
  if (projectedTotal === total) return { changed: false, value: container };
20342
- const projectedUsage = { ...usage3 };
20404
+ const projectedUsage = { ...usage4 };
20343
20405
  const remainderField = coordinates.some((entry) => entry.field === "input_tokens") ? "input_tokens" : coordinates[0].field;
20344
20406
  let assigned = 0;
20345
20407
  for (const entry of coordinates) {
@@ -20486,6 +20548,39 @@ function removeClaudeSkillListingEntries(text2, withheld, delisted) {
20486
20548
  function withheldClaudeSkillStub(name, tokens, budget) {
20487
20549
  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.]`;
20488
20550
  }
20551
+ var CLAUDE_WEB_SEARCH_TOOL_NAME = "WebSearch";
20552
+ var ANTHROPIC_WEB_SEARCH_TOOL_NAME = "web_search";
20553
+ var ANTHROPIC_WEB_SEARCH_TOOL_TYPE = "web_search_20250305";
20554
+ function isClaudeWebSearchTool(tool) {
20555
+ return tool.type === ANTHROPIC_WEB_SEARCH_TOOL_TYPE || tool.name === CLAUDE_WEB_SEARCH_TOOL_NAME || tool.name === ANTHROPIC_WEB_SEARCH_TOOL_NAME;
20556
+ }
20557
+ function isClaudeWebSearchToolChoice(choice) {
20558
+ return choice?.type === "tool" && (choice.name === CLAUDE_WEB_SEARCH_TOOL_NAME || choice.name === ANTHROPIC_WEB_SEARCH_TOOL_NAME);
20559
+ }
20560
+ function omitClaudeWebSearchTools(request) {
20561
+ const tools = request.tools;
20562
+ const kept = tools?.filter((tool) => !isClaudeWebSearchTool(tool));
20563
+ const toolsChanged = tools !== void 0 && kept !== void 0 && kept.length !== tools.length;
20564
+ const choice = request.tool_choice;
20565
+ const choiceChanged = isClaudeWebSearchToolChoice(choice);
20566
+ if (!toolsChanged && !choiceChanged) {
20567
+ return { request, changed: false };
20568
+ }
20569
+ const { tools: _tools, tool_choice: _toolChoice, ...rest } = request;
20570
+ return {
20571
+ request: {
20572
+ ...rest,
20573
+ ...toolsChanged ? kept.length === 0 ? {} : { tools: kept } : tools === void 0 ? {} : { tools },
20574
+ ...choiceChanged ? {
20575
+ tool_choice: {
20576
+ type: "auto",
20577
+ ...choice?.disable_parallel_tool_use === void 0 ? {} : { disable_parallel_tool_use: choice.disable_parallel_tool_use }
20578
+ }
20579
+ } : choice === void 0 ? {} : { tool_choice: choice }
20580
+ },
20581
+ changed: true
20582
+ };
20583
+ }
20489
20584
  var benchmarks_default = {
20490
20585
  version: 2,
20491
20586
  sources: {
@@ -20683,7 +20778,7 @@ var benchmarks_default = {
20683
20778
  };
20684
20779
  var models_default = {
20685
20780
  version: 1,
20686
- updatedAt: "2026-08-13T00:00:00Z",
20781
+ updatedAt: "2026-08-14T00:00:00Z",
20687
20782
  providers: {
20688
20783
  codex: {
20689
20784
  name: "Codex",
@@ -21068,13 +21163,37 @@ var models_default = {
21068
21163
  contextWindow: 256e3
21069
21164
  }
21070
21165
  ]
21166
+ },
21167
+ xai: {
21168
+ name: "xAI",
21169
+ defaultModel: "grok-4.6",
21170
+ 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)",
21171
+ models: [
21172
+ {
21173
+ modelId: "grok-4.6",
21174
+ name: "Grok-4.6",
21175
+ capabilityClass: "flagship",
21176
+ wire: "responses",
21177
+ contextWindow: 5e5,
21178
+ effort: {
21179
+ supported: true,
21180
+ levels: [
21181
+ "low",
21182
+ "medium",
21183
+ "high",
21184
+ "xhigh"
21185
+ ]
21186
+ },
21187
+ benchmarkKey: "grok-4.6"
21188
+ }
21189
+ ]
21071
21190
  }
21072
21191
  }
21073
21192
  };
21074
21193
  var KIMI_AUTH_PROVIDER_ID = "Claude Code with Moonshot Kimi";
21075
21194
  var KIMI_CODE_API_BASE_URL = "https://api.kimi.com/coding";
21076
21195
  var KIMI_CODE_MODEL = "k3";
21077
- var GATEWAY_PROVIDERS = ["codex", "cursor", "kimi", "opencode"];
21196
+ var GATEWAY_PROVIDERS = ["codex", "xai", "cursor", "opencode", "kimi"];
21078
21197
  var GATEWAY_MODEL_WIRES = ["anthropic", "responses", "chat-completions"];
21079
21198
  var GATEWAY_REASONING_EFFORTS = [
21080
21199
  "low",
@@ -21162,7 +21281,8 @@ var GatewayModelsRegistrySchema = external_exports.object({
21162
21281
  codex: GatewayProviderSchema,
21163
21282
  cursor: GatewayProviderSchema,
21164
21283
  kimi: GatewayProviderSchema,
21165
- opencode: GatewayProviderSchema
21284
+ opencode: GatewayProviderSchema,
21285
+ xai: GatewayProviderSchema
21166
21286
  }).strict()
21167
21287
  }).strict();
21168
21288
  var UNSUPPORTED_GATEWAY_MODEL_EFFORT = Object.freeze({ supported: false });
@@ -21427,8 +21547,8 @@ function validateRegistry(value) {
21427
21547
  if (model.quotaScope && provider !== "cursor") {
21428
21548
  throw new Error(`Gateway quota scope is only supported by Cursor: ${provider}/${model.modelId}`);
21429
21549
  }
21430
- if (model.wire && provider !== "opencode") {
21431
- throw new Error(`Gateway model wire is only supported by OpenCode: ${provider}/${model.modelId}`);
21550
+ if (model.wire && provider !== "opencode" && provider !== "xai") {
21551
+ throw new Error(`Gateway model wire is not supported by provider: ${provider}/${model.modelId}`);
21432
21552
  }
21433
21553
  if (model.effort?.supported) {
21434
21554
  if (new Set(model.effort.levels).size !== model.effort.levels.length) {
@@ -21883,14 +22003,14 @@ function nonNegativeCacheValue(value) {
21883
22003
  }
21884
22004
  return value;
21885
22005
  }
21886
- function anthropicUsageFromCanonical(usage3, advertisedContextWindow, options = {}) {
22006
+ function anthropicUsageFromCanonical(usage4, advertisedContextWindow, options = {}) {
21887
22007
  return toAnthropicCacheAwareUsage(
21888
- usage3?.input_tokens ?? 0,
21889
- usage3?.cached_input_tokens,
21890
- usage3?.cache_write_input_tokens,
21891
- options.forceOutputZero ? 0 : usage3?.output_tokens ?? 0,
22008
+ usage4?.input_tokens ?? 0,
22009
+ usage4?.cached_input_tokens,
22010
+ usage4?.cache_write_input_tokens,
22011
+ options.forceOutputZero ? 0 : usage4?.output_tokens ?? 0,
21892
22012
  advertisedContextWindow,
21893
- usage3?.context_window
22013
+ usage4?.context_window
21894
22014
  );
21895
22015
  }
21896
22016
  async function collectAnthropicMessage(events, fallbackModel, options = {}) {
@@ -23022,7 +23142,7 @@ function forChatGptBackend(request) {
23022
23142
  for (const field of CHATGPT_UNSUPPORTED_FIELDS) {
23023
23143
  delete copy[field];
23024
23144
  }
23025
- if (isClaudeCodeSuggestionMode(request)) {
23145
+ if (request.tool_choice === "none" || isClaudeCodeSuggestionMode(request)) {
23026
23146
  delete copy.tools;
23027
23147
  delete copy.tool_choice;
23028
23148
  delete copy.native_tools;
@@ -23731,7 +23851,7 @@ var execFileAsync = promisify(execFile);
23731
23851
  var MAX_CREDENTIAL_BYTES = 65536;
23732
23852
  var CREDENTIAL_OPEN_FLAGS = process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NONBLOCK;
23733
23853
  async function readBoundedFile(filePath, maxBytes) {
23734
- const handle = await fs7.open(filePath, CREDENTIAL_OPEN_FLAGS);
23854
+ const handle = await fs32.open(filePath, CREDENTIAL_OPEN_FLAGS);
23735
23855
  try {
23736
23856
  const stat22 = await handle.stat();
23737
23857
  if (!stat22.isFile() || stat22.size > maxBytes) return null;
@@ -23774,7 +23894,7 @@ function optionalNonEmptyString(value) {
23774
23894
  return typeof value === "string" && value.length > 0 ? value : void 0;
23775
23895
  }
23776
23896
  function codexAuthFilePath(deps) {
23777
- return path18__default.join(deps.env.CODEX_HOME || path18__default.join(deps.homedir(), ".codex"), "auth.json");
23897
+ return path19__default.join(deps.env.CODEX_HOME || path19__default.join(deps.homedir(), ".codex"), "auth.json");
23778
23898
  }
23779
23899
  async function resolveCodexCredentials(deps) {
23780
23900
  try {
@@ -23813,12 +23933,12 @@ function parseCursorCredentialJson(raw, method) {
23813
23933
  function cursorAuthFilePath(deps) {
23814
23934
  const home = deps.homedir();
23815
23935
  if (deps.platform === "win32") {
23816
- return path18__default.join(deps.env.APPDATA || path18__default.join(home, "AppData", "Roaming"), "Cursor", "auth.json");
23936
+ return path19__default.join(deps.env.APPDATA || path19__default.join(home, "AppData", "Roaming"), "Cursor", "auth.json");
23817
23937
  }
23818
23938
  if (deps.platform === "darwin") {
23819
- return path18__default.join(home, ".cursor", "auth.json");
23939
+ return path19__default.join(home, ".cursor", "auth.json");
23820
23940
  }
23821
- return path18__default.join(deps.env.XDG_CONFIG_HOME || path18__default.join(home, ".config"), "cursor", "auth.json");
23941
+ return path19__default.join(deps.env.XDG_CONFIG_HOME || path19__default.join(home, ".config"), "cursor", "auth.json");
23822
23942
  }
23823
23943
  async function resolveCursorCredentials(deps) {
23824
23944
  if (deps.platform === "darwin") {
@@ -23869,7 +23989,7 @@ var OpenAIChatCompletionsAdapter = class {
23869
23989
  const controller = new AbortController();
23870
23990
  const unlinkAbort = linkAbortSignal(options.signal, controller);
23871
23991
  const supportsImageInput = imageInputPolicy.get(this)?.(request.model) ?? true;
23872
- const omitTools = suggestionModeToolOmissionPolicy.has(this) && isClaudeCodeSuggestionMode2(request);
23992
+ const omitTools = toolOmissionPolicy.has(this) && shouldOmitTools(request);
23873
23993
  const payload = forChatCompletionsBackend(request, supportsImageInput, omitTools);
23874
23994
  wireLog("openai-chat.wire.request", { url: this.url, payload });
23875
23995
  let response;
@@ -23916,7 +24036,7 @@ var OpenAIChatCompletionsAdapter = class {
23916
24036
  };
23917
24037
  var imageInputPolicy = /* @__PURE__ */ new WeakMap();
23918
24038
  var argumentPruningPolicy = /* @__PURE__ */ new WeakMap();
23919
- var suggestionModeToolOmissionPolicy = /* @__PURE__ */ new WeakMap();
24039
+ var toolOmissionPolicy = /* @__PURE__ */ new WeakMap();
23920
24040
  var CLAUDE_CODE_SUGGESTION_MODE_PREFIX2 = "[SUGGESTION MODE: Suggest what the user might naturally type next into Claude Code.]";
23921
24041
  var CLAUDE_CODE_SUGGESTION_MODE_SUFFIXES = [
23922
24042
  "Reply with ONLY the suggestion.",
@@ -23934,9 +24054,19 @@ var OpencodeGoChatCompletionsAdapter = class extends OpenAIChatCompletionsAdapte
23934
24054
  });
23935
24055
  imageInputPolicy.set(this, (model) => !model.startsWith("deepseek-v4-"));
23936
24056
  argumentPruningPolicy.set(this, true);
23937
- suggestionModeToolOmissionPolicy.set(this, true);
24057
+ toolOmissionPolicy.set(this, true);
24058
+ }
24059
+ /**
24060
+ * preflight sizing은 wire에 실릴 catalog로 세야 한다. no-tools 조건에서는 실제 wire에
24061
+ * 도구가 없는데 전체 catalog를 청구하면 발생하지 않는 비용이 잡힌다.
24062
+ */
24063
+ wireTools(request) {
24064
+ return shouldOmitTools(request) ? [] : request.tools ?? [];
23938
24065
  }
23939
24066
  };
24067
+ function shouldOmitTools(request) {
24068
+ return request.tool_choice === "none" || isClaudeCodeSuggestionMode2(request);
24069
+ }
23940
24070
  function isClaudeCodeSuggestionMode2(request) {
23941
24071
  if (request.tool_choice === "required" || typeof request.tool_choice === "object") return false;
23942
24072
  const last = request.input.at(-1);
@@ -24140,7 +24270,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24140
24270
  let createdEmitted = false;
24141
24271
  let textSeen = false;
24142
24272
  let accumulatedText = "";
24143
- let usage3 = null;
24273
+ let usage4 = null;
24144
24274
  let failed = false;
24145
24275
  const toolCalls = /* @__PURE__ */ new Map();
24146
24276
  const MESSAGE_ITEM_ID = "chat_message_0";
@@ -24171,7 +24301,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24171
24301
  };
24172
24302
  }
24173
24303
  if (isRecord5(value.usage)) {
24174
- usage3 = chatUsage(value.usage);
24304
+ usage4 = chatUsage(value.usage);
24175
24305
  }
24176
24306
  const choices = Array.isArray(value.choices) ? value.choices : [];
24177
24307
  for (const choice of choices) {
@@ -24264,7 +24394,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24264
24394
  model: responseModel ?? "",
24265
24395
  // 하류 message_delta는 usage가 필수다. include_usage에도 usage 청크를 주지
24266
24396
  // 않는 백엔드에서는 0-usage로 완결하고, 실제 회계는 provider 콘솔이 맡는다.
24267
- usage: usage3 ?? { input_tokens: 0, output_tokens: 0 }
24397
+ usage: usage4 ?? { input_tokens: 0, output_tokens: 0 }
24268
24398
  }
24269
24399
  };
24270
24400
  }
@@ -24925,6 +25055,633 @@ function createOpencodeGoAdapter(wire, options = {}) {
24925
25055
  ...options.fetch ? { fetch: options.fetch } : {}
24926
25056
  });
24927
25057
  }
25058
+ var XAI_OIDC_ISSUER = "https://auth.x.ai";
25059
+ var XAI_CLI_REFRESH_URL = "https://auth.x.ai/oauth2/token";
25060
+ var XAI_CLI_DEFAULT_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
25061
+ var XAI_CLI_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
25062
+ var REFRESH_TIMEOUT_MS = 15e3;
25063
+ var FALLBACK_ACCESS_TOKEN_TTL_MS = 36e5;
25064
+ function xaiCliAuthFilePath(deps) {
25065
+ return path19__default.join(deps.env.GROK_HOME || path19__default.join(deps.homedir(), ".grok"), "auth.json");
25066
+ }
25067
+ function expiry(value) {
25068
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
25069
+ const parsed = typeof value === "number" ? value : Date.parse(value);
25070
+ if (!Number.isFinite(parsed)) return void 0;
25071
+ return parsed < 1e12 ? Math.round(parsed * 1e3) : Math.round(parsed);
25072
+ }
25073
+ function jwtExpiry(token) {
25074
+ const parts = token.split(".");
25075
+ if (parts.length < 2) return void 0;
25076
+ try {
25077
+ const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
25078
+ const record42 = credentialRecord(payload);
25079
+ const exp = record42?.exp;
25080
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return void 0;
25081
+ return Math.round(exp * 1e3);
25082
+ } catch {
25083
+ return void 0;
25084
+ }
25085
+ }
25086
+ function effectiveExpiry(entry, accessToken) {
25087
+ const fromEntry = expiry(entry.expires_at) ?? expiry(entry.expires);
25088
+ const fromJwt = jwtExpiry(accessToken);
25089
+ if (fromEntry !== void 0 && fromJwt !== void 0) return Math.min(fromEntry, fromJwt);
25090
+ return fromEntry ?? fromJwt;
25091
+ }
25092
+ function clientId(entryKey, entry) {
25093
+ const fromEntry = optionalTrimmedString(entry.oidc_client_id);
25094
+ if (fromEntry) return fromEntry;
25095
+ const suffix = optionalTrimmedString(entryKey.split("::").at(-1));
25096
+ return suffix ?? XAI_CLI_DEFAULT_CLIENT_ID;
25097
+ }
25098
+ function refreshToken(entry) {
25099
+ return optionalTrimmedString(entry.refresh_token) ?? optionalTrimmedString(entry.refresh);
25100
+ }
25101
+ async function defaultWriteAuthFile(filePath, contents) {
25102
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
25103
+ try {
25104
+ await fs32.writeFile(tmpPath, contents, { encoding: "utf8", mode: 384 });
25105
+ await fs32.rename(tmpPath, filePath);
25106
+ } catch (error51) {
25107
+ await fs32.unlink(tmpPath).catch(() => void 0);
25108
+ throw error51;
25109
+ }
25110
+ }
25111
+ async function persistRefreshedEntry(deps, filePath, entryKey, expected, patch, writeAuthFile) {
25112
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
25113
+ if (raw === null) return;
25114
+ const auth = credentialRecord(JSON.parse(raw));
25115
+ if (!auth) return;
25116
+ const current = credentialRecord(auth[entryKey]);
25117
+ if (!current) return;
25118
+ if (optionalTrimmedString(current.key) !== expected.accessToken) return;
25119
+ if (expected.refreshToken !== void 0 && refreshToken(current) !== expected.refreshToken) return;
25120
+ auth[entryKey] = { ...current, ...patch };
25121
+ await writeAuthFile(filePath, `${JSON.stringify(auth, null, 2)}
25122
+ `);
25123
+ }
25124
+ async function refreshAccessToken(entryKey, entry, fetchImpl, now) {
25125
+ const token = refreshToken(entry);
25126
+ if (!token) return null;
25127
+ const controller = new AbortController();
25128
+ const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
25129
+ try {
25130
+ const body = new URLSearchParams({
25131
+ grant_type: "refresh_token",
25132
+ client_id: clientId(entryKey, entry),
25133
+ refresh_token: token
25134
+ });
25135
+ const response = await fetchImpl(XAI_CLI_REFRESH_URL, {
25136
+ method: "POST",
25137
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
25138
+ body,
25139
+ signal: controller.signal
25140
+ });
25141
+ if (!response.ok) return null;
25142
+ const payload = credentialRecord(await response.json());
25143
+ const accessToken = optionalTrimmedString(payload?.access_token);
25144
+ if (!accessToken) return null;
25145
+ const expiresIn = payload?.expires_in;
25146
+ const expiresAt = typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn > 0 ? now() + Math.round(expiresIn * 1e3) : jwtExpiry(accessToken) ?? now() + FALLBACK_ACCESS_TOKEN_TTL_MS;
25147
+ const rotated = optionalTrimmedString(payload?.refresh_token);
25148
+ return {
25149
+ accessToken,
25150
+ expiresAt,
25151
+ ...rotated === void 0 ? {} : { refreshToken: rotated }
25152
+ };
25153
+ } catch {
25154
+ return null;
25155
+ } finally {
25156
+ clearTimeout(timer);
25157
+ }
25158
+ }
25159
+ async function resolveXaiCliAuth(deps, options = {}) {
25160
+ const now = options.now ?? Date.now;
25161
+ const fetchImpl = options.fetch ?? fetch;
25162
+ const writeAuthFile = options.writeAuthFile ?? defaultWriteAuthFile;
25163
+ const filePath = xaiCliAuthFilePath(deps);
25164
+ try {
25165
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
25166
+ if (raw === null || raw.length > MAX_CREDENTIAL_BYTES) return { status: "signed_out" };
25167
+ const auth = credentialRecord(JSON.parse(raw));
25168
+ if (!auth) return { status: "signed_out" };
25169
+ let sawExpired = false;
25170
+ for (const [entryKey, value] of Object.entries(auth)) {
25171
+ if (!entryKey.startsWith(`${XAI_OIDC_ISSUER}::`)) continue;
25172
+ const entry = credentialRecord(value);
25173
+ const issuer = optionalTrimmedString(entry?.oidc_issuer);
25174
+ const accessToken = optionalTrimmedString(entry?.key);
25175
+ if (!entry || issuer !== XAI_OIDC_ISSUER || !accessToken) continue;
25176
+ const expiresAt = effectiveExpiry(entry, accessToken);
25177
+ const expired2 = expiresAt !== void 0 && expiresAt <= now();
25178
+ const needsRefresh = options.forceRefresh === true || expiresAt !== void 0 && expiresAt - now() <= XAI_CLI_REFRESH_BUFFER_MS;
25179
+ if (needsRefresh) {
25180
+ const refreshed = await refreshAccessToken(entryKey, entry, fetchImpl, now);
25181
+ if (refreshed) {
25182
+ const userId2 = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
25183
+ const patch = {
25184
+ key: refreshed.accessToken,
25185
+ expires_at: new Date(refreshed.expiresAt).toISOString()
25186
+ };
25187
+ if (refreshed.refreshToken !== void 0) patch.refresh_token = refreshed.refreshToken;
25188
+ try {
25189
+ await persistRefreshedEntry(
25190
+ deps,
25191
+ filePath,
25192
+ entryKey,
25193
+ { accessToken, refreshToken: refreshToken(entry) },
25194
+ patch,
25195
+ writeAuthFile
25196
+ );
25197
+ } catch {
25198
+ }
25199
+ return {
25200
+ status: "ok",
25201
+ credentials: {
25202
+ accessToken: refreshed.accessToken,
25203
+ expiresAt: refreshed.expiresAt,
25204
+ ...userId2 === void 0 ? {} : { userId: userId2 }
25205
+ }
25206
+ };
25207
+ }
25208
+ if (options.forceRefresh === true || expired2) {
25209
+ sawExpired = true;
25210
+ continue;
25211
+ }
25212
+ } else if (expired2) {
25213
+ sawExpired = true;
25214
+ continue;
25215
+ }
25216
+ const userId = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
25217
+ return {
25218
+ status: "ok",
25219
+ credentials: {
25220
+ accessToken,
25221
+ ...expiresAt === void 0 ? {} : { expiresAt },
25222
+ ...userId === void 0 ? {} : { userId }
25223
+ }
25224
+ };
25225
+ }
25226
+ return { status: sawExpired ? "expired" : "signed_out" };
25227
+ } catch {
25228
+ return { status: "signed_out" };
25229
+ }
25230
+ }
25231
+ async function resolveXaiCliCredentials(deps, nowOrOptions = Date.now) {
25232
+ const options = typeof nowOrOptions === "function" ? { now: nowOrOptions } : nowOrOptions;
25233
+ const result = await resolveXaiCliAuth(deps, options);
25234
+ return result.status === "ok" ? result.credentials : null;
25235
+ }
25236
+ var XAI_CLI_RESPONSES_URL = "https://cli-chat-proxy.grok.com/v1/responses";
25237
+ var XAI_CLI_CLIENT_VERSION = "1.0.3";
25238
+ var DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES = 64 * 1024 * 1024;
25239
+ var DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS = 3e4;
25240
+ var DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS = 3e4;
25241
+ var XaiResponsesAdapter = class {
25242
+ capabilities = {};
25243
+ fetchImpl;
25244
+ maxBodyBytes;
25245
+ idleTimeoutMs;
25246
+ functionCallTimeoutMs;
25247
+ url;
25248
+ extraHeaders;
25249
+ constructor(options = {}) {
25250
+ this.url = XAI_CLI_RESPONSES_URL;
25251
+ this.extraHeaders = options.headers ?? {};
25252
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
25253
+ this.maxBodyBytes = positiveInteger(
25254
+ options.maxBodyBytes ?? DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES,
25255
+ "maxBodyBytes"
25256
+ );
25257
+ this.idleTimeoutMs = positiveInteger(
25258
+ options.idleTimeoutMs ?? DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS,
25259
+ "idleTimeoutMs"
25260
+ );
25261
+ this.functionCallTimeoutMs = positiveInteger(
25262
+ options.functionCallTimeoutMs ?? DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS,
25263
+ "functionCallTimeoutMs"
25264
+ );
25265
+ }
25266
+ async stream(request, options) {
25267
+ if (options.apiKey.length === 0) {
25268
+ throw new TypeError("apiKey must not be empty");
25269
+ }
25270
+ const controller = new AbortController();
25271
+ const unlinkAbort = linkAbortSignal(options.signal, controller);
25272
+ const payload = forXaiResponsesBackend(request, xaiWireTools(request));
25273
+ wireLog("xai-responses.wire.request", { url: this.url, payload });
25274
+ let response;
25275
+ try {
25276
+ response = await this.fetchImpl(this.url, {
25277
+ method: "POST",
25278
+ headers: {
25279
+ accept: "text/event-stream",
25280
+ authorization: `Bearer ${options.apiKey}`,
25281
+ "content-type": "application/json",
25282
+ "x-xai-token-auth": "xai-grok-cli",
25283
+ "x-grok-client-version": XAI_CLI_CLIENT_VERSION,
25284
+ "x-grok-model-override": request.model,
25285
+ ...this.extraHeaders
25286
+ },
25287
+ body: JSON.stringify(payload),
25288
+ signal: controller.signal
25289
+ });
25290
+ } catch (error51) {
25291
+ unlinkAbort();
25292
+ throw error51;
25293
+ }
25294
+ if (!response.ok) {
25295
+ if (process.env.FLEET_AI_GATEWAY_DEBUG === "1") {
25296
+ const roles = payload.input.map((item) => "role" in item ? item.role : item.type);
25297
+ console.error(`[ai-gateway] upstream ${response.status} input roles=${JSON.stringify(roles)} keys=${JSON.stringify(Object.keys(payload))}`);
25298
+ }
25299
+ try {
25300
+ const body = await readBoundedBody(response.body, {
25301
+ controller,
25302
+ idleTimeoutMs: this.idleTimeoutMs,
25303
+ maxBodyBytes: this.maxBodyBytes
25304
+ });
25305
+ return {
25306
+ ok: false,
25307
+ status: response.status,
25308
+ headers: response.headers,
25309
+ body
25310
+ };
25311
+ } finally {
25312
+ unlinkAbort();
25313
+ }
25314
+ }
25315
+ return {
25316
+ ok: true,
25317
+ status: response.status,
25318
+ headers: response.headers,
25319
+ events: parseXaiEventStream(response.body, {
25320
+ controller,
25321
+ idleTimeoutMs: this.idleTimeoutMs,
25322
+ maxBodyBytes: this.maxBodyBytes,
25323
+ onClose: unlinkAbort
25324
+ }, this.functionCallTimeoutMs)
25325
+ };
25326
+ }
25327
+ wireTools(request) {
25328
+ return xaiWireTools(request) ?? [];
25329
+ }
25330
+ };
25331
+ function forXaiResponsesBackend(request, tools = xaiWireTools(request)) {
25332
+ const { metadata: _metadata, native_tools: _nativeTools, ...rest } = request;
25333
+ return {
25334
+ ...rest,
25335
+ input: request.input.map((item) => {
25336
+ if (item.type === "function_call_output") {
25337
+ const { is_error: _isError, tool_references: _toolReferences, ...wireItem2 } = item;
25338
+ return wireItem2;
25339
+ }
25340
+ const { reasoning_content: _reasoningContent, ...wireItem } = item;
25341
+ return wireItem;
25342
+ }),
25343
+ ...tools === void 0 ? {} : { tools: [...tools] }
25344
+ };
25345
+ }
25346
+ function xaiWireTools(request) {
25347
+ if (request.tools === void 0) return void 0;
25348
+ const tools = request.tools;
25349
+ const toolSearchActive = tools.some((tool) => isToolSearchName(tool.name));
25350
+ const selectedName = request.tool_choice && typeof request.tool_choice === "object" ? request.tool_choice.name : void 0;
25351
+ const referencedNames = new Set(
25352
+ request.input.flatMap((item) => item.type === "function_call_output" ? item.tool_references ?? [] : [])
25353
+ );
25354
+ return tools.filter((tool) => !toolSearchActive || tool.defer_loading !== true || isToolSearchName(tool.name) || selectedName !== void 0 && toolNameMatches(tool.name, selectedName) || referencedNames.has(tool.name)).map(({ defer_loading: _deferLoading, ...tool }) => tool);
25355
+ }
25356
+ function toolLeafName(name) {
25357
+ const separator = name.lastIndexOf("__");
25358
+ return separator === -1 ? name : name.slice(separator + 2);
25359
+ }
25360
+ function isToolSearchName(name) {
25361
+ return toolLeafName(name).replace(/[_-]/g, "").toLowerCase() === "toolsearch";
25362
+ }
25363
+ function toolNameMatches(declaredName, selectedName) {
25364
+ return declaredName === selectedName || toolLeafName(declaredName) === toolLeafName(selectedName);
25365
+ }
25366
+ function parseXaiEventStream(body, options, functionCallTimeoutMs) {
25367
+ return assembleXaiFunctionCalls(
25368
+ parseUpstreamSseStream(
25369
+ body,
25370
+ { ...options, missingBodyMessage: "Grok CLI streaming response had no body" },
25371
+ parseEventFrame3
25372
+ ),
25373
+ options.controller,
25374
+ functionCallTimeoutMs
25375
+ );
25376
+ }
25377
+ async function* assembleXaiFunctionCalls(source, controller, timeoutMs) {
25378
+ const iterator = source[Symbol.asyncIterator]();
25379
+ const pending = /* @__PURE__ */ new Map();
25380
+ let completedNormally = false;
25381
+ try {
25382
+ while (true) {
25383
+ const deadlineAt = earliestXaiFunctionCallDeadline(pending);
25384
+ const result = deadlineAt === void 0 ? await iterator.next() : await nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs);
25385
+ if (result.done) {
25386
+ if (pending.size > 0) {
25387
+ throw incompleteXaiFunctionCall("stream ended before function call output_item.done");
25388
+ }
25389
+ completedNormally = true;
25390
+ return;
25391
+ }
25392
+ const event = result.value;
25393
+ if (event.type === "response.completed" && pending.size > 0) {
25394
+ throw incompleteXaiFunctionCall("response.completed arrived before function call output_item.done");
25395
+ }
25396
+ if (event.type === "response.output_item.added" && event.item.type === "function_call") {
25397
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
25398
+ pending.set(key, {
25399
+ added: event,
25400
+ // Each call gets a full timeout from its own added event. Waiting uses the
25401
+ // earliest active deadline, so a later parallel call is never shortened by
25402
+ // an earlier call's age.
25403
+ deadlineAt: Date.now() + timeoutMs
25404
+ });
25405
+ continue;
25406
+ }
25407
+ if (event.type === "response.function_call_arguments.done") {
25408
+ const call = pending.get(xaiFunctionCallKey(event.output_index, event.item_id));
25409
+ if (call !== void 0) {
25410
+ call.argumentsDone = event;
25411
+ continue;
25412
+ }
25413
+ }
25414
+ if (event.type === "response.output_item.done" && event.item.type === "function_call") {
25415
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
25416
+ const call = pending.get(key);
25417
+ if (call !== void 0) {
25418
+ pending.delete(key);
25419
+ yield call.added;
25420
+ if (call.argumentsDone !== void 0) {
25421
+ yield call.argumentsDone;
25422
+ } else if (event.item.arguments.length > 0) {
25423
+ yield {
25424
+ type: "response.function_call_arguments.done",
25425
+ item_id: event.item.id,
25426
+ output_index: event.output_index,
25427
+ arguments: event.item.arguments
25428
+ };
25429
+ }
25430
+ yield event;
25431
+ continue;
25432
+ }
25433
+ }
25434
+ yield event;
25435
+ }
25436
+ } finally {
25437
+ if (!completedNormally && !controller.signal.aborted) {
25438
+ controller.abort();
25439
+ }
25440
+ const returned = iterator.return?.();
25441
+ if (returned !== void 0) {
25442
+ await returned.catch(() => void 0);
25443
+ }
25444
+ }
25445
+ }
25446
+ function earliestXaiFunctionCallDeadline(pending) {
25447
+ let earliest;
25448
+ for (const call of pending.values()) {
25449
+ if (earliest === void 0 || call.deadlineAt < earliest) {
25450
+ earliest = call.deadlineAt;
25451
+ }
25452
+ }
25453
+ return earliest;
25454
+ }
25455
+ async function nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs) {
25456
+ const remainingMs = deadlineAt - Date.now();
25457
+ if (remainingMs <= 0) {
25458
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
25459
+ controller.abort(error51);
25460
+ throw error51;
25461
+ }
25462
+ let timeout;
25463
+ const next = iterator.next();
25464
+ void next.catch(() => void 0);
25465
+ try {
25466
+ return await Promise.race([
25467
+ next,
25468
+ new Promise((_, reject) => {
25469
+ timeout = setTimeout(() => {
25470
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
25471
+ controller.abort(error51);
25472
+ reject(error51);
25473
+ }, remainingMs);
25474
+ })
25475
+ ]);
25476
+ } finally {
25477
+ if (timeout !== void 0) {
25478
+ clearTimeout(timeout);
25479
+ }
25480
+ }
25481
+ }
25482
+ function incompleteXaiFunctionCall(reason) {
25483
+ return new UpstreamProtocolError(`Grok CLI ${reason}`);
25484
+ }
25485
+ function xaiFunctionCallKey(outputIndex, itemId) {
25486
+ return `${outputIndex}:${itemId}`;
25487
+ }
25488
+ function parseEventFrame3(frame) {
25489
+ const { event: eventName, data } = parseSseFrameFields(frame);
25490
+ if (data.length === 0 || data === "[DONE]") {
25491
+ return void 0;
25492
+ }
25493
+ let parsed;
25494
+ try {
25495
+ parsed = JSON.parse(data);
25496
+ } catch (error51) {
25497
+ throw new UpstreamProtocolError(
25498
+ `Grok CLI SSE contained invalid JSON: ${error51 instanceof Error ? error51.message : String(error51)}`
25499
+ );
25500
+ }
25501
+ if (isRecord7(parsed) && typeof parsed.type !== "string" && eventName !== void 0) {
25502
+ parsed = { ...parsed, type: eventName };
25503
+ }
25504
+ return canonicalEvent3(parsed);
25505
+ }
25506
+ function canonicalEvent3(value) {
25507
+ if (!isRecord7(value) || typeof value.type !== "string") {
25508
+ throw new UpstreamProtocolError("Grok CLI SSE event was not an object with a type");
25509
+ }
25510
+ switch (value.type) {
25511
+ case "response.created":
25512
+ return { type: value.type, response: responseSnapshot3(value.response) };
25513
+ case "response.content_part.added": {
25514
+ const part = record3(value.part, "response.content_part.added.part");
25515
+ if (part.type !== "output_text") {
25516
+ return void 0;
25517
+ }
25518
+ return {
25519
+ type: value.type,
25520
+ item_id: string32(value.item_id, "item_id"),
25521
+ output_index: number32(value.output_index, "output_index"),
25522
+ content_index: number32(value.content_index, "content_index"),
25523
+ part: {
25524
+ type: "output_text",
25525
+ text: typeof part.text === "string" ? part.text : ""
25526
+ }
25527
+ };
25528
+ }
25529
+ case "response.output_text.delta":
25530
+ return {
25531
+ type: value.type,
25532
+ item_id: string32(value.item_id, "item_id"),
25533
+ output_index: number32(value.output_index, "output_index"),
25534
+ content_index: number32(value.content_index, "content_index"),
25535
+ delta: string32(value.delta, "delta")
25536
+ };
25537
+ case "response.output_text.done":
25538
+ return {
25539
+ type: value.type,
25540
+ item_id: string32(value.item_id, "item_id"),
25541
+ output_index: number32(value.output_index, "output_index"),
25542
+ content_index: number32(value.content_index, "content_index"),
25543
+ text: string32(value.text, "text")
25544
+ };
25545
+ case "response.reasoning_summary_text.delta":
25546
+ case "response.reasoning_text.delta":
25547
+ return {
25548
+ type: "response.reasoning_summary_text.delta",
25549
+ item_id: string32(value.item_id, "item_id"),
25550
+ output_index: number32(value.output_index, "output_index"),
25551
+ delta: string32(value.delta, "delta")
25552
+ };
25553
+ case "response.output_item.added":
25554
+ case "response.output_item.done": {
25555
+ const item = outputItem3(value.item);
25556
+ if (item === void 0) {
25557
+ return void 0;
25558
+ }
25559
+ return {
25560
+ type: value.type,
25561
+ output_index: number32(value.output_index, "output_index"),
25562
+ item
25563
+ };
25564
+ }
25565
+ // Hold argument fragments until the Grok CLI proxy's partial-JSON behavior is observed.
25566
+ // The `.done` event carries the complete argument object, which downstream treats as the
25567
+ // remainder when nothing was streamed ahead of it.
25568
+ case "response.function_call_arguments.delta":
25569
+ return void 0;
25570
+ case "response.function_call_arguments.done":
25571
+ return {
25572
+ type: value.type,
25573
+ item_id: string32(value.item_id, "item_id"),
25574
+ output_index: number32(value.output_index, "output_index"),
25575
+ arguments: string32(value.arguments, "arguments")
25576
+ };
25577
+ case "response.completed":
25578
+ return { type: value.type, response: responseSnapshot3(value.response) };
25579
+ case "response.failed": {
25580
+ const response = record3(value.response, "response.failed.response");
25581
+ return {
25582
+ type: value.type,
25583
+ response: {
25584
+ ...responseSnapshot3(response),
25585
+ error: canonicalError3(response.error)
25586
+ }
25587
+ };
25588
+ }
25589
+ case "error":
25590
+ return { type: "error", error: canonicalError3(value.error ?? value) };
25591
+ default:
25592
+ return void 0;
25593
+ }
25594
+ }
25595
+ function responseSnapshot3(value) {
25596
+ const response = record3(value, "response");
25597
+ return {
25598
+ id: string32(response.id, "response.id"),
25599
+ model: string32(response.model, "response.model"),
25600
+ usage: response.usage === null || response.usage === void 0 ? null : usage3(response.usage)
25601
+ };
25602
+ }
25603
+ function usage3(value) {
25604
+ const parsed = record3(value, "usage");
25605
+ const inputTokens = number32(parsed.input_tokens, "usage.input_tokens");
25606
+ const outputTokens = number32(parsed.output_tokens, "usage.output_tokens");
25607
+ const inputDetails = optionalRecord3(parsed.input_tokens_details, "usage.input_tokens_details");
25608
+ const cachedInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cached_tokens, "usage.input_tokens_details.cached_tokens");
25609
+ const cacheWriteInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cache_write_tokens, "usage.input_tokens_details.cache_write_tokens");
25610
+ const outputDetails = optionalRecord3(parsed.output_tokens_details, "usage.output_tokens_details");
25611
+ const reasoningOutputTokens = outputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(outputDetails.reasoning_tokens, "usage.output_tokens_details.reasoning_tokens");
25612
+ const totalTokens = optionalNonNegativeNumber3(parsed.total_tokens, "usage.total_tokens");
25613
+ return {
25614
+ input_tokens: inputTokens,
25615
+ output_tokens: outputTokens,
25616
+ ...cachedInputTokens === void 0 ? {} : { cached_input_tokens: cachedInputTokens },
25617
+ ...cacheWriteInputTokens === void 0 ? {} : { cache_write_input_tokens: cacheWriteInputTokens },
25618
+ ...reasoningOutputTokens === void 0 ? {} : { reasoning_output_tokens: reasoningOutputTokens },
25619
+ ...totalTokens === void 0 ? {} : { total_tokens: totalTokens }
25620
+ };
25621
+ }
25622
+ function outputItem3(value) {
25623
+ const item = record3(value, "item");
25624
+ if (item.type === "message") {
25625
+ return {
25626
+ id: string32(item.id, "item.id"),
25627
+ type: "message",
25628
+ role: "assistant"
25629
+ };
25630
+ }
25631
+ if (item.type === "function_call") {
25632
+ const id = string32(item.id, "item.id");
25633
+ return {
25634
+ id,
25635
+ type: "function_call",
25636
+ call_id: typeof item.call_id === "string" ? item.call_id : id,
25637
+ name: string32(item.name, "item.name"),
25638
+ arguments: typeof item.arguments === "string" ? item.arguments : ""
25639
+ };
25640
+ }
25641
+ return void 0;
25642
+ }
25643
+ function canonicalError3(value) {
25644
+ const error51 = record3(value, "error");
25645
+ const message = string32(error51.message, "error.message");
25646
+ const type = typeof error51.type === "string" && error51.type !== "error" ? error51.type : typeof error51.code === "string" ? error51.code : "api_error";
25647
+ return { type, message };
25648
+ }
25649
+ function isRecord7(value) {
25650
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25651
+ }
25652
+ function record3(value, name) {
25653
+ if (!isRecord7(value)) {
25654
+ throw new UpstreamProtocolError(`${name} must be an object`);
25655
+ }
25656
+ return value;
25657
+ }
25658
+ function optionalRecord3(value, name) {
25659
+ if (value === void 0 || value === null) {
25660
+ return void 0;
25661
+ }
25662
+ return record3(value, name);
25663
+ }
25664
+ function string32(value, name) {
25665
+ if (typeof value !== "string") {
25666
+ throw new UpstreamProtocolError(`${name} must be a string`);
25667
+ }
25668
+ return value;
25669
+ }
25670
+ function number32(value, name) {
25671
+ if (typeof value !== "number" || !Number.isFinite(value)) {
25672
+ throw new UpstreamProtocolError(`${name} must be a number`);
25673
+ }
25674
+ return value;
25675
+ }
25676
+ function optionalNonNegativeNumber3(value, name) {
25677
+ if (value === void 0 || value === null) {
25678
+ return void 0;
25679
+ }
25680
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
25681
+ throw new UpstreamProtocolError(`${name} must be a finite nonnegative number`);
25682
+ }
25683
+ return value;
25684
+ }
24928
25685
  var NO_USER_FACING_BLOCK = "Do not tell the user access is blocked, disabled, or denied.";
24929
25686
  var CLIENT_TOOL_RETRY = `${NO_USER_FACING_BLOCK} Silently retry with the matching client bridge tool from the current catalog.`;
24930
25687
  function cursorNativeExecPolicyReplies(exec2, clientTools) {
@@ -24965,38 +25722,38 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
24965
25722
  "shell_command",
24966
25723
  "exec_command"
24967
25724
  ]);
24968
- if (isRecord7(exec2.readArgs)) {
25725
+ if (isRecord8(exec2.readArgs)) {
24969
25726
  return [execReply(exec2, "readResult", {
24970
25727
  error: { path: stringValue(exec2.readArgs.path), error: readMessage3 }
24971
25728
  })];
24972
25729
  }
24973
- if (isRecord7(exec2.writeArgs)) {
25730
+ if (isRecord8(exec2.writeArgs)) {
24974
25731
  return [execReply(exec2, "writeResult", {
24975
25732
  rejected: { path: stringValue(exec2.writeArgs.path), reason: mutationMessage }
24976
25733
  })];
24977
25734
  }
24978
- if (isRecord7(exec2.deleteArgs)) {
25735
+ if (isRecord8(exec2.deleteArgs)) {
24979
25736
  return [execReply(exec2, "deleteResult", {
24980
25737
  rejected: { path: stringValue(exec2.deleteArgs.path), reason: mutationMessage }
24981
25738
  })];
24982
25739
  }
24983
- if (isRecord7(exec2.lsArgs)) {
25740
+ if (isRecord8(exec2.lsArgs)) {
24984
25741
  return [execReply(exec2, "lsResult", {
24985
25742
  error: { path: stringValue(exec2.lsArgs.path), error: listMessage }
24986
25743
  })];
24987
25744
  }
24988
- if (isRecord7(exec2.grepArgs)) {
25745
+ if (isRecord8(exec2.grepArgs)) {
24989
25746
  return [execReply(exec2, "grepResult", { error: { error: grepMessage } })];
24990
25747
  }
24991
- if (isRecord7(exec2.shellArgs)) {
25748
+ if (isRecord8(exec2.shellArgs)) {
24992
25749
  return [execReply(exec2, "shellResult", shellFailure(exec2.shellArgs, shellMessage))];
24993
25750
  }
24994
- if (isRecord7(exec2.shellStreamArgs)) {
25751
+ if (isRecord8(exec2.shellStreamArgs)) {
24995
25752
  const args = exec2.shellStreamArgs;
24996
25753
  const cwd = stringValue(args.workingDirectory);
24997
25754
  return [
24998
25755
  execReply(exec2, "shellStream", {
24999
- start: isRecord7(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
25756
+ start: isRecord8(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
25000
25757
  }),
25001
25758
  execReply(exec2, "shellStream", { stderr: { data: shellMessage } }),
25002
25759
  execReply(exec2, "shellStream", { exit: { code: 1, cwd, aborted: true } }),
@@ -25004,7 +25761,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25004
25761
  { execClientControlMessage: { streamClose: { id: numberValue(exec2.id) } } }
25005
25762
  ];
25006
25763
  }
25007
- if (isRecord7(exec2.backgroundShellSpawnArgs)) {
25764
+ if (isRecord8(exec2.backgroundShellSpawnArgs)) {
25008
25765
  const args = exec2.backgroundShellSpawnArgs;
25009
25766
  return [execReply(exec2, "backgroundShellSpawnResult", {
25010
25767
  error: {
@@ -25014,15 +25771,15 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25014
25771
  }
25015
25772
  })];
25016
25773
  }
25017
- if (isRecord7(exec2.writeShellStdinArgs)) {
25774
+ if (isRecord8(exec2.writeShellStdinArgs)) {
25018
25775
  return [execReply(exec2, "writeShellStdinResult", { error: { error: shellMessage } })];
25019
25776
  }
25020
- if (isRecord7(exec2.fetchArgs)) {
25777
+ if (isRecord8(exec2.fetchArgs)) {
25021
25778
  return [execReply(exec2, "fetchResult", {
25022
25779
  error: { url: stringValue(exec2.fetchArgs.url), error: networkMessage }
25023
25780
  })];
25024
25781
  }
25025
- if (isRecord7(exec2.diagnosticsArgs)) {
25782
+ if (isRecord8(exec2.diagnosticsArgs)) {
25026
25783
  return [execReply(exec2, "diagnosticsResult", {
25027
25784
  error: {
25028
25785
  path: stringValue(exec2.diagnosticsArgs.path),
@@ -25030,12 +25787,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25030
25787
  }
25031
25788
  })];
25032
25789
  }
25033
- if (isRecord7(exec2.listMcpResourcesExecArgs)) {
25790
+ if (isRecord8(exec2.listMcpResourcesExecArgs)) {
25034
25791
  return [execReply(exec2, "listMcpResourcesExecResult", {
25035
25792
  error: { error: retryMessage(clientTools, ["ListMcpResources", "list_mcp_resources"]) }
25036
25793
  })];
25037
25794
  }
25038
- if (isRecord7(exec2.readMcpResourceExecArgs)) {
25795
+ if (isRecord8(exec2.readMcpResourceExecArgs)) {
25039
25796
  return [execReply(exec2, "readMcpResourceExecResult", {
25040
25797
  error: {
25041
25798
  uri: stringValue(exec2.readMcpResourceExecArgs.uri),
@@ -25043,12 +25800,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25043
25800
  }
25044
25801
  })];
25045
25802
  }
25046
- if (isRecord7(exec2.recordScreenArgs)) {
25803
+ if (isRecord8(exec2.recordScreenArgs)) {
25047
25804
  return [execReply(exec2, "recordScreenResult", {
25048
25805
  failure: { error: retryMessage(clientTools, ["record_screen", "computer_use"]) }
25049
25806
  })];
25050
25807
  }
25051
- if (isRecord7(exec2.computerUseArgs)) {
25808
+ if (isRecord8(exec2.computerUseArgs)) {
25052
25809
  return [execReply(exec2, "computerUseResult", {
25053
25810
  error: {
25054
25811
  error: retryMessage(clientTools, ["computer_use"]),
@@ -25058,7 +25815,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25058
25815
  }
25059
25816
  })];
25060
25817
  }
25061
- if (isRecord7(exec2.mcpArgs)) {
25818
+ if (isRecord8(exec2.mcpArgs)) {
25062
25819
  return [execReply(exec2, "mcpResult", {
25063
25820
  error: { error: retryMessage(clientTools, []) }
25064
25821
  })];
@@ -25096,7 +25853,7 @@ function retryMessage(clientTools, candidates) {
25096
25853
  const clientToolName = typeof clientTool === "string" ? clientTool : clientTool.clientName;
25097
25854
  const wireName = typeof clientTool === "string" ? clientTool : clientTool.wireName;
25098
25855
  if (seen.has(wireName)) continue;
25099
- if (toolLeafName(clientToolName).toLowerCase() !== candidate.toLowerCase()) continue;
25856
+ if (toolLeafName2(clientToolName).toLowerCase() !== candidate.toLowerCase()) continue;
25100
25857
  seen.add(wireName);
25101
25858
  matches.push(wireName);
25102
25859
  }
@@ -25116,12 +25873,12 @@ function retryMessage(clientTools, candidates) {
25116
25873
  function toolSearchWireName(clientTools) {
25117
25874
  for (const clientTool of clientTools) {
25118
25875
  const clientToolName = typeof clientTool === "string" ? clientTool : clientTool.clientName;
25119
- if (toolLeafName(clientToolName).replace(/[_-]/g, "").toLowerCase() !== "toolsearch") continue;
25876
+ if (toolLeafName2(clientToolName).replace(/[_-]/g, "").toLowerCase() !== "toolsearch") continue;
25120
25877
  return typeof clientTool === "string" ? clientTool : clientTool.wireName;
25121
25878
  }
25122
25879
  return void 0;
25123
25880
  }
25124
- function toolLeafName(name) {
25881
+ function toolLeafName2(name) {
25125
25882
  return name.split("__").at(-1) ?? name;
25126
25883
  }
25127
25884
  function numberValue(value) {
@@ -25130,7 +25887,7 @@ function numberValue(value) {
25130
25887
  function stringValue(value) {
25131
25888
  return typeof value === "string" ? value : "";
25132
25889
  }
25133
- function isRecord7(value) {
25890
+ function isRecord8(value) {
25134
25891
  return typeof value === "object" && value !== null && !Array.isArray(value);
25135
25892
  }
25136
25893
  var EXECUTE_HOOK_FIELD_NUMBER = 27;
@@ -25272,24 +26029,24 @@ var CURSOR_HOT_PATH_TOOL_LEAVES = [
25272
26029
  "toolsearch"
25273
26030
  ];
25274
26031
  function isCursorHotPathToolName(name) {
25275
- const leaf = toolLeafName2(name).replace(/[_-]/g, "").toLowerCase();
26032
+ const leaf = toolLeafName3(name).replace(/[_-]/g, "").toLowerCase();
25276
26033
  return CURSOR_HOT_PATH_TOOL_LEAVES.includes(leaf);
25277
26034
  }
25278
26035
  function isCursorNativeRedirectToolName(name) {
25279
- const leaf = toolLeafName2(name).replace(/[_-]/g, "").toLowerCase();
26036
+ const leaf = toolLeafName3(name).replace(/[_-]/g, "").toLowerCase();
25280
26037
  return ["read", "grep", "bash", "shellcommand", "execcommand"].includes(leaf);
25281
26038
  }
25282
26039
  function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25283
26040
  const messageId = numberValue2(exec2.id ?? 0);
25284
26041
  const execId = stringValue2(exec2.execId) || `redirect-${messageId}`;
25285
- if (isRecord8(exec2.readArgs)) {
25286
- const path72 = stringValue2(exec2.readArgs.path);
25287
- if (!path72) return null;
26042
+ if (isRecord9(exec2.readArgs)) {
26043
+ const path82 = stringValue2(exec2.readArgs.path);
26044
+ if (!path82) return null;
25288
26045
  if ([exec2.readArgs.offset, exec2.readArgs.limit].some((value) => typeof value === "number" && value < 0)) return null;
25289
26046
  const offset = positiveNumber(exec2.readArgs.offset);
25290
26047
  const limit = positiveNumber(exec2.readArgs.limit);
25291
26048
  if (offset !== void 0 || limit !== void 0) return null;
25292
- const mapped = tools.filter((tool) => matchesLeaf(tool, READ_CANDIDATES)).map((tool) => ({ tool, args: readArguments(tool.inputSchemaValue, path72) })).find((candidate) => candidate.args !== null);
26049
+ const mapped = tools.filter((tool) => matchesLeaf(tool, READ_CANDIDATES)).map((tool) => ({ tool, args: readArguments(tool.inputSchemaValue, path82) })).find((candidate) => candidate.args !== null);
25293
26050
  if (!mapped?.args) return null;
25294
26051
  return redirect(
25295
26052
  exec2,
@@ -25301,14 +26058,14 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25301
26058
  "readResult",
25302
26059
  "read-direct",
25303
26060
  mapped.args,
25304
- { path: path72 }
26061
+ { path: path82 }
25305
26062
  );
25306
26063
  }
25307
- if (isRecord8(exec2.grepArgs)) {
26064
+ if (isRecord9(exec2.grepArgs)) {
25308
26065
  const grepArgs = exec2.grepArgs;
25309
26066
  const pattern = stringValue2(grepArgs.pattern);
25310
26067
  if (!pattern.trim()) return null;
25311
- const path72 = stringValue2(grepArgs.path) || ".";
26068
+ const path82 = stringValue2(grepArgs.path) || ".";
25312
26069
  const glob = stringValue2(grepArgs.glob);
25313
26070
  const outputMode = normalizedGrepOutputMode(stringValue2(grepArgs.outputMode));
25314
26071
  if (!outputMode) return null;
@@ -25324,7 +26081,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25324
26081
  if (numericOptions.some((value) => typeof value === "number" && value < 0)) return null;
25325
26082
  const mappingInput = {
25326
26083
  pattern,
25327
- path: path72,
26084
+ path: path82,
25328
26085
  glob,
25329
26086
  outputMode,
25330
26087
  caseInsensitive: grepArgs.caseInsensitive === true,
@@ -25341,7 +26098,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25341
26098
  const mapped = tools.filter((tool) => matchesLeaf(tool, GREP_CANDIDATES)).map((tool) => ({ tool, args: grepArguments(tool, mappingInput) })).find((candidate) => candidate.args !== null);
25342
26099
  const nativeArgs = {
25343
26100
  pattern,
25344
- path: path72,
26101
+ path: path82,
25345
26102
  outputMode,
25346
26103
  ...glob ? { glob } : {},
25347
26104
  ...positiveNumber(grepArgs.offset) === void 0 ? {} : { offset: String(positiveNumber(grepArgs.offset)) }
@@ -25378,15 +26135,15 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25378
26135
  nativeArgs
25379
26136
  );
25380
26137
  }
25381
- if (isRecord8(exec2.shellArgs) || isRecord8(exec2.shellStreamArgs)) {
25382
- const argsRecord = isRecord8(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
26138
+ if (isRecord9(exec2.shellArgs) || isRecord9(exec2.shellStreamArgs)) {
26139
+ const argsRecord = isRecord9(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
25383
26140
  const command = stringValue2(argsRecord.command);
25384
26141
  if (!command) return null;
25385
26142
  const cwd = stringValue2(argsRecord.workingDirectory);
25386
26143
  const timeout = positiveNumber(argsRecord.timeout) ?? positiveNumber(argsRecord.hardTimeout);
25387
26144
  const mapped = tools.filter((tool) => matchesLeaf(tool, SHELL_CANDIDATES)).map((tool) => ({ tool, args: shellArguments(tool.inputSchemaValue, command, cwd || void 0, timeout) })).find((candidate) => candidate.args !== null);
25388
26145
  if (!mapped?.args) return null;
25389
- const stream = isRecord8(exec2.shellStreamArgs);
26146
+ const stream = isRecord9(exec2.shellStreamArgs);
25390
26147
  return redirect(
25391
26148
  exec2,
25392
26149
  mapped.tool,
@@ -25476,9 +26233,9 @@ function cursorNativeRedirectErrorReplies(correlation, error51) {
25476
26233
  }
25477
26234
  }
25478
26235
  }
25479
- function readArguments(schema, path72) {
26236
+ function readArguments(schema, path82) {
25480
26237
  const pathKey = firstSchemaProperty(schema, ["file_path", "path"]);
25481
- return pathKey ? { [pathKey]: path72 } : null;
26238
+ return pathKey ? { [pathKey]: path82 } : null;
25482
26239
  }
25483
26240
  function grepArguments(tool, input) {
25484
26241
  const leaf = normalizedLeaf(tool.clientName);
@@ -25639,7 +26396,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25639
26396
  output.slice(CURSOR_GREP_RECEIPT_PREFIX.length).trim(),
25640
26397
  "base64url"
25641
26398
  ).toString("utf8"));
25642
- if (!isRecord8(decoded)) throw new Error("receipt is not an object");
26399
+ if (!isRecord9(decoded)) throw new Error("receipt is not an object");
25643
26400
  if (decoded.ok === false && typeof decoded.error === "string") {
25644
26401
  return { ok: false, error: decoded.error };
25645
26402
  }
@@ -25652,7 +26409,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25652
26409
  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)) {
25653
26410
  throw new Error("receipt counts are invalid");
25654
26411
  }
25655
- 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")) {
26412
+ 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")) {
25656
26413
  throw new Error("receipt matches are invalid");
25657
26414
  }
25658
26415
  for (const key of ["totalFiles", "totalLines", "totalMatchedLines"]) {
@@ -25670,7 +26427,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25670
26427
  }
25671
26428
  }
25672
26429
  function buildGrepReceiptSuccess(args, receipt) {
25673
- const path72 = args.path || ".";
26430
+ const path82 = args.path || ".";
25674
26431
  let result;
25675
26432
  if (receipt.outputMode === "files_with_matches") {
25676
26433
  result = {
@@ -25716,15 +26473,15 @@ function buildGrepReceiptSuccess(args, receipt) {
25716
26473
  }
25717
26474
  return {
25718
26475
  pattern: args.pattern ?? "",
25719
- path: path72,
26476
+ path: path82,
25720
26477
  outputMode: receipt.outputMode,
25721
- workspaceResults: { [path72]: result }
26478
+ workspaceResults: { [path82]: result }
25722
26479
  };
25723
26480
  }
25724
26481
  function buildGrepSuccess(args, output) {
25725
26482
  const outputMode = normalizedGrepOutputMode(args.outputMode) ?? "content";
25726
26483
  const lines = output.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.length > 0 && !line.startsWith("[") && !/^no matches/i.test(line));
25727
- const path72 = args.path || ".";
26484
+ const path82 = args.path || ".";
25728
26485
  let result;
25729
26486
  if (outputMode === "files_with_matches") {
25730
26487
  result = {
@@ -25787,9 +26544,9 @@ function buildGrepSuccess(args, output) {
25787
26544
  }
25788
26545
  return {
25789
26546
  pattern: args.pattern ?? "",
25790
- path: path72,
26547
+ path: path82,
25791
26548
  outputMode,
25792
- workspaceResults: { [path72]: result }
26549
+ workspaceResults: { [path82]: result }
25793
26550
  };
25794
26551
  }
25795
26552
  function parseCallerShellOutput(output, isError) {
@@ -25851,7 +26608,7 @@ function redirect(exec2, tool, providerIdentifier, messageId, execId, execCase,
25851
26608
  }
25852
26609
  function execArgsToolCallId(exec2) {
25853
26610
  for (const value of Object.values(exec2)) {
25854
- if (!isRecord8(value)) continue;
26611
+ if (!isRecord9(value)) continue;
25855
26612
  const toolCallId = stringValue2(value.toolCallId);
25856
26613
  if (toolCallId) return toolCallId;
25857
26614
  }
@@ -25861,7 +26618,7 @@ function matchesLeaf(tool, candidates) {
25861
26618
  return candidates.some((candidate) => normalizedLeaf(tool.clientName) === normalizedLeaf(candidate));
25862
26619
  }
25863
26620
  function normalizedLeaf(name) {
25864
- return toolLeafName2(name).replace(/[_-]/g, "").toLowerCase();
26621
+ return toolLeafName3(name).replace(/[_-]/g, "").toLowerCase();
25865
26622
  }
25866
26623
  function normalizedGrepOutputMode(value) {
25867
26624
  if (!value || value === "content") return "content";
@@ -25872,7 +26629,7 @@ function firstSchemaProperty(schema, candidates) {
25872
26629
  return candidates.find((candidate) => schemaHasProperty(schema, candidate));
25873
26630
  }
25874
26631
  function schemaHasProperty(schema, name) {
25875
- return isRecord8(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
26632
+ return isRecord9(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
25876
26633
  }
25877
26634
  function execReply2(exec2, resultName, result) {
25878
26635
  return {
@@ -25883,7 +26640,7 @@ function execReply2(exec2, resultName, result) {
25883
26640
  }
25884
26641
  };
25885
26642
  }
25886
- function toolLeafName2(name) {
26643
+ function toolLeafName3(name) {
25887
26644
  return name.split("__").at(-1) ?? name;
25888
26645
  }
25889
26646
  function numberValue2(value) {
@@ -25893,13 +26650,13 @@ function numberOrUndefined(value) {
25893
26650
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
25894
26651
  }
25895
26652
  function positiveNumber(value) {
25896
- const number32 = numberOrUndefined(value);
25897
- return number32 !== void 0 && number32 > 0 ? number32 : void 0;
26653
+ const number42 = numberOrUndefined(value);
26654
+ return number42 !== void 0 && number42 > 0 ? number42 : void 0;
25898
26655
  }
25899
26656
  function stringValue2(value) {
25900
26657
  return typeof value === "string" ? value : "";
25901
26658
  }
25902
- function isRecord8(value) {
26659
+ function isRecord9(value) {
25903
26660
  return typeof value === "object" && value !== null && !Array.isArray(value);
25904
26661
  }
25905
26662
  var cursorAgentDescriptor = [
@@ -26730,18 +27487,18 @@ function decodeCursorServerMessage(payload) {
26730
27487
  const message = fromBinary(AgentServerMessageSchema, payload);
26731
27488
  const unknownExecFields = extractCursorUnknownExecFields(message);
26732
27489
  const json2 = toJson(AgentServerMessageSchema, message);
26733
- if (!isRecord9(json2)) throw new TypeError("Cursor server frame was not a message object");
27490
+ if (!isRecord10(json2)) throw new TypeError("Cursor server frame was not a message object");
26734
27491
  if (unknownExecFields.length > 0) {
26735
27492
  Object.defineProperty(json2, CURSOR_UNKNOWN_EXEC_FIELDS, { value: unknownExecFields });
26736
27493
  }
26737
27494
  return json2;
26738
27495
  }
26739
27496
  function extractCursorUnknownExecFields(message) {
26740
- if (!isRecord9(message) || !isRecord9(message.message)) return [];
26741
- if (message.message.case !== "execServerMessage" || !isRecord9(message.message.value)) return [];
27497
+ if (!isRecord10(message) || !isRecord10(message.message)) return [];
27498
+ if (message.message.case !== "execServerMessage" || !isRecord10(message.message.value)) return [];
26742
27499
  const fields = message.message.value.$unknown;
26743
27500
  if (!Array.isArray(fields)) return [];
26744
- return fields.filter((field) => isRecord9(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
27501
+ return fields.filter((field) => isRecord10(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
26745
27502
  }
26746
27503
  function parseConnectEndStreamError(payload) {
26747
27504
  try {
@@ -27036,7 +27793,7 @@ function cursorToolArgumentBytes(argumentsText) {
27036
27793
  } catch {
27037
27794
  return {};
27038
27795
  }
27039
- if (!isRecord9(parsed)) return {};
27796
+ if (!isRecord10(parsed)) return {};
27040
27797
  return Object.fromEntries(Object.entries(parsed).map(([name, value]) => [
27041
27798
  name,
27042
27799
  Buffer.from(toBinary(ValueSchema, fromJson(ValueSchema, value))).toString("base64")
@@ -28013,7 +28770,7 @@ function createCursorLiveRun(options) {
28013
28770
  let blobFetchBytes = 0;
28014
28771
  let blobFetchMisses = 0;
28015
28772
  let redirectOperationSequence = 0;
28016
- const usage3 = (segment) => {
28773
+ const usage4 = (segment) => {
28017
28774
  const outputTokens = Math.max(
28018
28775
  segment.contextOutputTokens,
28019
28776
  estimateTokens(segment.outputText, model)
@@ -28059,7 +28816,7 @@ function createCursorLiveRun(options) {
28059
28816
  else if (segment.started) {
28060
28817
  segment.queue.push({
28061
28818
  type: "response.completed",
28062
- response: { id: segment.responseId, model, usage: usage3(segment) }
28819
+ response: { id: segment.responseId, model, usage: usage4(segment) }
28063
28820
  });
28064
28821
  }
28065
28822
  report("turn.finish", {
@@ -28126,7 +28883,7 @@ function createCursorLiveRun(options) {
28126
28883
  response: {
28127
28884
  id: activeSegment.responseId,
28128
28885
  model,
28129
- usage: usage3(activeSegment)
28886
+ usage: usage4(activeSegment)
28130
28887
  }
28131
28888
  });
28132
28889
  }
@@ -28316,7 +29073,7 @@ ${argumentsText}`;
28316
29073
  const handleFrame = (frame, replayed = false) => {
28317
29074
  const unknownExecFields = frame[CURSOR_UNKNOWN_EXEC_FIELDS] ?? [];
28318
29075
  lastFrame = describeCursorServerFrame(frame, unknownExecFields);
28319
- const tokenDetails = isRecord9(frame.conversationCheckpointUpdate) && isRecord9(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
29076
+ const tokenDetails = isRecord10(frame.conversationCheckpointUpdate) && isRecord10(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
28320
29077
  const checkpointContextTokens = positiveTokenCount(tokenDetails?.usedTokens);
28321
29078
  const checkpointContextWindow = positiveTokenCount(tokenDetails?.maxTokens);
28322
29079
  if (!replayed) {
@@ -28329,7 +29086,7 @@ ${argumentsText}`;
28329
29086
  ...checkpointContextWindow === void 0 ? {} : { contextWindow: checkpointContextWindow }
28330
29087
  });
28331
29088
  }
28332
- if (isRecord9(frame.conversationCheckpointUpdate)) {
29089
+ if (isRecord10(frame.conversationCheckpointUpdate)) {
28333
29090
  if (checkpointContextTokens !== void 0) {
28334
29091
  wireLog("cursor.wire.checkpoint", {
28335
29092
  model: diagnosticModel,
@@ -28352,7 +29109,7 @@ ${argumentsText}`;
28352
29109
  }
28353
29110
  return;
28354
29111
  }
28355
- if (isRecord9(frame.kvServerMessage)) {
29112
+ if (isRecord10(frame.kvServerMessage)) {
28356
29113
  const kv = kvReply(frame.kvServerMessage, blobs);
28357
29114
  stream.write(encodeCursorClientMessage(kv.message));
28358
29115
  if (kv.fetch) {
@@ -28373,7 +29130,7 @@ ${argumentsText}`;
28373
29130
  });
28374
29131
  return;
28375
29132
  }
28376
- if (isRecord9(frame.interactionQuery)) {
29133
+ if (isRecord10(frame.interactionQuery)) {
28377
29134
  const reply = cursorInteractionQueryReply(frame.interactionQuery);
28378
29135
  stream.write(encodeCursorClientMessage(reply.message));
28379
29136
  report("client.reply", { model: diagnosticModel, reply: reply.replyKind });
@@ -28389,7 +29146,7 @@ ${argumentsText}`;
28389
29146
  }
28390
29147
  return;
28391
29148
  }
28392
- if (isRecord9(frame.error)) {
29149
+ if (isRecord10(frame.error)) {
28393
29150
  if (state === "attached") {
28394
29151
  emit({ type: "error", error: cursorError(frame.error) });
28395
29152
  completeRun("server_error");
@@ -28418,8 +29175,8 @@ ${argumentsText}`;
28418
29175
  return;
28419
29176
  }
28420
29177
  if (state !== "attached") return;
28421
- if (isRecord9(frame.execServerMessage)) {
28422
- if (isRecord9(frame.execServerMessage.requestContextArgs)) {
29178
+ if (isRecord10(frame.execServerMessage)) {
29179
+ if (isRecord10(frame.execServerMessage.requestContextArgs)) {
28423
29180
  stream.write(encodeCursorClientMessage(cursorRequestContextReply(frame.execServerMessage, tools)));
28424
29181
  report("client.reply", { model: diagnosticModel, reply: "exec.requestContext" });
28425
29182
  return;
@@ -28508,10 +29265,10 @@ ${argumentsText}`;
28508
29265
  }
28509
29266
  return;
28510
29267
  }
28511
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29268
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
28512
29269
  if (update === void 0) return;
28513
29270
  if (isSettledToolUpdate(update)) return;
28514
- if (isRecord9(update.textDelta) && typeof update.textDelta.text === "string") {
29271
+ if (isRecord10(update.textDelta) && typeof update.textDelta.text === "string") {
28515
29272
  activeSegment.outputText += update.textDelta.text;
28516
29273
  emit({
28517
29274
  type: "response.output_text.delta",
@@ -28522,7 +29279,7 @@ ${argumentsText}`;
28522
29279
  });
28523
29280
  return;
28524
29281
  }
28525
- if (isRecord9(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
29282
+ if (isRecord10(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
28526
29283
  activeSegment.outputText += update.thinkingDelta.text;
28527
29284
  emit({
28528
29285
  type: "response.reasoning_summary_text.delta",
@@ -28532,12 +29289,12 @@ ${argumentsText}`;
28532
29289
  });
28533
29290
  return;
28534
29291
  }
28535
- if (isRecord9(update.tokenDelta)) {
29292
+ if (isRecord10(update.tokenDelta)) {
28536
29293
  const tokens = positiveTokenCount(update.tokenDelta.tokens);
28537
29294
  if (tokens !== void 0) activeSegment.contextOutputTokens += tokens;
28538
29295
  return;
28539
29296
  }
28540
- if (isRecord9(update.toolCallStarted)) {
29297
+ if (isRecord10(update.toolCallStarted)) {
28541
29298
  const wireCall = mcpCallFromToolUpdate(update.toolCallStarted);
28542
29299
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28543
29300
  if (call) {
@@ -28547,7 +29304,7 @@ ${argumentsText}`;
28547
29304
  }
28548
29305
  return;
28549
29306
  }
28550
- if (isRecord9(update.partialToolCall)) {
29307
+ if (isRecord10(update.partialToolCall)) {
28551
29308
  const wireCall = mcpCallFromToolUpdate(update.partialToolCall);
28552
29309
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28553
29310
  if (!call) return;
@@ -28558,7 +29315,7 @@ ${argumentsText}`;
28558
29315
  rescheduleToolTurnFinish();
28559
29316
  return;
28560
29317
  }
28561
- if (isRecord9(update.toolCallCompleted)) {
29318
+ if (isRecord10(update.toolCallCompleted)) {
28562
29319
  const wireCall = mcpCallFromToolUpdate(update.toolCallCompleted);
28563
29320
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28564
29321
  if (!call) return;
@@ -28571,7 +29328,7 @@ ${argumentsText}`;
28571
29328
  rescheduleToolTurnFinish();
28572
29329
  return;
28573
29330
  }
28574
- if (isRecord9(update.turnEnded)) completeRun("turn_ended");
29331
+ if (isRecord10(update.turnEnded)) completeRun("turn_ended");
28575
29332
  };
28576
29333
  const eventsFor = (segment) => (async function* () {
28577
29334
  try {
@@ -28781,34 +29538,34 @@ var CURSOR_INTERACTION_QUERY_CASES = [
28781
29538
  ];
28782
29539
  var CURSOR_KV_CASES = ["getBlobArgs", "setBlobArgs"];
28783
29540
  function describeCursorServerFrame(frame, unknownExecFields = []) {
28784
- if (isRecord9(frame.interactionUpdate)) {
29541
+ if (isRecord10(frame.interactionUpdate)) {
28785
29542
  return `interactionUpdate.${cursorNestedRecordCase(
28786
29543
  frame.interactionUpdate,
28787
29544
  CURSOR_INTERACTION_UPDATE_CASES
28788
29545
  )}`;
28789
29546
  }
28790
- if (isRecord9(frame.execServerMessage)) {
29547
+ if (isRecord10(frame.execServerMessage)) {
28791
29548
  const knownCase = cursorNestedRecordCase(frame.execServerMessage, CURSOR_EXEC_CASES);
28792
29549
  return `execServerMessage.${knownCase === "unknown" ? cursorUnknownExecCaseName(unknownExecFields) : knownCase}`;
28793
29550
  }
28794
- if (isRecord9(frame.interactionQuery)) {
29551
+ if (isRecord10(frame.interactionQuery)) {
28795
29552
  return `interactionQuery.${cursorNestedRecordCase(
28796
29553
  frame.interactionQuery,
28797
29554
  CURSOR_INTERACTION_QUERY_CASES
28798
29555
  )}`;
28799
29556
  }
28800
- if (isRecord9(frame.kvServerMessage)) {
29557
+ if (isRecord10(frame.kvServerMessage)) {
28801
29558
  return `kvServerMessage.${cursorNestedRecordCase(frame.kvServerMessage, CURSOR_KV_CASES)}`;
28802
29559
  }
28803
- if (isRecord9(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
28804
- if (isRecord9(frame.error)) return "error";
29560
+ if (isRecord10(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
29561
+ if (isRecord10(frame.error)) return "error";
28805
29562
  return "unknown";
28806
29563
  }
28807
29564
  function isCursorHeartbeatFrame(frame) {
28808
- return isRecord9(frame.interactionUpdate) && isRecord9(frame.interactionUpdate.heartbeat);
29565
+ return isRecord10(frame.interactionUpdate) && isRecord10(frame.interactionUpdate.heartbeat);
28809
29566
  }
28810
29567
  function cursorNestedRecordCase(value, cases) {
28811
- return cases.find((candidate) => isRecord9(value[candidate])) ?? "unknown";
29568
+ return cases.find((candidate) => isRecord10(value[candidate])) ?? "unknown";
28812
29569
  }
28813
29570
  function positiveTokenCount(value) {
28814
29571
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) return void 0;
@@ -28820,8 +29577,8 @@ function cursorInteractionQueryReply(query) {
28820
29577
  const response = (result = {}) => ({
28821
29578
  interactionResponse: { id, ...result }
28822
29579
  });
28823
- if (isRecord9(query.createPlanRequestQuery)) {
28824
- const args = isRecord9(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
29580
+ if (isRecord10(query.createPlanRequestQuery)) {
29581
+ const args = isRecord10(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
28825
29582
  const name = stringValue3(args?.name)?.trim();
28826
29583
  const overview = stringValue3(args?.overview)?.trim();
28827
29584
  const plan = stringValue3(args?.plan)?.trim();
@@ -28837,7 +29594,7 @@ function cursorInteractionQueryReply(query) {
28837
29594
  ` } : {}
28838
29595
  };
28839
29596
  }
28840
- if (isRecord9(query.askQuestionInteractionQuery)) {
29597
+ if (isRecord10(query.askQuestionInteractionQuery)) {
28841
29598
  return {
28842
29599
  message: response({
28843
29600
  askQuestionInteractionResponse: {
@@ -28847,7 +29604,7 @@ function cursorInteractionQueryReply(query) {
28847
29604
  replyKind: "interaction.askQuestion.rejected"
28848
29605
  };
28849
29606
  }
28850
- if (isRecord9(query.switchModeRequestQuery)) {
29607
+ if (isRecord10(query.switchModeRequestQuery)) {
28851
29608
  return {
28852
29609
  message: response({
28853
29610
  switchModeRequestResponse: {
@@ -28857,19 +29614,19 @@ function cursorInteractionQueryReply(query) {
28857
29614
  replyKind: "interaction.switchMode.rejected"
28858
29615
  };
28859
29616
  }
28860
- if (isRecord9(query.webSearchRequestQuery)) {
29617
+ if (isRecord10(query.webSearchRequestQuery)) {
28861
29618
  return {
28862
29619
  message: response({ webSearchRequestResponse: { approved: {} } }),
28863
29620
  replyKind: "interaction.webSearch.approved"
28864
29621
  };
28865
29622
  }
28866
- if (isRecord9(query.exaSearchRequestQuery)) {
29623
+ if (isRecord10(query.exaSearchRequestQuery)) {
28867
29624
  return {
28868
29625
  message: response({ exaSearchRequestResponse: { approved: {} } }),
28869
29626
  replyKind: "interaction.exaSearch.approved"
28870
29627
  };
28871
29628
  }
28872
- if (isRecord9(query.exaFetchRequestQuery)) {
29629
+ if (isRecord10(query.exaFetchRequestQuery)) {
28873
29630
  return {
28874
29631
  message: response({ exaFetchRequestResponse: { approved: {} } }),
28875
29632
  replyKind: "interaction.exaFetch.approved"
@@ -28879,7 +29636,7 @@ function cursorInteractionQueryReply(query) {
28879
29636
  }
28880
29637
  function kvReply(kv, blobs) {
28881
29638
  const id = kv.id ?? 0;
28882
- if (isRecord9(kv.getBlobArgs)) {
29639
+ if (isRecord10(kv.getBlobArgs)) {
28883
29640
  const blobId = typeof kv.getBlobArgs.blobId === "string" ? kv.getBlobArgs.blobId : "";
28884
29641
  const blobData = blobs.get(blobId);
28885
29642
  return {
@@ -28891,7 +29648,7 @@ function kvReply(kv, blobs) {
28891
29648
  }
28892
29649
  };
28893
29650
  }
28894
- if (isRecord9(kv.setBlobArgs)) {
29651
+ if (isRecord10(kv.setBlobArgs)) {
28895
29652
  const blobId = typeof kv.setBlobArgs.blobId === "string" ? kv.setBlobArgs.blobId : "";
28896
29653
  const blobData = typeof kv.setBlobArgs.blobData === "string" ? kv.setBlobArgs.blobData : "";
28897
29654
  if (blobId) blobs.set(blobId, blobData);
@@ -28942,7 +29699,7 @@ function repairCursorArgumentValue(value, schema) {
28942
29699
  return { value: String(value), count: 1 };
28943
29700
  }
28944
29701
  if (Array.isArray(value)) {
28945
- const itemSchema = isRecord9(schema) ? schema.items : void 0;
29702
+ const itemSchema = isRecord10(schema) ? schema.items : void 0;
28946
29703
  if (itemSchema === void 0) return { value, count: 0 };
28947
29704
  let repairedValues;
28948
29705
  let count2 = 0;
@@ -28955,7 +29712,7 @@ function repairCursorArgumentValue(value, schema) {
28955
29712
  });
28956
29713
  return { value: repairedValues ?? value, count: count2 };
28957
29714
  }
28958
- if (!isRecord9(value) || !isRecord9(schema) || !isRecord9(schema.properties)) {
29715
+ if (!isRecord10(value) || !isRecord10(schema) || !isRecord10(schema.properties)) {
28959
29716
  return { value, count: 0 };
28960
29717
  }
28961
29718
  let repairedValue;
@@ -28971,12 +29728,12 @@ function repairCursorArgumentValue(value, schema) {
28971
29728
  return { value: repairedValue ?? value, count };
28972
29729
  }
28973
29730
  function cursorSchemaRequiresString(schema) {
28974
- if (!isRecord9(schema)) return false;
29731
+ if (!isRecord10(schema)) return false;
28975
29732
  if (schema.type === "string") return true;
28976
29733
  return Array.isArray(schema.type) && schema.type.includes("string") && schema.type.every((type) => type === "string" || type === "null");
28977
29734
  }
28978
29735
  function mcpCallFromToolUpdate(value) {
28979
- const toolCall = isRecord9(value.toolCall) ? value.toolCall : void 0;
29736
+ const toolCall = isRecord10(value.toolCall) ? value.toolCall : void 0;
28980
29737
  const args = toolCall ? mcpArgsFromToolCall(toolCall) : void 0;
28981
29738
  if (!args) return null;
28982
29739
  const publicCallId = stringValue3(value.callId);
@@ -29001,7 +29758,7 @@ var CURSOR_TOOL_UPDATE_CASES = [
29001
29758
  function cursorToolUpdateIdentifiers(update) {
29002
29759
  for (const key of CURSOR_TOOL_UPDATE_CASES) {
29003
29760
  const value = update[key];
29004
- if (!isRecord9(value)) continue;
29761
+ if (!isRecord10(value)) continue;
29005
29762
  const call = mcpCallFromToolUpdate(value);
29006
29763
  if (!call) return [];
29007
29764
  return [...new Set(
@@ -29011,9 +29768,9 @@ function cursorToolUpdateIdentifiers(update) {
29011
29768
  return void 0;
29012
29769
  }
29013
29770
  function isCursorClientToolFrame(frame, tools, redirectTools) {
29014
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29771
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29015
29772
  if (update !== void 0) return cursorToolUpdateIdentifiers(update) !== void 0;
29016
- const exec2 = isRecord9(frame.execServerMessage) ? frame.execServerMessage : void 0;
29773
+ const exec2 = isRecord10(frame.execServerMessage) ? frame.execServerMessage : void 0;
29017
29774
  if (exec2 === void 0) return false;
29018
29775
  const wireCall = mcpCallFromExecMessage(exec2);
29019
29776
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
@@ -29029,16 +29786,16 @@ function isCursorClientToolFrame(frame, tools, redirectTools) {
29029
29786
  ) !== null;
29030
29787
  }
29031
29788
  function isCursorParkedResidueFrame(frame, parked) {
29032
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29789
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29033
29790
  if (update === void 0) return false;
29034
- if (isRecord9(update.tokenDelta)) return true;
29791
+ if (isRecord10(update.tokenDelta)) return true;
29035
29792
  const identifiers = cursorToolUpdateIdentifiers(update);
29036
29793
  if (identifiers === void 0 || identifiers.length === 0 || parked === void 0) return false;
29037
29794
  const sealed = new Set(parked.flatMap((call) => [call.callId, call.toolCallId]));
29038
29795
  return identifiers.some((identifier) => sealed.has(identifier));
29039
29796
  }
29040
29797
  function mcpCallFromExecMessage(value) {
29041
- const args = isRecord9(value.mcpArgs) ? value.mcpArgs : void 0;
29798
+ const args = isRecord10(value.mcpArgs) ? value.mcpArgs : void 0;
29042
29799
  if (!args) return null;
29043
29800
  const toolCallId = stringValue3(args.toolCallId);
29044
29801
  if (!toolCallId) return null;
@@ -29056,14 +29813,14 @@ function mcpCallFromExecMessage(value) {
29056
29813
  };
29057
29814
  }
29058
29815
  function mcpArgsFromToolCall(toolCall) {
29059
- const direct = isRecord9(toolCall.mcpToolCall) ? toolCall.mcpToolCall : void 0;
29060
- if (direct && isRecord9(direct.args)) return direct.args;
29061
- const tool = isRecord9(toolCall.tool) ? toolCall.tool : void 0;
29062
- const nested = tool && isRecord9(tool.mcpToolCall) ? tool.mcpToolCall : void 0;
29063
- return nested && isRecord9(nested.args) ? nested.args : void 0;
29816
+ const direct = isRecord10(toolCall.mcpToolCall) ? toolCall.mcpToolCall : void 0;
29817
+ if (direct && isRecord10(direct.args)) return direct.args;
29818
+ const tool = isRecord10(toolCall.tool) ? toolCall.tool : void 0;
29819
+ const nested = tool && isRecord10(tool.mcpToolCall) ? tool.mcpToolCall : void 0;
29820
+ return nested && isRecord10(nested.args) ? nested.args : void 0;
29064
29821
  }
29065
29822
  function cursorMcpArguments(args) {
29066
- if (!isRecord9(args.args) || Object.keys(args.args).length === 0) return {};
29823
+ if (!isRecord10(args.args) || Object.keys(args.args).length === 0) return {};
29067
29824
  const decoded = {};
29068
29825
  for (const [name, value] of Object.entries(args.args)) {
29069
29826
  if (typeof value !== "string") {
@@ -29138,7 +29895,7 @@ function cursorError(value) {
29138
29895
  message: typeof value.message === "string" ? value.message : "Cursor request failed"
29139
29896
  };
29140
29897
  }
29141
- function isRecord9(value) {
29898
+ function isRecord10(value) {
29142
29899
  return typeof value === "object" && value !== null && !Array.isArray(value);
29143
29900
  }
29144
29901
  var DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES = 4 * 1024 * 1024;
@@ -29172,7 +29929,7 @@ var CURSOR_DIAGNOSTIC_EVENTS = /* @__PURE__ */ new Set([
29172
29929
  "turn.finish"
29173
29930
  ]);
29174
29931
  function createCursorDiagnosticLog(dir, options = {}) {
29175
- const logPath = path18__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
29932
+ const logPath = path19__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
29176
29933
  const backupPath = `${logPath}.1`;
29177
29934
  const maxBytes = positiveInteger2(options.maxBytes) ?? DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES;
29178
29935
  let initialized = false;
@@ -29230,43 +29987,43 @@ function createCursorDiagnosticLog(dir, options = {}) {
29230
29987
  }
29231
29988
  function serializeCursorDiagnosticEvent(event) {
29232
29989
  if (!CURSOR_DIAGNOSTIC_EVENTS.has(event.event)) return null;
29233
- const record32 = {
29990
+ const record42 = {
29234
29991
  timestamp: safeString(event.timestamp, 40),
29235
29992
  runId: safeString(event.runId, 64),
29236
29993
  event: event.event,
29237
29994
  elapsedMs: safeNumber(event.elapsedMs)
29238
29995
  };
29239
- addString(record32, "model", event.model, 128);
29240
- addString(record32, "wireModel", event.wireModel, 128);
29241
- addString(record32, "previousWireModel", event.previousWireModel, 128);
29996
+ addString(record42, "model", event.model, 128);
29997
+ addString(record42, "wireModel", event.wireModel, 128);
29998
+ addString(record42, "previousWireModel", event.previousWireModel, 128);
29242
29999
  if (event.requestedEffort && CURSOR_DIAGNOSTIC_EFFORTS.has(event.requestedEffort)) {
29243
- record32.requestedEffort = event.requestedEffort;
29244
- }
29245
- if (event.turn === "prompt" || event.turn === "tool-continuation") record32.turn = event.turn;
29246
- addNumber(record32, "status", event.status);
29247
- addString(record32, "frame", event.frame, 128);
29248
- addString(record32, "reply", event.reply, 128);
29249
- addNumber(record32, "sequence", event.sequence);
29250
- addNumber(record32, "count", event.count);
29251
- addNumber(record32, "frameCount", event.frameCount);
29252
- addString(record32, "lastFrame", event.lastFrame, 128);
29253
- addNumber(record32, "toolCount", event.toolCount);
29254
- addNumber(record32, "argumentRepairCount", event.argumentRepairCount);
29255
- addNumber(record32, "estimatedInputTokens", event.estimatedInputTokens);
29256
- addNumber(record32, "contextTokens", event.contextTokens);
29257
- addNumber(record32, "contextWindow", event.contextWindow);
29258
- addString(record32, "outcome", event.outcome, 128);
29259
- addNumber(record32, "operationSequence", event.operationSequence);
29260
- addString(record32, "adapter", event.adapter, 32);
29261
- addString(record32, "error", event.error, 128);
29262
- return `${JSON.stringify(record32)}
30000
+ record42.requestedEffort = event.requestedEffort;
30001
+ }
30002
+ if (event.turn === "prompt" || event.turn === "tool-continuation") record42.turn = event.turn;
30003
+ addNumber(record42, "status", event.status);
30004
+ addString(record42, "frame", event.frame, 128);
30005
+ addString(record42, "reply", event.reply, 128);
30006
+ addNumber(record42, "sequence", event.sequence);
30007
+ addNumber(record42, "count", event.count);
30008
+ addNumber(record42, "frameCount", event.frameCount);
30009
+ addString(record42, "lastFrame", event.lastFrame, 128);
30010
+ addNumber(record42, "toolCount", event.toolCount);
30011
+ addNumber(record42, "argumentRepairCount", event.argumentRepairCount);
30012
+ addNumber(record42, "estimatedInputTokens", event.estimatedInputTokens);
30013
+ addNumber(record42, "contextTokens", event.contextTokens);
30014
+ addNumber(record42, "contextWindow", event.contextWindow);
30015
+ addString(record42, "outcome", event.outcome, 128);
30016
+ addNumber(record42, "operationSequence", event.operationSequence);
30017
+ addString(record42, "adapter", event.adapter, 32);
30018
+ addString(record42, "error", event.error, 128);
30019
+ return `${JSON.stringify(record42)}
29263
30020
  `;
29264
30021
  }
29265
- function addString(record32, key, value, maxLength) {
29266
- if (value !== void 0) record32[key] = safeString(value, maxLength);
30022
+ function addString(record42, key, value, maxLength) {
30023
+ if (value !== void 0) record42[key] = safeString(value, maxLength);
29267
30024
  }
29268
- function addNumber(record32, key, value) {
29269
- if (value !== void 0) record32[key] = safeNumber(value);
30025
+ function addNumber(record42, key, value) {
30026
+ if (value !== void 0) record42[key] = safeNumber(value);
29270
30027
  }
29271
30028
  function safeString(value, maxLength) {
29272
30029
  return value.replace(/[\r\n\t]/g, " ").slice(0, maxLength);
@@ -29316,8 +30073,8 @@ function kimiAnthropicHeaders(requestHeaders, apiKey) {
29316
30073
  return headers;
29317
30074
  }
29318
30075
  function normalizeAiGatewaySettings(value) {
29319
- if (!isRecord10(value) || value.version !== 1) return { version: 1 };
29320
- const models = Array.isArray(value.models) ? value.models.filter((entry) => isRecord10(entry) && typeof entry.id === "string" && entry.id.length > 0).flatMap((entry) => {
30076
+ if (!isRecord11(value) || value.version !== 1) return { version: 1 };
30077
+ const models = Array.isArray(value.models) ? value.models.filter((entry) => isRecord11(entry) && typeof entry.id === "string" && entry.id.length > 0).flatMap((entry) => {
29321
30078
  const model = findGatewayModel(entry.id);
29322
30079
  if (!model) return [];
29323
30080
  const efforts = Array.isArray(entry.efforts) ? entry.efforts.filter((level) => typeof level === "string" && level.length > 0) : [];
@@ -29351,7 +30108,7 @@ function sanitizeProviderPriority(value) {
29351
30108
  }
29352
30109
  return cleaned.length > 0 ? cleaned : void 0;
29353
30110
  }
29354
- function isRecord10(value) {
30111
+ function isRecord11(value) {
29355
30112
  return typeof value === "object" && value !== null && !Array.isArray(value);
29356
30113
  }
29357
30114
  function resolveAiGatewaySelection(settings2) {
@@ -29391,15 +30148,15 @@ function sortGatewayModelsByProvider(models) {
29391
30148
  function parseAiGatewayUpdate(value) {
29392
30149
  if (value === null) return { ok: true, value: void 0 };
29393
30150
  if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false };
29394
- const record32 = value;
29395
- const extraKeys = Object.keys(record32).filter(
30151
+ const record42 = value;
30152
+ const extraKeys = Object.keys(record42).filter(
29396
30153
  (key) => key !== "models" && key !== "defaultModel" && key !== "providerPriority"
29397
30154
  );
29398
30155
  if (extraKeys.length > 0) return { ok: false };
29399
30156
  const models = [];
29400
- if (record32.models !== void 0) {
29401
- if (!Array.isArray(record32.models)) return { ok: false };
29402
- for (const raw of record32.models) {
30157
+ if (record42.models !== void 0) {
30158
+ if (!Array.isArray(record42.models)) return { ok: false };
30159
+ for (const raw of record42.models) {
29403
30160
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false };
29404
30161
  const entry = raw;
29405
30162
  if (Object.keys(entry).some((key) => key !== "id" && key !== "efforts" && key !== "hostOnly")) {
@@ -29420,11 +30177,11 @@ function parseAiGatewayUpdate(value) {
29420
30177
  }
29421
30178
  }
29422
30179
  let providerPriority;
29423
- const hasProviderPriority = Object.prototype.hasOwnProperty.call(record32, "providerPriority");
30180
+ const hasProviderPriority = Object.prototype.hasOwnProperty.call(record42, "providerPriority");
29424
30181
  if (hasProviderPriority) {
29425
- if (!Array.isArray(record32.providerPriority)) return { ok: false };
30182
+ if (!Array.isArray(record42.providerPriority)) return { ok: false };
29426
30183
  providerPriority = [];
29427
- for (const raw of record32.providerPriority) {
30184
+ for (const raw of record42.providerPriority) {
29428
30185
  if (typeof raw !== "string") return { ok: false };
29429
30186
  if (!GATEWAY_PROVIDERS.includes(raw)) return { ok: false };
29430
30187
  const provider = raw;
@@ -29596,6 +30353,10 @@ async function readCursorSubscriptionToken() {
29596
30353
  const credentials = await resolveCursorCredentials(defaultCredentialDeps);
29597
30354
  return credentials?.accessToken ?? null;
29598
30355
  }
30356
+ async function readXaiSubscriptionToken() {
30357
+ const credentials = await resolveXaiCliCredentials(defaultCredentialDeps);
30358
+ return credentials?.accessToken ?? null;
30359
+ }
29599
30360
  async function readCodexSubscriptionAuth() {
29600
30361
  const credentials = await resolveCodexCredentials(defaultCredentialDeps);
29601
30362
  if (!credentials?.accountId) return null;
@@ -29693,6 +30454,10 @@ function createAiGatewayRouter(deps) {
29693
30454
  for (const skill of pruned.withheld) withheldSkills.add(skill.name);
29694
30455
  if (pruned.changed) body = { ...body, messages: [...pruned.messages] };
29695
30456
  }
30457
+ if (target2 && target2.provider !== "kimi") {
30458
+ const omitted = omitClaudeWebSearchTools(body);
30459
+ if (omitted.changed) body = omitted.request;
30460
+ }
29696
30461
  let credential = "";
29697
30462
  let chatgptAccountId = "";
29698
30463
  if (target2?.provider === "cursor") {
@@ -29724,6 +30489,13 @@ function createAiGatewayRouter(deps) {
29724
30489
  return true;
29725
30490
  }
29726
30491
  credential = opencodeApiKey;
30492
+ } else if (target2?.provider === "xai") {
30493
+ const xaiToken = await deps.readXaiToken?.();
30494
+ if (!xaiToken) {
30495
+ writeAnthropicError(res, 401, "authentication_error", "No active Grok CLI sign-in was found. Run `grok login` first.");
30496
+ return true;
30497
+ }
30498
+ credential = xaiToken;
29727
30499
  }
29728
30500
  const controller = new AbortController();
29729
30501
  const abort = () => controller.abort(new Error("client disconnected"));
@@ -29760,7 +30532,7 @@ function createAiGatewayRouter(deps) {
29760
30532
  );
29761
30533
  return true;
29762
30534
  }
29763
- const gateway = deps.gateway ?? (target2.provider === "cursor" ? ownedCursorGateway : target2.provider === "opencode" ? createOpencodeGateway(opencodeGoWire(target2)) : createGatewayFor(target2, chatgptAccountId, deps.originator));
30535
+ 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));
29764
30536
  const diagnosticsEnabled = target2.provider === "cursor" ? cursorDiagnosticsEnabled() : void 0;
29765
30537
  const modelContextWindow = typeof target2.contextWindow === "number" && Number.isFinite(target2.contextWindow) && target2.contextWindow > 0 ? target2.contextWindow : void 0;
29766
30538
  const upstream = await gateway.stream(body, {
@@ -29866,11 +30638,11 @@ var LOCK_OWNER_FILE_NAME2 = "owner";
29866
30638
  var TEMP_FILE_PREFIX2 = `${AI_GATEWAY_SETTINGS_FILE_NAME}.`;
29867
30639
  function createAiGatewaySettingsStore(deps = {}) {
29868
30640
  const dataDir = deps.dataDir ?? getFleetDataDir();
29869
- const settingsPath = path18.join(dataDir, AI_GATEWAY_SETTINGS_FILE_NAME);
29870
- const legacyPath = deps.legacyDir === void 0 ? void 0 : path18.join(deps.legacyDir, AI_GATEWAY_SETTINGS_FILE_NAME);
30641
+ const settingsPath = path19.join(dataDir, AI_GATEWAY_SETTINGS_FILE_NAME);
30642
+ const legacyPath = deps.legacyDir === void 0 ? void 0 : path19.join(deps.legacyDir, AI_GATEWAY_SETTINGS_FILE_NAME);
29871
30643
  const store = createDurableJsonStore({
29872
30644
  filePath: settingsPath,
29873
- lockDir: path18.join(dataDir, LOCK_DIR_NAME2),
30645
+ lockDir: path19.join(dataDir, LOCK_DIR_NAME2),
29874
30646
  lockOwnerFileName: LOCK_OWNER_FILE_NAME2,
29875
30647
  sanitize: (value) => normalizeAiGatewaySettings(value),
29876
30648
  sensitivity: "sensitive",
@@ -30018,9 +30790,9 @@ function prepareAiGatewayLaunchProfile(profile, options) {
30018
30790
  return { ...profile, env };
30019
30791
  }
30020
30792
  function writeClaudeGatewayModelCache(baseUrl, env, homeDir, exposedModels = GATEWAY_MODELS) {
30021
- const configDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : path18__default.join(homeDir, ".claude");
30022
- const cacheDir = path18__default.join(configDir, "cache");
30023
- const cachePath = path18__default.join(cacheDir, "gateway-models.json");
30793
+ const configDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : path19__default.join(homeDir, ".claude");
30794
+ const cacheDir = path19__default.join(configDir, "cache");
30795
+ const cachePath = path19__default.join(cacheDir, "gateway-models.json");
30024
30796
  const models = buildAnthropicModelList(exposedModels).data.filter((model) => /^(claude|anthropic)/i.test(model.id)).map((model) => ({ id: model.id, display_name: model.display_name }));
30025
30797
  fs9__default.mkdirSync(cacheDir, { recursive: true, mode: 448 });
30026
30798
  writeAtomicSync(cachePath, JSON.stringify({ baseUrl, fetchedAt: Date.now(), models }), { mode: 384 });
@@ -30309,7 +31081,7 @@ async function resolveLoadout(deps) {
30309
31081
  }
30310
31082
 
30311
31083
  // ../../packages/fleet-admiral/src/ai-gateway/quota-snapshot.ts
30312
- function record3(value) {
31084
+ function record4(value) {
30313
31085
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
30314
31086
  }
30315
31087
  var AMOUNT_PATTERN = /^\d{1,15}$/;
@@ -30317,7 +31089,7 @@ var MAX_WINDOW_DURATION_MS2 = 400 * 24 * 36e5;
30317
31089
  var DURATION_BASES = /* @__PURE__ */ new Set(["upstream", "catalog"]);
30318
31090
  var START_BASES = /* @__PURE__ */ new Set(["upstream", "derived"]);
30319
31091
  function toWindowPeriod(value) {
30320
- const period = record3(value);
31092
+ const period = record4(value);
30321
31093
  if (!period) return void 0;
30322
31094
  const durationMs = period.durationMs;
30323
31095
  const durationBasis = period.durationBasis;
@@ -30334,7 +31106,7 @@ function toWindowPeriod(value) {
30334
31106
  };
30335
31107
  }
30336
31108
  function toWindowAmounts(value) {
30337
- const amounts = record3(value);
31109
+ const amounts = record4(value);
30338
31110
  if (!amounts) return void 0;
30339
31111
  const used = amounts.used;
30340
31112
  const limit = amounts.limit;
@@ -30343,14 +31115,14 @@ function toWindowAmounts(value) {
30343
31115
  return { used, limit };
30344
31116
  }
30345
31117
  function parseGatewayQuotaSnapshot(value) {
30346
- const providers = record3(record3(value)?.providers);
31118
+ const providers = record4(record4(value)?.providers);
30347
31119
  if (!providers) return void 0;
30348
31120
  const snapshot = {};
30349
31121
  for (const [id, value2] of Object.entries(providers)) {
30350
- const provider = record3(value2);
31122
+ const provider = record4(value2);
30351
31123
  if (!provider || typeof provider.status !== "string") continue;
30352
31124
  const windows = Array.isArray(provider.windows) ? provider.windows.flatMap((entry) => {
30353
- const window = record3(entry);
31125
+ const window = record4(entry);
30354
31126
  if (!window || typeof window.id !== "string" || typeof window.usedPercent !== "number") return [];
30355
31127
  const period = toWindowPeriod(window.period);
30356
31128
  const amounts = toWindowAmounts(window.amounts);
@@ -30418,7 +31190,7 @@ function createChildEnv(env, overlay) {
30418
31190
  return child;
30419
31191
  }
30420
31192
  function wrapWindowsShim(resolved, env, platform) {
30421
- if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path18__default.extname(resolved).toLowerCase())) {
31193
+ if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path19__default.extname(resolved).toLowerCase())) {
30422
31194
  return { bin: resolved, prefixArgs: [] };
30423
31195
  }
30424
31196
  rejectCmdExpansionSensitiveShim(resolved);
@@ -30436,13 +31208,13 @@ function forceWindowsArgQuoting(value) {
30436
31208
  return `${value} `;
30437
31209
  }
30438
31210
  function findOnPath(bin, pathValue, pathExts, platform) {
30439
- const pathSeparator = platform === "win32" ? WINDOWS_PATH_SEPARATOR : path18__default.delimiter;
30440
- if (hasPathSeparator(bin, platform) || path18__default.isAbsolute(bin)) {
31211
+ const pathSeparator = platform === "win32" ? WINDOWS_PATH_SEPARATOR : path19__default.delimiter;
31212
+ if (hasPathSeparator(bin, platform) || path19__default.isAbsolute(bin)) {
30441
31213
  return resolveWithExtensions(bin, pathExts, platform);
30442
31214
  }
30443
31215
  for (const entry of pathValue.split(pathSeparator)) {
30444
31216
  const searchDir = entry.length === 0 ? "." : entry;
30445
- const candidate = resolveWithExtensions(path18__default.join(searchDir, bin), pathExts, platform);
31217
+ const candidate = resolveWithExtensions(path19__default.join(searchDir, bin), pathExts, platform);
30446
31218
  if (candidate) {
30447
31219
  return candidate;
30448
31220
  }
@@ -30450,7 +31222,7 @@ function findOnPath(bin, pathValue, pathExts, platform) {
30450
31222
  return void 0;
30451
31223
  }
30452
31224
  function resolveWithExtensions(candidate, pathExts, platform) {
30453
- if (platform !== "win32" || path18__default.extname(candidate).length > 0) {
31225
+ if (platform !== "win32" || path19__default.extname(candidate).length > 0) {
30454
31226
  return isAccessibleExecutable(candidate, platform) ? candidate : void 0;
30455
31227
  }
30456
31228
  for (const ext of pathExts) {
@@ -30496,7 +31268,6 @@ function createClaudeFamilyCliDefinition(options) {
30496
31268
  async createProfile(profileOptions) {
30497
31269
  const { bin, prefixArgs } = resolveBinary("claude", "CLAUDE_BIN", profileOptions.env);
30498
31270
  const launchPrompt = sanitizeLaunchPrompt(profileOptions.prompt);
30499
- assertLaunchPromptShimSafe(launchPrompt, prefixArgs);
30500
31271
  const commandLineLimit = resolveLaunchCommandLineLimit(prefixArgs);
30501
31272
  const childEnv = createChildEnv(profileOptions.env, {});
30502
31273
  return {
@@ -30692,9 +31463,9 @@ function writePrivateJson(filePath, value, rootBase) {
30692
31463
  function writePrivateFile(filePath, content, rootBase) {
30693
31464
  const resolvedBase = ensureRootBase(rootBase);
30694
31465
  ensurePathWithinRoot(resolvedBase, filePath);
30695
- ensureDirectorySegments(resolvedBase, path18__default.dirname(filePath));
31466
+ ensureDirectorySegments(resolvedBase, path19__default.dirname(filePath));
30696
31467
  writeFileNoFollow(filePath, content);
30697
- chmodBestEffort(filePath, FILE_MODE);
31468
+ chmodBestEffort2(filePath, FILE_MODE);
30698
31469
  }
30699
31470
  function removePrivatePath(targetPath, rootBase) {
30700
31471
  const resolvedBase = assertRootBaseSafe(rootBase);
@@ -30722,7 +31493,7 @@ function cleanupPrivateRoot(rootPath, rootBase) {
30722
31493
  throw error51;
30723
31494
  }
30724
31495
  }
30725
- function chmodBestEffort(targetPath, mode) {
31496
+ function chmodBestEffort2(targetPath, mode) {
30726
31497
  try {
30727
31498
  chmodSync(targetPath, mode);
30728
31499
  } catch (_error) {
@@ -30739,20 +31510,20 @@ function writeFileNoFollow(filePath, content) {
30739
31510
  }
30740
31511
  }
30741
31512
  function ensureRootBase(rootBase) {
30742
- const resolvedBase = path18__default.resolve(rootBase);
30743
- const anchor = findExistingDirectoryAnchor(path18__default.dirname(resolvedBase));
31513
+ const resolvedBase = path19__default.resolve(rootBase);
31514
+ const anchor = findExistingDirectoryAnchor(path19__default.dirname(resolvedBase));
30744
31515
  ensureDirectorySegments(anchor, resolvedBase);
30745
31516
  assertDirectorySafe(resolvedBase, "Plugin root base");
30746
31517
  return resolvedBase;
30747
31518
  }
30748
31519
  function assertRootBaseSafe(rootBase) {
30749
- const resolvedBase = path18__default.resolve(rootBase);
30750
- assertExistingSegmentsSafe(findExistingDirectoryAnchor(path18__default.dirname(resolvedBase)), resolvedBase);
31520
+ const resolvedBase = path19__default.resolve(rootBase);
31521
+ assertExistingSegmentsSafe(findExistingDirectoryAnchor(path19__default.dirname(resolvedBase)), resolvedBase);
30751
31522
  assertDirectorySafe(resolvedBase, "Plugin root base");
30752
31523
  return resolvedBase;
30753
31524
  }
30754
31525
  function findExistingDirectoryAnchor(targetPath) {
30755
- const resolvedTarget = path18__default.resolve(targetPath);
31526
+ const resolvedTarget = path19__default.resolve(targetPath);
30756
31527
  let current = resolvedTarget;
30757
31528
  while (true) {
30758
31529
  try {
@@ -30760,7 +31531,7 @@ function findExistingDirectoryAnchor(targetPath) {
30760
31531
  return current;
30761
31532
  } catch (error51) {
30762
31533
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
30763
- const parent = path18__default.dirname(current);
31534
+ const parent = path19__default.dirname(current);
30764
31535
  if (parent === current) throw error51;
30765
31536
  current = parent;
30766
31537
  continue;
@@ -30779,17 +31550,17 @@ function assertDirectorySafe(dirPath, label) {
30779
31550
  }
30780
31551
  }
30781
31552
  function ensurePathWithinRoot(resolvedBase, candidatePath) {
30782
- const resolvedCandidate = path18__default.resolve(candidatePath);
30783
- const relative = path18__default.relative(resolvedBase, resolvedCandidate);
30784
- if (relative === "" || !relative.startsWith("..") && !path18__default.isAbsolute(relative)) return;
31553
+ const resolvedCandidate = path19__default.resolve(candidatePath);
31554
+ const relative = path19__default.relative(resolvedBase, resolvedCandidate);
31555
+ if (relative === "" || !relative.startsWith("..") && !path19__default.isAbsolute(relative)) return;
30785
31556
  throw new Error(`Plugin path escapes root base: ${candidatePath}`);
30786
31557
  }
30787
31558
  function ensureDirectorySegments(resolvedBase, dirPath) {
30788
- const target2 = path18__default.resolve(dirPath);
30789
- const relative = path18__default.relative(resolvedBase, target2);
31559
+ const target2 = path19__default.resolve(dirPath);
31560
+ const relative = path19__default.relative(resolvedBase, target2);
30790
31561
  let current = resolvedBase;
30791
- for (const segment of relative.split(path18__default.sep).filter(Boolean)) {
30792
- current = path18__default.join(current, segment);
31562
+ for (const segment of relative.split(path19__default.sep).filter(Boolean)) {
31563
+ current = path19__default.join(current, segment);
30793
31564
  try {
30794
31565
  const stat4 = lstatSync(current);
30795
31566
  if (stat4.isSymbolicLink()) {
@@ -30801,7 +31572,7 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
30801
31572
  } catch (error51) {
30802
31573
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
30803
31574
  mkdirSync(current, { mode: DIR_MODE });
30804
- chmodBestEffort(current, DIR_MODE);
31575
+ chmodBestEffort2(current, DIR_MODE);
30805
31576
  } else {
30806
31577
  throw error51;
30807
31578
  }
@@ -30810,11 +31581,11 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
30810
31581
  }
30811
31582
  }
30812
31583
  function assertExistingSegmentsSafe(resolvedBase, targetPath) {
30813
- const target2 = path18__default.resolve(targetPath);
30814
- const relative = path18__default.relative(resolvedBase, target2);
31584
+ const target2 = path19__default.resolve(targetPath);
31585
+ const relative = path19__default.relative(resolvedBase, target2);
30815
31586
  let current = resolvedBase;
30816
- for (const segment of relative.split(path18__default.sep).filter(Boolean)) {
30817
- current = path18__default.join(current, segment);
31587
+ for (const segment of relative.split(path19__default.sep).filter(Boolean)) {
31588
+ current = path19__default.join(current, segment);
30818
31589
  const stat4 = lstatSync(current);
30819
31590
  if (stat4.isSymbolicLink()) {
30820
31591
  throw new Error(`Plugin path segment is a symlink: ${current}`);
@@ -30826,13 +31597,13 @@ function assertExistingSegmentsSafe(resolvedBase, targetPath) {
30826
31597
  }
30827
31598
  }
30828
31599
  function assertExistingParentSegmentsSafe(resolvedBase, targetPath) {
30829
- assertExistingSegmentsSafe(resolvedBase, path18__default.dirname(targetPath));
31600
+ assertExistingSegmentsSafe(resolvedBase, path19__default.dirname(targetPath));
30830
31601
  }
30831
31602
  function assertSegmentRealpathWithinRoot(resolvedBase, segmentPath) {
30832
31603
  const baseRealpath = realpathSync(resolvedBase);
30833
31604
  const segmentRealpath = realpathSync(segmentPath);
30834
- const relative = path18__default.relative(baseRealpath, segmentRealpath);
30835
- if (relative === "" || !relative.startsWith("..") && !path18__default.isAbsolute(relative)) return;
31605
+ const relative = path19__default.relative(baseRealpath, segmentRealpath);
31606
+ if (relative === "" || !relative.startsWith("..") && !path19__default.isAbsolute(relative)) return;
30836
31607
  throw new Error(`Plugin path segment escapes root base: ${segmentPath}`);
30837
31608
  }
30838
31609
 
@@ -30852,18 +31623,18 @@ function renderAssetPluginRoot(pluginRoot, bundle, options) {
30852
31623
  options.doctrine ?? resolveDoctrineFromCliId(options.cliId);
30853
31624
  renderEmbeddedSkillAssets(pluginRoot);
30854
31625
  const workflowGuardScriptPath = writeWorkflowGuardScript(pluginRoot);
30855
- writePrivateJson(path18__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
31626
+ writePrivateJson(path19__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
30856
31627
  renderGatewayAgentAssets(pluginRoot, options);
30857
31628
  }
30858
31629
  function renderGatewayAgentAssets(pluginRoot, options) {
30859
31630
  for (const file2 of buildGatewayAgentFiles(options.gatewayDelegationModels ?? [], options.gatewayEffortExposure)) {
30860
- writePrivateFile(path18__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
31631
+ writePrivateFile(path19__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
30861
31632
  }
30862
31633
  }
30863
31634
  function writeWorkflowGuardScript(pluginRoot) {
30864
31635
  const asset = EMBEDDED_AGENT_CLI_HOOK_ASSETS.find((entry) => entry.relativePath === "workflow-guard.mjs");
30865
31636
  if (!asset) throw new Error("Missing embedded workflow-guard hook asset");
30866
- const scriptPath = path18__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
31637
+ const scriptPath = path19__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
30867
31638
  writePrivateFile(scriptPath, asset.content, pluginRoot);
30868
31639
  return scriptPath;
30869
31640
  }
@@ -30922,7 +31693,7 @@ function claudeCommandHook(hookExec) {
30922
31693
  }
30923
31694
  function renderEmbeddedSkillAssets(pluginRoot, doctrine) {
30924
31695
  for (const asset of selectSkillAssetsForDoctrine()) {
30925
- writePrivateFile(path18__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
31696
+ writePrivateFile(path19__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
30926
31697
  }
30927
31698
  }
30928
31699
  function selectSkillAssetsForDoctrine(_doctrine) {
@@ -30999,7 +31770,7 @@ function resolveRenderablePluginBundles(fleetRoot, options) {
30999
31770
  function homeMarketplaceTarget(fleetRoot) {
31000
31771
  return {
31001
31772
  name: FLEET_MARKETPLACE_NAME,
31002
- root: path18__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
31773
+ root: path19__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
31003
31774
  };
31004
31775
  }
31005
31776
  function groupRenderableBundlesByMarketplace(bundles) {
@@ -31015,17 +31786,17 @@ function groupRenderableBundlesByMarketplace(bundles) {
31015
31786
  return groups;
31016
31787
  }
31017
31788
  function renderPluginRoot(pluginRoot, bundle, options) {
31018
- const parentRoot = path18__default.dirname(pluginRoot);
31789
+ const parentRoot = path19__default.dirname(pluginRoot);
31019
31790
  ensurePrivateDir(parentRoot, parentRoot);
31020
31791
  const stageParent = createStagingDir(parentRoot);
31021
- const stagedPluginRoot = path18__default.join(stageParent, path18__default.basename(pluginRoot));
31792
+ const stagedPluginRoot = path19__default.join(stageParent, path19__default.basename(pluginRoot));
31022
31793
  try {
31023
31794
  ensurePrivateDir(stagedPluginRoot, stagedPluginRoot);
31024
- writePrivateJson(path18__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
31795
+ writePrivateJson(path19__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
31025
31796
  switch (bundle.source) {
31026
31797
  case "asset":
31027
- ensurePrivateDir(path18__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
31028
- ensurePrivateDir(path18__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
31798
+ ensurePrivateDir(path19__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
31799
+ ensurePrivateDir(path19__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
31029
31800
  renderAssetPluginRoot(stagedPluginRoot, bundle, options);
31030
31801
  break;
31031
31802
  }
@@ -31040,11 +31811,11 @@ function renderMarketplaceRoot(target2, bundles) {
31040
31811
  ensurePrivateDir(marketplaceRoot, marketplaceRoot);
31041
31812
  const stagedRoot = createStagingDir(marketplaceRoot);
31042
31813
  try {
31043
- writePrivateJson(path18__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
31814
+ writePrivateJson(path19__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
31044
31815
  pruneMarketplaceRoot(target2);
31045
31816
  pruneStalePluginDirs(target2, bundles);
31046
31817
  for (const entry of readdirSync(stagedRoot)) {
31047
- renameSync(path18__default.join(stagedRoot, entry), path18__default.join(marketplaceRoot, entry));
31818
+ renameSync(path19__default.join(stagedRoot, entry), path19__default.join(marketplaceRoot, entry));
31048
31819
  }
31049
31820
  } finally {
31050
31821
  cleanupPrivateRoot(stagedRoot, marketplaceRoot);
@@ -31052,11 +31823,11 @@ function renderMarketplaceRoot(target2, bundles) {
31052
31823
  }
31053
31824
  function pruneMarketplaceRoot(target2) {
31054
31825
  for (const entry of MARKETPLACE_PRUNE_ENTRIES) {
31055
- removePrivatePath(path18__default.join(target2.root, entry), target2.root);
31826
+ removePrivatePath(path19__default.join(target2.root, entry), target2.root);
31056
31827
  }
31057
31828
  }
31058
31829
  function pruneStalePluginDirs(target2, bundles) {
31059
- const pluginsDir = path18__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
31830
+ const pluginsDir = path19__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
31060
31831
  if (!existsSync(pluginsDir)) return;
31061
31832
  const activeDirectoryNames = /* @__PURE__ */ new Set();
31062
31833
  for (const bundle of bundles) {
@@ -31070,11 +31841,11 @@ function pruneStalePluginDirs(target2, bundles) {
31070
31841
  }
31071
31842
  for (const entry of readdirSync(pluginsDir)) {
31072
31843
  if (activeDirectoryNames.has(entry)) continue;
31073
- removePrivatePath(path18__default.join(pluginsDir, entry), target2.root);
31844
+ removePrivatePath(path19__default.join(pluginsDir, entry), target2.root);
31074
31845
  }
31075
31846
  }
31076
31847
  function createStagingDir(rootPath) {
31077
- const stageRoot = mkdtempSync(path18__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
31848
+ const stageRoot = mkdtempSync(path19__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
31078
31849
  return stageRoot;
31079
31850
  }
31080
31851
  function claudeMarketplace(target2, bundles) {
@@ -31096,7 +31867,7 @@ function claudeMarketplace(target2, bundles) {
31096
31867
  };
31097
31868
  }
31098
31869
  function pluginRootForTarget(target2, bundle) {
31099
- return path18__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
31870
+ return path19__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
31100
31871
  }
31101
31872
  function marketplacePluginPath(target2, bundle) {
31102
31873
  return `./${PLUGIN_BUNDLES_DIR_NAME}/${bundle.directoryName}`;
@@ -31127,6 +31898,22 @@ async function injectAgentCliProfile(profile, options) {
31127
31898
  const tempCleanups = [];
31128
31899
  try {
31129
31900
  const systemPromptFile = systemPromptMode === "off" ? void 0 : writeSystemPromptFile(profile.id, options.buildSystemPrompt(), (cleanup2) => tempCleanups.push(cleanup2));
31901
+ let promptArgs = [...profile.promptArgs ?? []];
31902
+ let deliveredViaFile = false;
31903
+ const cmdWrapped = profile.commandLineLimit?.via === "cmd-shim";
31904
+ const windowsLaunch = profile.commandLineLimit !== void 0;
31905
+ const convertPromptToFile = (body) => {
31906
+ promptArgs = [writeLaunchPromptPointer(
31907
+ body,
31908
+ (cleanupFn) => tempCleanups.push(cleanupFn),
31909
+ cmdWrapped
31910
+ )];
31911
+ deliveredViaFile = true;
31912
+ };
31913
+ if (promptArgs.length > 0 && windowsLaunch) {
31914
+ const body = takeLaunchPromptBody(promptArgs);
31915
+ if (launchPromptHasCmdUnsafeChars(body)) convertPromptToFile(body);
31916
+ }
31130
31917
  const plugin = await createAgentCliPlugin({
31131
31918
  cliId: profile.id,
31132
31919
  doctrine,
@@ -31163,26 +31950,39 @@ async function injectAgentCliProfile(profile, options) {
31163
31950
  systemPromptFile
31164
31951
  };
31165
31952
  const injectedArgs = buildAgentCliArgs(capability2.builderId, context);
31166
- const mergedArgs = mergeAgentCliArgs(profile, capability2.builderId, context, injectedArgs);
31953
+ const mergeArgs = (nextPromptArgs) => mergeAgentCliArgs(
31954
+ { ...profile, promptArgs: nextPromptArgs },
31955
+ capability2.builderId,
31956
+ context,
31957
+ injectedArgs
31958
+ );
31959
+ const argsWithoutPrompt = mergeArgs([]);
31960
+ const checkBudget = () => assertLaunchCommandLineBudget({
31961
+ args: mergeArgs(promptArgs),
31962
+ argsWithoutPrompt,
31963
+ bin: profile.bin,
31964
+ limit: profile.commandLineLimit,
31965
+ promptIsFixedLength: deliveredViaFile
31966
+ });
31167
31967
  try {
31168
- assertLaunchCommandLineBudget({
31169
- args: mergedArgs,
31170
- argsWithoutPrompt: mergeAgentCliArgs(
31171
- { ...profile, promptArgs: [] },
31172
- capability2.builderId,
31173
- context,
31174
- injectedArgs
31175
- ),
31176
- bin: profile.bin,
31177
- limit: profile.commandLineLimit
31178
- });
31968
+ checkBudget();
31179
31969
  } catch (error51) {
31180
- cleanup();
31181
- throw error51;
31970
+ const canMoveToFile = !deliveredViaFile && windowsLaunch && promptArgs.length === 1 && error51 instanceof LaunchPromptError && error51.code === "prompt_command_line_too_long";
31971
+ if (!canMoveToFile) {
31972
+ cleanup();
31973
+ throw error51;
31974
+ }
31975
+ convertPromptToFile(takeLaunchPromptBody(promptArgs));
31976
+ try {
31977
+ checkBudget();
31978
+ } catch (retryError) {
31979
+ cleanup();
31980
+ throw retryError;
31981
+ }
31182
31982
  }
31183
31983
  return {
31184
31984
  ...profile,
31185
- args: mergedArgs,
31985
+ args: mergeArgs(promptArgs),
31186
31986
  // 위치 인자는 이미 args 끝에 합쳐졌으므로 비운다. 남겨 두면 하류가 한 번 더 붙일 수 있다.
31187
31987
  promptArgs: [],
31188
31988
  cleanup
@@ -31208,21 +32008,27 @@ function buildAgentCliMcpServerConfigs(endpoints, tokens) {
31208
32008
  };
31209
32009
  });
31210
32010
  }
32011
+ function takeLaunchPromptBody(promptArgs) {
32012
+ if (promptArgs.length !== 1) {
32013
+ throw new Error(`Launch prompt file conversion expects a single positional prompt, got ${promptArgs.length}`);
32014
+ }
32015
+ return promptArgs[0];
32016
+ }
31211
32017
  function writeSystemPromptFile(cliId, systemPrompt, onCleanup) {
31212
- const tempDir = mkdtempSync(path18__default.join(os3__default.tmpdir(), `fleet-${cliId}-`));
31213
- onCleanup(() => rmBestEffort(tempDir));
31214
- const filePath = path18__default.join(tempDir, "system-prompt.md");
32018
+ const tempDir = mkdtempSync(path19__default.join(os3__default.tmpdir(), `fleet-${cliId}-`));
32019
+ onCleanup(() => rmBestEffort2(tempDir));
32020
+ const filePath = path19__default.join(tempDir, "system-prompt.md");
31215
32021
  writeFileSync(filePath, systemPrompt, { encoding: "utf8", flag: "wx", mode: SYSTEM_PROMPT_FILE_MODE });
31216
- chmodBestEffort2(filePath, SYSTEM_PROMPT_FILE_MODE);
32022
+ chmodBestEffort3(filePath, SYSTEM_PROMPT_FILE_MODE);
31217
32023
  return filePath;
31218
32024
  }
31219
- function chmodBestEffort2(targetPath, mode) {
32025
+ function chmodBestEffort3(targetPath, mode) {
31220
32026
  try {
31221
32027
  chmodSync(targetPath, mode);
31222
32028
  } catch {
31223
32029
  }
31224
32030
  }
31225
- function rmBestEffort(targetPath) {
32031
+ function rmBestEffort2(targetPath) {
31226
32032
  try {
31227
32033
  rmSync(targetPath, { force: true, recursive: true });
31228
32034
  } catch {
@@ -32383,18 +33189,18 @@ Always read \`schema/wiki-schema.md\` directly before composing or revising entr
32383
33189
  `;
32384
33190
  async function ensureWorkspaceSchema(paths) {
32385
33191
  await mkdir(paths.schemaDir, { recursive: true });
32386
- await writeDefaultFileIfMissing(path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME), DEFAULT_WORKSPACE_SCHEMA_AGENTS);
32387
- await writeDefaultFileIfMissing(path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME), DEFAULT_WORKSPACE_WIKI_SCHEMA);
33192
+ await writeDefaultFileIfMissing(path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME), DEFAULT_WORKSPACE_SCHEMA_AGENTS);
33193
+ await writeDefaultFileIfMissing(path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME), DEFAULT_WORKSPACE_WIKI_SCHEMA);
32388
33194
  await writeDefaultFileIfMissing(buildTemplatePath(paths, "prd"), DEFAULT_TEMPLATE_PRD);
32389
33195
  return readWorkspaceSchemaSummary(paths);
32390
33196
  }
32391
33197
  async function ensureWorkspaceDoctrine(paths) {
32392
33198
  await mkdir(paths.root, { recursive: true });
32393
- await writeDefaultFileIfMissing(path18__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
33199
+ await writeDefaultFileIfMissing(path19__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
32394
33200
  }
32395
33201
  async function readWorkspaceSchemaSummary(paths) {
32396
- const agentsPath = path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
32397
- const wikiSchemaPath = path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME);
33202
+ const agentsPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
33203
+ const wikiSchemaPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME);
32398
33204
  const wikiSchemaContent = await tryReadSchemaFile(paths, wikiSchemaPath);
32399
33205
  const templates = await scanTemplates(paths);
32400
33206
  if (wikiSchemaContent === null) {
@@ -32433,7 +33239,7 @@ async function scanTemplates(paths) {
32433
33239
  if (!entry.name.startsWith(WORKSPACE_TEMPLATE_PREFIX) || !entry.name.endsWith(WORKSPACE_TEMPLATE_SUFFIX)) continue;
32434
33240
  const id = entry.name.slice(WORKSPACE_TEMPLATE_PREFIX.length, -WORKSPACE_TEMPLATE_SUFFIX.length);
32435
33241
  if (!TEMPLATE_ID_PATTERN.test(id)) continue;
32436
- const filePath = path18__default.join(paths.schemaDir, entry.name);
33242
+ const filePath = path19__default.join(paths.schemaDir, entry.name);
32437
33243
  try {
32438
33244
  const parsed = parseTemplateMarkdown(await readFile(filePath, "utf8"));
32439
33245
  templates.push({
@@ -32465,7 +33271,7 @@ async function readSchemaCatalog(paths) {
32465
33271
  }
32466
33272
  async function readSchemaDocument(paths, resource, templateId) {
32467
33273
  const ref = resource === "schema" ? "schema/wiki-schema.md" : schemaTemplateRef(templateId ?? "");
32468
- const absolute = path18__default.resolve(paths.root, ref);
33274
+ const absolute = path19__default.resolve(paths.root, ref);
32469
33275
  await assertContainedSchemaFile(paths, absolute, false);
32470
33276
  return { ref, content: await readFile(absolute, "utf8") };
32471
33277
  }
@@ -32490,10 +33296,10 @@ async function validateSchemaTemplateCreate(paths, templateId, markdown) {
32490
33296
  if (folded.has(key)) throw new Error(`schema template contains duplicate ## section: ${section}`);
32491
33297
  folded.add(key);
32492
33298
  }
32493
- const absolute = path18__default.resolve(paths.root, ref);
33299
+ const absolute = path19__default.resolve(paths.root, ref);
32494
33300
  await assertContainedSchemaFile(paths, absolute, true);
32495
33301
  const entries = await readdir(paths.schemaDir).catch(() => []);
32496
- const basename = path18__default.basename(absolute).toLocaleLowerCase("en-US");
33302
+ const basename = path19__default.basename(absolute).toLocaleLowerCase("en-US");
32497
33303
  if (entries.some((entry) => entry.toLocaleLowerCase("en-US") === basename)) throw new Error("schema template target already exists");
32498
33304
  return absolute;
32499
33305
  }
@@ -32501,13 +33307,13 @@ function assertTemplateId(id) {
32501
33307
  if (!TEMPLATE_ID_PATTERN.test(id)) throw new Error("template_id must match /^[a-z][a-z0-9-]{0,63}$/");
32502
33308
  }
32503
33309
  async function assertContainedSchemaFile(paths, absolute, allowMissing) {
32504
- const schemaReal = await realpath(paths.schemaDir).catch(() => path18__default.resolve(paths.schemaDir));
32505
- const parentReal = await realpath(path18__default.dirname(absolute)).catch(() => path18__default.resolve(path18__default.dirname(absolute)));
33310
+ const schemaReal = await realpath(paths.schemaDir).catch(() => path19__default.resolve(paths.schemaDir));
33311
+ const parentReal = await realpath(path19__default.dirname(absolute)).catch(() => path19__default.resolve(path19__default.dirname(absolute)));
32506
33312
  if (parentReal !== schemaReal) throw new Error("schema resource escapes schema directory");
32507
- const relative = path18__default.relative(paths.root, absolute);
33313
+ const relative = path19__default.relative(paths.root, absolute);
32508
33314
  let cursor = paths.root;
32509
- for (const part of relative.split(path18__default.sep)) {
32510
- cursor = path18__default.join(cursor, part);
33315
+ for (const part of relative.split(path19__default.sep)) {
33316
+ cursor = path19__default.join(cursor, part);
32511
33317
  try {
32512
33318
  if ((await lstat(cursor)).isSymbolicLink()) throw new Error("schema resource path contains symlink");
32513
33319
  } catch (error51) {
@@ -32535,7 +33341,7 @@ async function validateTemplateCompliance(paths, templateId, body) {
32535
33341
  }
32536
33342
  }
32537
33343
  function inferTemplateIdFromTarget(target2, knownTemplateIds) {
32538
- const basename = path18__default.basename(target2, ".md");
33344
+ const basename = path19__default.basename(target2, ".md");
32539
33345
  const ids = knownTemplateIds ?? DEFAULT_TEMPLATE_IDS;
32540
33346
  const sorted = [...ids].sort((a, b) => b.length - a.length);
32541
33347
  for (const id of sorted) {
@@ -32567,7 +33373,7 @@ function extractSchemaSummary(content) {
32567
33373
  return lines.find((line) => line.length > 0 && !line.startsWith("#")) ?? "Workspace schema is present.";
32568
33374
  }
32569
33375
  function buildTemplatePath(paths, id) {
32570
- return path18__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
33376
+ return path19__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
32571
33377
  }
32572
33378
  function parseTemplateMarkdown(content) {
32573
33379
  const normalized = content.replace(/\r\n/g, "\n");
@@ -32672,18 +33478,18 @@ function isAlreadyExistsError(error51) {
32672
33478
 
32673
33479
  // ../../packages/fleet-wiki/src/paths.ts
32674
33480
  function resolveMemoryPaths(cwd) {
32675
- return createMemoryPaths(path18__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
33481
+ return createMemoryPaths(path19__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
32676
33482
  }
32677
33483
  function createMemoryPaths(root) {
32678
33484
  return {
32679
33485
  root,
32680
- rawDir: path18__default.join(root, RAW_DIRNAME),
32681
- wikiDir: path18__default.join(root, WIKI_DIRNAME),
32682
- schemaDir: path18__default.join(root, SCHEMA_DIRNAME),
32683
- queueDir: path18__default.join(root, QUEUE_DIRNAME),
32684
- archiveDir: path18__default.join(root, ARCHIVE_DIRNAME),
32685
- conflictsDir: path18__default.join(root, CONFLICTS_DIRNAME),
32686
- indexFile: path18__default.join(root, INDEX_FILENAME)
33486
+ rawDir: path19__default.join(root, RAW_DIRNAME),
33487
+ wikiDir: path19__default.join(root, WIKI_DIRNAME),
33488
+ schemaDir: path19__default.join(root, SCHEMA_DIRNAME),
33489
+ queueDir: path19__default.join(root, QUEUE_DIRNAME),
33490
+ archiveDir: path19__default.join(root, ARCHIVE_DIRNAME),
33491
+ conflictsDir: path19__default.join(root, CONFLICTS_DIRNAME),
33492
+ indexFile: path19__default.join(root, INDEX_FILENAME)
32687
33493
  };
32688
33494
  }
32689
33495
  function resolveToolMemoryPaths(ctx) {
@@ -32701,10 +33507,10 @@ async function ensureMemoryRoot(paths) {
32701
33507
  await ensureWorkspaceDoctrine(paths);
32702
33508
  }
32703
33509
  function getIndexMarkdownFile(paths) {
32704
- return path18__default.join(paths.wikiDir, INDEX_MD_FILENAME);
33510
+ return path19__default.join(paths.wikiDir, INDEX_MD_FILENAME);
32705
33511
  }
32706
33512
  function getLogFile(paths) {
32707
- return path18__default.join(paths.root, LOG_MD_FILENAME);
33513
+ return path19__default.join(paths.root, LOG_MD_FILENAME);
32708
33514
  }
32709
33515
 
32710
33516
  // ../../packages/fleet-wiki/src/conflicts.ts
@@ -32716,7 +33522,7 @@ async function createConflict(input, paths) {
32716
33522
  await ensureMemoryRoot(paths);
32717
33523
  const now = input.now ?? /* @__PURE__ */ new Date();
32718
33524
  const conflictId = buildConflictId(now, input.wikiId, input.reason, input.proposed);
32719
- const conflictDir = path18__default.join(paths.conflictsDir, conflictId);
33525
+ const conflictDir = path19__default.join(paths.conflictsDir, conflictId);
32720
33526
  await mkdir(conflictDir, { recursive: true });
32721
33527
  const meta3 = {
32722
33528
  id: conflictId,
@@ -32736,13 +33542,13 @@ async function createConflict(input, paths) {
32736
33542
  currentHash: input.currentHash,
32737
33543
  warnings: input.warnings
32738
33544
  };
32739
- await writeJsonFile(path18__default.join(conflictDir, CONFLICT_META_FILENAME), meta3, paths);
32740
- await writePatchFile(path18__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME), input.proposed, paths);
33545
+ await writeJsonFile(path19__default.join(conflictDir, CONFLICT_META_FILENAME), meta3, paths);
33546
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME), input.proposed, paths);
32741
33547
  if (input.current !== void 0) {
32742
- await writePatchFile(path18__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
33548
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
32743
33549
  }
32744
33550
  if (input.rawSource !== void 0) {
32745
- await writePatchFile(path18__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
33551
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
32746
33552
  }
32747
33553
  return {
32748
33554
  meta: meta3,
@@ -32756,7 +33562,7 @@ async function listConflicts(paths) {
32756
33562
  const metas = [];
32757
33563
  for (const id of ids) {
32758
33564
  try {
32759
- metas.push(await readJsonFile2(path18__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
33565
+ metas.push(await readJsonFile2(path19__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
32760
33566
  } catch {
32761
33567
  continue;
32762
33568
  }
@@ -32765,13 +33571,13 @@ async function listConflicts(paths) {
32765
33571
  }
32766
33572
  async function readConflict(conflictId, paths) {
32767
33573
  const conflictDir = resolveConflictDir(conflictId, paths);
32768
- const meta3 = await readJsonFile2(path18__default.join(conflictDir, CONFLICT_META_FILENAME));
32769
- const currentPath = path18__default.join(conflictDir, CONFLICT_CURRENT_FILENAME);
32770
- const rawSourcePath = path18__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME);
33574
+ const meta3 = await readJsonFile2(path19__default.join(conflictDir, CONFLICT_META_FILENAME));
33575
+ const currentPath = path19__default.join(conflictDir, CONFLICT_CURRENT_FILENAME);
33576
+ const rawSourcePath = path19__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME);
32771
33577
  return {
32772
33578
  meta: meta3,
32773
33579
  current: await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0,
32774
- proposed: await readPatchFile(path18__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
33580
+ proposed: await readPatchFile(path19__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
32775
33581
  rawSource: await pathExists(rawSourcePath) ? await readPatchFile(rawSourcePath) : void 0
32776
33582
  };
32777
33583
  }
@@ -32790,9 +33596,9 @@ function sanitizeConflictToken(value) {
32790
33596
  return value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "unknown";
32791
33597
  }
32792
33598
  function resolveConflictDir(conflictId, paths) {
32793
- const conflictDir = path18__default.resolve(paths.conflictsDir, conflictId);
32794
- const relative = path18__default.relative(paths.conflictsDir, conflictDir);
32795
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) {
33599
+ const conflictDir = path19__default.resolve(paths.conflictsDir, conflictId);
33600
+ const relative = path19__default.relative(paths.conflictsDir, conflictDir);
33601
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
32796
33602
  throw new Error(`[fleet-wiki] conflict id escapes conflicts/: ${conflictId}`);
32797
33603
  }
32798
33604
  return conflictDir;
@@ -32956,11 +33762,11 @@ async function validatePatch(patch, paths) {
32956
33762
  if (!target2 || !summary || !proposer || !created) throw new Error("patch frontmatter is incomplete");
32957
33763
  if (summary.length > 120) throw new Error("patch summary exceeds 120 chars");
32958
33764
  assertCanonicalPatchTarget(target2);
32959
- const absoluteTarget = path18__default.resolve(paths.root, target2);
32960
- if (!absoluteTarget.startsWith(`${paths.root}${path18__default.sep}`) && absoluteTarget !== paths.root) {
33765
+ const absoluteTarget = path19__default.resolve(paths.root, target2);
33766
+ if (!absoluteTarget.startsWith(`${paths.root}${path19__default.sep}`) && absoluteTarget !== paths.root) {
32961
33767
  throw new Error("patch target escapes wiki root");
32962
33768
  }
32963
- if (!absoluteTarget.startsWith(`${paths.wikiDir}${path18__default.sep}`)) throw new Error("wiki patch must target wiki/");
33769
+ if (!absoluteTarget.startsWith(`${paths.wikiDir}${path19__default.sep}`)) throw new Error("wiki patch must target wiki/");
32964
33770
  assertNoSymlinkPathComponents(target2, paths);
32965
33771
  if (op === "create_wiki" && await pathExists(absoluteTarget)) {
32966
33772
  throw new Error(
@@ -32981,19 +33787,19 @@ async function applyPatch(patch, paths) {
32981
33787
  async function enqueuePatch(patch, paths, metaOverrides) {
32982
33788
  await ensureMemoryRoot(paths);
32983
33789
  const patchId = buildPatchId(patch.frontmatter.created, patch.frontmatter.summary, patch.frontmatter.target, patch.body);
32984
- const queueDir = path18__default.join(paths.queueDir, patchId);
33790
+ const queueDir = path19__default.join(paths.queueDir, patchId);
32985
33791
  if (await pathExists(queueDir)) {
32986
33792
  throw new Error(`[fleet-wiki] patch id collision: ${patchId} - this should never happen with target+body hashing`);
32987
33793
  }
32988
33794
  await mkdir(queueDir, { recursive: true });
32989
- await writePatchFile(path18__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
33795
+ await writePatchFile(path19__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
32990
33796
  const meta3 = {
32991
33797
  id: patchId,
32992
33798
  status: "pending",
32993
33799
  createdAt: patch.frontmatter.created,
32994
33800
  ...metaOverrides
32995
33801
  };
32996
- await writeJsonFile(path18__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
33802
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
32997
33803
  await appendLog(paths, "patch enqueued", {
32998
33804
  patch_id: patchId,
32999
33805
  patch_set_id: meta3.patch_set_id ?? null,
@@ -33011,7 +33817,7 @@ async function listQueue(paths) {
33011
33817
  for (const id of ids) {
33012
33818
  if (id === "_sets") continue;
33013
33819
  try {
33014
- const meta3 = await readJsonFile2(path18__default.join(paths.queueDir, id, PATCH_META_FILENAME));
33820
+ const meta3 = await readJsonFile2(path19__default.join(paths.queueDir, id, PATCH_META_FILENAME));
33015
33821
  results.push({ id, meta: meta3 });
33016
33822
  } catch {
33017
33823
  continue;
@@ -33036,17 +33842,17 @@ async function resolveQueueSelection(id, paths) {
33036
33842
  }
33037
33843
  async function showQueue(id, paths) {
33038
33844
  const selection = await resolveQueueSelection(id, paths);
33039
- const queueDir = path18__default.join(paths.queueDir, selection.id);
33040
- const patch = await parsePatch(await readPatchFile(path18__default.join(queueDir, PATCH_FILENAME)));
33041
- const meta3 = await readJsonFile2(path18__default.join(queueDir, PATCH_META_FILENAME));
33845
+ const queueDir = path19__default.join(paths.queueDir, selection.id);
33846
+ const patch = await parsePatch(await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME)));
33847
+ const meta3 = await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME));
33042
33848
  return { patch, meta: meta3 };
33043
33849
  }
33044
33850
  async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
33045
33851
  assertSafeQueueId(id);
33046
33852
  return withPatchEditLock(paths, id, async () => {
33047
- const queueDir = path18__default.join(paths.queueDir, id);
33853
+ const queueDir = path19__default.join(paths.queueDir, id);
33048
33854
  if (expectedPatchHash !== void 0) {
33049
- const currentMarkdown = await readPatchFile(path18__default.join(queueDir, PATCH_FILENAME));
33855
+ const currentMarkdown = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
33050
33856
  const currentHash = computeContentHash(currentMarkdown);
33051
33857
  if (currentHash !== expectedPatchHash) {
33052
33858
  throw new Error(`[fleet-wiki] wiki_patch_edit stale base_patch_hash: expected ${currentHash}, got ${expectedPatchHash}`);
@@ -33055,8 +33861,8 @@ async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
33055
33861
  const patchMarkdown = serializePatch(patch);
33056
33862
  const patchHash = computeContentHash(patchMarkdown);
33057
33863
  const nextMeta = { ...meta3, lastEditHash: patchHash };
33058
- await writePatchFile(path18__default.join(queueDir, PATCH_FILENAME), patchMarkdown, paths);
33059
- await writeJsonFile(path18__default.join(queueDir, PATCH_META_FILENAME), nextMeta, paths);
33864
+ await writePatchFile(path19__default.join(queueDir, PATCH_FILENAME), patchMarkdown, paths);
33865
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), nextMeta, paths);
33060
33866
  return patchHash;
33061
33867
  });
33062
33868
  }
@@ -33080,8 +33886,8 @@ async function approvePatch(id, paths) {
33080
33886
  rawSourceRef: meta3.rawSourceRef,
33081
33887
  warnings: meta3.warnings
33082
33888
  });
33083
- const queueDir = path18__default.join(paths.queueDir, id);
33084
- await writeJsonFile(path18__default.join(queueDir, PATCH_META_FILENAME), {
33889
+ const queueDir = path19__default.join(paths.queueDir, id);
33890
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), {
33085
33891
  ...meta3,
33086
33892
  conflictId
33087
33893
  }, paths);
@@ -33117,7 +33923,7 @@ async function approvePatchSet(patchSetId, paths) {
33117
33923
  const failed = [];
33118
33924
  const missing = [];
33119
33925
  for (const patchId of patchSet.patchIds) {
33120
- const queueDir = path18__default.join(paths.queueDir, patchId);
33926
+ const queueDir = path19__default.join(paths.queueDir, patchId);
33121
33927
  if (!await pathExists(queueDir)) {
33122
33928
  missing.push(patchId);
33123
33929
  continue;
@@ -33183,7 +33989,7 @@ ${patch.body}`;
33183
33989
  }
33184
33990
  async function normalizeWikiEntryPatch(entry, target2, paths) {
33185
33991
  assertSafeEntryId(entry.id);
33186
- if (entry.id !== path18__default.basename(target2, ".md")) {
33992
+ if (entry.id !== path19__default.basename(target2, ".md")) {
33187
33993
  throw new Error("wiki patch body id must match target filename");
33188
33994
  }
33189
33995
  const inlineRawSourceRef = extractInlineRawSourceRef(entry.body);
@@ -33226,9 +34032,9 @@ function buildPatchId(createdAt, summary, target2, body) {
33226
34032
  }
33227
34033
  async function validatePatchBase(patch, meta3, paths) {
33228
34034
  if (patch.frontmatter.op !== "update_wiki" || !meta3?.baseVersion && !meta3?.baseHash) return;
33229
- const wikiId = path18__default.basename(patch.frontmatter.target, ".md");
34035
+ const wikiId = path19__default.basename(patch.frontmatter.target, ".md");
33230
34036
  const currentEntry = await readWikiEntry(wikiId, paths);
33231
- const currentPath = path18__default.join(paths.root, patch.frontmatter.target);
34037
+ const currentPath = path19__default.join(paths.root, patch.frontmatter.target);
33232
34038
  const currentMarkdown = await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0;
33233
34039
  if (meta3.baseVersion !== void 0 && currentEntry?.version !== meta3.baseVersion) {
33234
34040
  throw new Error(
@@ -33287,17 +34093,17 @@ function assertCanonicalPatchTarget(target2) {
33287
34093
  if (target2.endsWith("/")) {
33288
34094
  throw new Error("patch target must not end with a slash");
33289
34095
  }
33290
- if (target2.startsWith("/") || path18__default.posix.isAbsolute(target2) || path18__default.win32.isAbsolute(target2)) {
34096
+ if (target2.startsWith("/") || path19__default.posix.isAbsolute(target2) || path19__default.win32.isAbsolute(target2)) {
33291
34097
  throw new Error("patch target must be relative");
33292
34098
  }
33293
- if (path18__default.posix.normalize(target2) !== target2) {
34099
+ if (path19__default.posix.normalize(target2) !== target2) {
33294
34100
  throw new Error("patch target must not contain dot segments or redundant separators");
33295
34101
  }
33296
34102
  }
33297
34103
  function canonicalApprovalLockKey(paths, target2) {
33298
34104
  const wikiRoot = realpathSync(paths.wikiDir);
33299
- const relativeTarget = path18__default.posix.relative("wiki", target2);
33300
- const targetPath = path18__default.join(wikiRoot, ...relativeTarget.split("/"));
34105
+ const relativeTarget = path19__default.posix.relative("wiki", target2);
34106
+ const targetPath = path19__default.join(wikiRoot, ...relativeTarget.split("/"));
33301
34107
  return `${wikiRoot}\0${targetPath}`.toLowerCase();
33302
34108
  }
33303
34109
  function canonicalPatchEditLockKey(paths, patchId) {
@@ -33313,7 +34119,7 @@ function assertNoSymlinkPathComponents(target2, paths) {
33313
34119
  throw error51;
33314
34120
  }
33315
34121
  for (const part of parts) {
33316
- current = path18__default.join(current, part);
34122
+ current = path19__default.join(current, part);
33317
34123
  try {
33318
34124
  if (lstatSync(current).isSymbolicLink()) {
33319
34125
  throw new Error("patch target must not include symlink path components");
@@ -33328,8 +34134,8 @@ function assertSafeRawSourceRef(rawSourceRef, paths) {
33328
34134
  if (!rawSourceRef.startsWith("raw/")) {
33329
34135
  throw new Error("raw source provenance must point into raw/");
33330
34136
  }
33331
- const absoluteRef = path18__default.resolve(paths.root, rawSourceRef);
33332
- if (!absoluteRef.startsWith(`${paths.rawDir}${path18__default.sep}`)) {
34137
+ const absoluteRef = path19__default.resolve(paths.root, rawSourceRef);
34138
+ if (!absoluteRef.startsWith(`${paths.rawDir}${path19__default.sep}`)) {
33333
34139
  throw new Error("raw source provenance must point into raw/");
33334
34140
  }
33335
34141
  }
@@ -33345,14 +34151,14 @@ function classifyPatchConflict(error51) {
33345
34151
  }
33346
34152
  async function recordPatchConflict(patch, paths, reason, options) {
33347
34153
  const now = /* @__PURE__ */ new Date();
33348
- const targetPath = path18__default.join(paths.root, patch.frontmatter.target);
34154
+ const targetPath = path19__default.join(paths.root, patch.frontmatter.target);
33349
34155
  const current = await pathExists(targetPath) ? await readPatchFile(targetPath) : void 0;
33350
34156
  const currentEntry = current ? parseStoredWikiEntry(current) : void 0;
33351
34157
  const proposedEntry = parsePatchBodyEntry(patch.body);
33352
- const record6 = await createConflict({
34158
+ const record7 = await createConflict({
33353
34159
  reason,
33354
34160
  target: patch.frontmatter.target,
33355
- wikiId: proposedEntry?.id ?? path18__default.basename(patch.frontmatter.target, ".md"),
34161
+ wikiId: proposedEntry?.id ?? path19__default.basename(patch.frontmatter.target, ".md"),
33356
34162
  title: proposedEntry?.title,
33357
34163
  proposer: patch.frontmatter.proposer,
33358
34164
  rawSourceRef: options?.rawSourceRef,
@@ -33368,14 +34174,14 @@ async function recordPatchConflict(patch, paths, reason, options) {
33368
34174
  now
33369
34175
  }, paths);
33370
34176
  await appendLog(paths, "conflict detected", {
33371
- conflict_id: record6.meta.id,
34177
+ conflict_id: record7.meta.id,
33372
34178
  patch_id: options?.patchId ?? null,
33373
34179
  raw_source_ref: options?.rawSourceRef ?? null,
33374
34180
  reason,
33375
34181
  target: patch.frontmatter.target,
33376
- wiki_id: record6.meta.wikiId
34182
+ wiki_id: record7.meta.wikiId
33377
34183
  }, now);
33378
- return record6.meta.id;
34184
+ return record7.meta.id;
33379
34185
  }
33380
34186
  function parsePatchBodyEntry(content) {
33381
34187
  try {
@@ -33464,11 +34270,11 @@ function parseInlineArray(value) {
33464
34270
  return inner.split(",").map((item) => decodeFrontmatter(item.trim().replace(/^"(.*)"$/, "$1")));
33465
34271
  }
33466
34272
  async function archiveQueueEntry(id, paths, meta3) {
33467
- const fromDir = path18__default.join(paths.queueDir, id);
33468
- const toDir = path18__default.join(paths.archiveDir, id);
34273
+ const fromDir = path19__default.join(paths.queueDir, id);
34274
+ const toDir = path19__default.join(paths.archiveDir, id);
33469
34275
  await removePath(toDir);
33470
34276
  await movePath(fromDir, toDir);
33471
- await writeJsonFile(path18__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
34277
+ await writeJsonFile(path19__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
33472
34278
  }
33473
34279
  function buildQueueIdHelp(prefix, availableIds) {
33474
34280
  if (availableIds.length === 0) {
@@ -33500,15 +34306,15 @@ var PATCH_SET_DIRNAME = "_sets";
33500
34306
  var PATCH_SET_META_FILENAME = PATCH_META_FILENAME;
33501
34307
  function getPatchSetDir(paths, patchSetId) {
33502
34308
  assertSafePatchSetId(patchSetId);
33503
- const patchSetDir = path18__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId);
33504
- const relative = path18__default.relative(path18__default.join(paths.queueDir, PATCH_SET_DIRNAME), patchSetDir);
33505
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) {
34309
+ const patchSetDir = path19__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId);
34310
+ const relative = path19__default.relative(path19__default.join(paths.queueDir, PATCH_SET_DIRNAME), patchSetDir);
34311
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
33506
34312
  throw new Error(`[fleet-wiki] patch set id escapes queue/_sets: ${patchSetId}`);
33507
34313
  }
33508
34314
  return patchSetDir;
33509
34315
  }
33510
34316
  function getPatchSetMetaFile(paths, patchSetId) {
33511
- return path18__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
34317
+ return path19__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
33512
34318
  }
33513
34319
  function buildPatchSetId(createdAt, sourceRef) {
33514
34320
  const compact = createdAt.replace(/[:.]/g, "-");
@@ -33567,36 +34373,36 @@ async function readWikiEntry(id, paths) {
33567
34373
  const index = await loadIndex(paths);
33568
34374
  const indexed = index[id];
33569
34375
  if (indexed) {
33570
- const resolved = path18__default.resolve(paths.root, indexed.path);
33571
- const rel = path18__default.relative(paths.wikiDir, resolved);
33572
- if (!rel || rel.startsWith("..") || path18__default.isAbsolute(rel)) return null;
34376
+ const resolved = path19__default.resolve(paths.root, indexed.path);
34377
+ const rel = path19__default.relative(paths.wikiDir, resolved);
34378
+ if (!rel || rel.startsWith("..") || path19__default.isAbsolute(rel)) return null;
33573
34379
  return readMarkdownFile(resolved);
33574
34380
  }
33575
- const fallbackPath = path18__default.join(paths.wikiDir, `${id}.md`);
34381
+ const fallbackPath = path19__default.join(paths.wikiDir, `${id}.md`);
33576
34382
  if (await pathExists(fallbackPath)) {
33577
34383
  return readMarkdownFile(fallbackPath);
33578
34384
  }
33579
34385
  const records = await listWikiRecords(paths);
33580
- const match = records.find((record6) => record6.entry.id === id);
34386
+ const match = records.find((record7) => record7.entry.id === id);
33581
34387
  return match ? match.entry : null;
33582
34388
  }
33583
34389
  async function writeWikiEntryAtTarget(entry, target2, paths) {
33584
34390
  await ensureMemoryRoot(paths);
33585
34391
  assertSafeEntryId(entry.id);
33586
- const absoluteTarget = path18__default.resolve(paths.root, target2);
33587
- const relativeTarget = path18__default.relative(paths.wikiDir, absoluteTarget);
33588
- if (!relativeTarget || relativeTarget.startsWith("..") || path18__default.isAbsolute(relativeTarget)) {
34392
+ const absoluteTarget = path19__default.resolve(paths.root, target2);
34393
+ const relativeTarget = path19__default.relative(paths.wikiDir, absoluteTarget);
34394
+ if (!relativeTarget || relativeTarget.startsWith("..") || path19__default.isAbsolute(relativeTarget)) {
33589
34395
  throw new Error(`[fleet-wiki] wiki target escapes wiki/: ${target2}`);
33590
34396
  }
33591
34397
  if (!absoluteTarget.endsWith(".md")) {
33592
34398
  throw new Error(`[fleet-wiki] wiki target must end with .md: ${target2}`);
33593
34399
  }
33594
- if (path18__default.basename(absoluteTarget, ".md") !== entry.id) {
34400
+ if (path19__default.basename(absoluteTarget, ".md") !== entry.id) {
33595
34401
  throw new Error("wiki patch body id must match target filename");
33596
34402
  }
33597
- await mkdir(path18__default.dirname(absoluteTarget), { recursive: true });
34403
+ await mkdir(path19__default.dirname(absoluteTarget), { recursive: true });
33598
34404
  await writeAtomic(absoluteTarget, serializeWikiEntry(entry), paths);
33599
- return path18__default.join("wiki", relativeTarget).replaceAll(path18__default.sep, "/");
34405
+ return path19__default.join("wiki", relativeTarget).replaceAll(path19__default.sep, "/");
33600
34406
  }
33601
34407
  async function writeRawSourceEntry(entry, paths) {
33602
34408
  await ensureMemoryRoot(paths);
@@ -33615,11 +34421,11 @@ async function writeRawSourceEntry(entry, paths) {
33615
34421
  },
33616
34422
  entry.content
33617
34423
  );
33618
- await writeAtomic(path18__default.join(paths.root, relativePath), content, paths);
34424
+ await writeAtomic(path19__default.join(paths.root, relativePath), content, paths);
33619
34425
  return relativePath;
33620
34426
  }
33621
34427
  async function readRawSourceEntry(rawSourceRef, paths) {
33622
- const absolutePath = path18__default.resolve(paths.root, rawSourceRef);
34428
+ const absolutePath = path19__default.resolve(paths.root, rawSourceRef);
33623
34429
  assertWithinRawDir(absolutePath, paths);
33624
34430
  const parsed = parseMarkdown(await readFile(absolutePath, "utf8"));
33625
34431
  return {
@@ -33810,8 +34616,8 @@ function computeContentHash(content) {
33810
34616
  return crypto5.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 8);
33811
34617
  }
33812
34618
  function assertWithinRawDir(absolutePath, paths) {
33813
- const relative = path18__default.relative(paths.rawDir, absolutePath);
33814
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) {
34619
+ const relative = path19__default.relative(paths.rawDir, absolutePath);
34620
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
33815
34621
  throw new Error(`[fleet-wiki] raw source ref escapes raw/: ${absolutePath}`);
33816
34622
  }
33817
34623
  }
@@ -33867,7 +34673,7 @@ function parseWikiEntry(content) {
33867
34673
  async function listWikiRecords(paths) {
33868
34674
  return listMarkdownEntriesRecursive(paths.wikiDir, paths, (content, filePath) => ({
33869
34675
  entry: parseWikiEntry(content),
33870
- path: path18__default.relative(paths.root, filePath).replaceAll(path18__default.sep, "/")
34676
+ path: path19__default.relative(paths.root, filePath).replaceAll(path19__default.sep, "/")
33871
34677
  }));
33872
34678
  }
33873
34679
  async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
@@ -33880,7 +34686,7 @@ async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
33880
34686
  }
33881
34687
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
33882
34688
  for (const entry of sortedEntries) {
33883
- const filePath = path18__default.join(dirPath, entry.name);
34689
+ const filePath = path19__default.join(dirPath, entry.name);
33884
34690
  if (entry.isDirectory()) {
33885
34691
  items.push(...await listMarkdownEntriesRecursive(filePath, paths, parser));
33886
34692
  continue;
@@ -34015,8 +34821,8 @@ async function writeJsonAtomic(filePath, value, paths) {
34015
34821
  }
34016
34822
  async function writeAtomic(filePath, content, paths) {
34017
34823
  await ensureMemoryRoot(paths);
34018
- const tempPath = path18__default.join(
34019
- path18__default.dirname(filePath),
34824
+ const tempPath = path19__default.join(
34825
+ path19__default.dirname(filePath),
34020
34826
  `.tmp-${process.pid}-${Date.now()}-${crypto5.randomUUID()}-${os3__default.hostname()}`
34021
34827
  );
34022
34828
  await writeFile(tempPath, content, "utf8");
@@ -34097,7 +34903,7 @@ function extractLegacyMarkdownWikiLinks(body, wikiDir, basePath) {
34097
34903
  }
34098
34904
  function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
34099
34905
  if (!target2 || target2.startsWith("#")) return null;
34100
- if (path18__default.isAbsolute(target2)) return null;
34906
+ if (path19__default.isAbsolute(target2)) return null;
34101
34907
  if (/^[a-z][a-z0-9+.-]*:/i.test(target2)) return null;
34102
34908
  const withoutFragment = target2.split("#", 1)[0]?.split("?", 1)[0] ?? "";
34103
34909
  if (!withoutFragment.endsWith(".md")) return null;
@@ -34107,12 +34913,12 @@ function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
34107
34913
  } catch {
34108
34914
  return null;
34109
34915
  }
34110
- const resolved = path18__default.resolve(path18__default.dirname(basePath), decodedTarget);
34111
- const relative = path18__default.relative(wikiDir, resolved);
34112
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) return null;
34916
+ const resolved = path19__default.resolve(path19__default.dirname(basePath), decodedTarget);
34917
+ const relative = path19__default.relative(wikiDir, resolved);
34918
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) return null;
34113
34919
  return {
34114
34920
  target: target2,
34115
- entryId: path18__default.basename(relative, ".md")
34921
+ entryId: path19__default.basename(relative, ".md")
34116
34922
  };
34117
34923
  }
34118
34924
  var FLEET_WIKI_ENTRY_BEGIN = "<<<FLEET_WIKI_ENTRY_BEGIN";
@@ -34179,7 +34985,7 @@ async function enhancedSearch(paths, options) {
34179
34985
  for (const entry of entries) {
34180
34986
  if (!index[entry.id]) {
34181
34987
  index[entry.id] = {
34182
- path: path18__default.join("wiki", `${entry.id}.md`),
34988
+ path: path19__default.join("wiki", `${entry.id}.md`),
34183
34989
  title: entry.title,
34184
34990
  tags: entry.tags,
34185
34991
  updated: entry.updated
@@ -34315,7 +35121,7 @@ function toEnhancedHit(entry, signals) {
34315
35121
  score: enhancedScore,
34316
35122
  reason: signals.legacyReason ?? "body",
34317
35123
  excerpt,
34318
- path: path18__default.join("wiki", `${entry.id}.md`),
35124
+ path: path19__default.join("wiki", `${entry.id}.md`),
34319
35125
  tags: entry.tags,
34320
35126
  updated: entry.updated,
34321
35127
  version: entry.version,
@@ -34511,7 +35317,7 @@ function toRankedHit(entry, reason, detail, graphBoost, backlinksById) {
34511
35317
  score: basePriority * 100 + statusPriority * 10 + graphScore + (detail.tagBoost ?? 0),
34512
35318
  reason,
34513
35319
  excerpt,
34514
- path: path18__default.join("wiki", `${entry.id}.md`),
35320
+ path: path19__default.join("wiki", `${entry.id}.md`),
34515
35321
  tags: entry.tags,
34516
35322
  updated: entry.updated,
34517
35323
  version: entry.version,
@@ -36053,8 +36859,8 @@ function CreateObject(types, value) {
36053
36859
  }
36054
36860
  function FromUnionKey(types, value) {
36055
36861
  const flattened = Flatten(types);
36056
- const record6 = TryBuildRecord(flattened, value);
36057
- return IsSchema(record6) ? record6 : CreateObject(flattened, value);
36862
+ const record7 = TryBuildRecord(flattened, value);
36863
+ return IsSchema(record7) ? record7 : CreateObject(flattened, value);
36058
36864
  }
36059
36865
 
36060
36866
  // ../../node_modules/.pnpm/typebox@1.1.34/node_modules/typebox/build/type/engine/record/from_key.mjs
@@ -39277,13 +40083,13 @@ async function readClaims(entryId, paths) {
39277
40083
  }
39278
40084
  }
39279
40085
  function getClaimsDir(paths) {
39280
- return path18__default.join(paths.wikiDir, CLAIMS_DIRNAME);
40086
+ return path19__default.join(paths.wikiDir, CLAIMS_DIRNAME);
39281
40087
  }
39282
40088
  function getClaimsFile(paths, entryId) {
39283
40089
  assertSafeEntryId(entryId);
39284
- const claimsFile = path18__default.join(getClaimsDir(paths), `${entryId}.json`);
39285
- const relative = path18__default.relative(getClaimsDir(paths), claimsFile);
39286
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) {
40090
+ const claimsFile = path19__default.join(getClaimsDir(paths), `${entryId}.json`);
40091
+ const relative = path19__default.relative(getClaimsDir(paths), claimsFile);
40092
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
39287
40093
  throw new Error(`[fleet-wiki] claims sidecar escapes wiki/.claims: ${entryId}`);
39288
40094
  }
39289
40095
  return claimsFile;
@@ -39374,7 +40180,7 @@ function assertSafeClaimRawRef(ref) {
39374
40180
  if (!ref.startsWith("raw/")) {
39375
40181
  throw new Error(`claim sourceRef must point into raw/: ${ref}`);
39376
40182
  }
39377
- if (ref.includes("..") || path18__default.isAbsolute(ref)) {
40183
+ if (ref.includes("..") || path19__default.isAbsolute(ref)) {
39378
40184
  throw new Error(`claim sourceRef escapes raw/: ${ref}`);
39379
40185
  }
39380
40186
  }
@@ -39452,22 +40258,22 @@ async function runDryDock(paths, options = {}) {
39452
40258
  }
39453
40259
  for (const fileName of await listFileNames(paths.rawDir)) {
39454
40260
  if (!fileName.endsWith(".md")) continue;
39455
- const filePath = path18__default.join(paths.rawDir, fileName);
40261
+ const filePath = path19__default.join(paths.rawDir, fileName);
39456
40262
  issues.push(...safetyIssues(await readPatchFile(filePath), filePath));
39457
40263
  }
39458
40264
  for (const queueId of await listDirectoryNames(paths.queueDir)) {
39459
40265
  if (queueId === PATCH_SET_DIRNAME) continue;
39460
- const queueDir = path18__default.join(paths.queueDir, queueId);
40266
+ const queueDir = path19__default.join(paths.queueDir, queueId);
39461
40267
  try {
39462
- const patchContent = await readPatchFile(path18__default.join(queueDir, PATCH_FILENAME));
39463
- issues.push(...safetyIssues(patchContent, path18__default.join(queueDir, PATCH_FILENAME)));
39464
- await readJsonFile2(path18__default.join(queueDir, PATCH_META_FILENAME));
40268
+ const patchContent = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
40269
+ issues.push(...safetyIssues(patchContent, path19__default.join(queueDir, PATCH_FILENAME)));
40270
+ await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME));
39465
40271
  } catch {
39466
40272
  issues.push(issue2("malformed_queue", "error", "\uC190\uC0C1\uB41C queue \uC5D4\uD2B8\uB9AC", queueDir));
39467
40273
  }
39468
40274
  }
39469
- for (const patchSetId of await listDirectoryNames(path18__default.join(paths.queueDir, PATCH_SET_DIRNAME))) {
39470
- const patchSetMetaFile = path18__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId, PATCH_META_FILENAME);
40275
+ for (const patchSetId of await listDirectoryNames(path19__default.join(paths.queueDir, PATCH_SET_DIRNAME))) {
40276
+ const patchSetMetaFile = path19__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId, PATCH_META_FILENAME);
39471
40277
  let patchSet;
39472
40278
  try {
39473
40279
  patchSet = await readPatchSet(paths, patchSetId);
@@ -39476,8 +40282,8 @@ async function runDryDock(paths, options = {}) {
39476
40282
  continue;
39477
40283
  }
39478
40284
  for (const patchId of patchSet.patchIds) {
39479
- const queueMetaFile = path18__default.join(paths.queueDir, patchId, PATCH_META_FILENAME);
39480
- const archiveMetaFile = path18__default.join(paths.archiveDir, patchId, PATCH_META_FILENAME);
40285
+ const queueMetaFile = path19__default.join(paths.queueDir, patchId, PATCH_META_FILENAME);
40286
+ const archiveMetaFile = path19__default.join(paths.archiveDir, patchId, PATCH_META_FILENAME);
39481
40287
  if (!await pathExists(queueMetaFile) && !await pathExists(archiveMetaFile)) {
39482
40288
  issues.push(
39483
40289
  issue2(
@@ -39514,7 +40320,7 @@ async function runDryDock(paths, options = {}) {
39514
40320
  "conflict_unresolved",
39515
40321
  "warning",
39516
40322
  `\uBBF8\uD574\uACB0 conflict: ${conflict.reason} (${conflict.target})`,
39517
- path18__default.join(paths.conflictsDir, conflict.id, "meta.json")
40323
+ path19__default.join(paths.conflictsDir, conflict.id, "meta.json")
39518
40324
  )
39519
40325
  );
39520
40326
  }
@@ -39527,7 +40333,7 @@ async function runDryDock(paths, options = {}) {
39527
40333
  "unresolved_conflict",
39528
40334
  "warning",
39529
40335
  "\uC190\uC0C1\uB41C conflict \uC5D4\uD2B8\uB9AC",
39530
- path18__default.join(paths.conflictsDir, conflictId, "meta.json")
40336
+ path19__default.join(paths.conflictsDir, conflictId, "meta.json")
39531
40337
  )
39532
40338
  );
39533
40339
  }
@@ -39584,8 +40390,8 @@ async function claimIssues(paths, wikiIds) {
39584
40390
  const claimsDir = getClaimsDir(paths);
39585
40391
  for (const fileName of await listFileNames(claimsDir)) {
39586
40392
  if (!fileName.endsWith(".json")) continue;
39587
- const filePath = path18__default.join(claimsDir, fileName);
39588
- const entryIdFromFile = path18__default.basename(fileName, ".json");
40393
+ const filePath = path19__default.join(claimsDir, fileName);
40394
+ const entryIdFromFile = path19__default.basename(fileName, ".json");
39589
40395
  let raw;
39590
40396
  try {
39591
40397
  raw = await readJsonFile2(filePath);
@@ -39664,7 +40470,7 @@ function toSemanticEntry(filePath, frontmatter, body) {
39664
40470
  async function schemaIssues(paths) {
39665
40471
  const issues = [];
39666
40472
  const schema = await readWorkspaceSchemaSummary(paths);
39667
- const agentsPath = path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
40473
+ const agentsPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
39668
40474
  if (!await pathExists(schema.wikiSchemaPath)) {
39669
40475
  issues.push(issue2("schema_missing", "warning", `Workspace schema file is missing: schema/${WORKSPACE_SCHEMA_FILENAME}`, schema.wikiSchemaPath));
39670
40476
  } else {
@@ -40051,7 +40857,7 @@ async function listWikiMarkdownFiles(dirPath) {
40051
40857
  const files = [];
40052
40858
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
40053
40859
  for (const entry of sortedEntries) {
40054
- const filePath = path18__default.join(dirPath, entry.name);
40860
+ const filePath = path19__default.join(dirPath, entry.name);
40055
40861
  if (entry.isDirectory()) {
40056
40862
  files.push(...await listWikiMarkdownFiles(filePath));
40057
40863
  continue;
@@ -40275,7 +41081,7 @@ async function resolveCompileSource(input, paths, now) {
40275
41081
  }
40276
41082
  async function buildCompileProposals(input, paths, now, resolvedSource) {
40277
41083
  const sourceTarget = `wiki/sources/${resolvedSource.sourcePageId}.md`;
40278
- const sourceExists = await pathExists(path18__default.join(paths.root, sourceTarget));
41084
+ const sourceExists = await pathExists(path19__default.join(paths.root, sourceTarget));
40279
41085
  const existingEntries = await listWiki(paths);
40280
41086
  const sourcePageTitle = resolvedSource.sourceTitle?.trim() || `Source ${resolvedSource.sourcePageId}`;
40281
41087
  const existingSourceEntry = existingEntries.find((entry) => entry.id === resolvedSource.sourcePageId);
@@ -40297,7 +41103,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
40297
41103
  target: sourceTarget,
40298
41104
  summary: truncateSummary(`Compile source page ${sourcePageTitle}`),
40299
41105
  entry: sourceEntry,
40300
- baseHash: sourceExists ? computeContentHash(await readPatchFile(path18__default.join(paths.root, sourceTarget))) : void 0,
41106
+ baseHash: sourceExists ? computeContentHash(await readPatchFile(path19__default.join(paths.root, sourceTarget))) : void 0,
40301
41107
  baseVersion: existingSourceEntry?.version
40302
41108
  }];
40303
41109
  const relatedCandidates = await discoverRelatedEntryCandidates(paths, resolvedSource.sourceContent, resolvedSource.sourceTitle);
@@ -40317,7 +41123,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
40317
41123
  rawSourceRefs: mergeRawSourceRefs(existing.rawSourceRefs, existing.rawSourceRef, { ref: resolvedSource.rawSourceRef }),
40318
41124
  body: appendSourceCompileNote(existing.body, resolvedSource.sourcePageId, resolvedSource.rawSourceRef)
40319
41125
  },
40320
- baseHash: computeContentHash(await readPatchFile(path18__default.join(paths.wikiDir, `${existing.id}.md`))),
41126
+ baseHash: computeContentHash(await readPatchFile(path19__default.join(paths.wikiDir, `${existing.id}.md`))),
40321
41127
  baseVersion: existing.version
40322
41128
  });
40323
41129
  }
@@ -40491,7 +41297,7 @@ async function planIngest(input, paths, now) {
40491
41297
  const target2 = `wiki/${input.id}.md`;
40492
41298
  const proposer = input.proposer ?? "tool:wiki_ingest";
40493
41299
  const currentEntry = await readWikiEntry(input.id, paths);
40494
- const currentMarkdown = currentEntry ? await readPatchFile(path18__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
41300
+ const currentMarkdown = currentEntry ? await readPatchFile(path19__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
40495
41301
  const currentHash = currentMarkdown ? computeContentHash(currentMarkdown) : void 0;
40496
41302
  const rawSource = buildRawSourceEntry(input, now);
40497
41303
  await ensureWorkspaceSchema(paths);
@@ -40686,7 +41492,7 @@ async function stageIngestPlan(plan, paths) {
40686
41492
  })
40687
41493
  };
40688
41494
  if (plan.kind === "conflict") {
40689
- const record6 = await createConflict({
41495
+ const record7 = await createConflict({
40690
41496
  reason: plan.conflict.reason,
40691
41497
  target: `wiki/${entry.id}.md`,
40692
41498
  wikiId: entry.id,
@@ -40704,17 +41510,17 @@ async function stageIngestPlan(plan, paths) {
40704
41510
  warnings: plan.warnings
40705
41511
  }, paths);
40706
41512
  await appendLog(paths, "conflict detected", {
40707
- conflict_id: record6.meta.id,
41513
+ conflict_id: record7.meta.id,
40708
41514
  patch_id: null,
40709
41515
  raw_source_ref: rawSourceRef,
40710
41516
  reason: plan.conflict.reason,
40711
- target: record6.meta.target,
40712
- wiki_id: record6.meta.wikiId
41517
+ target: record7.meta.target,
41518
+ wiki_id: record7.meta.wikiId
40713
41519
  });
40714
41520
  return {
40715
41521
  ok: false,
40716
41522
  mode: plan.mode,
40717
- conflict_id: record6.meta.id,
41523
+ conflict_id: record7.meta.id,
40718
41524
  raw_source_ref: rawSourceRef,
40719
41525
  warnings: plan.warnings
40720
41526
  };
@@ -41170,11 +41976,11 @@ async function editQueuedPatch(input, paths) {
41170
41976
  };
41171
41977
  }
41172
41978
  async function readQueuedPatchSnapshot(paths, patchId) {
41173
- const queueDir = path18__default.join(paths.queueDir, patchId);
41174
- const markdown = await readPatchFile(path18__default.join(queueDir, PATCH_FILENAME));
41979
+ const queueDir = path19__default.join(paths.queueDir, patchId);
41980
+ const markdown = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
41175
41981
  return {
41176
41982
  patch: await parsePatch(markdown),
41177
- meta: await readJsonFile2(path18__default.join(queueDir, PATCH_META_FILENAME)),
41983
+ meta: await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME)),
41178
41984
  patchHash: computeContentHash(markdown)
41179
41985
  };
41180
41986
  }
@@ -41260,11 +42066,11 @@ function applyBodyReplacement(entry, replaceInput) {
41260
42066
  }
41261
42067
  function parseBodyReplace(value) {
41262
42068
  if (value === void 0 || value === null) return void 0;
41263
- const record6 = value;
42069
+ const record7 = value;
41264
42070
  return {
41265
- find: String(record6.find ?? ""),
41266
- replace: String(record6.replace ?? ""),
41267
- expected_occurrences: typeof record6.expected_occurrences === "number" ? record6.expected_occurrences : void 0
42071
+ find: String(record7.find ?? ""),
42072
+ replace: String(record7.replace ?? ""),
42073
+ expected_occurrences: typeof record7.expected_occurrences === "number" ? record7.expected_occurrences : void 0
41268
42074
  };
41269
42075
  }
41270
42076
  function stringParam(value) {
@@ -41936,7 +42742,7 @@ ${input.answer ?? ""}`)}`;
41936
42742
  assertSafeEntryId(targetId);
41937
42743
  const subdir = input.targetType === "synthesis" ? "synthesis" : "queries";
41938
42744
  const target2 = `wiki/${subdir}/${targetId}.md`;
41939
- const absoluteTarget = path18__default.join(paths.root, target2);
42745
+ const absoluteTarget = path19__default.join(paths.root, target2);
41940
42746
  const exists = await pathExists(absoluteTarget);
41941
42747
  const existingEntry = exists ? await readWikiEntry(targetId, paths) : null;
41942
42748
  if (exists && !existingEntry) {
@@ -42018,7 +42824,7 @@ function assertSafeRawRef(rawRef) {
42018
42824
  if (!rawRef.startsWith("raw/")) {
42019
42825
  throw new Error(`[fleet-wiki] wiki_query raw source ref must point into raw/: ${rawRef}`);
42020
42826
  }
42021
- if (rawRef.includes("..") || path18__default.isAbsolute(rawRef)) {
42827
+ if (rawRef.includes("..") || path19__default.isAbsolute(rawRef)) {
42022
42828
  throw new Error(`[fleet-wiki] wiki_query raw source ref escapes raw/: ${rawRef}`);
42023
42829
  }
42024
42830
  }
@@ -42587,15 +43393,15 @@ function buildWikiResolveSpec(resolver) {
42587
43393
  ]
42588
43394
  }, resolver);
42589
43395
  }
42590
- function buildWikiToolSpec(config2, usage3, resolver) {
43396
+ function buildWikiToolSpec(config2, usage4, resolver) {
42591
43397
  return {
42592
43398
  id: config2.name,
42593
43399
  tag: config2.name,
42594
43400
  title: config2.label,
42595
43401
  description: config2.description,
42596
43402
  promptSnippet: config2.promptSnippet,
42597
- whenToUse: usage3.whenToUse,
42598
- whenNotToUse: usage3.whenNotToUse,
43403
+ whenToUse: usage4.whenToUse,
43404
+ whenNotToUse: usage4.whenNotToUse,
42599
43405
  usageGuidelines: config2.promptGuidelines,
42600
43406
  parameters: config2.parameters,
42601
43407
  execute: async (args, ctx) => {
@@ -42624,16 +43430,16 @@ function createResolver(deps, hooks) {
42624
43430
  } };
42625
43431
  }
42626
43432
  function resolveLocked(workspace, hooks) {
42627
- const destination = path18__default.join(workspace.path, "knowledge");
42628
- const source = path18__default.join(workspace.cwd, ".fleet", "knowledge");
42629
- const markerPath = path18__default.join(workspace.path, MARKER_NAME);
43433
+ const destination = path19__default.join(workspace.path, "knowledge");
43434
+ const source = path19__default.join(workspace.cwd, ".fleet", "knowledge");
43435
+ const markerPath = path19__default.join(workspace.path, MARKER_NAME);
42630
43436
  const destinationState = inspectTree(destination, true);
42631
43437
  if (destinationState === "content") return createMemoryPaths(destination);
42632
43438
  if (destinationState === "unsafe") throw new Error("Unsafe Fleet Wiki destination state");
42633
43439
  const marker = readMarker(markerPath);
42634
43440
  const stagingEntries = inspectReservedControlState(workspace.path);
42635
43441
  if (marker) {
42636
- const staging2 = path18__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
43442
+ const staging2 = path19__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
42637
43443
  const stagingState = inspectTree(staging2);
42638
43444
  if (stagingState === "content") {
42639
43445
  removeEmptyDirectories(destination);
@@ -42648,7 +43454,7 @@ function resolveLocked(workspace, hooks) {
42648
43454
  if (sourceState !== "content") return createMemoryPaths(destination);
42649
43455
  removeEmptyDirectories(destination);
42650
43456
  const transactionId = randomUUID();
42651
- const staging = path18__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
43457
+ const staging = path19__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
42652
43458
  copyTree(source, staging, hooks);
42653
43459
  if (inspectTree(staging) !== "content") throw new Error("Invalid Fleet Wiki migration staging result");
42654
43460
  syncDirectory(staging);
@@ -42676,7 +43482,7 @@ function inspectTree(target2, regularRootIsContent = false, treeRoot = target2)
42676
43482
  if (nodeKind === "file") return regularRootIsContent ? "content" : "unsafe";
42677
43483
  let content = false;
42678
43484
  for (const entry of fs9.readdirSync(target2, { withFileTypes: true })) {
42679
- const entryPath = path18__default.join(target2, entry.name);
43485
+ const entryPath = path19__default.join(target2, entry.name);
42680
43486
  if (entry.isSymbolicLink()) {
42681
43487
  if (readSafeFileSymlink(treeRoot, entryPath) === null) return "unsafe";
42682
43488
  content = true;
@@ -42708,15 +43514,15 @@ function readMarker(markerPath) {
42708
43514
  throw new Error("Invalid Fleet Wiki migration marker");
42709
43515
  }
42710
43516
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Fleet Wiki migration marker");
42711
- const record6 = value;
42712
- 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");
42713
- return record6;
43517
+ const record7 = value;
43518
+ if (record7.version !== 1 || record7.outcome !== "copied" || typeof record7.transactionId !== "string" || !/^[0-9a-f-]{36}$/i.test(record7.transactionId) || typeof record7.completedAt !== "string") throw new Error("Invalid Fleet Wiki migration marker");
43519
+ return record7;
42714
43520
  }
42715
43521
  function copyTree(source, destination, hooks, sourceRoot = source) {
42716
43522
  fs9.mkdirSync(destination, { recursive: true });
42717
43523
  for (const entry of fs9.readdirSync(source, { withFileTypes: true })) {
42718
- const from = path18__default.join(source, entry.name);
42719
- const to = path18__default.join(destination, entry.name);
43524
+ const from = path19__default.join(source, entry.name);
43525
+ const to = path19__default.join(destination, entry.name);
42720
43526
  const stat4 = fs9.lstatSync(from);
42721
43527
  if (stat4.isSymbolicLink()) {
42722
43528
  const target2 = readSafeFileSymlink(sourceRoot, from);
@@ -42736,9 +43542,9 @@ function copyTree(source, destination, hooks, sourceRoot = source) {
42736
43542
  }
42737
43543
  function readSafeFileSymlink(treeRoot, linkPath) {
42738
43544
  const target2 = fs9.readlinkSync(linkPath);
42739
- if (path18__default.posix.isAbsolute(target2) || path18__default.win32.isAbsolute(target2)) return null;
42740
- const lexicalRoot = path18__default.resolve(treeRoot);
42741
- const lexicalTarget = path18__default.resolve(path18__default.dirname(linkPath), target2);
43545
+ if (path19__default.posix.isAbsolute(target2) || path19__default.win32.isAbsolute(target2)) return null;
43546
+ const lexicalRoot = path19__default.resolve(treeRoot);
43547
+ const lexicalTarget = path19__default.resolve(path19__default.dirname(linkPath), target2);
42742
43548
  if (!isWithinRoot(lexicalRoot, lexicalTarget)) return null;
42743
43549
  let canonicalRoot;
42744
43550
  let canonicalTarget;
@@ -42755,8 +43561,8 @@ function readSafeFileSymlink(treeRoot, linkPath) {
42755
43561
  return target2;
42756
43562
  }
42757
43563
  function isWithinRoot(root, target2) {
42758
- const relative = path18__default.relative(root, target2);
42759
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path18__default.sep}`) && !path18__default.isAbsolute(relative);
43564
+ const relative = path19__default.relative(root, target2);
43565
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path19__default.sep}`) && !path19__default.isAbsolute(relative);
42760
43566
  }
42761
43567
  function classifyWikiWorkspaceNodeForTest(stat4) {
42762
43568
  if (stat4.isSymbolicLink()) return "unsafe";
@@ -42771,13 +43577,13 @@ function removeEmptyDirectories(target2) {
42771
43577
  if (state === "empty") fs9.rmSync(target2, { recursive: true, force: false });
42772
43578
  }
42773
43579
  function removePriorStaging(workspacePath, stagingEntries) {
42774
- for (const name of stagingEntries) fs9.rmSync(path18__default.join(workspacePath, name), { recursive: true, force: false });
43580
+ for (const name of stagingEntries) fs9.rmSync(path19__default.join(workspacePath, name), { recursive: true, force: false });
42775
43581
  }
42776
43582
  function inspectReservedControlState(workspacePath) {
42777
43583
  const stagingEntries = [];
42778
43584
  for (const entry of fs9.readdirSync(workspacePath, { withFileTypes: true })) {
42779
43585
  if (entry.name.startsWith(`${MARKER_NAME}.`)) {
42780
- const residuePath = path18__default.join(workspacePath, entry.name);
43586
+ const residuePath = path19__default.join(workspacePath, entry.name);
42781
43587
  const residue = fs9.lstatSync(residuePath);
42782
43588
  if (MARKER_TEMP_REGEXP.test(entry.name) && residue.isFile() && !residue.isSymbolicLink()) {
42783
43589
  fs9.unlinkSync(residuePath);
@@ -42787,7 +43593,7 @@ function inspectReservedControlState(workspacePath) {
42787
43593
  }
42788
43594
  if (!entry.name.startsWith(STAGING_PREFIX)) continue;
42789
43595
  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");
42790
- if (inspectTree(path18__default.join(workspacePath, entry.name)) === "unsafe") throw new Error("Unsafe Fleet Wiki migration staging state");
43596
+ if (inspectTree(path19__default.join(workspacePath, entry.name)) === "unsafe") throw new Error("Unsafe Fleet Wiki migration staging state");
42791
43597
  stagingEntries.push(entry.name);
42792
43598
  }
42793
43599
  return stagingEntries;
@@ -42872,18 +43678,18 @@ function resolveConsolePackageRequire(currentFile, fallback) {
42872
43678
  function findConsolePackageRequire(currentFile) {
42873
43679
  const explicitRoot = process.env.FLEET_CONSOLE_PACKAGE_ROOT;
42874
43680
  if (explicitRoot) {
42875
- const explicitPackageJson = path18__default.join(explicitRoot, "package.json");
43681
+ const explicitPackageJson = path19__default.join(explicitRoot, "package.json");
42876
43682
  if (isFleetConsolePackage(explicitPackageJson)) return createRequire(explicitPackageJson);
42877
43683
  }
42878
- let dir = path18__default.dirname(currentFile);
43684
+ let dir = path19__default.dirname(currentFile);
42879
43685
  while (true) {
42880
- const packageJson = path18__default.join(dir, "package.json");
43686
+ const packageJson = path19__default.join(dir, "package.json");
42881
43687
  if (isFleetConsolePackage(packageJson)) return createRequire(packageJson);
42882
- const nestedConsolePackage = path18__default.join(dir, "runtime", "fleet-console", "package.json");
43688
+ const nestedConsolePackage = path19__default.join(dir, "runtime", "fleet-console", "package.json");
42883
43689
  if (isFleetConsolePackage(nestedConsolePackage)) return createRequire(nestedConsolePackage);
42884
- const siblingConsolePackage = path18__default.join(dir, "..", "..", "fleet-console", "package.json");
43690
+ const siblingConsolePackage = path19__default.join(dir, "..", "..", "fleet-console", "package.json");
42885
43691
  if (isFleetConsolePackage(siblingConsolePackage)) return createRequire(siblingConsolePackage);
42886
- const parent = path18__default.dirname(dir);
43692
+ const parent = path19__default.dirname(dir);
42887
43693
  if (parent === dir) return null;
42888
43694
  dir = parent;
42889
43695
  }
@@ -42950,7 +43756,7 @@ function resolveUseConptyDll(platform, env) {
42950
43756
  }
42951
43757
  function loadNodePty() {
42952
43758
  const nodePtyRequire = loadNodePtyRequire(fileURLToPath(import.meta.url));
42953
- ensureNodePtySpawnHelpersExecutable(path18__default.dirname(nodePtyRequire.resolve("node-pty/package.json")));
43759
+ ensureNodePtySpawnHelpersExecutable(path19__default.dirname(nodePtyRequire.resolve("node-pty/package.json")));
42954
43760
  return nodePtyRequire("node-pty");
42955
43761
  }
42956
43762
  function loadNodePtyRequire(currentFile) {
@@ -42959,7 +43765,7 @@ function loadNodePtyRequire(currentFile) {
42959
43765
  function ensureNodePtySpawnHelpersExecutable(packageRoot, platform = process4.platform, architecture = process4.arch) {
42960
43766
  if (platform !== "darwin") return;
42961
43767
  for (const directory of ["build/Release", "build/Debug", `prebuilds/darwin-${architecture}`]) {
42962
- const helper = path18__default.join(packageRoot, directory, "spawn-helper");
43768
+ const helper = path19__default.join(packageRoot, directory, "spawn-helper");
42963
43769
  try {
42964
43770
  const stat4 = lstatSync(helper);
42965
43771
  if (!stat4.isFile() || stat4.isSymbolicLink() || (stat4.mode & 73) === 73) continue;
@@ -43660,7 +44466,7 @@ function serializeAgentCliPathsWrite(write) {
43660
44466
  return result;
43661
44467
  }
43662
44468
  function normalizeAgentCliPaths(value) {
43663
- if (!isRecord11(value) || value.version !== 1 || !isRecord11(value.paths)) {
44469
+ if (!isRecord12(value) || value.version !== 1 || !isRecord12(value.paths)) {
43664
44470
  return { version: 1, paths: {} };
43665
44471
  }
43666
44472
  const paths = {};
@@ -43675,7 +44481,7 @@ function resolveAgentCliBinary(options) {
43675
44481
  const envName = OVERRIDE_ENV_BY_COMMAND[options.cliCommand];
43676
44482
  const envOverride = envName ? options.env[envName]?.trim() : void 0;
43677
44483
  if (envOverride) {
43678
- const searchedPathEntries2 = path18__default.isAbsolute(envOverride) ? [] : readPathEntries(options.env, platform);
44484
+ const searchedPathEntries2 = path19__default.isAbsolute(envOverride) ? [] : readPathEntries(options.env, platform);
43679
44485
  const resolved2 = resolveBinarySafely(envOverride, options.env, platform);
43680
44486
  if (!resolved2) {
43681
44487
  return { resolved: void 0, source: "env", error: "path_not_found", launchPath: envOverride, searchedPathEntries: searchedPathEntries2 };
@@ -43717,7 +44523,7 @@ function applyAgentCliPathEnvOverlay(env, cliId, userPaths) {
43717
44523
  return { ...env, [envName]: userPath };
43718
44524
  }
43719
44525
  function resolveConfiguredPath(executablePath, env, platform) {
43720
- if (executablePath.includes("\0") || executablePath.startsWith("~") || !path18__default.isAbsolute(executablePath)) {
44526
+ if (executablePath.includes("\0") || executablePath.startsWith("~") || !path19__default.isAbsolute(executablePath)) {
43721
44527
  return { resolved: void 0, error: "path_not_absolute" };
43722
44528
  }
43723
44529
  let stats;
@@ -43758,10 +44564,10 @@ function validateResolvedFile(resolved, platform) {
43758
44564
  }
43759
44565
  function readPathEntries(env, platform) {
43760
44566
  const value = platform === "win32" ? env.Path ?? env.PATH ?? "" : env.PATH ?? "";
43761
- const separator = platform === "win32" ? ";" : path18__default.delimiter;
44567
+ const separator = platform === "win32" ? ";" : path19__default.delimiter;
43762
44568
  return value.split(separator).filter((entry) => entry.length > 0);
43763
44569
  }
43764
- function isRecord11(value) {
44570
+ function isRecord12(value) {
43765
44571
  return typeof value === "object" && value !== null && !Array.isArray(value);
43766
44572
  }
43767
44573
  function isNodeError(error51) {
@@ -44153,9 +44959,9 @@ function claudeGatewayModelCache(options) {
44153
44959
 
44154
44960
  // ../../packages/core-agent/src/claude/config-dir.ts
44155
44961
  async function createIsolatedClaudeConfigDir(tempRoot = tmpdir()) {
44156
- const root = await mkdtemp(path18__default.join(tempRoot, "core-agent-claude-"));
44157
- const cachePath = path18__default.join(root, CLAUDE_GATEWAY_MODEL_CACHE_RELPATH);
44158
- await mkdir(path18__default.dirname(cachePath), { recursive: true, mode: 448 });
44962
+ const root = await mkdtemp(path19__default.join(tempRoot, "core-agent-claude-"));
44963
+ const cachePath = path19__default.join(root, CLAUDE_GATEWAY_MODEL_CACHE_RELPATH);
44964
+ await mkdir(path19__default.dirname(cachePath), { recursive: true, mode: 448 });
44159
44965
  let disposed = false;
44160
44966
  return {
44161
44967
  path: root,
@@ -44441,7 +45247,7 @@ function buildConsoleAutoNameHookCommand(entry) {
44441
45247
  return buildConsoleCliHookExec(entry, ["hook", "auto-name"]);
44442
45248
  }
44443
45249
  function buildConsoleCaptureHookCommand(entry, cliId, createCaptureHook = createSessionCaptureHookExec) {
44444
- const extension = path18__default.extname(entry.entryPath);
45250
+ const extension = path19__default.extname(entry.entryPath);
44445
45251
  if (JAVASCRIPT_ENTRY_EXTENSIONS.has(extension)) {
44446
45252
  return createCaptureHook({
44447
45253
  entryPath: entry.entryPath,
@@ -44467,11 +45273,11 @@ function toCaptureProvider(cliId) {
44467
45273
  }
44468
45274
  function withConsoleMarketplaceLock(target2, fn) {
44469
45275
  const lockDir = `${target2}${MARKETPLACE_LOCK_DIR_SUFFIX}`;
44470
- mkdirSync(path18__default.dirname(lockDir), { recursive: true });
45276
+ mkdirSync(path19__default.dirname(lockDir), { recursive: true });
44471
45277
  return withDirectoryLock({ lockDir }, fn);
44472
45278
  }
44473
45279
  function buildConsoleCliHookExec(entry, trailingArgs) {
44474
- const extension = path18__default.extname(entry.entryPath);
45280
+ const extension = path19__default.extname(entry.entryPath);
44475
45281
  if (JAVASCRIPT_ENTRY_EXTENSIONS.has(extension)) {
44476
45282
  return {
44477
45283
  command: entry.execPath,
@@ -44586,7 +45392,7 @@ function resolveHookEntryPath(candidate) {
44586
45392
  return CONSOLE_ENTRY_PATH;
44587
45393
  }
44588
45394
  function hasHookEntryExtension(entryPath) {
44589
- return HOOK_ENTRY_EXTENSIONS.has(path18__default.extname(entryPath));
45395
+ return HOOK_ENTRY_EXTENSIONS.has(path19__default.extname(entryPath));
44590
45396
  }
44591
45397
  async function createAgentCliLaunchSpec(options) {
44592
45398
  const cleanupStack = [];
@@ -44825,7 +45631,7 @@ function createConsoleObservabilityStore(deps = {}) {
44825
45631
  return terminalSessionsById.get(sessionId)?.cwd ?? workspacesByCliRunId.get(sessionId)?.session.cwd ?? null;
44826
45632
  }
44827
45633
  function createPendingTerminalSession(input) {
44828
- if (!path18__default.isAbsolute(input.cwd)) throw new Error("Terminal session cwd must be absolute");
45634
+ if (!path19__default.isAbsolute(input.cwd)) throw new Error("Terminal session cwd must be absolute");
44829
45635
  const createdAt = input.createdAt ?? now();
44830
45636
  const canonicalCwd = canonicalizeTheaterPath(input.cwd);
44831
45637
  const theaterId = workspaceHash(canonicalCwd);
@@ -44835,7 +45641,7 @@ function createConsoleObservabilityStore(deps = {}) {
44835
45641
  sessionId: input.sessionId,
44836
45642
  cwd: input.cwd,
44837
45643
  canonicalCwd,
44838
- cwdLabel: path18__default.basename(input.cwd) || input.cwd,
45644
+ cwdLabel: path19__default.basename(input.cwd) || input.cwd,
44839
45645
  cliId: input.cliId,
44840
45646
  createdAt,
44841
45647
  theaterId,
@@ -44852,7 +45658,7 @@ function createConsoleObservabilityStore(deps = {}) {
44852
45658
  sessionId: operation.sessionId,
44853
45659
  cwd: operation.cwd,
44854
45660
  canonicalCwd: canonicalizeTheaterPath(operation.cwd),
44855
- cwdLabel: path18__default.basename(operation.cwd) || operation.cwd,
45661
+ cwdLabel: path19__default.basename(operation.cwd) || operation.cwd,
44856
45662
  label: operation.label,
44857
45663
  labelSource: operation.labelSource,
44858
45664
  providerTitle: operation.providerTitle,
@@ -45113,7 +45919,7 @@ function defaultWorkspaceHash(canonicalCwd) {
45113
45919
  return crypto5.createHash("sha256").update(canonicalCwd).digest("hex").slice(0, 12);
45114
45920
  }
45115
45921
  function defaultCanonicalizeTheaterPath(cwd) {
45116
- const resolved = path18__default.resolve(cwd);
45922
+ const resolved = path19__default.resolve(cwd);
45117
45923
  try {
45118
45924
  return fs9__default.realpathSync.native(resolved);
45119
45925
  } catch {
@@ -45543,24 +46349,24 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45543
46349
  registerCleanup: (cleanup2) => ctx.host.lifecycle.registerCleanup(cleanup2)
45544
46350
  });
45545
46351
  async function handle({ req, res, pathname }) {
45546
- const path42 = pathname.slice(`${ctx.basePath}/agent`.length) || "/";
45547
- if (path42 === "/state") {
46352
+ const path43 = pathname.slice(`${ctx.basePath}/agent`.length) || "/";
46353
+ if (path43 === "/state") {
45548
46354
  if (req.method !== "GET") return methodNotAllowed2(res);
45549
46355
  ctx.host.http.writeJson(res, 200, { agentClis: await buildAgentCliLaunchMetadata() });
45550
46356
  return true;
45551
46357
  }
45552
- if (path42 === "/agent-cli/state") {
46358
+ if (path43 === "/agent-cli/state") {
45553
46359
  if (req.method !== "GET") return methodNotAllowed2(res);
45554
46360
  ctx.host.http.writeJson(res, 200, { clis: await detector.detect() });
45555
46361
  return true;
45556
46362
  }
45557
- if (path42 === "/agent-cli/diagnostics") {
46363
+ if (path43 === "/agent-cli/diagnostics") {
45558
46364
  if (req.method !== "GET") return methodNotAllowed2(res);
45559
46365
  if (!ctx.host.security.isTerminalAuthorized(req)) return unauthorized(res);
45560
46366
  ctx.host.http.writeJson(res, 200, await buildAgentCliDiagnostics());
45561
46367
  return true;
45562
46368
  }
45563
- if (path42 === "/agent-cli/path") {
46369
+ if (path43 === "/agent-cli/path") {
45564
46370
  if (req.method !== "PUT") return methodNotAllowed2(res);
45565
46371
  if (!ctx.host.security.isTerminalAuthorized(req)) return unauthorized(res);
45566
46372
  const body = await ctx.host.http.readJsonBody(req);
@@ -45580,15 +46386,15 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45580
46386
  ctx.host.http.writeJson(res, 200, { ok: true });
45581
46387
  return true;
45582
46388
  }
45583
- if (path42 === "/events") {
46389
+ if (path43 === "/events") {
45584
46390
  if (req.method !== "GET") return methodNotAllowed2(res);
45585
46391
  writeAgentSessionEvents(req, res, observability);
45586
46392
  return true;
45587
46393
  }
45588
- if (path42 === "/sessions") return handleSessions(req, res);
45589
- const sessionMatch = path42.match(/^\/sessions\/([^/]+)(?:\/([^/]+))?$/);
46394
+ if (path43 === "/sessions") return handleSessions(req, res);
46395
+ const sessionMatch = path43.match(/^\/sessions\/([^/]+)(?:\/([^/]+))?$/);
45590
46396
  if (sessionMatch) return handleSessionItem(req, res, decodeURIComponent(sessionMatch[1] ?? ""), sessionMatch[2] ?? "");
45591
- if (path42 === "/ticket") {
46397
+ if (path43 === "/ticket") {
45592
46398
  if (req.method !== "POST") return methodNotAllowed2(res);
45593
46399
  if (!ctx.host.security.isTerminalAuthorized(req)) {
45594
46400
  ctx.host.http.writeJson(res, 401, { error: "Unauthorized" });
@@ -45737,16 +46543,18 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45737
46543
  }
45738
46544
  const sessionId = crypto5.randomUUID();
45739
46545
  const session = observability.createPendingTerminalSession({ sessionId, cwd, cliId });
46546
+ const named = launchOptions.prompt === void 0 ? null : observability.autoNameTerminalSession(sessionId, deriveOperationLabel(launchOptions.prompt));
46547
+ const namedSession = named?.session ?? session;
45740
46548
  ctx.host.operations.create({
45741
46549
  id: session.sessionId,
45742
46550
  theaterId,
45743
46551
  type: AGENT_OPERATION_TYPE,
45744
46552
  pluginId: ctx.pluginId,
45745
- title: session.label ?? path18__default.basename(cwd),
46553
+ title: namedSession.label ?? session.label ?? path19__default.basename(cwd),
45746
46554
  // 공급자는 실행 시점에 한 번 확정되고 이후 어떤 patch도 다시 쓰지 않는다 —
45747
46555
  // toOperationPayload가 지우는 키 목록 밖이라 resume·복원을 지나도 그대로 남는다.
45748
46556
  payload: {
45749
- ...toOperationPayload(void 0, cwd, session),
46557
+ ...toOperationPayload(void 0, cwd, namedSession),
45750
46558
  [AGENT_LAUNCH_PROVIDER_PAYLOAD_KEY]: agentLaunchProviderFromModel(launchOptions.model),
45751
46559
  // Claude Code의 resume가 launch 좌표를 자체 복원한다고 가정하지 않는다 — 정규화된
45752
46560
  // 최초 선택을 Operation에 남겨 dormant·Console 재시작 뒤에도 같은 인자로 재개한다.
@@ -45772,7 +46580,7 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45772
46580
  });
45773
46581
  const runtimeSession = pendingRuntimeSessions.get(sessionId);
45774
46582
  pendingRuntimeSessions.delete(sessionId);
45775
- const created = runtimeSession ? observability.registerTerminalRuntimeSession(runtimeSession) ?? session : observability.updateTerminalSessionStatus(sessionId, "terminal-only") ?? session;
46583
+ const created = runtimeSession ? observability.registerTerminalRuntimeSession(runtimeSession) ?? namedSession : observability.updateTerminalSessionStatus(sessionId, "terminal-only") ?? namedSession;
45776
46584
  observability.notifySessionUpdated(created);
45777
46585
  ctx.host.operations.patch(sessionId, { payload: toOperationPayload(ctx.host.operations.get(sessionId)?.payload, cwd, created, void 0, observability.getDurableOperation(sessionId)?.providerTitle) });
45778
46586
  ctx.host.http.writeJson(res, 200, created);
@@ -45995,7 +46803,7 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45995
46803
  if (result?.renamed) {
45996
46804
  observability.notifySessionUpdated(result.session);
45997
46805
  const autoNameCwd = readPayloadString(ctx.host.operations.get(sessionId)?.payload ?? {}, "cwd") ?? result.session.cwdLabel;
45998
- ctx.host.operations.patch(sessionId, { title: result.session.label ?? path18__default.basename(autoNameCwd) });
46806
+ ctx.host.operations.patch(sessionId, { title: result.session.label ?? path19__default.basename(autoNameCwd) });
45999
46807
  }
46000
46808
  ctx.host.http.writeJson(res, 200, { ok: true, renamed: result?.renamed === true });
46001
46809
  return true;
@@ -46212,7 +47020,7 @@ function createTerminalWikiToolSpecs(fleetDataDir) {
46212
47020
  const resolver = createWikiWorkspaceResolver({
46213
47021
  ensureWorkspace: (cwd) => ensureWorkspaceDirectory(fleetDataDir, cwd),
46214
47022
  withMigrationLock: (workspace, operation) => withDirectoryLock(
46215
- { lockDir: path18__default.join(workspace.path, "knowledge.migration.lock") },
47023
+ { lockDir: path19__default.join(workspace.path, "knowledge.migration.lock") },
46216
47024
  operation
46217
47025
  )
46218
47026
  });
@@ -46696,7 +47504,7 @@ var AnalystTools = class {
46696
47504
  id: metadata.id,
46697
47505
  description: metadata.description,
46698
47506
  parameters: metadata.parameters,
46699
- execute: async (args) => execute(record4(args))
47507
+ execute: async (args) => execute(record5(args))
46700
47508
  };
46701
47509
  }
46702
47510
  events(args) {
@@ -46741,7 +47549,7 @@ var AnalystTools = class {
46741
47549
  return { artifact: { id: artifact.id, title, createdAt: artifact.createdAt } };
46742
47550
  }
46743
47551
  };
46744
- function record4(value) {
47552
+ function record5(value) {
46745
47553
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
46746
47554
  }
46747
47555
  function integer2(value) {
@@ -46919,9 +47727,9 @@ var AnalystSession = class {
46919
47727
  };
46920
47728
  function toAnalystEvents(event, toolNames, redact) {
46921
47729
  if (event.type === "stream_event") {
46922
- const inner = record5(event.event);
47730
+ const inner = record6(event.event);
46923
47731
  if (inner.type !== "content_block_delta") return [];
46924
- const delta = record5(inner.delta);
47732
+ const delta = record6(inner.delta);
46925
47733
  if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
46926
47734
  return [{ type: "chunk", text: redact(delta.text) }];
46927
47735
  }
@@ -46959,10 +47767,10 @@ function toAnalystEvents(event, toolNames, redact) {
46959
47767
  return [];
46960
47768
  }
46961
47769
  function blocks(message) {
46962
- const content = record5(message).content;
46963
- return Array.isArray(content) ? content.map(record5) : [];
47770
+ const content = record6(message).content;
47771
+ return Array.isArray(content) ? content.map(record6) : [];
46964
47772
  }
46965
- function record5(value) {
47773
+ function record6(value) {
46966
47774
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
46967
47775
  }
46968
47776
  function errorMessage2(error51) {
@@ -47166,7 +47974,7 @@ function analysisError(code, message) {
47166
47974
  return { error: { code, message } };
47167
47975
  }
47168
47976
  function isAnalysisSelection(catalog, value) {
47169
- if (!isRecord12(value) || !hasExactKeys(value, ["cliId", "model", "effort", "language"]) || typeof value.cliId !== "string" || typeof value.model !== "string" || value.effort !== void 0 && typeof value.effort !== "string" || value.language !== void 0 && value.language !== "en" && value.language !== "ko") return false;
47977
+ if (!isRecord13(value) || !hasExactKeys(value, ["cliId", "model", "effort", "language"]) || typeof value.cliId !== "string" || typeof value.model !== "string" || value.effort !== void 0 && typeof value.effort !== "string" || value.language !== void 0 && value.language !== "en" && value.language !== "ko") return false;
47170
47978
  const cli = catalog.clis.find((candidate) => candidate.cliId === value.cliId);
47171
47979
  if (!cli?.available) return false;
47172
47980
  const model = cli.models.find((candidate) => candidate.id === value.model);
@@ -47175,9 +47983,9 @@ function isAnalysisSelection(catalog, value) {
47175
47983
  return typeof value.effort === "string" && value.effort.length > 0 && model.effortLevels.includes(value.effort);
47176
47984
  }
47177
47985
  function isMessageBody(value) {
47178
- return isRecord12(value) && hasExactKeys(value, ["text"]) && typeof value.text === "string" && value.text.trim().length > 0;
47986
+ return isRecord13(value) && hasExactKeys(value, ["text"]) && typeof value.text === "string" && value.text.trim().length > 0;
47179
47987
  }
47180
- function isRecord12(value) {
47988
+ function isRecord13(value) {
47181
47989
  return typeof value === "object" && value !== null && !Array.isArray(value);
47182
47990
  }
47183
47991
  function hasExactKeys(value, keys) {
@@ -47210,14 +48018,14 @@ function registerAnalysisRoutes(ctx, deps = {}) {
47210
48018
  writeError(ctx, res, 403, ANALYSIS_ERROR_CODES.catalogInvalid, "Analysis request is not accepted by this host.");
47211
48019
  return true;
47212
48020
  }
47213
- const path42 = pathname.slice(`${ctx.basePath}/analysis`.length) || "/";
47214
- if (path42 === "/catalog") return handleCatalog(ctx, req, res, catalog);
47215
- if (path42 === "/stream") return handleGlobalStream(ctx, req, res, registry3);
47216
- const artifactMatch = path42.match(/^\/artifacts\/([^/]+)$/);
48021
+ const path43 = pathname.slice(`${ctx.basePath}/analysis`.length) || "/";
48022
+ if (path43 === "/catalog") return handleCatalog(ctx, req, res, catalog);
48023
+ if (path43 === "/stream") return handleGlobalStream(ctx, req, res, registry3);
48024
+ const artifactMatch = path43.match(/^\/artifacts\/([^/]+)$/);
47217
48025
  if (artifactMatch) return handleArtifact(ctx, req, res, decodeURIComponent(artifactMatch[1] ?? ""), registry3);
47218
- const clearArtifactsMatch = path42.match(/^\/([^/]+)\/artifacts$/);
48026
+ const clearArtifactsMatch = path43.match(/^\/([^/]+)\/artifacts$/);
47219
48027
  if (clearArtifactsMatch) return handleClearArtifacts(ctx, req, res, decodeURIComponent(clearArtifactsMatch[1] ?? ""), registry3);
47220
- const match = path42.match(/^\/([^/]+)\/(ready|start|message|stream|stop)$/);
48028
+ const match = path43.match(/^\/([^/]+)\/(ready|start|message|stream|stop)$/);
47221
48029
  if (!match) return false;
47222
48030
  const operationId = decodeURIComponent(match[1] ?? "");
47223
48031
  const action = match[2] ?? "";
@@ -47667,14 +48475,14 @@ async function handleStop(ctx, req, res, operationId, registry3) {
47667
48475
  }
47668
48476
  async function resolveTranscriptPath(capturePath, operationCreatedAt) {
47669
48477
  if (await fileExists2(capturePath)) return capturePath;
47670
- const dir = path18__default.dirname(capturePath);
48478
+ const dir = path19__default.dirname(capturePath);
47671
48479
  const bornCutoff = operationCreatedAt - 6e4;
47672
48480
  try {
47673
48481
  const entries = await promises.readdir(dir);
47674
48482
  const candidates = [];
47675
48483
  for (const entry of entries) {
47676
48484
  if (!entry.endsWith(".jsonl")) continue;
47677
- const candidate = path18__default.join(dir, entry);
48485
+ const candidate = path19__default.join(dir, entry);
47678
48486
  const stat4 = await promises.stat(candidate).catch(() => null);
47679
48487
  if (!stat4?.isFile()) continue;
47680
48488
  if (stat4.birthtimeMs > 0 && stat4.birthtimeMs < bornCutoff) continue;
@@ -47724,7 +48532,7 @@ function artifactHeaders() {
47724
48532
  return { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": ANALYSIS_ARTIFACT_CSP, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };
47725
48533
  }
47726
48534
  function registerAiGatewayRoutes(ctx, deps = {}) {
47727
- const ownedDiagnostics = deps.cursorDiagnostics ? void 0 : createCursorDiagnosticLog(path18__default.join(
48535
+ const ownedDiagnostics = deps.cursorDiagnostics ? void 0 : createCursorDiagnosticLog(path19__default.join(
47728
48536
  ctx.host.paths.pluginDataDir(ctx.pluginId),
47729
48537
  "ai-gateway"
47730
48538
  ));
@@ -47734,6 +48542,7 @@ function registerAiGatewayRoutes(ctx, deps = {}) {
47734
48542
  // 자격증명 조달은 호스트 결정이다 — Console은 core-ai-gateway가 export한 기본 reader를 주입한다.
47735
48543
  readAuth: deps.readAuth ?? (() => readCodexSubscriptionAuth()),
47736
48544
  readCursorToken: deps.readCursorToken ?? (() => readCursorSubscriptionToken()),
48545
+ readXaiToken: deps.readXaiToken ?? (() => readXaiSubscriptionToken()),
47737
48546
  readModelOverride: () => process.env[AI_GATEWAY_MODEL_ENV],
47738
48547
  cursorDiagnostics: deps.cursorDiagnostics ?? ownedDiagnostics?.write
47739
48548
  });
@@ -47863,8 +48672,8 @@ function registerTerminalModelAuthRoutes(ctx, deps) {
47863
48672
  }
47864
48673
  function createTerminalModelAuthRouter(ctx, deps) {
47865
48674
  return async function handleTerminalModelAuthRoute({ req, res, pathname }) {
47866
- const path42 = pathname.slice(`${ctx.basePath}/model-auth`.length) || "/";
47867
- if (path42 === "/state") {
48675
+ const path43 = pathname.slice(`${ctx.basePath}/model-auth`.length) || "/";
48676
+ if (path43 === "/state") {
47868
48677
  if (req.method !== "GET") {
47869
48678
  ctx.host.http.writeJson(res, 405, { error: "Method not allowed" });
47870
48679
  return true;
@@ -47872,7 +48681,7 @@ function createTerminalModelAuthRouter(ctx, deps) {
47872
48681
  ctx.host.http.writeJson(res, 200, await buildModelAuthState(deps.authService));
47873
48682
  return true;
47874
48683
  }
47875
- const providerId = parseProviderPath(path42);
48684
+ const providerId = parseProviderPath(path43);
47876
48685
  if (!providerId) return false;
47877
48686
  if (!isTerminalModelAuthProviderId(providerId)) {
47878
48687
  ctx.host.http.writeJson(res, 404, { error: "provider_not_found" });
@@ -47940,8 +48749,8 @@ async function findProvider(deps, providerId) {
47940
48749
  const state = await buildModelAuthState(deps.authService);
47941
48750
  return state.providers.find((provider) => provider.provider === providerId) ?? null;
47942
48751
  }
47943
- function parseProviderPath(path42) {
47944
- const parts = path42.split("/").filter(Boolean);
48752
+ function parseProviderPath(path43) {
48753
+ const parts = path43.split("/").filter(Boolean);
47945
48754
  if (parts.length !== 2 || parts[0] !== "providers") return null;
47946
48755
  try {
47947
48756
  return decodeURIComponent(parts[1] ?? "");
@@ -48076,7 +48885,7 @@ function isRestoredShellEvent(value, pluginId) {
48076
48885
  var CONTROL_HOLDER_EVENT_CHANNEL = "control:holder";
48077
48886
  function applyWireLog(ctx, stored) {
48078
48887
  setWireLogTarget(stored === void 0 ? void 0 : stored ? {
48079
- path: path18__default.join(ctx.host.paths.pluginDataDir(ctx.pluginId), "ai-gateway", "wire-log.jsonl"),
48888
+ path: path19__default.join(ctx.host.paths.pluginDataDir(ctx.pluginId), "ai-gateway", "wire-log.jsonl"),
48080
48889
  maxBytes: DEFAULT_WIRE_LOG_MAX_BYTES
48081
48890
  } : null);
48082
48891
  }