@dotobokuri/fleet-console 1.57.2 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/cli.mjs +30 -5
  2. package/dist/client/assets/{_baseUniq-dvybACFL.js → _baseUniq-DJ4C0UQF.js} +1 -1
  3. package/dist/client/assets/{arc-BM1EQJ5i.js → arc-DkQKttnC.js} +1 -1
  4. package/dist/client/assets/{architectureDiagram-Q4EWVU46-C5NpB_9B.js → architectureDiagram-Q4EWVU46-BpuET3uK.js} +1 -1
  5. package/dist/client/assets/{blockDiagram-DXYQGD6D-BemCHdjP.js → blockDiagram-DXYQGD6D-CatlulZp.js} +1 -1
  6. package/dist/client/assets/{c4Diagram-AHTNJAMY-BB7Qe4id.js → c4Diagram-AHTNJAMY-BPfWevDh.js} +1 -1
  7. package/dist/client/assets/channel-DDcyY5eB.js +1 -0
  8. package/dist/client/assets/{chunk-4BX2VUAB-CqmbYj1h.js → chunk-4BX2VUAB-a7lkla2P.js} +1 -1
  9. package/dist/client/assets/{chunk-4TB4RGXK-DY8csFL8.js → chunk-4TB4RGXK-Bh-20OVN.js} +1 -1
  10. package/dist/client/assets/{chunk-55IACEB6-Bc2JNsBB.js → chunk-55IACEB6-DiPm-_AS.js} +1 -1
  11. package/dist/client/assets/{chunk-EDXVE4YY-B7fkHilr.js → chunk-EDXVE4YY-BcGep4mz.js} +1 -1
  12. package/dist/client/assets/{chunk-FMBD7UC4-CKS1kchI.js → chunk-FMBD7UC4-Cn0A6Wm1.js} +1 -1
  13. package/dist/client/assets/{chunk-OYMX7WX6-BoSMhV9B.js → chunk-OYMX7WX6-DNTIDjw4.js} +1 -1
  14. package/dist/client/assets/{chunk-QZHKN3VN-B6NI5Nv8.js → chunk-QZHKN3VN-cji_BhbG.js} +1 -1
  15. package/dist/client/assets/{chunk-YZCP3GAM-DDwSQ8RI.js → chunk-YZCP3GAM-B6I5kLlB.js} +1 -1
  16. package/dist/client/assets/classDiagram-6PBFFD2Q-CqqUqRwS.js +1 -0
  17. package/dist/client/assets/classDiagram-v2-HSJHXN6E-CqqUqRwS.js +1 -0
  18. package/dist/client/assets/clone-CjMEm_X8.js +1 -0
  19. package/dist/client/assets/{cose-bilkent-S5V4N54A-VjTSxeFA.js → cose-bilkent-S5V4N54A-_Xmui3Dj.js} +1 -1
  20. package/dist/client/assets/{dagre-KV5264BT-BQSQIPKP.js → dagre-KV5264BT-BI_m6tGN.js} +1 -1
  21. package/dist/client/assets/{diagram-5BDNPKRD-C6e_Ovvo.js → diagram-5BDNPKRD-JDBqcRRR.js} +1 -1
  22. package/dist/client/assets/{diagram-G4DWMVQ6-D6vqaIMN.js → diagram-G4DWMVQ6-CdIHKaZT.js} +1 -1
  23. package/dist/client/assets/{diagram-MMDJMWI5-DFxtu5Sa.js → diagram-MMDJMWI5-CULX6wM5.js} +1 -1
  24. package/dist/client/assets/{diagram-TYMM5635-BcYaszXB.js → diagram-TYMM5635-C1JXiI2W.js} +1 -1
  25. package/dist/client/assets/{erDiagram-SMLLAGMA-DLSCg-9y.js → erDiagram-SMLLAGMA-RJI8bZrW.js} +1 -1
  26. package/dist/client/assets/{flowDiagram-DWJPFMVM-_kx-OfzH.js → flowDiagram-DWJPFMVM-CSrF7U0E.js} +1 -1
  27. package/dist/client/assets/{ganttDiagram-T4ZO3ILL-DluEefPv.js → ganttDiagram-T4ZO3ILL-CHp3LObA.js} +1 -1
  28. package/dist/client/assets/{gitGraphDiagram-UUTBAWPF-BDHypYJk.js → gitGraphDiagram-UUTBAWPF-BEeoTjqh.js} +1 -1
  29. package/dist/client/assets/{graph-CHPq19s3.js → graph-DNvMdh3j.js} +1 -1
  30. package/dist/client/assets/index-BG857Idy.css +1 -0
  31. package/dist/client/assets/index-CCNdSGui.js +483 -0
  32. package/dist/client/assets/{infoDiagram-42DDH7IO-BhntKSlv.js → infoDiagram-42DDH7IO-31kh8JMu.js} +1 -1
  33. package/dist/client/assets/{ishikawaDiagram-UXIWVN3A-Vo0lWYeZ.js → ishikawaDiagram-UXIWVN3A-DZgEgolJ.js} +1 -1
  34. package/dist/client/assets/{journeyDiagram-VCZTEJTY-B-jydfQ3.js → journeyDiagram-VCZTEJTY-DfZ3i3Bu.js} +1 -1
  35. package/dist/client/assets/{kanban-definition-6JOO6SKY-CR7_O2tt.js → kanban-definition-6JOO6SKY-giivFfnv.js} +1 -1
  36. package/dist/client/assets/{layout-C7qyIJFE.js → layout-DdVRNrH8.js} +1 -1
  37. package/dist/client/assets/{linear-ClKfz3Xw.js → linear-3cmeYdGh.js} +1 -1
  38. package/dist/client/assets/{mermaid.core-eHgX1dDu.js → mermaid.core-Cjqy_Y5Z.js} +4 -4
  39. package/dist/client/assets/{min-CBcfPH4t.js → min-Cgsd0one.js} +1 -1
  40. package/dist/client/assets/{mindmap-definition-QFDTVHPH-BrjeA0rz.js → mindmap-definition-QFDTVHPH-PfuGubxC.js} +1 -1
  41. package/dist/client/assets/{pieDiagram-DEJITSTG-Bx3gB3ns.js → pieDiagram-DEJITSTG-B9O6H439.js} +1 -1
  42. package/dist/client/assets/{quadrantDiagram-34T5L4WZ-Y_8L8YCa.js → quadrantDiagram-34T5L4WZ-DJH7RQzs.js} +1 -1
  43. package/dist/client/assets/{requirementDiagram-MS252O5E-BByFdhc4.js → requirementDiagram-MS252O5E-BZHTYV2q.js} +1 -1
  44. package/dist/client/assets/{sankeyDiagram-XADWPNL6-Du7m7fuy.js → sankeyDiagram-XADWPNL6-B5aGVyLG.js} +1 -1
  45. package/dist/client/assets/{sequenceDiagram-FGHM5R23-DovViawI.js → sequenceDiagram-FGHM5R23-D2890FYU.js} +1 -1
  46. package/dist/client/assets/{stateDiagram-FHFEXIEX-7fVJHvbx.js → stateDiagram-FHFEXIEX-DWmhZMWZ.js} +1 -1
  47. package/dist/client/assets/stateDiagram-v2-QKLJ7IA2-DoQKtZ4H.js +1 -0
  48. package/dist/client/assets/{timeline-definition-GMOUNBTQ-Dgsxq4-O.js → timeline-definition-GMOUNBTQ-B0pTOfcD.js} +1 -1
  49. package/dist/client/assets/{vennDiagram-DHZGUBPP-D2tu5aMx.js → vennDiagram-DHZGUBPP-D-S4XLnE.js} +1 -1
  50. package/dist/client/assets/{wardley-RL74JXVD-C4IVs_k4.js → wardley-RL74JXVD-ClPA8Fc3.js} +1 -1
  51. package/dist/client/assets/{wardleyDiagram-NUSXRM2D-DCVn_9G_.js → wardleyDiagram-NUSXRM2D-JJgj7CxJ.js} +1 -1
  52. package/dist/client/assets/{xychartDiagram-5P7HB3ND-D1TZkyWh.js → xychartDiagram-5P7HB3ND-BBIy9-Kq.js} +1 -1
  53. package/dist/client/index.html +2 -2
  54. package/dist/fleet-plugins/ledger/routes.mjs +35 -0
  55. package/dist/fleet-plugins/quota/routes.mjs +422 -61
  56. package/dist/fleet-plugins/scuttlebutt/routes.mjs +30 -5
  57. package/dist/fleet-plugins/terminal/routes.mjs +1317 -541
  58. package/dist/fleet.mjs +1541 -674
  59. package/package.json +1 -1
  60. package/dist/client/assets/channel-t207uO3V.js +0 -1
  61. package/dist/client/assets/classDiagram-6PBFFD2Q-Dg0z8qFh.js +0 -1
  62. package/dist/client/assets/classDiagram-v2-HSJHXN6E-Dg0z8qFh.js +0 -1
  63. package/dist/client/assets/clone-B47TzRxK.js +0 -1
  64. package/dist/client/assets/index-D6_LDhkV.css +0 -1
  65. package/dist/client/assets/index-DeiAnv0J.js +0 -483
  66. package/dist/client/assets/stateDiagram-v2-QKLJ7IA2-CQPjJLLI.js +0 -1
@@ -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 = {}) {
@@ -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") {
@@ -24140,7 +24260,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24140
24260
  let createdEmitted = false;
24141
24261
  let textSeen = false;
24142
24262
  let accumulatedText = "";
24143
- let usage3 = null;
24263
+ let usage4 = null;
24144
24264
  let failed = false;
24145
24265
  const toolCalls = /* @__PURE__ */ new Map();
24146
24266
  const MESSAGE_ITEM_ID = "chat_message_0";
@@ -24171,7 +24291,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24171
24291
  };
24172
24292
  }
24173
24293
  if (isRecord5(value.usage)) {
24174
- usage3 = chatUsage(value.usage);
24294
+ usage4 = chatUsage(value.usage);
24175
24295
  }
24176
24296
  const choices = Array.isArray(value.choices) ? value.choices : [];
24177
24297
  for (const choice of choices) {
@@ -24264,7 +24384,7 @@ async function* translateChatCompletionsStream(body, options, toolSchemas) {
24264
24384
  model: responseModel ?? "",
24265
24385
  // 하류 message_delta는 usage가 필수다. include_usage에도 usage 청크를 주지
24266
24386
  // 않는 백엔드에서는 0-usage로 완결하고, 실제 회계는 provider 콘솔이 맡는다.
24267
- usage: usage3 ?? { input_tokens: 0, output_tokens: 0 }
24387
+ usage: usage4 ?? { input_tokens: 0, output_tokens: 0 }
24268
24388
  }
24269
24389
  };
24270
24390
  }
@@ -24925,6 +25045,610 @@ function createOpencodeGoAdapter(wire, options = {}) {
24925
25045
  ...options.fetch ? { fetch: options.fetch } : {}
24926
25046
  });
24927
25047
  }
25048
+ var XAI_OIDC_ISSUER = "https://auth.x.ai";
25049
+ var XAI_CLI_REFRESH_URL = "https://auth.x.ai/oauth2/token";
25050
+ var XAI_CLI_DEFAULT_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
25051
+ var XAI_CLI_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
25052
+ var REFRESH_TIMEOUT_MS = 15e3;
25053
+ var FALLBACK_ACCESS_TOKEN_TTL_MS = 36e5;
25054
+ function xaiCliAuthFilePath(deps) {
25055
+ return path19__default.join(deps.env.GROK_HOME || path19__default.join(deps.homedir(), ".grok"), "auth.json");
25056
+ }
25057
+ function expiry(value) {
25058
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
25059
+ const parsed = typeof value === "number" ? value : Date.parse(value);
25060
+ if (!Number.isFinite(parsed)) return void 0;
25061
+ return parsed < 1e12 ? Math.round(parsed * 1e3) : Math.round(parsed);
25062
+ }
25063
+ function jwtExpiry(token) {
25064
+ const parts = token.split(".");
25065
+ if (parts.length < 2) return void 0;
25066
+ try {
25067
+ const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
25068
+ const record42 = credentialRecord(payload);
25069
+ const exp = record42?.exp;
25070
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return void 0;
25071
+ return Math.round(exp * 1e3);
25072
+ } catch {
25073
+ return void 0;
25074
+ }
25075
+ }
25076
+ function effectiveExpiry(entry, accessToken) {
25077
+ const fromEntry = expiry(entry.expires_at) ?? expiry(entry.expires);
25078
+ const fromJwt = jwtExpiry(accessToken);
25079
+ if (fromEntry !== void 0 && fromJwt !== void 0) return Math.min(fromEntry, fromJwt);
25080
+ return fromEntry ?? fromJwt;
25081
+ }
25082
+ function clientId(entryKey, entry) {
25083
+ const fromEntry = optionalTrimmedString(entry.oidc_client_id);
25084
+ if (fromEntry) return fromEntry;
25085
+ const suffix = optionalTrimmedString(entryKey.split("::").at(-1));
25086
+ return suffix ?? XAI_CLI_DEFAULT_CLIENT_ID;
25087
+ }
25088
+ function refreshToken(entry) {
25089
+ return optionalTrimmedString(entry.refresh_token) ?? optionalTrimmedString(entry.refresh);
25090
+ }
25091
+ async function defaultWriteAuthFile(filePath, contents) {
25092
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
25093
+ try {
25094
+ await fs32.writeFile(tmpPath, contents, { encoding: "utf8", mode: 384 });
25095
+ await fs32.rename(tmpPath, filePath);
25096
+ } catch (error51) {
25097
+ await fs32.unlink(tmpPath).catch(() => void 0);
25098
+ throw error51;
25099
+ }
25100
+ }
25101
+ async function persistRefreshedEntry(deps, filePath, entryKey, expected, patch, writeAuthFile) {
25102
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
25103
+ if (raw === null) return;
25104
+ const auth = credentialRecord(JSON.parse(raw));
25105
+ if (!auth) return;
25106
+ const current = credentialRecord(auth[entryKey]);
25107
+ if (!current) return;
25108
+ if (optionalTrimmedString(current.key) !== expected.accessToken) return;
25109
+ if (expected.refreshToken !== void 0 && refreshToken(current) !== expected.refreshToken) return;
25110
+ auth[entryKey] = { ...current, ...patch };
25111
+ await writeAuthFile(filePath, `${JSON.stringify(auth, null, 2)}
25112
+ `);
25113
+ }
25114
+ async function refreshAccessToken(entryKey, entry, fetchImpl, now) {
25115
+ const token = refreshToken(entry);
25116
+ if (!token) return null;
25117
+ const controller = new AbortController();
25118
+ const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
25119
+ try {
25120
+ const body = new URLSearchParams({
25121
+ grant_type: "refresh_token",
25122
+ client_id: clientId(entryKey, entry),
25123
+ refresh_token: token
25124
+ });
25125
+ const response = await fetchImpl(XAI_CLI_REFRESH_URL, {
25126
+ method: "POST",
25127
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
25128
+ body,
25129
+ signal: controller.signal
25130
+ });
25131
+ if (!response.ok) return null;
25132
+ const payload = credentialRecord(await response.json());
25133
+ const accessToken = optionalTrimmedString(payload?.access_token);
25134
+ if (!accessToken) return null;
25135
+ const expiresIn = payload?.expires_in;
25136
+ const expiresAt = typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn > 0 ? now() + Math.round(expiresIn * 1e3) : jwtExpiry(accessToken) ?? now() + FALLBACK_ACCESS_TOKEN_TTL_MS;
25137
+ const rotated = optionalTrimmedString(payload?.refresh_token);
25138
+ return {
25139
+ accessToken,
25140
+ expiresAt,
25141
+ ...rotated === void 0 ? {} : { refreshToken: rotated }
25142
+ };
25143
+ } catch {
25144
+ return null;
25145
+ } finally {
25146
+ clearTimeout(timer);
25147
+ }
25148
+ }
25149
+ async function resolveXaiCliAuth(deps, options = {}) {
25150
+ const now = options.now ?? Date.now;
25151
+ const fetchImpl = options.fetch ?? fetch;
25152
+ const writeAuthFile = options.writeAuthFile ?? defaultWriteAuthFile;
25153
+ const filePath = xaiCliAuthFilePath(deps);
25154
+ try {
25155
+ const raw = await deps.readBounded(filePath, MAX_CREDENTIAL_BYTES);
25156
+ if (raw === null || raw.length > MAX_CREDENTIAL_BYTES) return { status: "signed_out" };
25157
+ const auth = credentialRecord(JSON.parse(raw));
25158
+ if (!auth) return { status: "signed_out" };
25159
+ let sawExpired = false;
25160
+ for (const [entryKey, value] of Object.entries(auth)) {
25161
+ if (!entryKey.startsWith(`${XAI_OIDC_ISSUER}::`)) continue;
25162
+ const entry = credentialRecord(value);
25163
+ const issuer = optionalTrimmedString(entry?.oidc_issuer);
25164
+ const accessToken = optionalTrimmedString(entry?.key);
25165
+ if (!entry || issuer !== XAI_OIDC_ISSUER || !accessToken) continue;
25166
+ const expiresAt = effectiveExpiry(entry, accessToken);
25167
+ const expired2 = expiresAt !== void 0 && expiresAt <= now();
25168
+ const needsRefresh = options.forceRefresh === true || expiresAt !== void 0 && expiresAt - now() <= XAI_CLI_REFRESH_BUFFER_MS;
25169
+ if (needsRefresh) {
25170
+ const refreshed = await refreshAccessToken(entryKey, entry, fetchImpl, now);
25171
+ if (refreshed) {
25172
+ const userId2 = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
25173
+ const patch = {
25174
+ key: refreshed.accessToken,
25175
+ expires_at: new Date(refreshed.expiresAt).toISOString()
25176
+ };
25177
+ if (refreshed.refreshToken !== void 0) patch.refresh_token = refreshed.refreshToken;
25178
+ try {
25179
+ await persistRefreshedEntry(
25180
+ deps,
25181
+ filePath,
25182
+ entryKey,
25183
+ { accessToken, refreshToken: refreshToken(entry) },
25184
+ patch,
25185
+ writeAuthFile
25186
+ );
25187
+ } catch {
25188
+ }
25189
+ return {
25190
+ status: "ok",
25191
+ credentials: {
25192
+ accessToken: refreshed.accessToken,
25193
+ expiresAt: refreshed.expiresAt,
25194
+ ...userId2 === void 0 ? {} : { userId: userId2 }
25195
+ }
25196
+ };
25197
+ }
25198
+ if (options.forceRefresh === true || expired2) {
25199
+ sawExpired = true;
25200
+ continue;
25201
+ }
25202
+ } else if (expired2) {
25203
+ sawExpired = true;
25204
+ continue;
25205
+ }
25206
+ const userId = optionalTrimmedString(entry.user_id) ?? optionalTrimmedString(entry.principal_id);
25207
+ return {
25208
+ status: "ok",
25209
+ credentials: {
25210
+ accessToken,
25211
+ ...expiresAt === void 0 ? {} : { expiresAt },
25212
+ ...userId === void 0 ? {} : { userId }
25213
+ }
25214
+ };
25215
+ }
25216
+ return { status: sawExpired ? "expired" : "signed_out" };
25217
+ } catch {
25218
+ return { status: "signed_out" };
25219
+ }
25220
+ }
25221
+ async function resolveXaiCliCredentials(deps, nowOrOptions = Date.now) {
25222
+ const options = typeof nowOrOptions === "function" ? { now: nowOrOptions } : nowOrOptions;
25223
+ const result = await resolveXaiCliAuth(deps, options);
25224
+ return result.status === "ok" ? result.credentials : null;
25225
+ }
25226
+ var XAI_CLI_RESPONSES_URL = "https://cli-chat-proxy.grok.com/v1/responses";
25227
+ var XAI_CLI_CLIENT_VERSION = "1.0.3";
25228
+ var DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES = 64 * 1024 * 1024;
25229
+ var DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS = 3e4;
25230
+ var DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS = 3e4;
25231
+ var XaiResponsesAdapter = class {
25232
+ capabilities = {};
25233
+ fetchImpl;
25234
+ maxBodyBytes;
25235
+ idleTimeoutMs;
25236
+ functionCallTimeoutMs;
25237
+ url;
25238
+ extraHeaders;
25239
+ constructor(options = {}) {
25240
+ this.url = XAI_CLI_RESPONSES_URL;
25241
+ this.extraHeaders = options.headers ?? {};
25242
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
25243
+ this.maxBodyBytes = positiveInteger(
25244
+ options.maxBodyBytes ?? DEFAULT_XAI_RESPONSES_MAX_UPSTREAM_BODY_BYTES,
25245
+ "maxBodyBytes"
25246
+ );
25247
+ this.idleTimeoutMs = positiveInteger(
25248
+ options.idleTimeoutMs ?? DEFAULT_XAI_RESPONSES_UPSTREAM_IDLE_TIMEOUT_MS,
25249
+ "idleTimeoutMs"
25250
+ );
25251
+ this.functionCallTimeoutMs = positiveInteger(
25252
+ options.functionCallTimeoutMs ?? DEFAULT_XAI_RESPONSES_FUNCTION_CALL_TIMEOUT_MS,
25253
+ "functionCallTimeoutMs"
25254
+ );
25255
+ }
25256
+ async stream(request, options) {
25257
+ if (options.apiKey.length === 0) {
25258
+ throw new TypeError("apiKey must not be empty");
25259
+ }
25260
+ const controller = new AbortController();
25261
+ const unlinkAbort = linkAbortSignal(options.signal, controller);
25262
+ const payload = forXaiResponsesBackend(request);
25263
+ wireLog("xai-responses.wire.request", { url: this.url, payload });
25264
+ let response;
25265
+ try {
25266
+ response = await this.fetchImpl(this.url, {
25267
+ method: "POST",
25268
+ headers: {
25269
+ accept: "text/event-stream",
25270
+ authorization: `Bearer ${options.apiKey}`,
25271
+ "content-type": "application/json",
25272
+ "x-xai-token-auth": "xai-grok-cli",
25273
+ "x-grok-client-version": XAI_CLI_CLIENT_VERSION,
25274
+ "x-grok-model-override": request.model,
25275
+ ...this.extraHeaders
25276
+ },
25277
+ body: JSON.stringify(payload),
25278
+ signal: controller.signal
25279
+ });
25280
+ } catch (error51) {
25281
+ unlinkAbort();
25282
+ throw error51;
25283
+ }
25284
+ if (!response.ok) {
25285
+ if (process.env.FLEET_AI_GATEWAY_DEBUG === "1") {
25286
+ const roles = payload.input.map((item) => "role" in item ? item.role : item.type);
25287
+ console.error(`[ai-gateway] upstream ${response.status} input roles=${JSON.stringify(roles)} keys=${JSON.stringify(Object.keys(payload))}`);
25288
+ }
25289
+ try {
25290
+ const body = await readBoundedBody(response.body, {
25291
+ controller,
25292
+ idleTimeoutMs: this.idleTimeoutMs,
25293
+ maxBodyBytes: this.maxBodyBytes
25294
+ });
25295
+ return {
25296
+ ok: false,
25297
+ status: response.status,
25298
+ headers: response.headers,
25299
+ body
25300
+ };
25301
+ } finally {
25302
+ unlinkAbort();
25303
+ }
25304
+ }
25305
+ return {
25306
+ ok: true,
25307
+ status: response.status,
25308
+ headers: response.headers,
25309
+ events: parseXaiEventStream(response.body, {
25310
+ controller,
25311
+ idleTimeoutMs: this.idleTimeoutMs,
25312
+ maxBodyBytes: this.maxBodyBytes,
25313
+ onClose: unlinkAbort
25314
+ }, this.functionCallTimeoutMs)
25315
+ };
25316
+ }
25317
+ };
25318
+ function forXaiResponsesBackend(request) {
25319
+ const { metadata: _metadata, native_tools: _nativeTools, ...rest } = request;
25320
+ return {
25321
+ ...rest,
25322
+ input: request.input.map((item) => {
25323
+ if (item.type === "function_call_output") {
25324
+ const { is_error: _isError, tool_references: _toolReferences, ...wireItem2 } = item;
25325
+ return wireItem2;
25326
+ }
25327
+ const { reasoning_content: _reasoningContent, ...wireItem } = item;
25328
+ return wireItem;
25329
+ }),
25330
+ ...request.tools === void 0 ? {} : { tools: request.tools.map(({ defer_loading: _deferLoading, ...tool }) => tool) }
25331
+ };
25332
+ }
25333
+ function parseXaiEventStream(body, options, functionCallTimeoutMs) {
25334
+ return assembleXaiFunctionCalls(
25335
+ parseUpstreamSseStream(
25336
+ body,
25337
+ { ...options, missingBodyMessage: "Grok CLI streaming response had no body" },
25338
+ parseEventFrame3
25339
+ ),
25340
+ options.controller,
25341
+ functionCallTimeoutMs
25342
+ );
25343
+ }
25344
+ async function* assembleXaiFunctionCalls(source, controller, timeoutMs) {
25345
+ const iterator = source[Symbol.asyncIterator]();
25346
+ const pending = /* @__PURE__ */ new Map();
25347
+ let completedNormally = false;
25348
+ try {
25349
+ while (true) {
25350
+ const deadlineAt = earliestXaiFunctionCallDeadline(pending);
25351
+ const result = deadlineAt === void 0 ? await iterator.next() : await nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs);
25352
+ if (result.done) {
25353
+ if (pending.size > 0) {
25354
+ throw incompleteXaiFunctionCall("stream ended before function call output_item.done");
25355
+ }
25356
+ completedNormally = true;
25357
+ return;
25358
+ }
25359
+ const event = result.value;
25360
+ if (event.type === "response.completed" && pending.size > 0) {
25361
+ throw incompleteXaiFunctionCall("response.completed arrived before function call output_item.done");
25362
+ }
25363
+ if (event.type === "response.output_item.added" && event.item.type === "function_call") {
25364
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
25365
+ pending.set(key, {
25366
+ added: event,
25367
+ // Each call gets a full timeout from its own added event. Waiting uses the
25368
+ // earliest active deadline, so a later parallel call is never shortened by
25369
+ // an earlier call's age.
25370
+ deadlineAt: Date.now() + timeoutMs
25371
+ });
25372
+ continue;
25373
+ }
25374
+ if (event.type === "response.function_call_arguments.done") {
25375
+ const call = pending.get(xaiFunctionCallKey(event.output_index, event.item_id));
25376
+ if (call !== void 0) {
25377
+ call.argumentsDone = event;
25378
+ continue;
25379
+ }
25380
+ }
25381
+ if (event.type === "response.output_item.done" && event.item.type === "function_call") {
25382
+ const key = xaiFunctionCallKey(event.output_index, event.item.id);
25383
+ const call = pending.get(key);
25384
+ if (call !== void 0) {
25385
+ pending.delete(key);
25386
+ yield call.added;
25387
+ if (call.argumentsDone !== void 0) {
25388
+ yield call.argumentsDone;
25389
+ } else if (event.item.arguments.length > 0) {
25390
+ yield {
25391
+ type: "response.function_call_arguments.done",
25392
+ item_id: event.item.id,
25393
+ output_index: event.output_index,
25394
+ arguments: event.item.arguments
25395
+ };
25396
+ }
25397
+ yield event;
25398
+ continue;
25399
+ }
25400
+ }
25401
+ yield event;
25402
+ }
25403
+ } finally {
25404
+ if (!completedNormally && !controller.signal.aborted) {
25405
+ controller.abort();
25406
+ }
25407
+ const returned = iterator.return?.();
25408
+ if (returned !== void 0) {
25409
+ await returned.catch(() => void 0);
25410
+ }
25411
+ }
25412
+ }
25413
+ function earliestXaiFunctionCallDeadline(pending) {
25414
+ let earliest;
25415
+ for (const call of pending.values()) {
25416
+ if (earliest === void 0 || call.deadlineAt < earliest) {
25417
+ earliest = call.deadlineAt;
25418
+ }
25419
+ }
25420
+ return earliest;
25421
+ }
25422
+ async function nextXaiEventBeforeDeadline(iterator, deadlineAt, controller, timeoutMs) {
25423
+ const remainingMs = deadlineAt - Date.now();
25424
+ if (remainingMs <= 0) {
25425
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
25426
+ controller.abort(error51);
25427
+ throw error51;
25428
+ }
25429
+ let timeout;
25430
+ const next = iterator.next();
25431
+ void next.catch(() => void 0);
25432
+ try {
25433
+ return await Promise.race([
25434
+ next,
25435
+ new Promise((_, reject) => {
25436
+ timeout = setTimeout(() => {
25437
+ const error51 = incompleteXaiFunctionCall(`function call assembly exceeded ${timeoutMs}ms`);
25438
+ controller.abort(error51);
25439
+ reject(error51);
25440
+ }, remainingMs);
25441
+ })
25442
+ ]);
25443
+ } finally {
25444
+ if (timeout !== void 0) {
25445
+ clearTimeout(timeout);
25446
+ }
25447
+ }
25448
+ }
25449
+ function incompleteXaiFunctionCall(reason) {
25450
+ return new UpstreamProtocolError(`Grok CLI ${reason}`);
25451
+ }
25452
+ function xaiFunctionCallKey(outputIndex, itemId) {
25453
+ return `${outputIndex}:${itemId}`;
25454
+ }
25455
+ function parseEventFrame3(frame) {
25456
+ const { event: eventName, data } = parseSseFrameFields(frame);
25457
+ if (data.length === 0 || data === "[DONE]") {
25458
+ return void 0;
25459
+ }
25460
+ let parsed;
25461
+ try {
25462
+ parsed = JSON.parse(data);
25463
+ } catch (error51) {
25464
+ throw new UpstreamProtocolError(
25465
+ `Grok CLI SSE contained invalid JSON: ${error51 instanceof Error ? error51.message : String(error51)}`
25466
+ );
25467
+ }
25468
+ if (isRecord7(parsed) && typeof parsed.type !== "string" && eventName !== void 0) {
25469
+ parsed = { ...parsed, type: eventName };
25470
+ }
25471
+ return canonicalEvent3(parsed);
25472
+ }
25473
+ function canonicalEvent3(value) {
25474
+ if (!isRecord7(value) || typeof value.type !== "string") {
25475
+ throw new UpstreamProtocolError("Grok CLI SSE event was not an object with a type");
25476
+ }
25477
+ switch (value.type) {
25478
+ case "response.created":
25479
+ return { type: value.type, response: responseSnapshot3(value.response) };
25480
+ case "response.content_part.added": {
25481
+ const part = record3(value.part, "response.content_part.added.part");
25482
+ if (part.type !== "output_text") {
25483
+ return void 0;
25484
+ }
25485
+ return {
25486
+ type: value.type,
25487
+ item_id: string32(value.item_id, "item_id"),
25488
+ output_index: number32(value.output_index, "output_index"),
25489
+ content_index: number32(value.content_index, "content_index"),
25490
+ part: {
25491
+ type: "output_text",
25492
+ text: typeof part.text === "string" ? part.text : ""
25493
+ }
25494
+ };
25495
+ }
25496
+ case "response.output_text.delta":
25497
+ return {
25498
+ type: value.type,
25499
+ item_id: string32(value.item_id, "item_id"),
25500
+ output_index: number32(value.output_index, "output_index"),
25501
+ content_index: number32(value.content_index, "content_index"),
25502
+ delta: string32(value.delta, "delta")
25503
+ };
25504
+ case "response.output_text.done":
25505
+ return {
25506
+ type: value.type,
25507
+ item_id: string32(value.item_id, "item_id"),
25508
+ output_index: number32(value.output_index, "output_index"),
25509
+ content_index: number32(value.content_index, "content_index"),
25510
+ text: string32(value.text, "text")
25511
+ };
25512
+ case "response.reasoning_summary_text.delta":
25513
+ case "response.reasoning_text.delta":
25514
+ return {
25515
+ type: "response.reasoning_summary_text.delta",
25516
+ item_id: string32(value.item_id, "item_id"),
25517
+ output_index: number32(value.output_index, "output_index"),
25518
+ delta: string32(value.delta, "delta")
25519
+ };
25520
+ case "response.output_item.added":
25521
+ case "response.output_item.done": {
25522
+ const item = outputItem3(value.item);
25523
+ if (item === void 0) {
25524
+ return void 0;
25525
+ }
25526
+ return {
25527
+ type: value.type,
25528
+ output_index: number32(value.output_index, "output_index"),
25529
+ item
25530
+ };
25531
+ }
25532
+ // Hold argument fragments until the Grok CLI proxy's partial-JSON behavior is observed.
25533
+ // The `.done` event carries the complete argument object, which downstream treats as the
25534
+ // remainder when nothing was streamed ahead of it.
25535
+ case "response.function_call_arguments.delta":
25536
+ return void 0;
25537
+ case "response.function_call_arguments.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
+ arguments: string32(value.arguments, "arguments")
25543
+ };
25544
+ case "response.completed":
25545
+ return { type: value.type, response: responseSnapshot3(value.response) };
25546
+ case "response.failed": {
25547
+ const response = record3(value.response, "response.failed.response");
25548
+ return {
25549
+ type: value.type,
25550
+ response: {
25551
+ ...responseSnapshot3(response),
25552
+ error: canonicalError3(response.error)
25553
+ }
25554
+ };
25555
+ }
25556
+ case "error":
25557
+ return { type: "error", error: canonicalError3(value.error ?? value) };
25558
+ default:
25559
+ return void 0;
25560
+ }
25561
+ }
25562
+ function responseSnapshot3(value) {
25563
+ const response = record3(value, "response");
25564
+ return {
25565
+ id: string32(response.id, "response.id"),
25566
+ model: string32(response.model, "response.model"),
25567
+ usage: response.usage === null || response.usage === void 0 ? null : usage3(response.usage)
25568
+ };
25569
+ }
25570
+ function usage3(value) {
25571
+ const parsed = record3(value, "usage");
25572
+ const inputTokens = number32(parsed.input_tokens, "usage.input_tokens");
25573
+ const outputTokens = number32(parsed.output_tokens, "usage.output_tokens");
25574
+ const inputDetails = optionalRecord3(parsed.input_tokens_details, "usage.input_tokens_details");
25575
+ const cachedInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cached_tokens, "usage.input_tokens_details.cached_tokens");
25576
+ const cacheWriteInputTokens = inputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(inputDetails.cache_write_tokens, "usage.input_tokens_details.cache_write_tokens");
25577
+ const outputDetails = optionalRecord3(parsed.output_tokens_details, "usage.output_tokens_details");
25578
+ const reasoningOutputTokens = outputDetails === void 0 ? void 0 : optionalNonNegativeNumber3(outputDetails.reasoning_tokens, "usage.output_tokens_details.reasoning_tokens");
25579
+ const totalTokens = optionalNonNegativeNumber3(parsed.total_tokens, "usage.total_tokens");
25580
+ return {
25581
+ input_tokens: inputTokens,
25582
+ output_tokens: outputTokens,
25583
+ ...cachedInputTokens === void 0 ? {} : { cached_input_tokens: cachedInputTokens },
25584
+ ...cacheWriteInputTokens === void 0 ? {} : { cache_write_input_tokens: cacheWriteInputTokens },
25585
+ ...reasoningOutputTokens === void 0 ? {} : { reasoning_output_tokens: reasoningOutputTokens },
25586
+ ...totalTokens === void 0 ? {} : { total_tokens: totalTokens }
25587
+ };
25588
+ }
25589
+ function outputItem3(value) {
25590
+ const item = record3(value, "item");
25591
+ if (item.type === "message") {
25592
+ return {
25593
+ id: string32(item.id, "item.id"),
25594
+ type: "message",
25595
+ role: "assistant"
25596
+ };
25597
+ }
25598
+ if (item.type === "function_call") {
25599
+ const id = string32(item.id, "item.id");
25600
+ return {
25601
+ id,
25602
+ type: "function_call",
25603
+ call_id: typeof item.call_id === "string" ? item.call_id : id,
25604
+ name: string32(item.name, "item.name"),
25605
+ arguments: typeof item.arguments === "string" ? item.arguments : ""
25606
+ };
25607
+ }
25608
+ return void 0;
25609
+ }
25610
+ function canonicalError3(value) {
25611
+ const error51 = record3(value, "error");
25612
+ const message = string32(error51.message, "error.message");
25613
+ const type = typeof error51.type === "string" && error51.type !== "error" ? error51.type : typeof error51.code === "string" ? error51.code : "api_error";
25614
+ return { type, message };
25615
+ }
25616
+ function isRecord7(value) {
25617
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25618
+ }
25619
+ function record3(value, name) {
25620
+ if (!isRecord7(value)) {
25621
+ throw new UpstreamProtocolError(`${name} must be an object`);
25622
+ }
25623
+ return value;
25624
+ }
25625
+ function optionalRecord3(value, name) {
25626
+ if (value === void 0 || value === null) {
25627
+ return void 0;
25628
+ }
25629
+ return record3(value, name);
25630
+ }
25631
+ function string32(value, name) {
25632
+ if (typeof value !== "string") {
25633
+ throw new UpstreamProtocolError(`${name} must be a string`);
25634
+ }
25635
+ return value;
25636
+ }
25637
+ function number32(value, name) {
25638
+ if (typeof value !== "number" || !Number.isFinite(value)) {
25639
+ throw new UpstreamProtocolError(`${name} must be a number`);
25640
+ }
25641
+ return value;
25642
+ }
25643
+ function optionalNonNegativeNumber3(value, name) {
25644
+ if (value === void 0 || value === null) {
25645
+ return void 0;
25646
+ }
25647
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
25648
+ throw new UpstreamProtocolError(`${name} must be a finite nonnegative number`);
25649
+ }
25650
+ return value;
25651
+ }
24928
25652
  var NO_USER_FACING_BLOCK = "Do not tell the user access is blocked, disabled, or denied.";
24929
25653
  var CLIENT_TOOL_RETRY = `${NO_USER_FACING_BLOCK} Silently retry with the matching client bridge tool from the current catalog.`;
24930
25654
  function cursorNativeExecPolicyReplies(exec2, clientTools) {
@@ -24965,38 +25689,38 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
24965
25689
  "shell_command",
24966
25690
  "exec_command"
24967
25691
  ]);
24968
- if (isRecord7(exec2.readArgs)) {
25692
+ if (isRecord8(exec2.readArgs)) {
24969
25693
  return [execReply(exec2, "readResult", {
24970
25694
  error: { path: stringValue(exec2.readArgs.path), error: readMessage3 }
24971
25695
  })];
24972
25696
  }
24973
- if (isRecord7(exec2.writeArgs)) {
25697
+ if (isRecord8(exec2.writeArgs)) {
24974
25698
  return [execReply(exec2, "writeResult", {
24975
25699
  rejected: { path: stringValue(exec2.writeArgs.path), reason: mutationMessage }
24976
25700
  })];
24977
25701
  }
24978
- if (isRecord7(exec2.deleteArgs)) {
25702
+ if (isRecord8(exec2.deleteArgs)) {
24979
25703
  return [execReply(exec2, "deleteResult", {
24980
25704
  rejected: { path: stringValue(exec2.deleteArgs.path), reason: mutationMessage }
24981
25705
  })];
24982
25706
  }
24983
- if (isRecord7(exec2.lsArgs)) {
25707
+ if (isRecord8(exec2.lsArgs)) {
24984
25708
  return [execReply(exec2, "lsResult", {
24985
25709
  error: { path: stringValue(exec2.lsArgs.path), error: listMessage }
24986
25710
  })];
24987
25711
  }
24988
- if (isRecord7(exec2.grepArgs)) {
25712
+ if (isRecord8(exec2.grepArgs)) {
24989
25713
  return [execReply(exec2, "grepResult", { error: { error: grepMessage } })];
24990
25714
  }
24991
- if (isRecord7(exec2.shellArgs)) {
25715
+ if (isRecord8(exec2.shellArgs)) {
24992
25716
  return [execReply(exec2, "shellResult", shellFailure(exec2.shellArgs, shellMessage))];
24993
25717
  }
24994
- if (isRecord7(exec2.shellStreamArgs)) {
25718
+ if (isRecord8(exec2.shellStreamArgs)) {
24995
25719
  const args = exec2.shellStreamArgs;
24996
25720
  const cwd = stringValue(args.workingDirectory);
24997
25721
  return [
24998
25722
  execReply(exec2, "shellStream", {
24999
- start: isRecord7(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
25723
+ start: isRecord8(args.requestedSandboxPolicy) ? { sandboxPolicy: args.requestedSandboxPolicy } : {}
25000
25724
  }),
25001
25725
  execReply(exec2, "shellStream", { stderr: { data: shellMessage } }),
25002
25726
  execReply(exec2, "shellStream", { exit: { code: 1, cwd, aborted: true } }),
@@ -25004,7 +25728,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25004
25728
  { execClientControlMessage: { streamClose: { id: numberValue(exec2.id) } } }
25005
25729
  ];
25006
25730
  }
25007
- if (isRecord7(exec2.backgroundShellSpawnArgs)) {
25731
+ if (isRecord8(exec2.backgroundShellSpawnArgs)) {
25008
25732
  const args = exec2.backgroundShellSpawnArgs;
25009
25733
  return [execReply(exec2, "backgroundShellSpawnResult", {
25010
25734
  error: {
@@ -25014,15 +25738,15 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25014
25738
  }
25015
25739
  })];
25016
25740
  }
25017
- if (isRecord7(exec2.writeShellStdinArgs)) {
25741
+ if (isRecord8(exec2.writeShellStdinArgs)) {
25018
25742
  return [execReply(exec2, "writeShellStdinResult", { error: { error: shellMessage } })];
25019
25743
  }
25020
- if (isRecord7(exec2.fetchArgs)) {
25744
+ if (isRecord8(exec2.fetchArgs)) {
25021
25745
  return [execReply(exec2, "fetchResult", {
25022
25746
  error: { url: stringValue(exec2.fetchArgs.url), error: networkMessage }
25023
25747
  })];
25024
25748
  }
25025
- if (isRecord7(exec2.diagnosticsArgs)) {
25749
+ if (isRecord8(exec2.diagnosticsArgs)) {
25026
25750
  return [execReply(exec2, "diagnosticsResult", {
25027
25751
  error: {
25028
25752
  path: stringValue(exec2.diagnosticsArgs.path),
@@ -25030,12 +25754,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25030
25754
  }
25031
25755
  })];
25032
25756
  }
25033
- if (isRecord7(exec2.listMcpResourcesExecArgs)) {
25757
+ if (isRecord8(exec2.listMcpResourcesExecArgs)) {
25034
25758
  return [execReply(exec2, "listMcpResourcesExecResult", {
25035
25759
  error: { error: retryMessage(clientTools, ["ListMcpResources", "list_mcp_resources"]) }
25036
25760
  })];
25037
25761
  }
25038
- if (isRecord7(exec2.readMcpResourceExecArgs)) {
25762
+ if (isRecord8(exec2.readMcpResourceExecArgs)) {
25039
25763
  return [execReply(exec2, "readMcpResourceExecResult", {
25040
25764
  error: {
25041
25765
  uri: stringValue(exec2.readMcpResourceExecArgs.uri),
@@ -25043,12 +25767,12 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25043
25767
  }
25044
25768
  })];
25045
25769
  }
25046
- if (isRecord7(exec2.recordScreenArgs)) {
25770
+ if (isRecord8(exec2.recordScreenArgs)) {
25047
25771
  return [execReply(exec2, "recordScreenResult", {
25048
25772
  failure: { error: retryMessage(clientTools, ["record_screen", "computer_use"]) }
25049
25773
  })];
25050
25774
  }
25051
- if (isRecord7(exec2.computerUseArgs)) {
25775
+ if (isRecord8(exec2.computerUseArgs)) {
25052
25776
  return [execReply(exec2, "computerUseResult", {
25053
25777
  error: {
25054
25778
  error: retryMessage(clientTools, ["computer_use"]),
@@ -25058,7 +25782,7 @@ function cursorNativeExecPolicyReplies(exec2, clientTools) {
25058
25782
  }
25059
25783
  })];
25060
25784
  }
25061
- if (isRecord7(exec2.mcpArgs)) {
25785
+ if (isRecord8(exec2.mcpArgs)) {
25062
25786
  return [execReply(exec2, "mcpResult", {
25063
25787
  error: { error: retryMessage(clientTools, []) }
25064
25788
  })];
@@ -25130,7 +25854,7 @@ function numberValue(value) {
25130
25854
  function stringValue(value) {
25131
25855
  return typeof value === "string" ? value : "";
25132
25856
  }
25133
- function isRecord7(value) {
25857
+ function isRecord8(value) {
25134
25858
  return typeof value === "object" && value !== null && !Array.isArray(value);
25135
25859
  }
25136
25860
  var EXECUTE_HOOK_FIELD_NUMBER = 27;
@@ -25282,14 +26006,14 @@ function isCursorNativeRedirectToolName(name) {
25282
26006
  function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25283
26007
  const messageId = numberValue2(exec2.id ?? 0);
25284
26008
  const execId = stringValue2(exec2.execId) || `redirect-${messageId}`;
25285
- if (isRecord8(exec2.readArgs)) {
25286
- const path72 = stringValue2(exec2.readArgs.path);
25287
- if (!path72) return null;
26009
+ if (isRecord9(exec2.readArgs)) {
26010
+ const path82 = stringValue2(exec2.readArgs.path);
26011
+ if (!path82) return null;
25288
26012
  if ([exec2.readArgs.offset, exec2.readArgs.limit].some((value) => typeof value === "number" && value < 0)) return null;
25289
26013
  const offset = positiveNumber(exec2.readArgs.offset);
25290
26014
  const limit = positiveNumber(exec2.readArgs.limit);
25291
26015
  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);
26016
+ const mapped = tools.filter((tool) => matchesLeaf(tool, READ_CANDIDATES)).map((tool) => ({ tool, args: readArguments(tool.inputSchemaValue, path82) })).find((candidate) => candidate.args !== null);
25293
26017
  if (!mapped?.args) return null;
25294
26018
  return redirect(
25295
26019
  exec2,
@@ -25301,14 +26025,14 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25301
26025
  "readResult",
25302
26026
  "read-direct",
25303
26027
  mapped.args,
25304
- { path: path72 }
26028
+ { path: path82 }
25305
26029
  );
25306
26030
  }
25307
- if (isRecord8(exec2.grepArgs)) {
26031
+ if (isRecord9(exec2.grepArgs)) {
25308
26032
  const grepArgs = exec2.grepArgs;
25309
26033
  const pattern = stringValue2(grepArgs.pattern);
25310
26034
  if (!pattern.trim()) return null;
25311
- const path72 = stringValue2(grepArgs.path) || ".";
26035
+ const path82 = stringValue2(grepArgs.path) || ".";
25312
26036
  const glob = stringValue2(grepArgs.glob);
25313
26037
  const outputMode = normalizedGrepOutputMode(stringValue2(grepArgs.outputMode));
25314
26038
  if (!outputMode) return null;
@@ -25324,7 +26048,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25324
26048
  if (numericOptions.some((value) => typeof value === "number" && value < 0)) return null;
25325
26049
  const mappingInput = {
25326
26050
  pattern,
25327
- path: path72,
26051
+ path: path82,
25328
26052
  glob,
25329
26053
  outputMode,
25330
26054
  caseInsensitive: grepArgs.caseInsensitive === true,
@@ -25341,7 +26065,7 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25341
26065
  const mapped = tools.filter((tool) => matchesLeaf(tool, GREP_CANDIDATES)).map((tool) => ({ tool, args: grepArguments(tool, mappingInput) })).find((candidate) => candidate.args !== null);
25342
26066
  const nativeArgs = {
25343
26067
  pattern,
25344
- path: path72,
26068
+ path: path82,
25345
26069
  outputMode,
25346
26070
  ...glob ? { glob } : {},
25347
26071
  ...positiveNumber(grepArgs.offset) === void 0 ? {} : { offset: String(positiveNumber(grepArgs.offset)) }
@@ -25378,15 +26102,15 @@ function cursorNativeExecRedirect(exec2, tools, providerIdentifier) {
25378
26102
  nativeArgs
25379
26103
  );
25380
26104
  }
25381
- if (isRecord8(exec2.shellArgs) || isRecord8(exec2.shellStreamArgs)) {
25382
- const argsRecord = isRecord8(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
26105
+ if (isRecord9(exec2.shellArgs) || isRecord9(exec2.shellStreamArgs)) {
26106
+ const argsRecord = isRecord9(exec2.shellArgs) ? exec2.shellArgs : exec2.shellStreamArgs;
25383
26107
  const command = stringValue2(argsRecord.command);
25384
26108
  if (!command) return null;
25385
26109
  const cwd = stringValue2(argsRecord.workingDirectory);
25386
26110
  const timeout = positiveNumber(argsRecord.timeout) ?? positiveNumber(argsRecord.hardTimeout);
25387
26111
  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
26112
  if (!mapped?.args) return null;
25389
- const stream = isRecord8(exec2.shellStreamArgs);
26113
+ const stream = isRecord9(exec2.shellStreamArgs);
25390
26114
  return redirect(
25391
26115
  exec2,
25392
26116
  mapped.tool,
@@ -25476,9 +26200,9 @@ function cursorNativeRedirectErrorReplies(correlation, error51) {
25476
26200
  }
25477
26201
  }
25478
26202
  }
25479
- function readArguments(schema, path72) {
26203
+ function readArguments(schema, path82) {
25480
26204
  const pathKey = firstSchemaProperty(schema, ["file_path", "path"]);
25481
- return pathKey ? { [pathKey]: path72 } : null;
26205
+ return pathKey ? { [pathKey]: path82 } : null;
25482
26206
  }
25483
26207
  function grepArguments(tool, input) {
25484
26208
  const leaf = normalizedLeaf(tool.clientName);
@@ -25639,7 +26363,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25639
26363
  output.slice(CURSOR_GREP_RECEIPT_PREFIX.length).trim(),
25640
26364
  "base64url"
25641
26365
  ).toString("utf8"));
25642
- if (!isRecord8(decoded)) throw new Error("receipt is not an object");
26366
+ if (!isRecord9(decoded)) throw new Error("receipt is not an object");
25643
26367
  if (decoded.ok === false && typeof decoded.error === "string") {
25644
26368
  return { ok: false, error: decoded.error };
25645
26369
  }
@@ -25652,7 +26376,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25652
26376
  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
26377
  throw new Error("receipt counts are invalid");
25654
26378
  }
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")) {
26379
+ 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
26380
  throw new Error("receipt matches are invalid");
25657
26381
  }
25658
26382
  for (const key of ["totalFiles", "totalLines", "totalMatchedLines"]) {
@@ -25670,7 +26394,7 @@ function parseGrepShellReceipt(output, expectedOutputMode) {
25670
26394
  }
25671
26395
  }
25672
26396
  function buildGrepReceiptSuccess(args, receipt) {
25673
- const path72 = args.path || ".";
26397
+ const path82 = args.path || ".";
25674
26398
  let result;
25675
26399
  if (receipt.outputMode === "files_with_matches") {
25676
26400
  result = {
@@ -25716,15 +26440,15 @@ function buildGrepReceiptSuccess(args, receipt) {
25716
26440
  }
25717
26441
  return {
25718
26442
  pattern: args.pattern ?? "",
25719
- path: path72,
26443
+ path: path82,
25720
26444
  outputMode: receipt.outputMode,
25721
- workspaceResults: { [path72]: result }
26445
+ workspaceResults: { [path82]: result }
25722
26446
  };
25723
26447
  }
25724
26448
  function buildGrepSuccess(args, output) {
25725
26449
  const outputMode = normalizedGrepOutputMode(args.outputMode) ?? "content";
25726
26450
  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 || ".";
26451
+ const path82 = args.path || ".";
25728
26452
  let result;
25729
26453
  if (outputMode === "files_with_matches") {
25730
26454
  result = {
@@ -25787,9 +26511,9 @@ function buildGrepSuccess(args, output) {
25787
26511
  }
25788
26512
  return {
25789
26513
  pattern: args.pattern ?? "",
25790
- path: path72,
26514
+ path: path82,
25791
26515
  outputMode,
25792
- workspaceResults: { [path72]: result }
26516
+ workspaceResults: { [path82]: result }
25793
26517
  };
25794
26518
  }
25795
26519
  function parseCallerShellOutput(output, isError) {
@@ -25851,7 +26575,7 @@ function redirect(exec2, tool, providerIdentifier, messageId, execId, execCase,
25851
26575
  }
25852
26576
  function execArgsToolCallId(exec2) {
25853
26577
  for (const value of Object.values(exec2)) {
25854
- if (!isRecord8(value)) continue;
26578
+ if (!isRecord9(value)) continue;
25855
26579
  const toolCallId = stringValue2(value.toolCallId);
25856
26580
  if (toolCallId) return toolCallId;
25857
26581
  }
@@ -25872,7 +26596,7 @@ function firstSchemaProperty(schema, candidates) {
25872
26596
  return candidates.find((candidate) => schemaHasProperty(schema, candidate));
25873
26597
  }
25874
26598
  function schemaHasProperty(schema, name) {
25875
- return isRecord8(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
26599
+ return isRecord9(schema.properties) && Object.prototype.hasOwnProperty.call(schema.properties, name);
25876
26600
  }
25877
26601
  function execReply2(exec2, resultName, result) {
25878
26602
  return {
@@ -25893,13 +26617,13 @@ function numberOrUndefined(value) {
25893
26617
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
25894
26618
  }
25895
26619
  function positiveNumber(value) {
25896
- const number32 = numberOrUndefined(value);
25897
- return number32 !== void 0 && number32 > 0 ? number32 : void 0;
26620
+ const number42 = numberOrUndefined(value);
26621
+ return number42 !== void 0 && number42 > 0 ? number42 : void 0;
25898
26622
  }
25899
26623
  function stringValue2(value) {
25900
26624
  return typeof value === "string" ? value : "";
25901
26625
  }
25902
- function isRecord8(value) {
26626
+ function isRecord9(value) {
25903
26627
  return typeof value === "object" && value !== null && !Array.isArray(value);
25904
26628
  }
25905
26629
  var cursorAgentDescriptor = [
@@ -26730,18 +27454,18 @@ function decodeCursorServerMessage(payload) {
26730
27454
  const message = fromBinary(AgentServerMessageSchema, payload);
26731
27455
  const unknownExecFields = extractCursorUnknownExecFields(message);
26732
27456
  const json2 = toJson(AgentServerMessageSchema, message);
26733
- if (!isRecord9(json2)) throw new TypeError("Cursor server frame was not a message object");
27457
+ if (!isRecord10(json2)) throw new TypeError("Cursor server frame was not a message object");
26734
27458
  if (unknownExecFields.length > 0) {
26735
27459
  Object.defineProperty(json2, CURSOR_UNKNOWN_EXEC_FIELDS, { value: unknownExecFields });
26736
27460
  }
26737
27461
  return json2;
26738
27462
  }
26739
27463
  function extractCursorUnknownExecFields(message) {
26740
- if (!isRecord9(message) || !isRecord9(message.message)) return [];
26741
- if (message.message.case !== "execServerMessage" || !isRecord9(message.message.value)) return [];
27464
+ if (!isRecord10(message) || !isRecord10(message.message)) return [];
27465
+ if (message.message.case !== "execServerMessage" || !isRecord10(message.message.value)) return [];
26742
27466
  const fields = message.message.value.$unknown;
26743
27467
  if (!Array.isArray(fields)) return [];
26744
- return fields.filter((field) => isRecord9(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
27468
+ return fields.filter((field) => isRecord10(field) && typeof field.no === "number" && typeof field.wireType === "number" && field.data instanceof Uint8Array);
26745
27469
  }
26746
27470
  function parseConnectEndStreamError(payload) {
26747
27471
  try {
@@ -27036,7 +27760,7 @@ function cursorToolArgumentBytes(argumentsText) {
27036
27760
  } catch {
27037
27761
  return {};
27038
27762
  }
27039
- if (!isRecord9(parsed)) return {};
27763
+ if (!isRecord10(parsed)) return {};
27040
27764
  return Object.fromEntries(Object.entries(parsed).map(([name, value]) => [
27041
27765
  name,
27042
27766
  Buffer.from(toBinary(ValueSchema, fromJson(ValueSchema, value))).toString("base64")
@@ -28013,7 +28737,7 @@ function createCursorLiveRun(options) {
28013
28737
  let blobFetchBytes = 0;
28014
28738
  let blobFetchMisses = 0;
28015
28739
  let redirectOperationSequence = 0;
28016
- const usage3 = (segment) => {
28740
+ const usage4 = (segment) => {
28017
28741
  const outputTokens = Math.max(
28018
28742
  segment.contextOutputTokens,
28019
28743
  estimateTokens(segment.outputText, model)
@@ -28059,7 +28783,7 @@ function createCursorLiveRun(options) {
28059
28783
  else if (segment.started) {
28060
28784
  segment.queue.push({
28061
28785
  type: "response.completed",
28062
- response: { id: segment.responseId, model, usage: usage3(segment) }
28786
+ response: { id: segment.responseId, model, usage: usage4(segment) }
28063
28787
  });
28064
28788
  }
28065
28789
  report("turn.finish", {
@@ -28126,7 +28850,7 @@ function createCursorLiveRun(options) {
28126
28850
  response: {
28127
28851
  id: activeSegment.responseId,
28128
28852
  model,
28129
- usage: usage3(activeSegment)
28853
+ usage: usage4(activeSegment)
28130
28854
  }
28131
28855
  });
28132
28856
  }
@@ -28316,7 +29040,7 @@ ${argumentsText}`;
28316
29040
  const handleFrame = (frame, replayed = false) => {
28317
29041
  const unknownExecFields = frame[CURSOR_UNKNOWN_EXEC_FIELDS] ?? [];
28318
29042
  lastFrame = describeCursorServerFrame(frame, unknownExecFields);
28319
- const tokenDetails = isRecord9(frame.conversationCheckpointUpdate) && isRecord9(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
29043
+ const tokenDetails = isRecord10(frame.conversationCheckpointUpdate) && isRecord10(frame.conversationCheckpointUpdate.tokenDetails) ? frame.conversationCheckpointUpdate.tokenDetails : void 0;
28320
29044
  const checkpointContextTokens = positiveTokenCount(tokenDetails?.usedTokens);
28321
29045
  const checkpointContextWindow = positiveTokenCount(tokenDetails?.maxTokens);
28322
29046
  if (!replayed) {
@@ -28329,7 +29053,7 @@ ${argumentsText}`;
28329
29053
  ...checkpointContextWindow === void 0 ? {} : { contextWindow: checkpointContextWindow }
28330
29054
  });
28331
29055
  }
28332
- if (isRecord9(frame.conversationCheckpointUpdate)) {
29056
+ if (isRecord10(frame.conversationCheckpointUpdate)) {
28333
29057
  if (checkpointContextTokens !== void 0) {
28334
29058
  wireLog("cursor.wire.checkpoint", {
28335
29059
  model: diagnosticModel,
@@ -28352,7 +29076,7 @@ ${argumentsText}`;
28352
29076
  }
28353
29077
  return;
28354
29078
  }
28355
- if (isRecord9(frame.kvServerMessage)) {
29079
+ if (isRecord10(frame.kvServerMessage)) {
28356
29080
  const kv = kvReply(frame.kvServerMessage, blobs);
28357
29081
  stream.write(encodeCursorClientMessage(kv.message));
28358
29082
  if (kv.fetch) {
@@ -28373,7 +29097,7 @@ ${argumentsText}`;
28373
29097
  });
28374
29098
  return;
28375
29099
  }
28376
- if (isRecord9(frame.interactionQuery)) {
29100
+ if (isRecord10(frame.interactionQuery)) {
28377
29101
  const reply = cursorInteractionQueryReply(frame.interactionQuery);
28378
29102
  stream.write(encodeCursorClientMessage(reply.message));
28379
29103
  report("client.reply", { model: diagnosticModel, reply: reply.replyKind });
@@ -28389,7 +29113,7 @@ ${argumentsText}`;
28389
29113
  }
28390
29114
  return;
28391
29115
  }
28392
- if (isRecord9(frame.error)) {
29116
+ if (isRecord10(frame.error)) {
28393
29117
  if (state === "attached") {
28394
29118
  emit({ type: "error", error: cursorError(frame.error) });
28395
29119
  completeRun("server_error");
@@ -28418,8 +29142,8 @@ ${argumentsText}`;
28418
29142
  return;
28419
29143
  }
28420
29144
  if (state !== "attached") return;
28421
- if (isRecord9(frame.execServerMessage)) {
28422
- if (isRecord9(frame.execServerMessage.requestContextArgs)) {
29145
+ if (isRecord10(frame.execServerMessage)) {
29146
+ if (isRecord10(frame.execServerMessage.requestContextArgs)) {
28423
29147
  stream.write(encodeCursorClientMessage(cursorRequestContextReply(frame.execServerMessage, tools)));
28424
29148
  report("client.reply", { model: diagnosticModel, reply: "exec.requestContext" });
28425
29149
  return;
@@ -28508,10 +29232,10 @@ ${argumentsText}`;
28508
29232
  }
28509
29233
  return;
28510
29234
  }
28511
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29235
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
28512
29236
  if (update === void 0) return;
28513
29237
  if (isSettledToolUpdate(update)) return;
28514
- if (isRecord9(update.textDelta) && typeof update.textDelta.text === "string") {
29238
+ if (isRecord10(update.textDelta) && typeof update.textDelta.text === "string") {
28515
29239
  activeSegment.outputText += update.textDelta.text;
28516
29240
  emit({
28517
29241
  type: "response.output_text.delta",
@@ -28522,7 +29246,7 @@ ${argumentsText}`;
28522
29246
  });
28523
29247
  return;
28524
29248
  }
28525
- if (isRecord9(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
29249
+ if (isRecord10(update.thinkingDelta) && typeof update.thinkingDelta.text === "string") {
28526
29250
  activeSegment.outputText += update.thinkingDelta.text;
28527
29251
  emit({
28528
29252
  type: "response.reasoning_summary_text.delta",
@@ -28532,12 +29256,12 @@ ${argumentsText}`;
28532
29256
  });
28533
29257
  return;
28534
29258
  }
28535
- if (isRecord9(update.tokenDelta)) {
29259
+ if (isRecord10(update.tokenDelta)) {
28536
29260
  const tokens = positiveTokenCount(update.tokenDelta.tokens);
28537
29261
  if (tokens !== void 0) activeSegment.contextOutputTokens += tokens;
28538
29262
  return;
28539
29263
  }
28540
- if (isRecord9(update.toolCallStarted)) {
29264
+ if (isRecord10(update.toolCallStarted)) {
28541
29265
  const wireCall = mcpCallFromToolUpdate(update.toolCallStarted);
28542
29266
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28543
29267
  if (call) {
@@ -28547,7 +29271,7 @@ ${argumentsText}`;
28547
29271
  }
28548
29272
  return;
28549
29273
  }
28550
- if (isRecord9(update.partialToolCall)) {
29274
+ if (isRecord10(update.partialToolCall)) {
28551
29275
  const wireCall = mcpCallFromToolUpdate(update.partialToolCall);
28552
29276
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28553
29277
  if (!call) return;
@@ -28558,7 +29282,7 @@ ${argumentsText}`;
28558
29282
  rescheduleToolTurnFinish();
28559
29283
  return;
28560
29284
  }
28561
- if (isRecord9(update.toolCallCompleted)) {
29285
+ if (isRecord10(update.toolCallCompleted)) {
28562
29286
  const wireCall = mcpCallFromToolUpdate(update.toolCallCompleted);
28563
29287
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
28564
29288
  if (!call) return;
@@ -28571,7 +29295,7 @@ ${argumentsText}`;
28571
29295
  rescheduleToolTurnFinish();
28572
29296
  return;
28573
29297
  }
28574
- if (isRecord9(update.turnEnded)) completeRun("turn_ended");
29298
+ if (isRecord10(update.turnEnded)) completeRun("turn_ended");
28575
29299
  };
28576
29300
  const eventsFor = (segment) => (async function* () {
28577
29301
  try {
@@ -28781,34 +29505,34 @@ var CURSOR_INTERACTION_QUERY_CASES = [
28781
29505
  ];
28782
29506
  var CURSOR_KV_CASES = ["getBlobArgs", "setBlobArgs"];
28783
29507
  function describeCursorServerFrame(frame, unknownExecFields = []) {
28784
- if (isRecord9(frame.interactionUpdate)) {
29508
+ if (isRecord10(frame.interactionUpdate)) {
28785
29509
  return `interactionUpdate.${cursorNestedRecordCase(
28786
29510
  frame.interactionUpdate,
28787
29511
  CURSOR_INTERACTION_UPDATE_CASES
28788
29512
  )}`;
28789
29513
  }
28790
- if (isRecord9(frame.execServerMessage)) {
29514
+ if (isRecord10(frame.execServerMessage)) {
28791
29515
  const knownCase = cursorNestedRecordCase(frame.execServerMessage, CURSOR_EXEC_CASES);
28792
29516
  return `execServerMessage.${knownCase === "unknown" ? cursorUnknownExecCaseName(unknownExecFields) : knownCase}`;
28793
29517
  }
28794
- if (isRecord9(frame.interactionQuery)) {
29518
+ if (isRecord10(frame.interactionQuery)) {
28795
29519
  return `interactionQuery.${cursorNestedRecordCase(
28796
29520
  frame.interactionQuery,
28797
29521
  CURSOR_INTERACTION_QUERY_CASES
28798
29522
  )}`;
28799
29523
  }
28800
- if (isRecord9(frame.kvServerMessage)) {
29524
+ if (isRecord10(frame.kvServerMessage)) {
28801
29525
  return `kvServerMessage.${cursorNestedRecordCase(frame.kvServerMessage, CURSOR_KV_CASES)}`;
28802
29526
  }
28803
- if (isRecord9(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
28804
- if (isRecord9(frame.error)) return "error";
29527
+ if (isRecord10(frame.conversationCheckpointUpdate)) return "conversationCheckpointUpdate";
29528
+ if (isRecord10(frame.error)) return "error";
28805
29529
  return "unknown";
28806
29530
  }
28807
29531
  function isCursorHeartbeatFrame(frame) {
28808
- return isRecord9(frame.interactionUpdate) && isRecord9(frame.interactionUpdate.heartbeat);
29532
+ return isRecord10(frame.interactionUpdate) && isRecord10(frame.interactionUpdate.heartbeat);
28809
29533
  }
28810
29534
  function cursorNestedRecordCase(value, cases) {
28811
- return cases.find((candidate) => isRecord9(value[candidate])) ?? "unknown";
29535
+ return cases.find((candidate) => isRecord10(value[candidate])) ?? "unknown";
28812
29536
  }
28813
29537
  function positiveTokenCount(value) {
28814
29538
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) return void 0;
@@ -28820,8 +29544,8 @@ function cursorInteractionQueryReply(query) {
28820
29544
  const response = (result = {}) => ({
28821
29545
  interactionResponse: { id, ...result }
28822
29546
  });
28823
- if (isRecord9(query.createPlanRequestQuery)) {
28824
- const args = isRecord9(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
29547
+ if (isRecord10(query.createPlanRequestQuery)) {
29548
+ const args = isRecord10(query.createPlanRequestQuery.args) ? query.createPlanRequestQuery.args : void 0;
28825
29549
  const name = stringValue3(args?.name)?.trim();
28826
29550
  const overview = stringValue3(args?.overview)?.trim();
28827
29551
  const plan = stringValue3(args?.plan)?.trim();
@@ -28837,7 +29561,7 @@ function cursorInteractionQueryReply(query) {
28837
29561
  ` } : {}
28838
29562
  };
28839
29563
  }
28840
- if (isRecord9(query.askQuestionInteractionQuery)) {
29564
+ if (isRecord10(query.askQuestionInteractionQuery)) {
28841
29565
  return {
28842
29566
  message: response({
28843
29567
  askQuestionInteractionResponse: {
@@ -28847,7 +29571,7 @@ function cursorInteractionQueryReply(query) {
28847
29571
  replyKind: "interaction.askQuestion.rejected"
28848
29572
  };
28849
29573
  }
28850
- if (isRecord9(query.switchModeRequestQuery)) {
29574
+ if (isRecord10(query.switchModeRequestQuery)) {
28851
29575
  return {
28852
29576
  message: response({
28853
29577
  switchModeRequestResponse: {
@@ -28857,19 +29581,19 @@ function cursorInteractionQueryReply(query) {
28857
29581
  replyKind: "interaction.switchMode.rejected"
28858
29582
  };
28859
29583
  }
28860
- if (isRecord9(query.webSearchRequestQuery)) {
29584
+ if (isRecord10(query.webSearchRequestQuery)) {
28861
29585
  return {
28862
29586
  message: response({ webSearchRequestResponse: { approved: {} } }),
28863
29587
  replyKind: "interaction.webSearch.approved"
28864
29588
  };
28865
29589
  }
28866
- if (isRecord9(query.exaSearchRequestQuery)) {
29590
+ if (isRecord10(query.exaSearchRequestQuery)) {
28867
29591
  return {
28868
29592
  message: response({ exaSearchRequestResponse: { approved: {} } }),
28869
29593
  replyKind: "interaction.exaSearch.approved"
28870
29594
  };
28871
29595
  }
28872
- if (isRecord9(query.exaFetchRequestQuery)) {
29596
+ if (isRecord10(query.exaFetchRequestQuery)) {
28873
29597
  return {
28874
29598
  message: response({ exaFetchRequestResponse: { approved: {} } }),
28875
29599
  replyKind: "interaction.exaFetch.approved"
@@ -28879,7 +29603,7 @@ function cursorInteractionQueryReply(query) {
28879
29603
  }
28880
29604
  function kvReply(kv, blobs) {
28881
29605
  const id = kv.id ?? 0;
28882
- if (isRecord9(kv.getBlobArgs)) {
29606
+ if (isRecord10(kv.getBlobArgs)) {
28883
29607
  const blobId = typeof kv.getBlobArgs.blobId === "string" ? kv.getBlobArgs.blobId : "";
28884
29608
  const blobData = blobs.get(blobId);
28885
29609
  return {
@@ -28891,7 +29615,7 @@ function kvReply(kv, blobs) {
28891
29615
  }
28892
29616
  };
28893
29617
  }
28894
- if (isRecord9(kv.setBlobArgs)) {
29618
+ if (isRecord10(kv.setBlobArgs)) {
28895
29619
  const blobId = typeof kv.setBlobArgs.blobId === "string" ? kv.setBlobArgs.blobId : "";
28896
29620
  const blobData = typeof kv.setBlobArgs.blobData === "string" ? kv.setBlobArgs.blobData : "";
28897
29621
  if (blobId) blobs.set(blobId, blobData);
@@ -28942,7 +29666,7 @@ function repairCursorArgumentValue(value, schema) {
28942
29666
  return { value: String(value), count: 1 };
28943
29667
  }
28944
29668
  if (Array.isArray(value)) {
28945
- const itemSchema = isRecord9(schema) ? schema.items : void 0;
29669
+ const itemSchema = isRecord10(schema) ? schema.items : void 0;
28946
29670
  if (itemSchema === void 0) return { value, count: 0 };
28947
29671
  let repairedValues;
28948
29672
  let count2 = 0;
@@ -28955,7 +29679,7 @@ function repairCursorArgumentValue(value, schema) {
28955
29679
  });
28956
29680
  return { value: repairedValues ?? value, count: count2 };
28957
29681
  }
28958
- if (!isRecord9(value) || !isRecord9(schema) || !isRecord9(schema.properties)) {
29682
+ if (!isRecord10(value) || !isRecord10(schema) || !isRecord10(schema.properties)) {
28959
29683
  return { value, count: 0 };
28960
29684
  }
28961
29685
  let repairedValue;
@@ -28971,12 +29695,12 @@ function repairCursorArgumentValue(value, schema) {
28971
29695
  return { value: repairedValue ?? value, count };
28972
29696
  }
28973
29697
  function cursorSchemaRequiresString(schema) {
28974
- if (!isRecord9(schema)) return false;
29698
+ if (!isRecord10(schema)) return false;
28975
29699
  if (schema.type === "string") return true;
28976
29700
  return Array.isArray(schema.type) && schema.type.includes("string") && schema.type.every((type) => type === "string" || type === "null");
28977
29701
  }
28978
29702
  function mcpCallFromToolUpdate(value) {
28979
- const toolCall = isRecord9(value.toolCall) ? value.toolCall : void 0;
29703
+ const toolCall = isRecord10(value.toolCall) ? value.toolCall : void 0;
28980
29704
  const args = toolCall ? mcpArgsFromToolCall(toolCall) : void 0;
28981
29705
  if (!args) return null;
28982
29706
  const publicCallId = stringValue3(value.callId);
@@ -29001,7 +29725,7 @@ var CURSOR_TOOL_UPDATE_CASES = [
29001
29725
  function cursorToolUpdateIdentifiers(update) {
29002
29726
  for (const key of CURSOR_TOOL_UPDATE_CASES) {
29003
29727
  const value = update[key];
29004
- if (!isRecord9(value)) continue;
29728
+ if (!isRecord10(value)) continue;
29005
29729
  const call = mcpCallFromToolUpdate(value);
29006
29730
  if (!call) return [];
29007
29731
  return [...new Set(
@@ -29011,9 +29735,9 @@ function cursorToolUpdateIdentifiers(update) {
29011
29735
  return void 0;
29012
29736
  }
29013
29737
  function isCursorClientToolFrame(frame, tools, redirectTools) {
29014
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29738
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29015
29739
  if (update !== void 0) return cursorToolUpdateIdentifiers(update) !== void 0;
29016
- const exec2 = isRecord9(frame.execServerMessage) ? frame.execServerMessage : void 0;
29740
+ const exec2 = isRecord10(frame.execServerMessage) ? frame.execServerMessage : void 0;
29017
29741
  if (exec2 === void 0) return false;
29018
29742
  const wireCall = mcpCallFromExecMessage(exec2);
29019
29743
  const call = wireCall ? cursorClientMcpCall(wireCall, tools) : null;
@@ -29029,16 +29753,16 @@ function isCursorClientToolFrame(frame, tools, redirectTools) {
29029
29753
  ) !== null;
29030
29754
  }
29031
29755
  function isCursorParkedResidueFrame(frame, parked) {
29032
- const update = isRecord9(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29756
+ const update = isRecord10(frame.interactionUpdate) ? frame.interactionUpdate : void 0;
29033
29757
  if (update === void 0) return false;
29034
- if (isRecord9(update.tokenDelta)) return true;
29758
+ if (isRecord10(update.tokenDelta)) return true;
29035
29759
  const identifiers = cursorToolUpdateIdentifiers(update);
29036
29760
  if (identifiers === void 0 || identifiers.length === 0 || parked === void 0) return false;
29037
29761
  const sealed = new Set(parked.flatMap((call) => [call.callId, call.toolCallId]));
29038
29762
  return identifiers.some((identifier) => sealed.has(identifier));
29039
29763
  }
29040
29764
  function mcpCallFromExecMessage(value) {
29041
- const args = isRecord9(value.mcpArgs) ? value.mcpArgs : void 0;
29765
+ const args = isRecord10(value.mcpArgs) ? value.mcpArgs : void 0;
29042
29766
  if (!args) return null;
29043
29767
  const toolCallId = stringValue3(args.toolCallId);
29044
29768
  if (!toolCallId) return null;
@@ -29056,14 +29780,14 @@ function mcpCallFromExecMessage(value) {
29056
29780
  };
29057
29781
  }
29058
29782
  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;
29783
+ const direct = isRecord10(toolCall.mcpToolCall) ? toolCall.mcpToolCall : void 0;
29784
+ if (direct && isRecord10(direct.args)) return direct.args;
29785
+ const tool = isRecord10(toolCall.tool) ? toolCall.tool : void 0;
29786
+ const nested = tool && isRecord10(tool.mcpToolCall) ? tool.mcpToolCall : void 0;
29787
+ return nested && isRecord10(nested.args) ? nested.args : void 0;
29064
29788
  }
29065
29789
  function cursorMcpArguments(args) {
29066
- if (!isRecord9(args.args) || Object.keys(args.args).length === 0) return {};
29790
+ if (!isRecord10(args.args) || Object.keys(args.args).length === 0) return {};
29067
29791
  const decoded = {};
29068
29792
  for (const [name, value] of Object.entries(args.args)) {
29069
29793
  if (typeof value !== "string") {
@@ -29138,7 +29862,7 @@ function cursorError(value) {
29138
29862
  message: typeof value.message === "string" ? value.message : "Cursor request failed"
29139
29863
  };
29140
29864
  }
29141
- function isRecord9(value) {
29865
+ function isRecord10(value) {
29142
29866
  return typeof value === "object" && value !== null && !Array.isArray(value);
29143
29867
  }
29144
29868
  var DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES = 4 * 1024 * 1024;
@@ -29172,7 +29896,7 @@ var CURSOR_DIAGNOSTIC_EVENTS = /* @__PURE__ */ new Set([
29172
29896
  "turn.finish"
29173
29897
  ]);
29174
29898
  function createCursorDiagnosticLog(dir, options = {}) {
29175
- const logPath = path18__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
29899
+ const logPath = path19__default.join(dir, CURSOR_DIAGNOSTIC_FILE);
29176
29900
  const backupPath = `${logPath}.1`;
29177
29901
  const maxBytes = positiveInteger2(options.maxBytes) ?? DEFAULT_CURSOR_DIAGNOSTIC_MAX_BYTES;
29178
29902
  let initialized = false;
@@ -29230,43 +29954,43 @@ function createCursorDiagnosticLog(dir, options = {}) {
29230
29954
  }
29231
29955
  function serializeCursorDiagnosticEvent(event) {
29232
29956
  if (!CURSOR_DIAGNOSTIC_EVENTS.has(event.event)) return null;
29233
- const record32 = {
29957
+ const record42 = {
29234
29958
  timestamp: safeString(event.timestamp, 40),
29235
29959
  runId: safeString(event.runId, 64),
29236
29960
  event: event.event,
29237
29961
  elapsedMs: safeNumber(event.elapsedMs)
29238
29962
  };
29239
- addString(record32, "model", event.model, 128);
29240
- addString(record32, "wireModel", event.wireModel, 128);
29241
- addString(record32, "previousWireModel", event.previousWireModel, 128);
29963
+ addString(record42, "model", event.model, 128);
29964
+ addString(record42, "wireModel", event.wireModel, 128);
29965
+ addString(record42, "previousWireModel", event.previousWireModel, 128);
29242
29966
  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)}
29967
+ record42.requestedEffort = event.requestedEffort;
29968
+ }
29969
+ if (event.turn === "prompt" || event.turn === "tool-continuation") record42.turn = event.turn;
29970
+ addNumber(record42, "status", event.status);
29971
+ addString(record42, "frame", event.frame, 128);
29972
+ addString(record42, "reply", event.reply, 128);
29973
+ addNumber(record42, "sequence", event.sequence);
29974
+ addNumber(record42, "count", event.count);
29975
+ addNumber(record42, "frameCount", event.frameCount);
29976
+ addString(record42, "lastFrame", event.lastFrame, 128);
29977
+ addNumber(record42, "toolCount", event.toolCount);
29978
+ addNumber(record42, "argumentRepairCount", event.argumentRepairCount);
29979
+ addNumber(record42, "estimatedInputTokens", event.estimatedInputTokens);
29980
+ addNumber(record42, "contextTokens", event.contextTokens);
29981
+ addNumber(record42, "contextWindow", event.contextWindow);
29982
+ addString(record42, "outcome", event.outcome, 128);
29983
+ addNumber(record42, "operationSequence", event.operationSequence);
29984
+ addString(record42, "adapter", event.adapter, 32);
29985
+ addString(record42, "error", event.error, 128);
29986
+ return `${JSON.stringify(record42)}
29263
29987
  `;
29264
29988
  }
29265
- function addString(record32, key, value, maxLength) {
29266
- if (value !== void 0) record32[key] = safeString(value, maxLength);
29989
+ function addString(record42, key, value, maxLength) {
29990
+ if (value !== void 0) record42[key] = safeString(value, maxLength);
29267
29991
  }
29268
- function addNumber(record32, key, value) {
29269
- if (value !== void 0) record32[key] = safeNumber(value);
29992
+ function addNumber(record42, key, value) {
29993
+ if (value !== void 0) record42[key] = safeNumber(value);
29270
29994
  }
29271
29995
  function safeString(value, maxLength) {
29272
29996
  return value.replace(/[\r\n\t]/g, " ").slice(0, maxLength);
@@ -29316,8 +30040,8 @@ function kimiAnthropicHeaders(requestHeaders, apiKey) {
29316
30040
  return headers;
29317
30041
  }
29318
30042
  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) => {
30043
+ if (!isRecord11(value) || value.version !== 1) return { version: 1 };
30044
+ const models = Array.isArray(value.models) ? value.models.filter((entry) => isRecord11(entry) && typeof entry.id === "string" && entry.id.length > 0).flatMap((entry) => {
29321
30045
  const model = findGatewayModel(entry.id);
29322
30046
  if (!model) return [];
29323
30047
  const efforts = Array.isArray(entry.efforts) ? entry.efforts.filter((level) => typeof level === "string" && level.length > 0) : [];
@@ -29351,7 +30075,7 @@ function sanitizeProviderPriority(value) {
29351
30075
  }
29352
30076
  return cleaned.length > 0 ? cleaned : void 0;
29353
30077
  }
29354
- function isRecord10(value) {
30078
+ function isRecord11(value) {
29355
30079
  return typeof value === "object" && value !== null && !Array.isArray(value);
29356
30080
  }
29357
30081
  function resolveAiGatewaySelection(settings2) {
@@ -29391,15 +30115,15 @@ function sortGatewayModelsByProvider(models) {
29391
30115
  function parseAiGatewayUpdate(value) {
29392
30116
  if (value === null) return { ok: true, value: void 0 };
29393
30117
  if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false };
29394
- const record32 = value;
29395
- const extraKeys = Object.keys(record32).filter(
30118
+ const record42 = value;
30119
+ const extraKeys = Object.keys(record42).filter(
29396
30120
  (key) => key !== "models" && key !== "defaultModel" && key !== "providerPriority"
29397
30121
  );
29398
30122
  if (extraKeys.length > 0) return { ok: false };
29399
30123
  const models = [];
29400
- if (record32.models !== void 0) {
29401
- if (!Array.isArray(record32.models)) return { ok: false };
29402
- for (const raw of record32.models) {
30124
+ if (record42.models !== void 0) {
30125
+ if (!Array.isArray(record42.models)) return { ok: false };
30126
+ for (const raw of record42.models) {
29403
30127
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false };
29404
30128
  const entry = raw;
29405
30129
  if (Object.keys(entry).some((key) => key !== "id" && key !== "efforts" && key !== "hostOnly")) {
@@ -29420,11 +30144,11 @@ function parseAiGatewayUpdate(value) {
29420
30144
  }
29421
30145
  }
29422
30146
  let providerPriority;
29423
- const hasProviderPriority = Object.prototype.hasOwnProperty.call(record32, "providerPriority");
30147
+ const hasProviderPriority = Object.prototype.hasOwnProperty.call(record42, "providerPriority");
29424
30148
  if (hasProviderPriority) {
29425
- if (!Array.isArray(record32.providerPriority)) return { ok: false };
30149
+ if (!Array.isArray(record42.providerPriority)) return { ok: false };
29426
30150
  providerPriority = [];
29427
- for (const raw of record32.providerPriority) {
30151
+ for (const raw of record42.providerPriority) {
29428
30152
  if (typeof raw !== "string") return { ok: false };
29429
30153
  if (!GATEWAY_PROVIDERS.includes(raw)) return { ok: false };
29430
30154
  const provider = raw;
@@ -29596,6 +30320,10 @@ async function readCursorSubscriptionToken() {
29596
30320
  const credentials = await resolveCursorCredentials(defaultCredentialDeps);
29597
30321
  return credentials?.accessToken ?? null;
29598
30322
  }
30323
+ async function readXaiSubscriptionToken() {
30324
+ const credentials = await resolveXaiCliCredentials(defaultCredentialDeps);
30325
+ return credentials?.accessToken ?? null;
30326
+ }
29599
30327
  async function readCodexSubscriptionAuth() {
29600
30328
  const credentials = await resolveCodexCredentials(defaultCredentialDeps);
29601
30329
  if (!credentials?.accountId) return null;
@@ -29693,6 +30421,10 @@ function createAiGatewayRouter(deps) {
29693
30421
  for (const skill of pruned.withheld) withheldSkills.add(skill.name);
29694
30422
  if (pruned.changed) body = { ...body, messages: [...pruned.messages] };
29695
30423
  }
30424
+ if (target2 && target2.provider !== "kimi") {
30425
+ const omitted = omitClaudeWebSearchTools(body);
30426
+ if (omitted.changed) body = omitted.request;
30427
+ }
29696
30428
  let credential = "";
29697
30429
  let chatgptAccountId = "";
29698
30430
  if (target2?.provider === "cursor") {
@@ -29724,6 +30456,13 @@ function createAiGatewayRouter(deps) {
29724
30456
  return true;
29725
30457
  }
29726
30458
  credential = opencodeApiKey;
30459
+ } else if (target2?.provider === "xai") {
30460
+ const xaiToken = await deps.readXaiToken?.();
30461
+ if (!xaiToken) {
30462
+ writeAnthropicError(res, 401, "authentication_error", "No active Grok CLI sign-in was found. Run `grok login` first.");
30463
+ return true;
30464
+ }
30465
+ credential = xaiToken;
29727
30466
  }
29728
30467
  const controller = new AbortController();
29729
30468
  const abort = () => controller.abort(new Error("client disconnected"));
@@ -29760,7 +30499,7 @@ function createAiGatewayRouter(deps) {
29760
30499
  );
29761
30500
  return true;
29762
30501
  }
29763
- const gateway = deps.gateway ?? (target2.provider === "cursor" ? ownedCursorGateway : target2.provider === "opencode" ? createOpencodeGateway(opencodeGoWire(target2)) : createGatewayFor(target2, chatgptAccountId, deps.originator));
30502
+ 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
30503
  const diagnosticsEnabled = target2.provider === "cursor" ? cursorDiagnosticsEnabled() : void 0;
29765
30504
  const modelContextWindow = typeof target2.contextWindow === "number" && Number.isFinite(target2.contextWindow) && target2.contextWindow > 0 ? target2.contextWindow : void 0;
29766
30505
  const upstream = await gateway.stream(body, {
@@ -29866,11 +30605,11 @@ var LOCK_OWNER_FILE_NAME2 = "owner";
29866
30605
  var TEMP_FILE_PREFIX2 = `${AI_GATEWAY_SETTINGS_FILE_NAME}.`;
29867
30606
  function createAiGatewaySettingsStore(deps = {}) {
29868
30607
  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);
30608
+ const settingsPath = path19.join(dataDir, AI_GATEWAY_SETTINGS_FILE_NAME);
30609
+ const legacyPath = deps.legacyDir === void 0 ? void 0 : path19.join(deps.legacyDir, AI_GATEWAY_SETTINGS_FILE_NAME);
29871
30610
  const store = createDurableJsonStore({
29872
30611
  filePath: settingsPath,
29873
- lockDir: path18.join(dataDir, LOCK_DIR_NAME2),
30612
+ lockDir: path19.join(dataDir, LOCK_DIR_NAME2),
29874
30613
  lockOwnerFileName: LOCK_OWNER_FILE_NAME2,
29875
30614
  sanitize: (value) => normalizeAiGatewaySettings(value),
29876
30615
  sensitivity: "sensitive",
@@ -30018,9 +30757,9 @@ function prepareAiGatewayLaunchProfile(profile, options) {
30018
30757
  return { ...profile, env };
30019
30758
  }
30020
30759
  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");
30760
+ const configDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : path19__default.join(homeDir, ".claude");
30761
+ const cacheDir = path19__default.join(configDir, "cache");
30762
+ const cachePath = path19__default.join(cacheDir, "gateway-models.json");
30024
30763
  const models = buildAnthropicModelList(exposedModels).data.filter((model) => /^(claude|anthropic)/i.test(model.id)).map((model) => ({ id: model.id, display_name: model.display_name }));
30025
30764
  fs9__default.mkdirSync(cacheDir, { recursive: true, mode: 448 });
30026
30765
  writeAtomicSync(cachePath, JSON.stringify({ baseUrl, fetchedAt: Date.now(), models }), { mode: 384 });
@@ -30309,7 +31048,7 @@ async function resolveLoadout(deps) {
30309
31048
  }
30310
31049
 
30311
31050
  // ../../packages/fleet-admiral/src/ai-gateway/quota-snapshot.ts
30312
- function record3(value) {
31051
+ function record4(value) {
30313
31052
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
30314
31053
  }
30315
31054
  var AMOUNT_PATTERN = /^\d{1,15}$/;
@@ -30317,7 +31056,7 @@ var MAX_WINDOW_DURATION_MS2 = 400 * 24 * 36e5;
30317
31056
  var DURATION_BASES = /* @__PURE__ */ new Set(["upstream", "catalog"]);
30318
31057
  var START_BASES = /* @__PURE__ */ new Set(["upstream", "derived"]);
30319
31058
  function toWindowPeriod(value) {
30320
- const period = record3(value);
31059
+ const period = record4(value);
30321
31060
  if (!period) return void 0;
30322
31061
  const durationMs = period.durationMs;
30323
31062
  const durationBasis = period.durationBasis;
@@ -30334,7 +31073,7 @@ function toWindowPeriod(value) {
30334
31073
  };
30335
31074
  }
30336
31075
  function toWindowAmounts(value) {
30337
- const amounts = record3(value);
31076
+ const amounts = record4(value);
30338
31077
  if (!amounts) return void 0;
30339
31078
  const used = amounts.used;
30340
31079
  const limit = amounts.limit;
@@ -30343,14 +31082,14 @@ function toWindowAmounts(value) {
30343
31082
  return { used, limit };
30344
31083
  }
30345
31084
  function parseGatewayQuotaSnapshot(value) {
30346
- const providers = record3(record3(value)?.providers);
31085
+ const providers = record4(record4(value)?.providers);
30347
31086
  if (!providers) return void 0;
30348
31087
  const snapshot = {};
30349
31088
  for (const [id, value2] of Object.entries(providers)) {
30350
- const provider = record3(value2);
31089
+ const provider = record4(value2);
30351
31090
  if (!provider || typeof provider.status !== "string") continue;
30352
31091
  const windows = Array.isArray(provider.windows) ? provider.windows.flatMap((entry) => {
30353
- const window = record3(entry);
31092
+ const window = record4(entry);
30354
31093
  if (!window || typeof window.id !== "string" || typeof window.usedPercent !== "number") return [];
30355
31094
  const period = toWindowPeriod(window.period);
30356
31095
  const amounts = toWindowAmounts(window.amounts);
@@ -30418,7 +31157,7 @@ function createChildEnv(env, overlay) {
30418
31157
  return child;
30419
31158
  }
30420
31159
  function wrapWindowsShim(resolved, env, platform) {
30421
- if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path18__default.extname(resolved).toLowerCase())) {
31160
+ if (platform !== "win32" || !WINDOWS_SHIM_EXTENSIONS.has(path19__default.extname(resolved).toLowerCase())) {
30422
31161
  return { bin: resolved, prefixArgs: [] };
30423
31162
  }
30424
31163
  rejectCmdExpansionSensitiveShim(resolved);
@@ -30436,13 +31175,13 @@ function forceWindowsArgQuoting(value) {
30436
31175
  return `${value} `;
30437
31176
  }
30438
31177
  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)) {
31178
+ const pathSeparator = platform === "win32" ? WINDOWS_PATH_SEPARATOR : path19__default.delimiter;
31179
+ if (hasPathSeparator(bin, platform) || path19__default.isAbsolute(bin)) {
30441
31180
  return resolveWithExtensions(bin, pathExts, platform);
30442
31181
  }
30443
31182
  for (const entry of pathValue.split(pathSeparator)) {
30444
31183
  const searchDir = entry.length === 0 ? "." : entry;
30445
- const candidate = resolveWithExtensions(path18__default.join(searchDir, bin), pathExts, platform);
31184
+ const candidate = resolveWithExtensions(path19__default.join(searchDir, bin), pathExts, platform);
30446
31185
  if (candidate) {
30447
31186
  return candidate;
30448
31187
  }
@@ -30450,7 +31189,7 @@ function findOnPath(bin, pathValue, pathExts, platform) {
30450
31189
  return void 0;
30451
31190
  }
30452
31191
  function resolveWithExtensions(candidate, pathExts, platform) {
30453
- if (platform !== "win32" || path18__default.extname(candidate).length > 0) {
31192
+ if (platform !== "win32" || path19__default.extname(candidate).length > 0) {
30454
31193
  return isAccessibleExecutable(candidate, platform) ? candidate : void 0;
30455
31194
  }
30456
31195
  for (const ext of pathExts) {
@@ -30496,7 +31235,6 @@ function createClaudeFamilyCliDefinition(options) {
30496
31235
  async createProfile(profileOptions) {
30497
31236
  const { bin, prefixArgs } = resolveBinary("claude", "CLAUDE_BIN", profileOptions.env);
30498
31237
  const launchPrompt = sanitizeLaunchPrompt(profileOptions.prompt);
30499
- assertLaunchPromptShimSafe(launchPrompt, prefixArgs);
30500
31238
  const commandLineLimit = resolveLaunchCommandLineLimit(prefixArgs);
30501
31239
  const childEnv = createChildEnv(profileOptions.env, {});
30502
31240
  return {
@@ -30692,9 +31430,9 @@ function writePrivateJson(filePath, value, rootBase) {
30692
31430
  function writePrivateFile(filePath, content, rootBase) {
30693
31431
  const resolvedBase = ensureRootBase(rootBase);
30694
31432
  ensurePathWithinRoot(resolvedBase, filePath);
30695
- ensureDirectorySegments(resolvedBase, path18__default.dirname(filePath));
31433
+ ensureDirectorySegments(resolvedBase, path19__default.dirname(filePath));
30696
31434
  writeFileNoFollow(filePath, content);
30697
- chmodBestEffort(filePath, FILE_MODE);
31435
+ chmodBestEffort2(filePath, FILE_MODE);
30698
31436
  }
30699
31437
  function removePrivatePath(targetPath, rootBase) {
30700
31438
  const resolvedBase = assertRootBaseSafe(rootBase);
@@ -30722,7 +31460,7 @@ function cleanupPrivateRoot(rootPath, rootBase) {
30722
31460
  throw error51;
30723
31461
  }
30724
31462
  }
30725
- function chmodBestEffort(targetPath, mode) {
31463
+ function chmodBestEffort2(targetPath, mode) {
30726
31464
  try {
30727
31465
  chmodSync(targetPath, mode);
30728
31466
  } catch (_error) {
@@ -30739,20 +31477,20 @@ function writeFileNoFollow(filePath, content) {
30739
31477
  }
30740
31478
  }
30741
31479
  function ensureRootBase(rootBase) {
30742
- const resolvedBase = path18__default.resolve(rootBase);
30743
- const anchor = findExistingDirectoryAnchor(path18__default.dirname(resolvedBase));
31480
+ const resolvedBase = path19__default.resolve(rootBase);
31481
+ const anchor = findExistingDirectoryAnchor(path19__default.dirname(resolvedBase));
30744
31482
  ensureDirectorySegments(anchor, resolvedBase);
30745
31483
  assertDirectorySafe(resolvedBase, "Plugin root base");
30746
31484
  return resolvedBase;
30747
31485
  }
30748
31486
  function assertRootBaseSafe(rootBase) {
30749
- const resolvedBase = path18__default.resolve(rootBase);
30750
- assertExistingSegmentsSafe(findExistingDirectoryAnchor(path18__default.dirname(resolvedBase)), resolvedBase);
31487
+ const resolvedBase = path19__default.resolve(rootBase);
31488
+ assertExistingSegmentsSafe(findExistingDirectoryAnchor(path19__default.dirname(resolvedBase)), resolvedBase);
30751
31489
  assertDirectorySafe(resolvedBase, "Plugin root base");
30752
31490
  return resolvedBase;
30753
31491
  }
30754
31492
  function findExistingDirectoryAnchor(targetPath) {
30755
- const resolvedTarget = path18__default.resolve(targetPath);
31493
+ const resolvedTarget = path19__default.resolve(targetPath);
30756
31494
  let current = resolvedTarget;
30757
31495
  while (true) {
30758
31496
  try {
@@ -30760,7 +31498,7 @@ function findExistingDirectoryAnchor(targetPath) {
30760
31498
  return current;
30761
31499
  } catch (error51) {
30762
31500
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
30763
- const parent = path18__default.dirname(current);
31501
+ const parent = path19__default.dirname(current);
30764
31502
  if (parent === current) throw error51;
30765
31503
  current = parent;
30766
31504
  continue;
@@ -30779,17 +31517,17 @@ function assertDirectorySafe(dirPath, label) {
30779
31517
  }
30780
31518
  }
30781
31519
  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;
31520
+ const resolvedCandidate = path19__default.resolve(candidatePath);
31521
+ const relative = path19__default.relative(resolvedBase, resolvedCandidate);
31522
+ if (relative === "" || !relative.startsWith("..") && !path19__default.isAbsolute(relative)) return;
30785
31523
  throw new Error(`Plugin path escapes root base: ${candidatePath}`);
30786
31524
  }
30787
31525
  function ensureDirectorySegments(resolvedBase, dirPath) {
30788
- const target2 = path18__default.resolve(dirPath);
30789
- const relative = path18__default.relative(resolvedBase, target2);
31526
+ const target2 = path19__default.resolve(dirPath);
31527
+ const relative = path19__default.relative(resolvedBase, target2);
30790
31528
  let current = resolvedBase;
30791
- for (const segment of relative.split(path18__default.sep).filter(Boolean)) {
30792
- current = path18__default.join(current, segment);
31529
+ for (const segment of relative.split(path19__default.sep).filter(Boolean)) {
31530
+ current = path19__default.join(current, segment);
30793
31531
  try {
30794
31532
  const stat4 = lstatSync(current);
30795
31533
  if (stat4.isSymbolicLink()) {
@@ -30801,7 +31539,7 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
30801
31539
  } catch (error51) {
30802
31540
  if (error51 instanceof Error && "code" in error51 && error51.code === "ENOENT") {
30803
31541
  mkdirSync(current, { mode: DIR_MODE });
30804
- chmodBestEffort(current, DIR_MODE);
31542
+ chmodBestEffort2(current, DIR_MODE);
30805
31543
  } else {
30806
31544
  throw error51;
30807
31545
  }
@@ -30810,11 +31548,11 @@ function ensureDirectorySegments(resolvedBase, dirPath) {
30810
31548
  }
30811
31549
  }
30812
31550
  function assertExistingSegmentsSafe(resolvedBase, targetPath) {
30813
- const target2 = path18__default.resolve(targetPath);
30814
- const relative = path18__default.relative(resolvedBase, target2);
31551
+ const target2 = path19__default.resolve(targetPath);
31552
+ const relative = path19__default.relative(resolvedBase, target2);
30815
31553
  let current = resolvedBase;
30816
- for (const segment of relative.split(path18__default.sep).filter(Boolean)) {
30817
- current = path18__default.join(current, segment);
31554
+ for (const segment of relative.split(path19__default.sep).filter(Boolean)) {
31555
+ current = path19__default.join(current, segment);
30818
31556
  const stat4 = lstatSync(current);
30819
31557
  if (stat4.isSymbolicLink()) {
30820
31558
  throw new Error(`Plugin path segment is a symlink: ${current}`);
@@ -30826,13 +31564,13 @@ function assertExistingSegmentsSafe(resolvedBase, targetPath) {
30826
31564
  }
30827
31565
  }
30828
31566
  function assertExistingParentSegmentsSafe(resolvedBase, targetPath) {
30829
- assertExistingSegmentsSafe(resolvedBase, path18__default.dirname(targetPath));
31567
+ assertExistingSegmentsSafe(resolvedBase, path19__default.dirname(targetPath));
30830
31568
  }
30831
31569
  function assertSegmentRealpathWithinRoot(resolvedBase, segmentPath) {
30832
31570
  const baseRealpath = realpathSync(resolvedBase);
30833
31571
  const segmentRealpath = realpathSync(segmentPath);
30834
- const relative = path18__default.relative(baseRealpath, segmentRealpath);
30835
- if (relative === "" || !relative.startsWith("..") && !path18__default.isAbsolute(relative)) return;
31572
+ const relative = path19__default.relative(baseRealpath, segmentRealpath);
31573
+ if (relative === "" || !relative.startsWith("..") && !path19__default.isAbsolute(relative)) return;
30836
31574
  throw new Error(`Plugin path segment escapes root base: ${segmentPath}`);
30837
31575
  }
30838
31576
 
@@ -30852,18 +31590,18 @@ function renderAssetPluginRoot(pluginRoot, bundle, options) {
30852
31590
  options.doctrine ?? resolveDoctrineFromCliId(options.cliId);
30853
31591
  renderEmbeddedSkillAssets(pluginRoot);
30854
31592
  const workflowGuardScriptPath = writeWorkflowGuardScript(pluginRoot);
30855
- writePrivateJson(path18__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
31593
+ writePrivateJson(path19__default.join(pluginRoot, "hooks", "hooks.json"), claudeHooks(options, workflowGuardScriptPath), pluginRoot);
30856
31594
  renderGatewayAgentAssets(pluginRoot, options);
30857
31595
  }
30858
31596
  function renderGatewayAgentAssets(pluginRoot, options) {
30859
31597
  for (const file2 of buildGatewayAgentFiles(options.gatewayDelegationModels ?? [], options.gatewayEffortExposure)) {
30860
- writePrivateFile(path18__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
31598
+ writePrivateFile(path19__default.join(pluginRoot, "agents", file2.fileName), file2.content, pluginRoot);
30861
31599
  }
30862
31600
  }
30863
31601
  function writeWorkflowGuardScript(pluginRoot) {
30864
31602
  const asset = EMBEDDED_AGENT_CLI_HOOK_ASSETS.find((entry) => entry.relativePath === "workflow-guard.mjs");
30865
31603
  if (!asset) throw new Error("Missing embedded workflow-guard hook asset");
30866
- const scriptPath = path18__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
31604
+ const scriptPath = path19__default.join(pluginRoot, "hooks", "workflow-guard.mjs");
30867
31605
  writePrivateFile(scriptPath, asset.content, pluginRoot);
30868
31606
  return scriptPath;
30869
31607
  }
@@ -30922,7 +31660,7 @@ function claudeCommandHook(hookExec) {
30922
31660
  }
30923
31661
  function renderEmbeddedSkillAssets(pluginRoot, doctrine) {
30924
31662
  for (const asset of selectSkillAssetsForDoctrine()) {
30925
- writePrivateFile(path18__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
31663
+ writePrivateFile(path19__default.join(pluginRoot, "skills", asset.relativePath), asset.content, pluginRoot);
30926
31664
  }
30927
31665
  }
30928
31666
  function selectSkillAssetsForDoctrine(_doctrine) {
@@ -30999,7 +31737,7 @@ function resolveRenderablePluginBundles(fleetRoot, options) {
30999
31737
  function homeMarketplaceTarget(fleetRoot) {
31000
31738
  return {
31001
31739
  name: FLEET_MARKETPLACE_NAME,
31002
- root: path18__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
31740
+ root: path19__default.join(fleetRoot, MARKETPLACE_DIR_NAME)
31003
31741
  };
31004
31742
  }
31005
31743
  function groupRenderableBundlesByMarketplace(bundles) {
@@ -31015,17 +31753,17 @@ function groupRenderableBundlesByMarketplace(bundles) {
31015
31753
  return groups;
31016
31754
  }
31017
31755
  function renderPluginRoot(pluginRoot, bundle, options) {
31018
- const parentRoot = path18__default.dirname(pluginRoot);
31756
+ const parentRoot = path19__default.dirname(pluginRoot);
31019
31757
  ensurePrivateDir(parentRoot, parentRoot);
31020
31758
  const stageParent = createStagingDir(parentRoot);
31021
- const stagedPluginRoot = path18__default.join(stageParent, path18__default.basename(pluginRoot));
31759
+ const stagedPluginRoot = path19__default.join(stageParent, path19__default.basename(pluginRoot));
31022
31760
  try {
31023
31761
  ensurePrivateDir(stagedPluginRoot, stagedPluginRoot);
31024
- writePrivateJson(path18__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
31762
+ writePrivateJson(path19__default.join(stagedPluginRoot, ".claude-plugin", "plugin.json"), claudeManifest(bundle), stagedPluginRoot);
31025
31763
  switch (bundle.source) {
31026
31764
  case "asset":
31027
- ensurePrivateDir(path18__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
31028
- ensurePrivateDir(path18__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
31765
+ ensurePrivateDir(path19__default.join(stagedPluginRoot, "agents"), stagedPluginRoot);
31766
+ ensurePrivateDir(path19__default.join(stagedPluginRoot, "skills"), stagedPluginRoot);
31029
31767
  renderAssetPluginRoot(stagedPluginRoot, bundle, options);
31030
31768
  break;
31031
31769
  }
@@ -31040,11 +31778,11 @@ function renderMarketplaceRoot(target2, bundles) {
31040
31778
  ensurePrivateDir(marketplaceRoot, marketplaceRoot);
31041
31779
  const stagedRoot = createStagingDir(marketplaceRoot);
31042
31780
  try {
31043
- writePrivateJson(path18__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
31781
+ writePrivateJson(path19__default.join(stagedRoot, ".claude-plugin", "marketplace.json"), claudeMarketplace(target2, bundles), stagedRoot);
31044
31782
  pruneMarketplaceRoot(target2);
31045
31783
  pruneStalePluginDirs(target2, bundles);
31046
31784
  for (const entry of readdirSync(stagedRoot)) {
31047
- renameSync(path18__default.join(stagedRoot, entry), path18__default.join(marketplaceRoot, entry));
31785
+ renameSync(path19__default.join(stagedRoot, entry), path19__default.join(marketplaceRoot, entry));
31048
31786
  }
31049
31787
  } finally {
31050
31788
  cleanupPrivateRoot(stagedRoot, marketplaceRoot);
@@ -31052,11 +31790,11 @@ function renderMarketplaceRoot(target2, bundles) {
31052
31790
  }
31053
31791
  function pruneMarketplaceRoot(target2) {
31054
31792
  for (const entry of MARKETPLACE_PRUNE_ENTRIES) {
31055
- removePrivatePath(path18__default.join(target2.root, entry), target2.root);
31793
+ removePrivatePath(path19__default.join(target2.root, entry), target2.root);
31056
31794
  }
31057
31795
  }
31058
31796
  function pruneStalePluginDirs(target2, bundles) {
31059
- const pluginsDir = path18__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
31797
+ const pluginsDir = path19__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME);
31060
31798
  if (!existsSync(pluginsDir)) return;
31061
31799
  const activeDirectoryNames = /* @__PURE__ */ new Set();
31062
31800
  for (const bundle of bundles) {
@@ -31070,11 +31808,11 @@ function pruneStalePluginDirs(target2, bundles) {
31070
31808
  }
31071
31809
  for (const entry of readdirSync(pluginsDir)) {
31072
31810
  if (activeDirectoryNames.has(entry)) continue;
31073
- removePrivatePath(path18__default.join(pluginsDir, entry), target2.root);
31811
+ removePrivatePath(path19__default.join(pluginsDir, entry), target2.root);
31074
31812
  }
31075
31813
  }
31076
31814
  function createStagingDir(rootPath) {
31077
- const stageRoot = mkdtempSync(path18__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
31815
+ const stageRoot = mkdtempSync(path19__default.join(rootPath, `.fleet-stage-${process.pid}-${Date.now()}-`));
31078
31816
  return stageRoot;
31079
31817
  }
31080
31818
  function claudeMarketplace(target2, bundles) {
@@ -31096,7 +31834,7 @@ function claudeMarketplace(target2, bundles) {
31096
31834
  };
31097
31835
  }
31098
31836
  function pluginRootForTarget(target2, bundle) {
31099
- return path18__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
31837
+ return path19__default.join(target2.root, PLUGIN_BUNDLES_DIR_NAME, bundle.directoryName);
31100
31838
  }
31101
31839
  function marketplacePluginPath(target2, bundle) {
31102
31840
  return `./${PLUGIN_BUNDLES_DIR_NAME}/${bundle.directoryName}`;
@@ -31127,6 +31865,22 @@ async function injectAgentCliProfile(profile, options) {
31127
31865
  const tempCleanups = [];
31128
31866
  try {
31129
31867
  const systemPromptFile = systemPromptMode === "off" ? void 0 : writeSystemPromptFile(profile.id, options.buildSystemPrompt(), (cleanup2) => tempCleanups.push(cleanup2));
31868
+ let promptArgs = [...profile.promptArgs ?? []];
31869
+ let deliveredViaFile = false;
31870
+ const cmdWrapped = profile.commandLineLimit?.via === "cmd-shim";
31871
+ const windowsLaunch = profile.commandLineLimit !== void 0;
31872
+ const convertPromptToFile = (body) => {
31873
+ promptArgs = [writeLaunchPromptPointer(
31874
+ body,
31875
+ (cleanupFn) => tempCleanups.push(cleanupFn),
31876
+ cmdWrapped
31877
+ )];
31878
+ deliveredViaFile = true;
31879
+ };
31880
+ if (promptArgs.length > 0 && windowsLaunch) {
31881
+ const body = takeLaunchPromptBody(promptArgs);
31882
+ if (launchPromptHasCmdUnsafeChars(body)) convertPromptToFile(body);
31883
+ }
31130
31884
  const plugin = await createAgentCliPlugin({
31131
31885
  cliId: profile.id,
31132
31886
  doctrine,
@@ -31163,26 +31917,39 @@ async function injectAgentCliProfile(profile, options) {
31163
31917
  systemPromptFile
31164
31918
  };
31165
31919
  const injectedArgs = buildAgentCliArgs(capability2.builderId, context);
31166
- const mergedArgs = mergeAgentCliArgs(profile, capability2.builderId, context, injectedArgs);
31920
+ const mergeArgs = (nextPromptArgs) => mergeAgentCliArgs(
31921
+ { ...profile, promptArgs: nextPromptArgs },
31922
+ capability2.builderId,
31923
+ context,
31924
+ injectedArgs
31925
+ );
31926
+ const argsWithoutPrompt = mergeArgs([]);
31927
+ const checkBudget = () => assertLaunchCommandLineBudget({
31928
+ args: mergeArgs(promptArgs),
31929
+ argsWithoutPrompt,
31930
+ bin: profile.bin,
31931
+ limit: profile.commandLineLimit,
31932
+ promptIsFixedLength: deliveredViaFile
31933
+ });
31167
31934
  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
- });
31935
+ checkBudget();
31179
31936
  } catch (error51) {
31180
- cleanup();
31181
- throw error51;
31937
+ const canMoveToFile = !deliveredViaFile && windowsLaunch && promptArgs.length === 1 && error51 instanceof LaunchPromptError && error51.code === "prompt_command_line_too_long";
31938
+ if (!canMoveToFile) {
31939
+ cleanup();
31940
+ throw error51;
31941
+ }
31942
+ convertPromptToFile(takeLaunchPromptBody(promptArgs));
31943
+ try {
31944
+ checkBudget();
31945
+ } catch (retryError) {
31946
+ cleanup();
31947
+ throw retryError;
31948
+ }
31182
31949
  }
31183
31950
  return {
31184
31951
  ...profile,
31185
- args: mergedArgs,
31952
+ args: mergeArgs(promptArgs),
31186
31953
  // 위치 인자는 이미 args 끝에 합쳐졌으므로 비운다. 남겨 두면 하류가 한 번 더 붙일 수 있다.
31187
31954
  promptArgs: [],
31188
31955
  cleanup
@@ -31208,21 +31975,27 @@ function buildAgentCliMcpServerConfigs(endpoints, tokens) {
31208
31975
  };
31209
31976
  });
31210
31977
  }
31978
+ function takeLaunchPromptBody(promptArgs) {
31979
+ if (promptArgs.length !== 1) {
31980
+ throw new Error(`Launch prompt file conversion expects a single positional prompt, got ${promptArgs.length}`);
31981
+ }
31982
+ return promptArgs[0];
31983
+ }
31211
31984
  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");
31985
+ const tempDir = mkdtempSync(path19__default.join(os3__default.tmpdir(), `fleet-${cliId}-`));
31986
+ onCleanup(() => rmBestEffort2(tempDir));
31987
+ const filePath = path19__default.join(tempDir, "system-prompt.md");
31215
31988
  writeFileSync(filePath, systemPrompt, { encoding: "utf8", flag: "wx", mode: SYSTEM_PROMPT_FILE_MODE });
31216
- chmodBestEffort2(filePath, SYSTEM_PROMPT_FILE_MODE);
31989
+ chmodBestEffort3(filePath, SYSTEM_PROMPT_FILE_MODE);
31217
31990
  return filePath;
31218
31991
  }
31219
- function chmodBestEffort2(targetPath, mode) {
31992
+ function chmodBestEffort3(targetPath, mode) {
31220
31993
  try {
31221
31994
  chmodSync(targetPath, mode);
31222
31995
  } catch {
31223
31996
  }
31224
31997
  }
31225
- function rmBestEffort(targetPath) {
31998
+ function rmBestEffort2(targetPath) {
31226
31999
  try {
31227
32000
  rmSync(targetPath, { force: true, recursive: true });
31228
32001
  } catch {
@@ -32383,18 +33156,18 @@ Always read \`schema/wiki-schema.md\` directly before composing or revising entr
32383
33156
  `;
32384
33157
  async function ensureWorkspaceSchema(paths) {
32385
33158
  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);
33159
+ await writeDefaultFileIfMissing(path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME), DEFAULT_WORKSPACE_SCHEMA_AGENTS);
33160
+ await writeDefaultFileIfMissing(path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME), DEFAULT_WORKSPACE_WIKI_SCHEMA);
32388
33161
  await writeDefaultFileIfMissing(buildTemplatePath(paths, "prd"), DEFAULT_TEMPLATE_PRD);
32389
33162
  return readWorkspaceSchemaSummary(paths);
32390
33163
  }
32391
33164
  async function ensureWorkspaceDoctrine(paths) {
32392
33165
  await mkdir(paths.root, { recursive: true });
32393
- await writeDefaultFileIfMissing(path18__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
33166
+ await writeDefaultFileIfMissing(path19__default.join(paths.root, WORKSPACE_KNOWLEDGE_AGENTS_FILENAME), DEFAULT_WORKSPACE_KNOWLEDGE_AGENTS);
32394
33167
  }
32395
33168
  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);
33169
+ const agentsPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
33170
+ const wikiSchemaPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_FILENAME);
32398
33171
  const wikiSchemaContent = await tryReadSchemaFile(paths, wikiSchemaPath);
32399
33172
  const templates = await scanTemplates(paths);
32400
33173
  if (wikiSchemaContent === null) {
@@ -32433,7 +33206,7 @@ async function scanTemplates(paths) {
32433
33206
  if (!entry.name.startsWith(WORKSPACE_TEMPLATE_PREFIX) || !entry.name.endsWith(WORKSPACE_TEMPLATE_SUFFIX)) continue;
32434
33207
  const id = entry.name.slice(WORKSPACE_TEMPLATE_PREFIX.length, -WORKSPACE_TEMPLATE_SUFFIX.length);
32435
33208
  if (!TEMPLATE_ID_PATTERN.test(id)) continue;
32436
- const filePath = path18__default.join(paths.schemaDir, entry.name);
33209
+ const filePath = path19__default.join(paths.schemaDir, entry.name);
32437
33210
  try {
32438
33211
  const parsed = parseTemplateMarkdown(await readFile(filePath, "utf8"));
32439
33212
  templates.push({
@@ -32465,7 +33238,7 @@ async function readSchemaCatalog(paths) {
32465
33238
  }
32466
33239
  async function readSchemaDocument(paths, resource, templateId) {
32467
33240
  const ref = resource === "schema" ? "schema/wiki-schema.md" : schemaTemplateRef(templateId ?? "");
32468
- const absolute = path18__default.resolve(paths.root, ref);
33241
+ const absolute = path19__default.resolve(paths.root, ref);
32469
33242
  await assertContainedSchemaFile(paths, absolute, false);
32470
33243
  return { ref, content: await readFile(absolute, "utf8") };
32471
33244
  }
@@ -32490,10 +33263,10 @@ async function validateSchemaTemplateCreate(paths, templateId, markdown) {
32490
33263
  if (folded.has(key)) throw new Error(`schema template contains duplicate ## section: ${section}`);
32491
33264
  folded.add(key);
32492
33265
  }
32493
- const absolute = path18__default.resolve(paths.root, ref);
33266
+ const absolute = path19__default.resolve(paths.root, ref);
32494
33267
  await assertContainedSchemaFile(paths, absolute, true);
32495
33268
  const entries = await readdir(paths.schemaDir).catch(() => []);
32496
- const basename = path18__default.basename(absolute).toLocaleLowerCase("en-US");
33269
+ const basename = path19__default.basename(absolute).toLocaleLowerCase("en-US");
32497
33270
  if (entries.some((entry) => entry.toLocaleLowerCase("en-US") === basename)) throw new Error("schema template target already exists");
32498
33271
  return absolute;
32499
33272
  }
@@ -32501,13 +33274,13 @@ function assertTemplateId(id) {
32501
33274
  if (!TEMPLATE_ID_PATTERN.test(id)) throw new Error("template_id must match /^[a-z][a-z0-9-]{0,63}$/");
32502
33275
  }
32503
33276
  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)));
33277
+ const schemaReal = await realpath(paths.schemaDir).catch(() => path19__default.resolve(paths.schemaDir));
33278
+ const parentReal = await realpath(path19__default.dirname(absolute)).catch(() => path19__default.resolve(path19__default.dirname(absolute)));
32506
33279
  if (parentReal !== schemaReal) throw new Error("schema resource escapes schema directory");
32507
- const relative = path18__default.relative(paths.root, absolute);
33280
+ const relative = path19__default.relative(paths.root, absolute);
32508
33281
  let cursor = paths.root;
32509
- for (const part of relative.split(path18__default.sep)) {
32510
- cursor = path18__default.join(cursor, part);
33282
+ for (const part of relative.split(path19__default.sep)) {
33283
+ cursor = path19__default.join(cursor, part);
32511
33284
  try {
32512
33285
  if ((await lstat(cursor)).isSymbolicLink()) throw new Error("schema resource path contains symlink");
32513
33286
  } catch (error51) {
@@ -32535,7 +33308,7 @@ async function validateTemplateCompliance(paths, templateId, body) {
32535
33308
  }
32536
33309
  }
32537
33310
  function inferTemplateIdFromTarget(target2, knownTemplateIds) {
32538
- const basename = path18__default.basename(target2, ".md");
33311
+ const basename = path19__default.basename(target2, ".md");
32539
33312
  const ids = knownTemplateIds ?? DEFAULT_TEMPLATE_IDS;
32540
33313
  const sorted = [...ids].sort((a, b) => b.length - a.length);
32541
33314
  for (const id of sorted) {
@@ -32567,7 +33340,7 @@ function extractSchemaSummary(content) {
32567
33340
  return lines.find((line) => line.length > 0 && !line.startsWith("#")) ?? "Workspace schema is present.";
32568
33341
  }
32569
33342
  function buildTemplatePath(paths, id) {
32570
- return path18__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
33343
+ return path19__default.join(paths.schemaDir, `${WORKSPACE_TEMPLATE_PREFIX}${id}${WORKSPACE_TEMPLATE_SUFFIX}`);
32571
33344
  }
32572
33345
  function parseTemplateMarkdown(content) {
32573
33346
  const normalized = content.replace(/\r\n/g, "\n");
@@ -32672,18 +33445,18 @@ function isAlreadyExistsError(error51) {
32672
33445
 
32673
33446
  // ../../packages/fleet-wiki/src/paths.ts
32674
33447
  function resolveMemoryPaths(cwd) {
32675
- return createMemoryPaths(path18__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
33448
+ return createMemoryPaths(path19__default.join(cwd, KNOWLEDGE_ROOT_DIRNAME));
32676
33449
  }
32677
33450
  function createMemoryPaths(root) {
32678
33451
  return {
32679
33452
  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)
33453
+ rawDir: path19__default.join(root, RAW_DIRNAME),
33454
+ wikiDir: path19__default.join(root, WIKI_DIRNAME),
33455
+ schemaDir: path19__default.join(root, SCHEMA_DIRNAME),
33456
+ queueDir: path19__default.join(root, QUEUE_DIRNAME),
33457
+ archiveDir: path19__default.join(root, ARCHIVE_DIRNAME),
33458
+ conflictsDir: path19__default.join(root, CONFLICTS_DIRNAME),
33459
+ indexFile: path19__default.join(root, INDEX_FILENAME)
32687
33460
  };
32688
33461
  }
32689
33462
  function resolveToolMemoryPaths(ctx) {
@@ -32701,10 +33474,10 @@ async function ensureMemoryRoot(paths) {
32701
33474
  await ensureWorkspaceDoctrine(paths);
32702
33475
  }
32703
33476
  function getIndexMarkdownFile(paths) {
32704
- return path18__default.join(paths.wikiDir, INDEX_MD_FILENAME);
33477
+ return path19__default.join(paths.wikiDir, INDEX_MD_FILENAME);
32705
33478
  }
32706
33479
  function getLogFile(paths) {
32707
- return path18__default.join(paths.root, LOG_MD_FILENAME);
33480
+ return path19__default.join(paths.root, LOG_MD_FILENAME);
32708
33481
  }
32709
33482
 
32710
33483
  // ../../packages/fleet-wiki/src/conflicts.ts
@@ -32716,7 +33489,7 @@ async function createConflict(input, paths) {
32716
33489
  await ensureMemoryRoot(paths);
32717
33490
  const now = input.now ?? /* @__PURE__ */ new Date();
32718
33491
  const conflictId = buildConflictId(now, input.wikiId, input.reason, input.proposed);
32719
- const conflictDir = path18__default.join(paths.conflictsDir, conflictId);
33492
+ const conflictDir = path19__default.join(paths.conflictsDir, conflictId);
32720
33493
  await mkdir(conflictDir, { recursive: true });
32721
33494
  const meta3 = {
32722
33495
  id: conflictId,
@@ -32736,13 +33509,13 @@ async function createConflict(input, paths) {
32736
33509
  currentHash: input.currentHash,
32737
33510
  warnings: input.warnings
32738
33511
  };
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);
33512
+ await writeJsonFile(path19__default.join(conflictDir, CONFLICT_META_FILENAME), meta3, paths);
33513
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME), input.proposed, paths);
32741
33514
  if (input.current !== void 0) {
32742
- await writePatchFile(path18__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
33515
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_CURRENT_FILENAME), input.current, paths);
32743
33516
  }
32744
33517
  if (input.rawSource !== void 0) {
32745
- await writePatchFile(path18__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
33518
+ await writePatchFile(path19__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME), input.rawSource, paths);
32746
33519
  }
32747
33520
  return {
32748
33521
  meta: meta3,
@@ -32756,7 +33529,7 @@ async function listConflicts(paths) {
32756
33529
  const metas = [];
32757
33530
  for (const id of ids) {
32758
33531
  try {
32759
- metas.push(await readJsonFile2(path18__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
33532
+ metas.push(await readJsonFile2(path19__default.join(paths.conflictsDir, id, CONFLICT_META_FILENAME)));
32760
33533
  } catch {
32761
33534
  continue;
32762
33535
  }
@@ -32765,13 +33538,13 @@ async function listConflicts(paths) {
32765
33538
  }
32766
33539
  async function readConflict(conflictId, paths) {
32767
33540
  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);
33541
+ const meta3 = await readJsonFile2(path19__default.join(conflictDir, CONFLICT_META_FILENAME));
33542
+ const currentPath = path19__default.join(conflictDir, CONFLICT_CURRENT_FILENAME);
33543
+ const rawSourcePath = path19__default.join(conflictDir, CONFLICT_RAW_SOURCE_FILENAME);
32771
33544
  return {
32772
33545
  meta: meta3,
32773
33546
  current: await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0,
32774
- proposed: await readPatchFile(path18__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
33547
+ proposed: await readPatchFile(path19__default.join(conflictDir, CONFLICT_PROPOSED_FILENAME)),
32775
33548
  rawSource: await pathExists(rawSourcePath) ? await readPatchFile(rawSourcePath) : void 0
32776
33549
  };
32777
33550
  }
@@ -32790,9 +33563,9 @@ function sanitizeConflictToken(value) {
32790
33563
  return value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "unknown";
32791
33564
  }
32792
33565
  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)) {
33566
+ const conflictDir = path19__default.resolve(paths.conflictsDir, conflictId);
33567
+ const relative = path19__default.relative(paths.conflictsDir, conflictDir);
33568
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
32796
33569
  throw new Error(`[fleet-wiki] conflict id escapes conflicts/: ${conflictId}`);
32797
33570
  }
32798
33571
  return conflictDir;
@@ -32956,11 +33729,11 @@ async function validatePatch(patch, paths) {
32956
33729
  if (!target2 || !summary || !proposer || !created) throw new Error("patch frontmatter is incomplete");
32957
33730
  if (summary.length > 120) throw new Error("patch summary exceeds 120 chars");
32958
33731
  assertCanonicalPatchTarget(target2);
32959
- const absoluteTarget = path18__default.resolve(paths.root, target2);
32960
- if (!absoluteTarget.startsWith(`${paths.root}${path18__default.sep}`) && absoluteTarget !== paths.root) {
33732
+ const absoluteTarget = path19__default.resolve(paths.root, target2);
33733
+ if (!absoluteTarget.startsWith(`${paths.root}${path19__default.sep}`) && absoluteTarget !== paths.root) {
32961
33734
  throw new Error("patch target escapes wiki root");
32962
33735
  }
32963
- if (!absoluteTarget.startsWith(`${paths.wikiDir}${path18__default.sep}`)) throw new Error("wiki patch must target wiki/");
33736
+ if (!absoluteTarget.startsWith(`${paths.wikiDir}${path19__default.sep}`)) throw new Error("wiki patch must target wiki/");
32964
33737
  assertNoSymlinkPathComponents(target2, paths);
32965
33738
  if (op === "create_wiki" && await pathExists(absoluteTarget)) {
32966
33739
  throw new Error(
@@ -32981,19 +33754,19 @@ async function applyPatch(patch, paths) {
32981
33754
  async function enqueuePatch(patch, paths, metaOverrides) {
32982
33755
  await ensureMemoryRoot(paths);
32983
33756
  const patchId = buildPatchId(patch.frontmatter.created, patch.frontmatter.summary, patch.frontmatter.target, patch.body);
32984
- const queueDir = path18__default.join(paths.queueDir, patchId);
33757
+ const queueDir = path19__default.join(paths.queueDir, patchId);
32985
33758
  if (await pathExists(queueDir)) {
32986
33759
  throw new Error(`[fleet-wiki] patch id collision: ${patchId} - this should never happen with target+body hashing`);
32987
33760
  }
32988
33761
  await mkdir(queueDir, { recursive: true });
32989
- await writePatchFile(path18__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
33762
+ await writePatchFile(path19__default.join(queueDir, PATCH_FILENAME), serializePatch(patch), paths);
32990
33763
  const meta3 = {
32991
33764
  id: patchId,
32992
33765
  status: "pending",
32993
33766
  createdAt: patch.frontmatter.created,
32994
33767
  ...metaOverrides
32995
33768
  };
32996
- await writeJsonFile(path18__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
33769
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), meta3, paths);
32997
33770
  await appendLog(paths, "patch enqueued", {
32998
33771
  patch_id: patchId,
32999
33772
  patch_set_id: meta3.patch_set_id ?? null,
@@ -33011,7 +33784,7 @@ async function listQueue(paths) {
33011
33784
  for (const id of ids) {
33012
33785
  if (id === "_sets") continue;
33013
33786
  try {
33014
- const meta3 = await readJsonFile2(path18__default.join(paths.queueDir, id, PATCH_META_FILENAME));
33787
+ const meta3 = await readJsonFile2(path19__default.join(paths.queueDir, id, PATCH_META_FILENAME));
33015
33788
  results.push({ id, meta: meta3 });
33016
33789
  } catch {
33017
33790
  continue;
@@ -33036,17 +33809,17 @@ async function resolveQueueSelection(id, paths) {
33036
33809
  }
33037
33810
  async function showQueue(id, paths) {
33038
33811
  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));
33812
+ const queueDir = path19__default.join(paths.queueDir, selection.id);
33813
+ const patch = await parsePatch(await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME)));
33814
+ const meta3 = await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME));
33042
33815
  return { patch, meta: meta3 };
33043
33816
  }
33044
33817
  async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
33045
33818
  assertSafeQueueId(id);
33046
33819
  return withPatchEditLock(paths, id, async () => {
33047
- const queueDir = path18__default.join(paths.queueDir, id);
33820
+ const queueDir = path19__default.join(paths.queueDir, id);
33048
33821
  if (expectedPatchHash !== void 0) {
33049
- const currentMarkdown = await readPatchFile(path18__default.join(queueDir, PATCH_FILENAME));
33822
+ const currentMarkdown = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
33050
33823
  const currentHash = computeContentHash(currentMarkdown);
33051
33824
  if (currentHash !== expectedPatchHash) {
33052
33825
  throw new Error(`[fleet-wiki] wiki_patch_edit stale base_patch_hash: expected ${currentHash}, got ${expectedPatchHash}`);
@@ -33055,8 +33828,8 @@ async function rewriteQueuedPatch(id, paths, patch, meta3, expectedPatchHash) {
33055
33828
  const patchMarkdown = serializePatch(patch);
33056
33829
  const patchHash = computeContentHash(patchMarkdown);
33057
33830
  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);
33831
+ await writePatchFile(path19__default.join(queueDir, PATCH_FILENAME), patchMarkdown, paths);
33832
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), nextMeta, paths);
33060
33833
  return patchHash;
33061
33834
  });
33062
33835
  }
@@ -33080,8 +33853,8 @@ async function approvePatch(id, paths) {
33080
33853
  rawSourceRef: meta3.rawSourceRef,
33081
33854
  warnings: meta3.warnings
33082
33855
  });
33083
- const queueDir = path18__default.join(paths.queueDir, id);
33084
- await writeJsonFile(path18__default.join(queueDir, PATCH_META_FILENAME), {
33856
+ const queueDir = path19__default.join(paths.queueDir, id);
33857
+ await writeJsonFile(path19__default.join(queueDir, PATCH_META_FILENAME), {
33085
33858
  ...meta3,
33086
33859
  conflictId
33087
33860
  }, paths);
@@ -33117,7 +33890,7 @@ async function approvePatchSet(patchSetId, paths) {
33117
33890
  const failed = [];
33118
33891
  const missing = [];
33119
33892
  for (const patchId of patchSet.patchIds) {
33120
- const queueDir = path18__default.join(paths.queueDir, patchId);
33893
+ const queueDir = path19__default.join(paths.queueDir, patchId);
33121
33894
  if (!await pathExists(queueDir)) {
33122
33895
  missing.push(patchId);
33123
33896
  continue;
@@ -33183,7 +33956,7 @@ ${patch.body}`;
33183
33956
  }
33184
33957
  async function normalizeWikiEntryPatch(entry, target2, paths) {
33185
33958
  assertSafeEntryId(entry.id);
33186
- if (entry.id !== path18__default.basename(target2, ".md")) {
33959
+ if (entry.id !== path19__default.basename(target2, ".md")) {
33187
33960
  throw new Error("wiki patch body id must match target filename");
33188
33961
  }
33189
33962
  const inlineRawSourceRef = extractInlineRawSourceRef(entry.body);
@@ -33226,9 +33999,9 @@ function buildPatchId(createdAt, summary, target2, body) {
33226
33999
  }
33227
34000
  async function validatePatchBase(patch, meta3, paths) {
33228
34001
  if (patch.frontmatter.op !== "update_wiki" || !meta3?.baseVersion && !meta3?.baseHash) return;
33229
- const wikiId = path18__default.basename(patch.frontmatter.target, ".md");
34002
+ const wikiId = path19__default.basename(patch.frontmatter.target, ".md");
33230
34003
  const currentEntry = await readWikiEntry(wikiId, paths);
33231
- const currentPath = path18__default.join(paths.root, patch.frontmatter.target);
34004
+ const currentPath = path19__default.join(paths.root, patch.frontmatter.target);
33232
34005
  const currentMarkdown = await pathExists(currentPath) ? await readPatchFile(currentPath) : void 0;
33233
34006
  if (meta3.baseVersion !== void 0 && currentEntry?.version !== meta3.baseVersion) {
33234
34007
  throw new Error(
@@ -33287,17 +34060,17 @@ function assertCanonicalPatchTarget(target2) {
33287
34060
  if (target2.endsWith("/")) {
33288
34061
  throw new Error("patch target must not end with a slash");
33289
34062
  }
33290
- if (target2.startsWith("/") || path18__default.posix.isAbsolute(target2) || path18__default.win32.isAbsolute(target2)) {
34063
+ if (target2.startsWith("/") || path19__default.posix.isAbsolute(target2) || path19__default.win32.isAbsolute(target2)) {
33291
34064
  throw new Error("patch target must be relative");
33292
34065
  }
33293
- if (path18__default.posix.normalize(target2) !== target2) {
34066
+ if (path19__default.posix.normalize(target2) !== target2) {
33294
34067
  throw new Error("patch target must not contain dot segments or redundant separators");
33295
34068
  }
33296
34069
  }
33297
34070
  function canonicalApprovalLockKey(paths, target2) {
33298
34071
  const wikiRoot = realpathSync(paths.wikiDir);
33299
- const relativeTarget = path18__default.posix.relative("wiki", target2);
33300
- const targetPath = path18__default.join(wikiRoot, ...relativeTarget.split("/"));
34072
+ const relativeTarget = path19__default.posix.relative("wiki", target2);
34073
+ const targetPath = path19__default.join(wikiRoot, ...relativeTarget.split("/"));
33301
34074
  return `${wikiRoot}\0${targetPath}`.toLowerCase();
33302
34075
  }
33303
34076
  function canonicalPatchEditLockKey(paths, patchId) {
@@ -33313,7 +34086,7 @@ function assertNoSymlinkPathComponents(target2, paths) {
33313
34086
  throw error51;
33314
34087
  }
33315
34088
  for (const part of parts) {
33316
- current = path18__default.join(current, part);
34089
+ current = path19__default.join(current, part);
33317
34090
  try {
33318
34091
  if (lstatSync(current).isSymbolicLink()) {
33319
34092
  throw new Error("patch target must not include symlink path components");
@@ -33328,8 +34101,8 @@ function assertSafeRawSourceRef(rawSourceRef, paths) {
33328
34101
  if (!rawSourceRef.startsWith("raw/")) {
33329
34102
  throw new Error("raw source provenance must point into raw/");
33330
34103
  }
33331
- const absoluteRef = path18__default.resolve(paths.root, rawSourceRef);
33332
- if (!absoluteRef.startsWith(`${paths.rawDir}${path18__default.sep}`)) {
34104
+ const absoluteRef = path19__default.resolve(paths.root, rawSourceRef);
34105
+ if (!absoluteRef.startsWith(`${paths.rawDir}${path19__default.sep}`)) {
33333
34106
  throw new Error("raw source provenance must point into raw/");
33334
34107
  }
33335
34108
  }
@@ -33345,14 +34118,14 @@ function classifyPatchConflict(error51) {
33345
34118
  }
33346
34119
  async function recordPatchConflict(patch, paths, reason, options) {
33347
34120
  const now = /* @__PURE__ */ new Date();
33348
- const targetPath = path18__default.join(paths.root, patch.frontmatter.target);
34121
+ const targetPath = path19__default.join(paths.root, patch.frontmatter.target);
33349
34122
  const current = await pathExists(targetPath) ? await readPatchFile(targetPath) : void 0;
33350
34123
  const currentEntry = current ? parseStoredWikiEntry(current) : void 0;
33351
34124
  const proposedEntry = parsePatchBodyEntry(patch.body);
33352
- const record6 = await createConflict({
34125
+ const record7 = await createConflict({
33353
34126
  reason,
33354
34127
  target: patch.frontmatter.target,
33355
- wikiId: proposedEntry?.id ?? path18__default.basename(patch.frontmatter.target, ".md"),
34128
+ wikiId: proposedEntry?.id ?? path19__default.basename(patch.frontmatter.target, ".md"),
33356
34129
  title: proposedEntry?.title,
33357
34130
  proposer: patch.frontmatter.proposer,
33358
34131
  rawSourceRef: options?.rawSourceRef,
@@ -33368,14 +34141,14 @@ async function recordPatchConflict(patch, paths, reason, options) {
33368
34141
  now
33369
34142
  }, paths);
33370
34143
  await appendLog(paths, "conflict detected", {
33371
- conflict_id: record6.meta.id,
34144
+ conflict_id: record7.meta.id,
33372
34145
  patch_id: options?.patchId ?? null,
33373
34146
  raw_source_ref: options?.rawSourceRef ?? null,
33374
34147
  reason,
33375
34148
  target: patch.frontmatter.target,
33376
- wiki_id: record6.meta.wikiId
34149
+ wiki_id: record7.meta.wikiId
33377
34150
  }, now);
33378
- return record6.meta.id;
34151
+ return record7.meta.id;
33379
34152
  }
33380
34153
  function parsePatchBodyEntry(content) {
33381
34154
  try {
@@ -33464,11 +34237,11 @@ function parseInlineArray(value) {
33464
34237
  return inner.split(",").map((item) => decodeFrontmatter(item.trim().replace(/^"(.*)"$/, "$1")));
33465
34238
  }
33466
34239
  async function archiveQueueEntry(id, paths, meta3) {
33467
- const fromDir = path18__default.join(paths.queueDir, id);
33468
- const toDir = path18__default.join(paths.archiveDir, id);
34240
+ const fromDir = path19__default.join(paths.queueDir, id);
34241
+ const toDir = path19__default.join(paths.archiveDir, id);
33469
34242
  await removePath(toDir);
33470
34243
  await movePath(fromDir, toDir);
33471
- await writeJsonFile(path18__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
34244
+ await writeJsonFile(path19__default.join(toDir, PATCH_META_FILENAME), meta3, paths);
33472
34245
  }
33473
34246
  function buildQueueIdHelp(prefix, availableIds) {
33474
34247
  if (availableIds.length === 0) {
@@ -33500,15 +34273,15 @@ var PATCH_SET_DIRNAME = "_sets";
33500
34273
  var PATCH_SET_META_FILENAME = PATCH_META_FILENAME;
33501
34274
  function getPatchSetDir(paths, patchSetId) {
33502
34275
  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)) {
34276
+ const patchSetDir = path19__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId);
34277
+ const relative = path19__default.relative(path19__default.join(paths.queueDir, PATCH_SET_DIRNAME), patchSetDir);
34278
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
33506
34279
  throw new Error(`[fleet-wiki] patch set id escapes queue/_sets: ${patchSetId}`);
33507
34280
  }
33508
34281
  return patchSetDir;
33509
34282
  }
33510
34283
  function getPatchSetMetaFile(paths, patchSetId) {
33511
- return path18__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
34284
+ return path19__default.join(getPatchSetDir(paths, patchSetId), PATCH_SET_META_FILENAME);
33512
34285
  }
33513
34286
  function buildPatchSetId(createdAt, sourceRef) {
33514
34287
  const compact = createdAt.replace(/[:.]/g, "-");
@@ -33567,36 +34340,36 @@ async function readWikiEntry(id, paths) {
33567
34340
  const index = await loadIndex(paths);
33568
34341
  const indexed = index[id];
33569
34342
  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;
34343
+ const resolved = path19__default.resolve(paths.root, indexed.path);
34344
+ const rel = path19__default.relative(paths.wikiDir, resolved);
34345
+ if (!rel || rel.startsWith("..") || path19__default.isAbsolute(rel)) return null;
33573
34346
  return readMarkdownFile(resolved);
33574
34347
  }
33575
- const fallbackPath = path18__default.join(paths.wikiDir, `${id}.md`);
34348
+ const fallbackPath = path19__default.join(paths.wikiDir, `${id}.md`);
33576
34349
  if (await pathExists(fallbackPath)) {
33577
34350
  return readMarkdownFile(fallbackPath);
33578
34351
  }
33579
34352
  const records = await listWikiRecords(paths);
33580
- const match = records.find((record6) => record6.entry.id === id);
34353
+ const match = records.find((record7) => record7.entry.id === id);
33581
34354
  return match ? match.entry : null;
33582
34355
  }
33583
34356
  async function writeWikiEntryAtTarget(entry, target2, paths) {
33584
34357
  await ensureMemoryRoot(paths);
33585
34358
  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)) {
34359
+ const absoluteTarget = path19__default.resolve(paths.root, target2);
34360
+ const relativeTarget = path19__default.relative(paths.wikiDir, absoluteTarget);
34361
+ if (!relativeTarget || relativeTarget.startsWith("..") || path19__default.isAbsolute(relativeTarget)) {
33589
34362
  throw new Error(`[fleet-wiki] wiki target escapes wiki/: ${target2}`);
33590
34363
  }
33591
34364
  if (!absoluteTarget.endsWith(".md")) {
33592
34365
  throw new Error(`[fleet-wiki] wiki target must end with .md: ${target2}`);
33593
34366
  }
33594
- if (path18__default.basename(absoluteTarget, ".md") !== entry.id) {
34367
+ if (path19__default.basename(absoluteTarget, ".md") !== entry.id) {
33595
34368
  throw new Error("wiki patch body id must match target filename");
33596
34369
  }
33597
- await mkdir(path18__default.dirname(absoluteTarget), { recursive: true });
34370
+ await mkdir(path19__default.dirname(absoluteTarget), { recursive: true });
33598
34371
  await writeAtomic(absoluteTarget, serializeWikiEntry(entry), paths);
33599
- return path18__default.join("wiki", relativeTarget).replaceAll(path18__default.sep, "/");
34372
+ return path19__default.join("wiki", relativeTarget).replaceAll(path19__default.sep, "/");
33600
34373
  }
33601
34374
  async function writeRawSourceEntry(entry, paths) {
33602
34375
  await ensureMemoryRoot(paths);
@@ -33615,11 +34388,11 @@ async function writeRawSourceEntry(entry, paths) {
33615
34388
  },
33616
34389
  entry.content
33617
34390
  );
33618
- await writeAtomic(path18__default.join(paths.root, relativePath), content, paths);
34391
+ await writeAtomic(path19__default.join(paths.root, relativePath), content, paths);
33619
34392
  return relativePath;
33620
34393
  }
33621
34394
  async function readRawSourceEntry(rawSourceRef, paths) {
33622
- const absolutePath = path18__default.resolve(paths.root, rawSourceRef);
34395
+ const absolutePath = path19__default.resolve(paths.root, rawSourceRef);
33623
34396
  assertWithinRawDir(absolutePath, paths);
33624
34397
  const parsed = parseMarkdown(await readFile(absolutePath, "utf8"));
33625
34398
  return {
@@ -33810,8 +34583,8 @@ function computeContentHash(content) {
33810
34583
  return crypto5.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 8);
33811
34584
  }
33812
34585
  function assertWithinRawDir(absolutePath, paths) {
33813
- const relative = path18__default.relative(paths.rawDir, absolutePath);
33814
- if (!relative || relative.startsWith("..") || path18__default.isAbsolute(relative)) {
34586
+ const relative = path19__default.relative(paths.rawDir, absolutePath);
34587
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
33815
34588
  throw new Error(`[fleet-wiki] raw source ref escapes raw/: ${absolutePath}`);
33816
34589
  }
33817
34590
  }
@@ -33867,7 +34640,7 @@ function parseWikiEntry(content) {
33867
34640
  async function listWikiRecords(paths) {
33868
34641
  return listMarkdownEntriesRecursive(paths.wikiDir, paths, (content, filePath) => ({
33869
34642
  entry: parseWikiEntry(content),
33870
- path: path18__default.relative(paths.root, filePath).replaceAll(path18__default.sep, "/")
34643
+ path: path19__default.relative(paths.root, filePath).replaceAll(path19__default.sep, "/")
33871
34644
  }));
33872
34645
  }
33873
34646
  async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
@@ -33880,7 +34653,7 @@ async function listMarkdownEntriesRecursive(dirPath, paths, parser) {
33880
34653
  }
33881
34654
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
33882
34655
  for (const entry of sortedEntries) {
33883
- const filePath = path18__default.join(dirPath, entry.name);
34656
+ const filePath = path19__default.join(dirPath, entry.name);
33884
34657
  if (entry.isDirectory()) {
33885
34658
  items.push(...await listMarkdownEntriesRecursive(filePath, paths, parser));
33886
34659
  continue;
@@ -34015,8 +34788,8 @@ async function writeJsonAtomic(filePath, value, paths) {
34015
34788
  }
34016
34789
  async function writeAtomic(filePath, content, paths) {
34017
34790
  await ensureMemoryRoot(paths);
34018
- const tempPath = path18__default.join(
34019
- path18__default.dirname(filePath),
34791
+ const tempPath = path19__default.join(
34792
+ path19__default.dirname(filePath),
34020
34793
  `.tmp-${process.pid}-${Date.now()}-${crypto5.randomUUID()}-${os3__default.hostname()}`
34021
34794
  );
34022
34795
  await writeFile(tempPath, content, "utf8");
@@ -34097,7 +34870,7 @@ function extractLegacyMarkdownWikiLinks(body, wikiDir, basePath) {
34097
34870
  }
34098
34871
  function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
34099
34872
  if (!target2 || target2.startsWith("#")) return null;
34100
- if (path18__default.isAbsolute(target2)) return null;
34873
+ if (path19__default.isAbsolute(target2)) return null;
34101
34874
  if (/^[a-z][a-z0-9+.-]*:/i.test(target2)) return null;
34102
34875
  const withoutFragment = target2.split("#", 1)[0]?.split("?", 1)[0] ?? "";
34103
34876
  if (!withoutFragment.endsWith(".md")) return null;
@@ -34107,12 +34880,12 @@ function resolveLegacyWikiTarget(target2, wikiDir, basePath) {
34107
34880
  } catch {
34108
34881
  return null;
34109
34882
  }
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;
34883
+ const resolved = path19__default.resolve(path19__default.dirname(basePath), decodedTarget);
34884
+ const relative = path19__default.relative(wikiDir, resolved);
34885
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) return null;
34113
34886
  return {
34114
34887
  target: target2,
34115
- entryId: path18__default.basename(relative, ".md")
34888
+ entryId: path19__default.basename(relative, ".md")
34116
34889
  };
34117
34890
  }
34118
34891
  var FLEET_WIKI_ENTRY_BEGIN = "<<<FLEET_WIKI_ENTRY_BEGIN";
@@ -34179,7 +34952,7 @@ async function enhancedSearch(paths, options) {
34179
34952
  for (const entry of entries) {
34180
34953
  if (!index[entry.id]) {
34181
34954
  index[entry.id] = {
34182
- path: path18__default.join("wiki", `${entry.id}.md`),
34955
+ path: path19__default.join("wiki", `${entry.id}.md`),
34183
34956
  title: entry.title,
34184
34957
  tags: entry.tags,
34185
34958
  updated: entry.updated
@@ -34315,7 +35088,7 @@ function toEnhancedHit(entry, signals) {
34315
35088
  score: enhancedScore,
34316
35089
  reason: signals.legacyReason ?? "body",
34317
35090
  excerpt,
34318
- path: path18__default.join("wiki", `${entry.id}.md`),
35091
+ path: path19__default.join("wiki", `${entry.id}.md`),
34319
35092
  tags: entry.tags,
34320
35093
  updated: entry.updated,
34321
35094
  version: entry.version,
@@ -34511,7 +35284,7 @@ function toRankedHit(entry, reason, detail, graphBoost, backlinksById) {
34511
35284
  score: basePriority * 100 + statusPriority * 10 + graphScore + (detail.tagBoost ?? 0),
34512
35285
  reason,
34513
35286
  excerpt,
34514
- path: path18__default.join("wiki", `${entry.id}.md`),
35287
+ path: path19__default.join("wiki", `${entry.id}.md`),
34515
35288
  tags: entry.tags,
34516
35289
  updated: entry.updated,
34517
35290
  version: entry.version,
@@ -36053,8 +36826,8 @@ function CreateObject(types, value) {
36053
36826
  }
36054
36827
  function FromUnionKey(types, value) {
36055
36828
  const flattened = Flatten(types);
36056
- const record6 = TryBuildRecord(flattened, value);
36057
- return IsSchema(record6) ? record6 : CreateObject(flattened, value);
36829
+ const record7 = TryBuildRecord(flattened, value);
36830
+ return IsSchema(record7) ? record7 : CreateObject(flattened, value);
36058
36831
  }
36059
36832
 
36060
36833
  // ../../node_modules/.pnpm/typebox@1.1.34/node_modules/typebox/build/type/engine/record/from_key.mjs
@@ -39277,13 +40050,13 @@ async function readClaims(entryId, paths) {
39277
40050
  }
39278
40051
  }
39279
40052
  function getClaimsDir(paths) {
39280
- return path18__default.join(paths.wikiDir, CLAIMS_DIRNAME);
40053
+ return path19__default.join(paths.wikiDir, CLAIMS_DIRNAME);
39281
40054
  }
39282
40055
  function getClaimsFile(paths, entryId) {
39283
40056
  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)) {
40057
+ const claimsFile = path19__default.join(getClaimsDir(paths), `${entryId}.json`);
40058
+ const relative = path19__default.relative(getClaimsDir(paths), claimsFile);
40059
+ if (!relative || relative.startsWith("..") || path19__default.isAbsolute(relative)) {
39287
40060
  throw new Error(`[fleet-wiki] claims sidecar escapes wiki/.claims: ${entryId}`);
39288
40061
  }
39289
40062
  return claimsFile;
@@ -39374,7 +40147,7 @@ function assertSafeClaimRawRef(ref) {
39374
40147
  if (!ref.startsWith("raw/")) {
39375
40148
  throw new Error(`claim sourceRef must point into raw/: ${ref}`);
39376
40149
  }
39377
- if (ref.includes("..") || path18__default.isAbsolute(ref)) {
40150
+ if (ref.includes("..") || path19__default.isAbsolute(ref)) {
39378
40151
  throw new Error(`claim sourceRef escapes raw/: ${ref}`);
39379
40152
  }
39380
40153
  }
@@ -39452,22 +40225,22 @@ async function runDryDock(paths, options = {}) {
39452
40225
  }
39453
40226
  for (const fileName of await listFileNames(paths.rawDir)) {
39454
40227
  if (!fileName.endsWith(".md")) continue;
39455
- const filePath = path18__default.join(paths.rawDir, fileName);
40228
+ const filePath = path19__default.join(paths.rawDir, fileName);
39456
40229
  issues.push(...safetyIssues(await readPatchFile(filePath), filePath));
39457
40230
  }
39458
40231
  for (const queueId of await listDirectoryNames(paths.queueDir)) {
39459
40232
  if (queueId === PATCH_SET_DIRNAME) continue;
39460
- const queueDir = path18__default.join(paths.queueDir, queueId);
40233
+ const queueDir = path19__default.join(paths.queueDir, queueId);
39461
40234
  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));
40235
+ const patchContent = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
40236
+ issues.push(...safetyIssues(patchContent, path19__default.join(queueDir, PATCH_FILENAME)));
40237
+ await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME));
39465
40238
  } catch {
39466
40239
  issues.push(issue2("malformed_queue", "error", "\uC190\uC0C1\uB41C queue \uC5D4\uD2B8\uB9AC", queueDir));
39467
40240
  }
39468
40241
  }
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);
40242
+ for (const patchSetId of await listDirectoryNames(path19__default.join(paths.queueDir, PATCH_SET_DIRNAME))) {
40243
+ const patchSetMetaFile = path19__default.join(paths.queueDir, PATCH_SET_DIRNAME, patchSetId, PATCH_META_FILENAME);
39471
40244
  let patchSet;
39472
40245
  try {
39473
40246
  patchSet = await readPatchSet(paths, patchSetId);
@@ -39476,8 +40249,8 @@ async function runDryDock(paths, options = {}) {
39476
40249
  continue;
39477
40250
  }
39478
40251
  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);
40252
+ const queueMetaFile = path19__default.join(paths.queueDir, patchId, PATCH_META_FILENAME);
40253
+ const archiveMetaFile = path19__default.join(paths.archiveDir, patchId, PATCH_META_FILENAME);
39481
40254
  if (!await pathExists(queueMetaFile) && !await pathExists(archiveMetaFile)) {
39482
40255
  issues.push(
39483
40256
  issue2(
@@ -39514,7 +40287,7 @@ async function runDryDock(paths, options = {}) {
39514
40287
  "conflict_unresolved",
39515
40288
  "warning",
39516
40289
  `\uBBF8\uD574\uACB0 conflict: ${conflict.reason} (${conflict.target})`,
39517
- path18__default.join(paths.conflictsDir, conflict.id, "meta.json")
40290
+ path19__default.join(paths.conflictsDir, conflict.id, "meta.json")
39518
40291
  )
39519
40292
  );
39520
40293
  }
@@ -39527,7 +40300,7 @@ async function runDryDock(paths, options = {}) {
39527
40300
  "unresolved_conflict",
39528
40301
  "warning",
39529
40302
  "\uC190\uC0C1\uB41C conflict \uC5D4\uD2B8\uB9AC",
39530
- path18__default.join(paths.conflictsDir, conflictId, "meta.json")
40303
+ path19__default.join(paths.conflictsDir, conflictId, "meta.json")
39531
40304
  )
39532
40305
  );
39533
40306
  }
@@ -39584,8 +40357,8 @@ async function claimIssues(paths, wikiIds) {
39584
40357
  const claimsDir = getClaimsDir(paths);
39585
40358
  for (const fileName of await listFileNames(claimsDir)) {
39586
40359
  if (!fileName.endsWith(".json")) continue;
39587
- const filePath = path18__default.join(claimsDir, fileName);
39588
- const entryIdFromFile = path18__default.basename(fileName, ".json");
40360
+ const filePath = path19__default.join(claimsDir, fileName);
40361
+ const entryIdFromFile = path19__default.basename(fileName, ".json");
39589
40362
  let raw;
39590
40363
  try {
39591
40364
  raw = await readJsonFile2(filePath);
@@ -39664,7 +40437,7 @@ function toSemanticEntry(filePath, frontmatter, body) {
39664
40437
  async function schemaIssues(paths) {
39665
40438
  const issues = [];
39666
40439
  const schema = await readWorkspaceSchemaSummary(paths);
39667
- const agentsPath = path18__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
40440
+ const agentsPath = path19__default.join(paths.schemaDir, WORKSPACE_SCHEMA_AGENTS_FILENAME);
39668
40441
  if (!await pathExists(schema.wikiSchemaPath)) {
39669
40442
  issues.push(issue2("schema_missing", "warning", `Workspace schema file is missing: schema/${WORKSPACE_SCHEMA_FILENAME}`, schema.wikiSchemaPath));
39670
40443
  } else {
@@ -40051,7 +40824,7 @@ async function listWikiMarkdownFiles(dirPath) {
40051
40824
  const files = [];
40052
40825
  const sortedEntries = entries.sort((left, right) => left.name.localeCompare(right.name));
40053
40826
  for (const entry of sortedEntries) {
40054
- const filePath = path18__default.join(dirPath, entry.name);
40827
+ const filePath = path19__default.join(dirPath, entry.name);
40055
40828
  if (entry.isDirectory()) {
40056
40829
  files.push(...await listWikiMarkdownFiles(filePath));
40057
40830
  continue;
@@ -40275,7 +41048,7 @@ async function resolveCompileSource(input, paths, now) {
40275
41048
  }
40276
41049
  async function buildCompileProposals(input, paths, now, resolvedSource) {
40277
41050
  const sourceTarget = `wiki/sources/${resolvedSource.sourcePageId}.md`;
40278
- const sourceExists = await pathExists(path18__default.join(paths.root, sourceTarget));
41051
+ const sourceExists = await pathExists(path19__default.join(paths.root, sourceTarget));
40279
41052
  const existingEntries = await listWiki(paths);
40280
41053
  const sourcePageTitle = resolvedSource.sourceTitle?.trim() || `Source ${resolvedSource.sourcePageId}`;
40281
41054
  const existingSourceEntry = existingEntries.find((entry) => entry.id === resolvedSource.sourcePageId);
@@ -40297,7 +41070,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
40297
41070
  target: sourceTarget,
40298
41071
  summary: truncateSummary(`Compile source page ${sourcePageTitle}`),
40299
41072
  entry: sourceEntry,
40300
- baseHash: sourceExists ? computeContentHash(await readPatchFile(path18__default.join(paths.root, sourceTarget))) : void 0,
41073
+ baseHash: sourceExists ? computeContentHash(await readPatchFile(path19__default.join(paths.root, sourceTarget))) : void 0,
40301
41074
  baseVersion: existingSourceEntry?.version
40302
41075
  }];
40303
41076
  const relatedCandidates = await discoverRelatedEntryCandidates(paths, resolvedSource.sourceContent, resolvedSource.sourceTitle);
@@ -40317,7 +41090,7 @@ async function buildCompileProposals(input, paths, now, resolvedSource) {
40317
41090
  rawSourceRefs: mergeRawSourceRefs(existing.rawSourceRefs, existing.rawSourceRef, { ref: resolvedSource.rawSourceRef }),
40318
41091
  body: appendSourceCompileNote(existing.body, resolvedSource.sourcePageId, resolvedSource.rawSourceRef)
40319
41092
  },
40320
- baseHash: computeContentHash(await readPatchFile(path18__default.join(paths.wikiDir, `${existing.id}.md`))),
41093
+ baseHash: computeContentHash(await readPatchFile(path19__default.join(paths.wikiDir, `${existing.id}.md`))),
40321
41094
  baseVersion: existing.version
40322
41095
  });
40323
41096
  }
@@ -40491,7 +41264,7 @@ async function planIngest(input, paths, now) {
40491
41264
  const target2 = `wiki/${input.id}.md`;
40492
41265
  const proposer = input.proposer ?? "tool:wiki_ingest";
40493
41266
  const currentEntry = await readWikiEntry(input.id, paths);
40494
- const currentMarkdown = currentEntry ? await readPatchFile(path18__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
41267
+ const currentMarkdown = currentEntry ? await readPatchFile(path19__default.join(paths.wikiDir, `${input.id}.md`)) : void 0;
40495
41268
  const currentHash = currentMarkdown ? computeContentHash(currentMarkdown) : void 0;
40496
41269
  const rawSource = buildRawSourceEntry(input, now);
40497
41270
  await ensureWorkspaceSchema(paths);
@@ -40686,7 +41459,7 @@ async function stageIngestPlan(plan, paths) {
40686
41459
  })
40687
41460
  };
40688
41461
  if (plan.kind === "conflict") {
40689
- const record6 = await createConflict({
41462
+ const record7 = await createConflict({
40690
41463
  reason: plan.conflict.reason,
40691
41464
  target: `wiki/${entry.id}.md`,
40692
41465
  wikiId: entry.id,
@@ -40704,17 +41477,17 @@ async function stageIngestPlan(plan, paths) {
40704
41477
  warnings: plan.warnings
40705
41478
  }, paths);
40706
41479
  await appendLog(paths, "conflict detected", {
40707
- conflict_id: record6.meta.id,
41480
+ conflict_id: record7.meta.id,
40708
41481
  patch_id: null,
40709
41482
  raw_source_ref: rawSourceRef,
40710
41483
  reason: plan.conflict.reason,
40711
- target: record6.meta.target,
40712
- wiki_id: record6.meta.wikiId
41484
+ target: record7.meta.target,
41485
+ wiki_id: record7.meta.wikiId
40713
41486
  });
40714
41487
  return {
40715
41488
  ok: false,
40716
41489
  mode: plan.mode,
40717
- conflict_id: record6.meta.id,
41490
+ conflict_id: record7.meta.id,
40718
41491
  raw_source_ref: rawSourceRef,
40719
41492
  warnings: plan.warnings
40720
41493
  };
@@ -41170,11 +41943,11 @@ async function editQueuedPatch(input, paths) {
41170
41943
  };
41171
41944
  }
41172
41945
  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));
41946
+ const queueDir = path19__default.join(paths.queueDir, patchId);
41947
+ const markdown = await readPatchFile(path19__default.join(queueDir, PATCH_FILENAME));
41175
41948
  return {
41176
41949
  patch: await parsePatch(markdown),
41177
- meta: await readJsonFile2(path18__default.join(queueDir, PATCH_META_FILENAME)),
41950
+ meta: await readJsonFile2(path19__default.join(queueDir, PATCH_META_FILENAME)),
41178
41951
  patchHash: computeContentHash(markdown)
41179
41952
  };
41180
41953
  }
@@ -41260,11 +42033,11 @@ function applyBodyReplacement(entry, replaceInput) {
41260
42033
  }
41261
42034
  function parseBodyReplace(value) {
41262
42035
  if (value === void 0 || value === null) return void 0;
41263
- const record6 = value;
42036
+ const record7 = value;
41264
42037
  return {
41265
- find: String(record6.find ?? ""),
41266
- replace: String(record6.replace ?? ""),
41267
- expected_occurrences: typeof record6.expected_occurrences === "number" ? record6.expected_occurrences : void 0
42038
+ find: String(record7.find ?? ""),
42039
+ replace: String(record7.replace ?? ""),
42040
+ expected_occurrences: typeof record7.expected_occurrences === "number" ? record7.expected_occurrences : void 0
41268
42041
  };
41269
42042
  }
41270
42043
  function stringParam(value) {
@@ -41936,7 +42709,7 @@ ${input.answer ?? ""}`)}`;
41936
42709
  assertSafeEntryId(targetId);
41937
42710
  const subdir = input.targetType === "synthesis" ? "synthesis" : "queries";
41938
42711
  const target2 = `wiki/${subdir}/${targetId}.md`;
41939
- const absoluteTarget = path18__default.join(paths.root, target2);
42712
+ const absoluteTarget = path19__default.join(paths.root, target2);
41940
42713
  const exists = await pathExists(absoluteTarget);
41941
42714
  const existingEntry = exists ? await readWikiEntry(targetId, paths) : null;
41942
42715
  if (exists && !existingEntry) {
@@ -42018,7 +42791,7 @@ function assertSafeRawRef(rawRef) {
42018
42791
  if (!rawRef.startsWith("raw/")) {
42019
42792
  throw new Error(`[fleet-wiki] wiki_query raw source ref must point into raw/: ${rawRef}`);
42020
42793
  }
42021
- if (rawRef.includes("..") || path18__default.isAbsolute(rawRef)) {
42794
+ if (rawRef.includes("..") || path19__default.isAbsolute(rawRef)) {
42022
42795
  throw new Error(`[fleet-wiki] wiki_query raw source ref escapes raw/: ${rawRef}`);
42023
42796
  }
42024
42797
  }
@@ -42587,15 +43360,15 @@ function buildWikiResolveSpec(resolver) {
42587
43360
  ]
42588
43361
  }, resolver);
42589
43362
  }
42590
- function buildWikiToolSpec(config2, usage3, resolver) {
43363
+ function buildWikiToolSpec(config2, usage4, resolver) {
42591
43364
  return {
42592
43365
  id: config2.name,
42593
43366
  tag: config2.name,
42594
43367
  title: config2.label,
42595
43368
  description: config2.description,
42596
43369
  promptSnippet: config2.promptSnippet,
42597
- whenToUse: usage3.whenToUse,
42598
- whenNotToUse: usage3.whenNotToUse,
43370
+ whenToUse: usage4.whenToUse,
43371
+ whenNotToUse: usage4.whenNotToUse,
42599
43372
  usageGuidelines: config2.promptGuidelines,
42600
43373
  parameters: config2.parameters,
42601
43374
  execute: async (args, ctx) => {
@@ -42624,16 +43397,16 @@ function createResolver(deps, hooks) {
42624
43397
  } };
42625
43398
  }
42626
43399
  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);
43400
+ const destination = path19__default.join(workspace.path, "knowledge");
43401
+ const source = path19__default.join(workspace.cwd, ".fleet", "knowledge");
43402
+ const markerPath = path19__default.join(workspace.path, MARKER_NAME);
42630
43403
  const destinationState = inspectTree(destination, true);
42631
43404
  if (destinationState === "content") return createMemoryPaths(destination);
42632
43405
  if (destinationState === "unsafe") throw new Error("Unsafe Fleet Wiki destination state");
42633
43406
  const marker = readMarker(markerPath);
42634
43407
  const stagingEntries = inspectReservedControlState(workspace.path);
42635
43408
  if (marker) {
42636
- const staging2 = path18__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
43409
+ const staging2 = path19__default.join(workspace.path, `${STAGING_PREFIX}${marker.transactionId}`);
42637
43410
  const stagingState = inspectTree(staging2);
42638
43411
  if (stagingState === "content") {
42639
43412
  removeEmptyDirectories(destination);
@@ -42648,7 +43421,7 @@ function resolveLocked(workspace, hooks) {
42648
43421
  if (sourceState !== "content") return createMemoryPaths(destination);
42649
43422
  removeEmptyDirectories(destination);
42650
43423
  const transactionId = randomUUID();
42651
- const staging = path18__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
43424
+ const staging = path19__default.join(workspace.path, `${STAGING_PREFIX}${transactionId}`);
42652
43425
  copyTree(source, staging, hooks);
42653
43426
  if (inspectTree(staging) !== "content") throw new Error("Invalid Fleet Wiki migration staging result");
42654
43427
  syncDirectory(staging);
@@ -42676,7 +43449,7 @@ function inspectTree(target2, regularRootIsContent = false, treeRoot = target2)
42676
43449
  if (nodeKind === "file") return regularRootIsContent ? "content" : "unsafe";
42677
43450
  let content = false;
42678
43451
  for (const entry of fs9.readdirSync(target2, { withFileTypes: true })) {
42679
- const entryPath = path18__default.join(target2, entry.name);
43452
+ const entryPath = path19__default.join(target2, entry.name);
42680
43453
  if (entry.isSymbolicLink()) {
42681
43454
  if (readSafeFileSymlink(treeRoot, entryPath) === null) return "unsafe";
42682
43455
  content = true;
@@ -42708,15 +43481,15 @@ function readMarker(markerPath) {
42708
43481
  throw new Error("Invalid Fleet Wiki migration marker");
42709
43482
  }
42710
43483
  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;
43484
+ const record7 = value;
43485
+ 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");
43486
+ return record7;
42714
43487
  }
42715
43488
  function copyTree(source, destination, hooks, sourceRoot = source) {
42716
43489
  fs9.mkdirSync(destination, { recursive: true });
42717
43490
  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);
43491
+ const from = path19__default.join(source, entry.name);
43492
+ const to = path19__default.join(destination, entry.name);
42720
43493
  const stat4 = fs9.lstatSync(from);
42721
43494
  if (stat4.isSymbolicLink()) {
42722
43495
  const target2 = readSafeFileSymlink(sourceRoot, from);
@@ -42736,9 +43509,9 @@ function copyTree(source, destination, hooks, sourceRoot = source) {
42736
43509
  }
42737
43510
  function readSafeFileSymlink(treeRoot, linkPath) {
42738
43511
  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);
43512
+ if (path19__default.posix.isAbsolute(target2) || path19__default.win32.isAbsolute(target2)) return null;
43513
+ const lexicalRoot = path19__default.resolve(treeRoot);
43514
+ const lexicalTarget = path19__default.resolve(path19__default.dirname(linkPath), target2);
42742
43515
  if (!isWithinRoot(lexicalRoot, lexicalTarget)) return null;
42743
43516
  let canonicalRoot;
42744
43517
  let canonicalTarget;
@@ -42755,8 +43528,8 @@ function readSafeFileSymlink(treeRoot, linkPath) {
42755
43528
  return target2;
42756
43529
  }
42757
43530
  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);
43531
+ const relative = path19__default.relative(root, target2);
43532
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path19__default.sep}`) && !path19__default.isAbsolute(relative);
42760
43533
  }
42761
43534
  function classifyWikiWorkspaceNodeForTest(stat4) {
42762
43535
  if (stat4.isSymbolicLink()) return "unsafe";
@@ -42771,13 +43544,13 @@ function removeEmptyDirectories(target2) {
42771
43544
  if (state === "empty") fs9.rmSync(target2, { recursive: true, force: false });
42772
43545
  }
42773
43546
  function removePriorStaging(workspacePath, stagingEntries) {
42774
- for (const name of stagingEntries) fs9.rmSync(path18__default.join(workspacePath, name), { recursive: true, force: false });
43547
+ for (const name of stagingEntries) fs9.rmSync(path19__default.join(workspacePath, name), { recursive: true, force: false });
42775
43548
  }
42776
43549
  function inspectReservedControlState(workspacePath) {
42777
43550
  const stagingEntries = [];
42778
43551
  for (const entry of fs9.readdirSync(workspacePath, { withFileTypes: true })) {
42779
43552
  if (entry.name.startsWith(`${MARKER_NAME}.`)) {
42780
- const residuePath = path18__default.join(workspacePath, entry.name);
43553
+ const residuePath = path19__default.join(workspacePath, entry.name);
42781
43554
  const residue = fs9.lstatSync(residuePath);
42782
43555
  if (MARKER_TEMP_REGEXP.test(entry.name) && residue.isFile() && !residue.isSymbolicLink()) {
42783
43556
  fs9.unlinkSync(residuePath);
@@ -42787,7 +43560,7 @@ function inspectReservedControlState(workspacePath) {
42787
43560
  }
42788
43561
  if (!entry.name.startsWith(STAGING_PREFIX)) continue;
42789
43562
  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");
43563
+ if (inspectTree(path19__default.join(workspacePath, entry.name)) === "unsafe") throw new Error("Unsafe Fleet Wiki migration staging state");
42791
43564
  stagingEntries.push(entry.name);
42792
43565
  }
42793
43566
  return stagingEntries;
@@ -42872,18 +43645,18 @@ function resolveConsolePackageRequire(currentFile, fallback) {
42872
43645
  function findConsolePackageRequire(currentFile) {
42873
43646
  const explicitRoot = process.env.FLEET_CONSOLE_PACKAGE_ROOT;
42874
43647
  if (explicitRoot) {
42875
- const explicitPackageJson = path18__default.join(explicitRoot, "package.json");
43648
+ const explicitPackageJson = path19__default.join(explicitRoot, "package.json");
42876
43649
  if (isFleetConsolePackage(explicitPackageJson)) return createRequire(explicitPackageJson);
42877
43650
  }
42878
- let dir = path18__default.dirname(currentFile);
43651
+ let dir = path19__default.dirname(currentFile);
42879
43652
  while (true) {
42880
- const packageJson = path18__default.join(dir, "package.json");
43653
+ const packageJson = path19__default.join(dir, "package.json");
42881
43654
  if (isFleetConsolePackage(packageJson)) return createRequire(packageJson);
42882
- const nestedConsolePackage = path18__default.join(dir, "runtime", "fleet-console", "package.json");
43655
+ const nestedConsolePackage = path19__default.join(dir, "runtime", "fleet-console", "package.json");
42883
43656
  if (isFleetConsolePackage(nestedConsolePackage)) return createRequire(nestedConsolePackage);
42884
- const siblingConsolePackage = path18__default.join(dir, "..", "..", "fleet-console", "package.json");
43657
+ const siblingConsolePackage = path19__default.join(dir, "..", "..", "fleet-console", "package.json");
42885
43658
  if (isFleetConsolePackage(siblingConsolePackage)) return createRequire(siblingConsolePackage);
42886
- const parent = path18__default.dirname(dir);
43659
+ const parent = path19__default.dirname(dir);
42887
43660
  if (parent === dir) return null;
42888
43661
  dir = parent;
42889
43662
  }
@@ -42950,7 +43723,7 @@ function resolveUseConptyDll(platform, env) {
42950
43723
  }
42951
43724
  function loadNodePty() {
42952
43725
  const nodePtyRequire = loadNodePtyRequire(fileURLToPath(import.meta.url));
42953
- ensureNodePtySpawnHelpersExecutable(path18__default.dirname(nodePtyRequire.resolve("node-pty/package.json")));
43726
+ ensureNodePtySpawnHelpersExecutable(path19__default.dirname(nodePtyRequire.resolve("node-pty/package.json")));
42954
43727
  return nodePtyRequire("node-pty");
42955
43728
  }
42956
43729
  function loadNodePtyRequire(currentFile) {
@@ -42959,7 +43732,7 @@ function loadNodePtyRequire(currentFile) {
42959
43732
  function ensureNodePtySpawnHelpersExecutable(packageRoot, platform = process4.platform, architecture = process4.arch) {
42960
43733
  if (platform !== "darwin") return;
42961
43734
  for (const directory of ["build/Release", "build/Debug", `prebuilds/darwin-${architecture}`]) {
42962
- const helper = path18__default.join(packageRoot, directory, "spawn-helper");
43735
+ const helper = path19__default.join(packageRoot, directory, "spawn-helper");
42963
43736
  try {
42964
43737
  const stat4 = lstatSync(helper);
42965
43738
  if (!stat4.isFile() || stat4.isSymbolicLink() || (stat4.mode & 73) === 73) continue;
@@ -43660,7 +44433,7 @@ function serializeAgentCliPathsWrite(write) {
43660
44433
  return result;
43661
44434
  }
43662
44435
  function normalizeAgentCliPaths(value) {
43663
- if (!isRecord11(value) || value.version !== 1 || !isRecord11(value.paths)) {
44436
+ if (!isRecord12(value) || value.version !== 1 || !isRecord12(value.paths)) {
43664
44437
  return { version: 1, paths: {} };
43665
44438
  }
43666
44439
  const paths = {};
@@ -43675,7 +44448,7 @@ function resolveAgentCliBinary(options) {
43675
44448
  const envName = OVERRIDE_ENV_BY_COMMAND[options.cliCommand];
43676
44449
  const envOverride = envName ? options.env[envName]?.trim() : void 0;
43677
44450
  if (envOverride) {
43678
- const searchedPathEntries2 = path18__default.isAbsolute(envOverride) ? [] : readPathEntries(options.env, platform);
44451
+ const searchedPathEntries2 = path19__default.isAbsolute(envOverride) ? [] : readPathEntries(options.env, platform);
43679
44452
  const resolved2 = resolveBinarySafely(envOverride, options.env, platform);
43680
44453
  if (!resolved2) {
43681
44454
  return { resolved: void 0, source: "env", error: "path_not_found", launchPath: envOverride, searchedPathEntries: searchedPathEntries2 };
@@ -43717,7 +44490,7 @@ function applyAgentCliPathEnvOverlay(env, cliId, userPaths) {
43717
44490
  return { ...env, [envName]: userPath };
43718
44491
  }
43719
44492
  function resolveConfiguredPath(executablePath, env, platform) {
43720
- if (executablePath.includes("\0") || executablePath.startsWith("~") || !path18__default.isAbsolute(executablePath)) {
44493
+ if (executablePath.includes("\0") || executablePath.startsWith("~") || !path19__default.isAbsolute(executablePath)) {
43721
44494
  return { resolved: void 0, error: "path_not_absolute" };
43722
44495
  }
43723
44496
  let stats;
@@ -43758,10 +44531,10 @@ function validateResolvedFile(resolved, platform) {
43758
44531
  }
43759
44532
  function readPathEntries(env, platform) {
43760
44533
  const value = platform === "win32" ? env.Path ?? env.PATH ?? "" : env.PATH ?? "";
43761
- const separator = platform === "win32" ? ";" : path18__default.delimiter;
44534
+ const separator = platform === "win32" ? ";" : path19__default.delimiter;
43762
44535
  return value.split(separator).filter((entry) => entry.length > 0);
43763
44536
  }
43764
- function isRecord11(value) {
44537
+ function isRecord12(value) {
43765
44538
  return typeof value === "object" && value !== null && !Array.isArray(value);
43766
44539
  }
43767
44540
  function isNodeError(error51) {
@@ -44153,9 +44926,9 @@ function claudeGatewayModelCache(options) {
44153
44926
 
44154
44927
  // ../../packages/core-agent/src/claude/config-dir.ts
44155
44928
  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 });
44929
+ const root = await mkdtemp(path19__default.join(tempRoot, "core-agent-claude-"));
44930
+ const cachePath = path19__default.join(root, CLAUDE_GATEWAY_MODEL_CACHE_RELPATH);
44931
+ await mkdir(path19__default.dirname(cachePath), { recursive: true, mode: 448 });
44159
44932
  let disposed = false;
44160
44933
  return {
44161
44934
  path: root,
@@ -44441,7 +45214,7 @@ function buildConsoleAutoNameHookCommand(entry) {
44441
45214
  return buildConsoleCliHookExec(entry, ["hook", "auto-name"]);
44442
45215
  }
44443
45216
  function buildConsoleCaptureHookCommand(entry, cliId, createCaptureHook = createSessionCaptureHookExec) {
44444
- const extension = path18__default.extname(entry.entryPath);
45217
+ const extension = path19__default.extname(entry.entryPath);
44445
45218
  if (JAVASCRIPT_ENTRY_EXTENSIONS.has(extension)) {
44446
45219
  return createCaptureHook({
44447
45220
  entryPath: entry.entryPath,
@@ -44467,11 +45240,11 @@ function toCaptureProvider(cliId) {
44467
45240
  }
44468
45241
  function withConsoleMarketplaceLock(target2, fn) {
44469
45242
  const lockDir = `${target2}${MARKETPLACE_LOCK_DIR_SUFFIX}`;
44470
- mkdirSync(path18__default.dirname(lockDir), { recursive: true });
45243
+ mkdirSync(path19__default.dirname(lockDir), { recursive: true });
44471
45244
  return withDirectoryLock({ lockDir }, fn);
44472
45245
  }
44473
45246
  function buildConsoleCliHookExec(entry, trailingArgs) {
44474
- const extension = path18__default.extname(entry.entryPath);
45247
+ const extension = path19__default.extname(entry.entryPath);
44475
45248
  if (JAVASCRIPT_ENTRY_EXTENSIONS.has(extension)) {
44476
45249
  return {
44477
45250
  command: entry.execPath,
@@ -44586,7 +45359,7 @@ function resolveHookEntryPath(candidate) {
44586
45359
  return CONSOLE_ENTRY_PATH;
44587
45360
  }
44588
45361
  function hasHookEntryExtension(entryPath) {
44589
- return HOOK_ENTRY_EXTENSIONS.has(path18__default.extname(entryPath));
45362
+ return HOOK_ENTRY_EXTENSIONS.has(path19__default.extname(entryPath));
44590
45363
  }
44591
45364
  async function createAgentCliLaunchSpec(options) {
44592
45365
  const cleanupStack = [];
@@ -44825,7 +45598,7 @@ function createConsoleObservabilityStore(deps = {}) {
44825
45598
  return terminalSessionsById.get(sessionId)?.cwd ?? workspacesByCliRunId.get(sessionId)?.session.cwd ?? null;
44826
45599
  }
44827
45600
  function createPendingTerminalSession(input) {
44828
- if (!path18__default.isAbsolute(input.cwd)) throw new Error("Terminal session cwd must be absolute");
45601
+ if (!path19__default.isAbsolute(input.cwd)) throw new Error("Terminal session cwd must be absolute");
44829
45602
  const createdAt = input.createdAt ?? now();
44830
45603
  const canonicalCwd = canonicalizeTheaterPath(input.cwd);
44831
45604
  const theaterId = workspaceHash(canonicalCwd);
@@ -44835,7 +45608,7 @@ function createConsoleObservabilityStore(deps = {}) {
44835
45608
  sessionId: input.sessionId,
44836
45609
  cwd: input.cwd,
44837
45610
  canonicalCwd,
44838
- cwdLabel: path18__default.basename(input.cwd) || input.cwd,
45611
+ cwdLabel: path19__default.basename(input.cwd) || input.cwd,
44839
45612
  cliId: input.cliId,
44840
45613
  createdAt,
44841
45614
  theaterId,
@@ -44852,7 +45625,7 @@ function createConsoleObservabilityStore(deps = {}) {
44852
45625
  sessionId: operation.sessionId,
44853
45626
  cwd: operation.cwd,
44854
45627
  canonicalCwd: canonicalizeTheaterPath(operation.cwd),
44855
- cwdLabel: path18__default.basename(operation.cwd) || operation.cwd,
45628
+ cwdLabel: path19__default.basename(operation.cwd) || operation.cwd,
44856
45629
  label: operation.label,
44857
45630
  labelSource: operation.labelSource,
44858
45631
  providerTitle: operation.providerTitle,
@@ -45113,7 +45886,7 @@ function defaultWorkspaceHash(canonicalCwd) {
45113
45886
  return crypto5.createHash("sha256").update(canonicalCwd).digest("hex").slice(0, 12);
45114
45887
  }
45115
45888
  function defaultCanonicalizeTheaterPath(cwd) {
45116
- const resolved = path18__default.resolve(cwd);
45889
+ const resolved = path19__default.resolve(cwd);
45117
45890
  try {
45118
45891
  return fs9__default.realpathSync.native(resolved);
45119
45892
  } catch {
@@ -45543,24 +46316,24 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45543
46316
  registerCleanup: (cleanup2) => ctx.host.lifecycle.registerCleanup(cleanup2)
45544
46317
  });
45545
46318
  async function handle({ req, res, pathname }) {
45546
- const path42 = pathname.slice(`${ctx.basePath}/agent`.length) || "/";
45547
- if (path42 === "/state") {
46319
+ const path43 = pathname.slice(`${ctx.basePath}/agent`.length) || "/";
46320
+ if (path43 === "/state") {
45548
46321
  if (req.method !== "GET") return methodNotAllowed2(res);
45549
46322
  ctx.host.http.writeJson(res, 200, { agentClis: await buildAgentCliLaunchMetadata() });
45550
46323
  return true;
45551
46324
  }
45552
- if (path42 === "/agent-cli/state") {
46325
+ if (path43 === "/agent-cli/state") {
45553
46326
  if (req.method !== "GET") return methodNotAllowed2(res);
45554
46327
  ctx.host.http.writeJson(res, 200, { clis: await detector.detect() });
45555
46328
  return true;
45556
46329
  }
45557
- if (path42 === "/agent-cli/diagnostics") {
46330
+ if (path43 === "/agent-cli/diagnostics") {
45558
46331
  if (req.method !== "GET") return methodNotAllowed2(res);
45559
46332
  if (!ctx.host.security.isTerminalAuthorized(req)) return unauthorized(res);
45560
46333
  ctx.host.http.writeJson(res, 200, await buildAgentCliDiagnostics());
45561
46334
  return true;
45562
46335
  }
45563
- if (path42 === "/agent-cli/path") {
46336
+ if (path43 === "/agent-cli/path") {
45564
46337
  if (req.method !== "PUT") return methodNotAllowed2(res);
45565
46338
  if (!ctx.host.security.isTerminalAuthorized(req)) return unauthorized(res);
45566
46339
  const body = await ctx.host.http.readJsonBody(req);
@@ -45580,15 +46353,15 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45580
46353
  ctx.host.http.writeJson(res, 200, { ok: true });
45581
46354
  return true;
45582
46355
  }
45583
- if (path42 === "/events") {
46356
+ if (path43 === "/events") {
45584
46357
  if (req.method !== "GET") return methodNotAllowed2(res);
45585
46358
  writeAgentSessionEvents(req, res, observability);
45586
46359
  return true;
45587
46360
  }
45588
- if (path42 === "/sessions") return handleSessions(req, res);
45589
- const sessionMatch = path42.match(/^\/sessions\/([^/]+)(?:\/([^/]+))?$/);
46361
+ if (path43 === "/sessions") return handleSessions(req, res);
46362
+ const sessionMatch = path43.match(/^\/sessions\/([^/]+)(?:\/([^/]+))?$/);
45590
46363
  if (sessionMatch) return handleSessionItem(req, res, decodeURIComponent(sessionMatch[1] ?? ""), sessionMatch[2] ?? "");
45591
- if (path42 === "/ticket") {
46364
+ if (path43 === "/ticket") {
45592
46365
  if (req.method !== "POST") return methodNotAllowed2(res);
45593
46366
  if (!ctx.host.security.isTerminalAuthorized(req)) {
45594
46367
  ctx.host.http.writeJson(res, 401, { error: "Unauthorized" });
@@ -45737,16 +46510,18 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45737
46510
  }
45738
46511
  const sessionId = crypto5.randomUUID();
45739
46512
  const session = observability.createPendingTerminalSession({ sessionId, cwd, cliId });
46513
+ const named = launchOptions.prompt === void 0 ? null : observability.autoNameTerminalSession(sessionId, deriveOperationLabel(launchOptions.prompt));
46514
+ const namedSession = named?.session ?? session;
45740
46515
  ctx.host.operations.create({
45741
46516
  id: session.sessionId,
45742
46517
  theaterId,
45743
46518
  type: AGENT_OPERATION_TYPE,
45744
46519
  pluginId: ctx.pluginId,
45745
- title: session.label ?? path18__default.basename(cwd),
46520
+ title: namedSession.label ?? session.label ?? path19__default.basename(cwd),
45746
46521
  // 공급자는 실행 시점에 한 번 확정되고 이후 어떤 patch도 다시 쓰지 않는다 —
45747
46522
  // toOperationPayload가 지우는 키 목록 밖이라 resume·복원을 지나도 그대로 남는다.
45748
46523
  payload: {
45749
- ...toOperationPayload(void 0, cwd, session),
46524
+ ...toOperationPayload(void 0, cwd, namedSession),
45750
46525
  [AGENT_LAUNCH_PROVIDER_PAYLOAD_KEY]: agentLaunchProviderFromModel(launchOptions.model),
45751
46526
  // Claude Code의 resume가 launch 좌표를 자체 복원한다고 가정하지 않는다 — 정규화된
45752
46527
  // 최초 선택을 Operation에 남겨 dormant·Console 재시작 뒤에도 같은 인자로 재개한다.
@@ -45772,7 +46547,7 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45772
46547
  });
45773
46548
  const runtimeSession = pendingRuntimeSessions.get(sessionId);
45774
46549
  pendingRuntimeSessions.delete(sessionId);
45775
- const created = runtimeSession ? observability.registerTerminalRuntimeSession(runtimeSession) ?? session : observability.updateTerminalSessionStatus(sessionId, "terminal-only") ?? session;
46550
+ const created = runtimeSession ? observability.registerTerminalRuntimeSession(runtimeSession) ?? namedSession : observability.updateTerminalSessionStatus(sessionId, "terminal-only") ?? namedSession;
45776
46551
  observability.notifySessionUpdated(created);
45777
46552
  ctx.host.operations.patch(sessionId, { payload: toOperationPayload(ctx.host.operations.get(sessionId)?.payload, cwd, created, void 0, observability.getDurableOperation(sessionId)?.providerTitle) });
45778
46553
  ctx.host.http.writeJson(res, 200, created);
@@ -45995,7 +46770,7 @@ async function createAgentApi(ctx, terminalRuntime, deps) {
45995
46770
  if (result?.renamed) {
45996
46771
  observability.notifySessionUpdated(result.session);
45997
46772
  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) });
46773
+ ctx.host.operations.patch(sessionId, { title: result.session.label ?? path19__default.basename(autoNameCwd) });
45999
46774
  }
46000
46775
  ctx.host.http.writeJson(res, 200, { ok: true, renamed: result?.renamed === true });
46001
46776
  return true;
@@ -46212,7 +46987,7 @@ function createTerminalWikiToolSpecs(fleetDataDir) {
46212
46987
  const resolver = createWikiWorkspaceResolver({
46213
46988
  ensureWorkspace: (cwd) => ensureWorkspaceDirectory(fleetDataDir, cwd),
46214
46989
  withMigrationLock: (workspace, operation) => withDirectoryLock(
46215
- { lockDir: path18__default.join(workspace.path, "knowledge.migration.lock") },
46990
+ { lockDir: path19__default.join(workspace.path, "knowledge.migration.lock") },
46216
46991
  operation
46217
46992
  )
46218
46993
  });
@@ -46696,7 +47471,7 @@ var AnalystTools = class {
46696
47471
  id: metadata.id,
46697
47472
  description: metadata.description,
46698
47473
  parameters: metadata.parameters,
46699
- execute: async (args) => execute(record4(args))
47474
+ execute: async (args) => execute(record5(args))
46700
47475
  };
46701
47476
  }
46702
47477
  events(args) {
@@ -46741,7 +47516,7 @@ var AnalystTools = class {
46741
47516
  return { artifact: { id: artifact.id, title, createdAt: artifact.createdAt } };
46742
47517
  }
46743
47518
  };
46744
- function record4(value) {
47519
+ function record5(value) {
46745
47520
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
46746
47521
  }
46747
47522
  function integer2(value) {
@@ -46919,9 +47694,9 @@ var AnalystSession = class {
46919
47694
  };
46920
47695
  function toAnalystEvents(event, toolNames, redact) {
46921
47696
  if (event.type === "stream_event") {
46922
- const inner = record5(event.event);
47697
+ const inner = record6(event.event);
46923
47698
  if (inner.type !== "content_block_delta") return [];
46924
- const delta = record5(inner.delta);
47699
+ const delta = record6(inner.delta);
46925
47700
  if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
46926
47701
  return [{ type: "chunk", text: redact(delta.text) }];
46927
47702
  }
@@ -46959,10 +47734,10 @@ function toAnalystEvents(event, toolNames, redact) {
46959
47734
  return [];
46960
47735
  }
46961
47736
  function blocks(message) {
46962
- const content = record5(message).content;
46963
- return Array.isArray(content) ? content.map(record5) : [];
47737
+ const content = record6(message).content;
47738
+ return Array.isArray(content) ? content.map(record6) : [];
46964
47739
  }
46965
- function record5(value) {
47740
+ function record6(value) {
46966
47741
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
46967
47742
  }
46968
47743
  function errorMessage2(error51) {
@@ -47166,7 +47941,7 @@ function analysisError(code, message) {
47166
47941
  return { error: { code, message } };
47167
47942
  }
47168
47943
  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;
47944
+ 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
47945
  const cli = catalog.clis.find((candidate) => candidate.cliId === value.cliId);
47171
47946
  if (!cli?.available) return false;
47172
47947
  const model = cli.models.find((candidate) => candidate.id === value.model);
@@ -47175,9 +47950,9 @@ function isAnalysisSelection(catalog, value) {
47175
47950
  return typeof value.effort === "string" && value.effort.length > 0 && model.effortLevels.includes(value.effort);
47176
47951
  }
47177
47952
  function isMessageBody(value) {
47178
- return isRecord12(value) && hasExactKeys(value, ["text"]) && typeof value.text === "string" && value.text.trim().length > 0;
47953
+ return isRecord13(value) && hasExactKeys(value, ["text"]) && typeof value.text === "string" && value.text.trim().length > 0;
47179
47954
  }
47180
- function isRecord12(value) {
47955
+ function isRecord13(value) {
47181
47956
  return typeof value === "object" && value !== null && !Array.isArray(value);
47182
47957
  }
47183
47958
  function hasExactKeys(value, keys) {
@@ -47210,14 +47985,14 @@ function registerAnalysisRoutes(ctx, deps = {}) {
47210
47985
  writeError(ctx, res, 403, ANALYSIS_ERROR_CODES.catalogInvalid, "Analysis request is not accepted by this host.");
47211
47986
  return true;
47212
47987
  }
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\/([^/]+)$/);
47988
+ const path43 = pathname.slice(`${ctx.basePath}/analysis`.length) || "/";
47989
+ if (path43 === "/catalog") return handleCatalog(ctx, req, res, catalog);
47990
+ if (path43 === "/stream") return handleGlobalStream(ctx, req, res, registry3);
47991
+ const artifactMatch = path43.match(/^\/artifacts\/([^/]+)$/);
47217
47992
  if (artifactMatch) return handleArtifact(ctx, req, res, decodeURIComponent(artifactMatch[1] ?? ""), registry3);
47218
- const clearArtifactsMatch = path42.match(/^\/([^/]+)\/artifacts$/);
47993
+ const clearArtifactsMatch = path43.match(/^\/([^/]+)\/artifacts$/);
47219
47994
  if (clearArtifactsMatch) return handleClearArtifacts(ctx, req, res, decodeURIComponent(clearArtifactsMatch[1] ?? ""), registry3);
47220
- const match = path42.match(/^\/([^/]+)\/(ready|start|message|stream|stop)$/);
47995
+ const match = path43.match(/^\/([^/]+)\/(ready|start|message|stream|stop)$/);
47221
47996
  if (!match) return false;
47222
47997
  const operationId = decodeURIComponent(match[1] ?? "");
47223
47998
  const action = match[2] ?? "";
@@ -47667,14 +48442,14 @@ async function handleStop(ctx, req, res, operationId, registry3) {
47667
48442
  }
47668
48443
  async function resolveTranscriptPath(capturePath, operationCreatedAt) {
47669
48444
  if (await fileExists2(capturePath)) return capturePath;
47670
- const dir = path18__default.dirname(capturePath);
48445
+ const dir = path19__default.dirname(capturePath);
47671
48446
  const bornCutoff = operationCreatedAt - 6e4;
47672
48447
  try {
47673
48448
  const entries = await promises.readdir(dir);
47674
48449
  const candidates = [];
47675
48450
  for (const entry of entries) {
47676
48451
  if (!entry.endsWith(".jsonl")) continue;
47677
- const candidate = path18__default.join(dir, entry);
48452
+ const candidate = path19__default.join(dir, entry);
47678
48453
  const stat4 = await promises.stat(candidate).catch(() => null);
47679
48454
  if (!stat4?.isFile()) continue;
47680
48455
  if (stat4.birthtimeMs > 0 && stat4.birthtimeMs < bornCutoff) continue;
@@ -47724,7 +48499,7 @@ function artifactHeaders() {
47724
48499
  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
48500
  }
47726
48501
  function registerAiGatewayRoutes(ctx, deps = {}) {
47727
- const ownedDiagnostics = deps.cursorDiagnostics ? void 0 : createCursorDiagnosticLog(path18__default.join(
48502
+ const ownedDiagnostics = deps.cursorDiagnostics ? void 0 : createCursorDiagnosticLog(path19__default.join(
47728
48503
  ctx.host.paths.pluginDataDir(ctx.pluginId),
47729
48504
  "ai-gateway"
47730
48505
  ));
@@ -47734,6 +48509,7 @@ function registerAiGatewayRoutes(ctx, deps = {}) {
47734
48509
  // 자격증명 조달은 호스트 결정이다 — Console은 core-ai-gateway가 export한 기본 reader를 주입한다.
47735
48510
  readAuth: deps.readAuth ?? (() => readCodexSubscriptionAuth()),
47736
48511
  readCursorToken: deps.readCursorToken ?? (() => readCursorSubscriptionToken()),
48512
+ readXaiToken: deps.readXaiToken ?? (() => readXaiSubscriptionToken()),
47737
48513
  readModelOverride: () => process.env[AI_GATEWAY_MODEL_ENV],
47738
48514
  cursorDiagnostics: deps.cursorDiagnostics ?? ownedDiagnostics?.write
47739
48515
  });
@@ -47863,8 +48639,8 @@ function registerTerminalModelAuthRoutes(ctx, deps) {
47863
48639
  }
47864
48640
  function createTerminalModelAuthRouter(ctx, deps) {
47865
48641
  return async function handleTerminalModelAuthRoute({ req, res, pathname }) {
47866
- const path42 = pathname.slice(`${ctx.basePath}/model-auth`.length) || "/";
47867
- if (path42 === "/state") {
48642
+ const path43 = pathname.slice(`${ctx.basePath}/model-auth`.length) || "/";
48643
+ if (path43 === "/state") {
47868
48644
  if (req.method !== "GET") {
47869
48645
  ctx.host.http.writeJson(res, 405, { error: "Method not allowed" });
47870
48646
  return true;
@@ -47872,7 +48648,7 @@ function createTerminalModelAuthRouter(ctx, deps) {
47872
48648
  ctx.host.http.writeJson(res, 200, await buildModelAuthState(deps.authService));
47873
48649
  return true;
47874
48650
  }
47875
- const providerId = parseProviderPath(path42);
48651
+ const providerId = parseProviderPath(path43);
47876
48652
  if (!providerId) return false;
47877
48653
  if (!isTerminalModelAuthProviderId(providerId)) {
47878
48654
  ctx.host.http.writeJson(res, 404, { error: "provider_not_found" });
@@ -47940,8 +48716,8 @@ async function findProvider(deps, providerId) {
47940
48716
  const state = await buildModelAuthState(deps.authService);
47941
48717
  return state.providers.find((provider) => provider.provider === providerId) ?? null;
47942
48718
  }
47943
- function parseProviderPath(path42) {
47944
- const parts = path42.split("/").filter(Boolean);
48719
+ function parseProviderPath(path43) {
48720
+ const parts = path43.split("/").filter(Boolean);
47945
48721
  if (parts.length !== 2 || parts[0] !== "providers") return null;
47946
48722
  try {
47947
48723
  return decodeURIComponent(parts[1] ?? "");
@@ -48076,7 +48852,7 @@ function isRestoredShellEvent(value, pluginId) {
48076
48852
  var CONTROL_HOLDER_EVENT_CHANNEL = "control:holder";
48077
48853
  function applyWireLog(ctx, stored) {
48078
48854
  setWireLogTarget(stored === void 0 ? void 0 : stored ? {
48079
- path: path18__default.join(ctx.host.paths.pluginDataDir(ctx.pluginId), "ai-gateway", "wire-log.jsonl"),
48855
+ path: path19__default.join(ctx.host.paths.pluginDataDir(ctx.pluginId), "ai-gateway", "wire-log.jsonl"),
48080
48856
  maxBytes: DEFAULT_WIRE_LOG_MAX_BYTES
48081
48857
  } : null);
48082
48858
  }