context-mode 2.0.0-next.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -86,16 +87,15 @@ var require_src = __commonJS({
86
87
  });
87
88
 
88
89
  // src/entries/cli.ts
89
- import { spawn as spawn2 } from "node:child_process";
90
- import { readFileSync as readFileSync5, realpathSync as realpathSync5 } from "node:fs";
91
- import path8 from "node:path";
90
+ import { spawn as spawn4 } from "node:child_process";
91
+ import { readFileSync as readFileSync12, realpathSync as realpathSync9 } from "node:fs";
92
+ import path14 from "node:path";
92
93
  import { fileURLToPath as fileURLToPath2 } from "node:url";
93
94
 
94
95
  // src/core/contracts/constants.ts
95
96
  var SERVER_KEY = "context-mode";
96
97
  var TOOL_ORDER = Object.freeze(["ctx_execute", "ctx_batch", "ctx_index", "ctx_search", "ctx_resume", "ctx_stats", "ctx_doctor", "ctx_upgrade", "ctx_purge"]);
97
98
  var OUTPUT_CAP = 16384;
98
- var REPORT_CAP = 4096;
99
99
  var WEIGHT = Object.freeze({ toolerr: 900, decision: 700, prompt: 500, edit: 400, index: 200 });
100
100
  var DECAY_X1000 = Object.freeze([
101
101
  1e3,
@@ -228,6 +228,7 @@ var DECAY_X1000 = Object.freeze([
228
228
  250
229
229
  ]);
230
230
  var EXEC_TIMEOUT_MS = 6e5;
231
+ var DB_TIMEOUT_MS = 5e3;
231
232
  var DB_WAL_SUFFIX = "-wal";
232
233
  var DB_SHM_SUFFIX = "-shm";
233
234
  var HOOK_TIMEOUT_MS = 5e3;
@@ -242,6 +243,8 @@ var NODE_MIN = "24.15.0";
242
243
  var DATA_ROOT = "~/.context-mode";
243
244
  var HOST_PLUGINS_DIR_NAME = "plugins";
244
245
  var INSTALLED_PLUGINS_FILE = "installed_plugins.json";
246
+ var PROJECT_PLUGIN_SCOPES = Object.freeze(["local", "project"]);
247
+ var PLUGIN_SCOPE_RANK = Object.freeze({ local: 0, project: 1, user: 2, managed: 2 });
245
248
  var MCP_HINT_EVERY_DEFAULT = 10;
246
249
  function readHintEvery(raw) {
247
250
  if (raw === void 0 || raw.trim() === "") return MCP_HINT_EVERY_DEFAULT;
@@ -256,6 +259,24 @@ var DENY_WHAT = Object.freeze({
256
259
  webfetch: "WebFetch"
257
260
  });
258
261
  var DENY_WEBFETCH_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
262
+ var HOOK_FAIL_TOOL_KEYS = Object.freeze(["tool_name", "toolName", "tool"]);
263
+ var HOOK_FAIL_EVENT_KEYS = Object.freeze(["hook_event_name", "hookEventName", "type"]);
264
+ var HOOK_FAIL_INPUT_KEYS = Object.freeze(["tool_input", "toolArgs", "input", "args"]);
265
+ var HOOK_FAIL_CWD_KEYS = Object.freeze(["cwd", "directory"]);
266
+ var HOOK_FAIL_PRE_EVENTS = Object.freeze(["pretooluse", "beforetool", "tool_call", "execute.before", "tool.execute.before"]);
267
+ var HOOK_FAULT_STAGES = Object.freeze(["decode", "project", "policy", "store", "encode"]);
268
+ var HOOK_FAIL_TOOLS = Object.freeze({
269
+ shell: Object.freeze(["Bash", "bash", "shell"]),
270
+ read: Object.freeze(["Read", "read_file"]),
271
+ grep: Object.freeze(["Grep", "grep_search"]),
272
+ fetch: Object.freeze(["WebFetch", "web_fetch", "fetch"])
273
+ });
274
+ var HOOK_FAIL_REDIRECT = Object.freeze({
275
+ read: "Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",
276
+ shell: "Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",
277
+ grep: "Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",
278
+ fetch: "Index the URL with ctx_index and query it with ctx_search."
279
+ });
259
280
  var BOUNDED_COMMANDS = Object.freeze(["pwd", "whoami", "uname", "id", "realpath", "ln"]);
260
281
  var BOUNDED_GIT_SUBCOMMANDS = Object.freeze(["status"]);
261
282
  var VERSION_PROBE_FLAGS = Object.freeze(["--version", "-v"]);
@@ -278,7 +299,33 @@ var EDIT_TOOLS = Object.freeze(["Write", "Edit"]);
278
299
  var EDIT_PATH_KEYS = Object.freeze(["file_path", "path"]);
279
300
  var AGENT_ARG = "--agent";
280
301
  var STATS_COLUMNS = Object.freeze(["Scope", "Produced", "Returned", "Saved", "Reduction %"]);
302
+ var STATS_EMPTY_LINES = Object.freeze([
303
+ "Ready. Your savings show up here after the first tool call.",
304
+ "Large outputs from ctx_execute, ctx_batch and ctx_index stay in the",
305
+ "sandbox, and only the short answer goes to the chat."
306
+ ]);
307
+ var STATS_KIND_LABELS = Object.freeze([
308
+ // D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
309
+ ["index", "Content indexed"],
310
+ ["edit", "File edits"],
311
+ ["toolerr", "Issues kept"],
312
+ ["decision", "Your decisions"],
313
+ ["cmd", "Other tool calls"],
314
+ ["prompt", "Your prompts"]
315
+ ]);
316
+ var STATS_JOURNAL_HINTS = Object.freeze([
317
+ "ctx_resume brings back your last task, files changed and open issues",
318
+ "after a compact or a restart; ctx_search finds indexed content by words."
319
+ ]);
320
+ var STATS_WAYS = Object.freeze([
321
+ ["sandbox", "\u2588", "sandbox run"],
322
+ ["index", "\u2593", "index + search"],
323
+ ["redirect", "\u2592", "hook sent to sandbox"],
324
+ ["replace", "\u2591", "hook cut down"]
325
+ ]);
326
+ var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
281
327
  var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
328
+ var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
282
329
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
283
330
  var DOCTOR_LABEL = Object.freeze({
284
331
  D1: "version",
@@ -294,7 +341,11 @@ var DOCTOR_LABEL = Object.freeze({
294
341
  D10: "enforcement mode",
295
342
  D11: "shell"
296
343
  });
297
- var REPORT_TRUNCATED_LINE = `(report truncated at ${REPORT_CAP} B; run ctx_doctor again after the first fix)`;
344
+ var REPORT_SOURCE_LABEL = "ctx_doctor:report";
345
+ var REPORT_POINTER = `ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(REPORT_SOURCE_LABEL)}})`;
346
+ var GIT_LS_REMOTE_TAG_ARGS = Object.freeze(["--tags", "--refs"]);
347
+ var RELEASE_TAG_PATTERN = "v*";
348
+ var D1_GIT_CHECK_FIX = `git ls-remote --tags --refs ${RELEASE_REPO_URL} "${RELEASE_TAG_PATTERN}"`;
298
349
  var D2_NODE_FIX = `install Node ${NODE_MIN} or later`;
299
350
  var D3_PARTS = Object.freeze(["MCP entry", "hook entries", "hook timeout"]);
300
351
  var AGENT_HOME_DIR = Object.freeze({
@@ -385,12 +436,13 @@ var V1_STATUSLINE_COMMAND = "context-mode statusline";
385
436
  var V1_PI_PACKAGE = "npm:context-mode";
386
437
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
387
438
  var V1_TMP_PREFIX = "context-mode-";
388
- var V1_TOML_SECTION_PREFIX = "[mcp_servers.context-mode";
439
+ var V1_TOML_SECTION_ROOT = "mcp_servers";
389
440
  var V1_HOOKS_DIR_NAME = "hooks";
390
441
  var SETTINGS_FILE = "settings.json";
391
442
  var CLAUDE_USER_CONFIG_FILE = ".claude.json";
392
443
  var HOOKS_JSON_FILE = "hooks.json";
393
444
  var CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
445
+ var CODEX_HOME_ENV = "CODEX_HOME";
394
446
  var COPILOT_HOME_ENV = "COPILOT_HOME";
395
447
  var KIRO_HOME_ENV = "KIRO_HOME";
396
448
  var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
@@ -425,6 +477,7 @@ var V1_BIN_COMMAND = SERVER_KEY;
425
477
  var VSCODE_MCP_SERVERS_KEY = "servers";
426
478
  var ZCODE_EVENTS_KEY = "events";
427
479
  var PI_ROLE = "custom";
480
+ var PI_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
428
481
  var PI_PACKAGE_SOURCE_KEY = "source";
429
482
  var V1_PATH_SEPS = Object.freeze(["/", "\\"]);
430
483
  var HOST_SEP_TOKEN = "${/}";
@@ -448,16 +501,23 @@ var V1_REASON = Object.freeze({
448
501
  dataDir: "old context-mode data dir <agent home>/context-mode/",
449
502
  dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
450
503
  dataRoot: "old context-mode content under ~/.context-mode/",
451
- tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, no action needed"
504
+ tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
452
505
  });
453
506
  var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
454
507
  var OPENCODE_TOOL_PREFIX = SERVER_KEY + "_";
508
+ var SERVER_ENTRY_FILE = "server.mjs";
509
+ var VSCODE_WORKSPACE_VAR = "${workspaceFolder}";
510
+ var OPENCODE_PLUGIN_PATH = Object.freeze(["opencode", "plugin.js"]);
511
+ var HOST_NODE_COMMAND = "node";
512
+ var EXE_SUFFIX = ".exe";
455
513
  var ATOMIC_RENAME_RETRIES = 5;
456
514
  var ATOMIC_RENAME_DELAY_MS = 50;
457
515
  var ATOMIC_RENAME_BUSY_CODES = ["EPERM", "EBUSY", "EACCES"];
458
516
  var ATOMIC_TMP_PREFIX = ".";
459
517
  var ATOMIC_TMP_MARK = ".cm-tmp-";
460
518
  var JSON_INDENT_UNIT = " ";
519
+ var MCP_COMMAND_FIELD = "command";
520
+ var MCP_ARGS_FIELD = "args";
461
521
  var ZCODE_MCP_FEATURE_KEY = Object.freeze(["features", "mcp"]);
462
522
  var CODEX_OMIT_TOOLS_FROM_FIELD = "omit_tools_from";
463
523
  var CODEX_OMIT_DEFERRED = Object.freeze(["deferred"]);
@@ -477,9 +537,66 @@ var OWN_MCP_ENTRY = Object.freeze({
477
537
  var REPORT_ENV_ENUMS = Object.freeze({
478
538
  NODE_ENV: Object.freeze(["development", "production", "test"])
479
539
  });
540
+ var DOCTOR_ENV_PREFIX = "Environment: ";
541
+ var DOCTOR_DOCS_LABEL = "Docs: ";
542
+ var DOCTOR_REPORT_LINE = "Report file: ";
543
+ var DOCTOR_GH_LINE = "File it: ";
544
+ var DOCTOR_URL_LINE = "Or open: ";
545
+ var DOCTOR_GH_NEXT = " --";
546
+ var DOCTOR_NOTE_PREFIXES = Object.freeze([
547
+ DOCTOR_ENV_PREFIX,
548
+ DOCTOR_DOCS_LABEL,
549
+ DOCTOR_REPORT_LINE,
550
+ DOCTOR_GH_LINE,
551
+ DOCTOR_GH_NEXT.trim(),
552
+ DOCTOR_URL_LINE
553
+ ]);
554
+ var ISSUE_REPO_SLUG = "mksglu/context-mode";
555
+ var ISSUE_FORM_FILE = "agent-report.yml";
556
+ var ISSUE_URL_MAX = 8e3;
557
+ var ISSUE_FORM_HEADINGS = Object.freeze([
558
+ "Summary",
559
+ "ctx-report",
560
+ "What happened",
561
+ "Hook errors",
562
+ "Journal rows",
563
+ "Agent config",
564
+ "Expected",
565
+ "Steps",
566
+ "Environment"
567
+ ]);
568
+ var DOCTOR_ENV_NAMES = Object.freeze([
569
+ "CODEX_HOME",
570
+ "CLAUDE_CONFIG_DIR",
571
+ "CLAUDE_PLUGIN_ROOT",
572
+ "COPILOT_HOME",
573
+ "KIRO_HOME",
574
+ "OPENCODE_CONFIG_DIR",
575
+ "PI_CODING_AGENT_DIR",
576
+ "XDG_CONFIG_HOME",
577
+ "SHELL"
578
+ ]);
579
+ var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
580
+ var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
581
+ var NATIVE_INSTALL = Object.freeze({
582
+ "claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
583
+ codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
584
+ gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
585
+ qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
586
+ opencode: ["opencode plugin add context-mode@next"],
587
+ pi: ["pi install npm:context-mode@next"],
588
+ "copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
589
+ vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
590
+ kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
591
+ zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
592
+ });
593
+ var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
480
594
 
481
595
  // src/adapters/claude-code.ts
482
596
  var TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
597
+ var SHELL_TOOL_NAMES = Object.freeze(["Bash", "PowerShell"]);
598
+ var POWERSHELL_TOOL = "PowerShell";
599
+ var SHELL_CANONICAL = "Bash";
483
600
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
484
601
  var MCP_PREFIX = "mcp__";
485
602
  var MCP_SEP = "__";
@@ -488,9 +605,9 @@ function canonicalName(name, ownPrefix) {
488
605
  if (name.startsWith(ownPrefix)) return name.slice(ownPrefix.length);
489
606
  if (!name.startsWith(MCP_PREFIX)) return name;
490
607
  const rest = name.slice(MCP_PREFIX.length);
491
- const sep = rest.indexOf(MCP_SEP);
492
- if (sep < 0) return name;
493
- return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP.length);
608
+ const sep2 = rest.indexOf(MCP_SEP);
609
+ if (sep2 < 0) return name;
610
+ return "mcp:" + rest.slice(0, sep2) + ":" + rest.slice(sep2 + MCP_SEP.length);
494
611
  }
495
612
  function outputOf(resp) {
496
613
  if (resp === void 0) return "";
@@ -538,7 +655,7 @@ function readResult(resp) {
538
655
  }
539
656
  return info;
540
657
  }
541
- function decodeClaudeShape(raw, agent, ownPrefix, sources) {
658
+ function decodeClaudeShape(raw, agent, ownPrefix, sources2) {
542
659
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(agent + ": hook payload is not a JSON object");
543
660
  const p3 = raw;
544
661
  const event = CLAUDE_SHAPE_EVENTS.find((e) => e === p3.hook_event_name);
@@ -548,7 +665,7 @@ function decodeClaudeShape(raw, agent, ownPrefix, sources) {
548
665
  ev.agentId = p3.agent_id;
549
666
  if (typeof p3.agent_type === "string") ev.agentType = p3.agent_type;
550
667
  }
551
- if (event === "SessionStart" && typeof p3.source === "string" && sources[p3.source] !== void 0) ev.source = sources[p3.source];
668
+ if (event === "SessionStart" && typeof p3.source === "string" && sources2[p3.source] !== void 0) ev.source = sources2[p3.source];
552
669
  if (event === "UserPromptSubmit" && typeof p3.prompt === "string") ev.prompt = p3.prompt;
553
670
  if (event === "PreToolUse" || event === "PostToolUse") {
554
671
  const name = String(p3.tool_name ?? "");
@@ -605,6 +722,7 @@ function requireFields(raw) {
605
722
  function decode(raw) {
606
723
  requireFields(raw);
607
724
  const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
725
+ if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
608
726
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
609
727
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
610
728
  const cmd = typeof ev.tool.input.command === "string" ? ev.tool.input.command : JSON.stringify(ev.tool.input);
@@ -754,7 +872,8 @@ var RESULT_SUCCESS = "success";
754
872
  function isRecord(v) {
755
873
  return typeof v === "object" && v !== null && !Array.isArray(v);
756
874
  }
757
- var NATIVE_TO_CANONICAL3 = { bash: "Bash" };
875
+ var SHELL_TOOL_NAMES2 = Object.freeze(["bash", "powershell"]);
876
+ var NATIVE_TO_CANONICAL3 = Object.fromEntries(SHELL_TOOL_NAMES2.map((n3) => [n3, "Bash"]));
758
877
  function canonicalName3(name) {
759
878
  if (name.startsWith(TOOL_NAME_PREFIX5)) return name.slice(TOOL_NAME_PREFIX5.length);
760
879
  if (Object.hasOwn(NATIVE_TO_CANONICAL3, name)) return NATIVE_TO_CANONICAL3[name];
@@ -835,11 +954,11 @@ var VSCODE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostTool
835
954
  var MCP_PREFIX2 = "mcp_";
836
955
  var MCP_SEP2 = "_";
837
956
  var SESSION_START_NEW = "new";
838
- var SHELL_TOOL_NAMES = Object.freeze(["run_in_terminal", "runTerminalCommand", "bash", "powershell"]);
957
+ var SHELL_TOOL_NAMES3 = Object.freeze(["run_in_terminal", "runTerminalCommand", "bash", "powershell"]);
839
958
  var READ_TOOL_NAMES = Object.freeze(["read_file", "view"]);
840
959
  var WEBFETCH_TOOL_NAMES = Object.freeze(["fetch_webpage", "web_fetch"]);
841
960
  var NATIVE_TO_CANONICAL4 = Object.fromEntries([
842
- ...SHELL_TOOL_NAMES.map((n3) => [n3, "Bash"]),
961
+ ...SHELL_TOOL_NAMES3.map((n3) => [n3, "Bash"]),
843
962
  ...READ_TOOL_NAMES.map((n3) => [n3, "Read"]),
844
963
  ...WEBFETCH_TOOL_NAMES.map((n3) => [n3, "WebFetch"])
845
964
  ]);
@@ -848,9 +967,9 @@ function canonicalName4(name) {
848
967
  if (Object.hasOwn(NATIVE_TO_CANONICAL4, name)) return NATIVE_TO_CANONICAL4[name];
849
968
  if (!name.startsWith(MCP_PREFIX2)) return name;
850
969
  const rest = name.slice(MCP_PREFIX2.length);
851
- const sep = rest.indexOf(MCP_SEP2);
852
- if (sep <= 0 || sep === rest.length - 1) return name;
853
- return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP2.length);
970
+ const sep2 = rest.indexOf(MCP_SEP2);
971
+ if (sep2 <= 0 || sep2 === rest.length - 1) return name;
972
+ return "mcp:" + rest.slice(0, sep2) + ":" + rest.slice(sep2 + MCP_SEP2.length);
854
973
  }
855
974
  var isNum = (v) => typeof v === "number" && Number.isFinite(v);
856
975
  function policyInput(name, canonical, input) {
@@ -967,8 +1086,8 @@ var KIRO_EVENTS = {
967
1086
  };
968
1087
  var PROMPT_ENV = "USER_PROMPT";
969
1088
  var MCP_PREFIX3 = "mcp_";
970
- var SHELL_TOOL_NAMES2 = Object.freeze(["execute_bash", "execute_pwsh", "shell"]);
971
- var NATIVE_TO_CANONICAL5 = Object.fromEntries(SHELL_TOOL_NAMES2.map((n3) => [n3, "Bash"]));
1089
+ var SHELL_TOOL_NAMES4 = Object.freeze(["execute_bash", "execute_pwsh", "shell"]);
1090
+ var NATIVE_TO_CANONICAL5 = Object.fromEntries(SHELL_TOOL_NAMES4.map((n3) => [n3, "Bash"]));
972
1091
  var MCP_SEP3 = "_";
973
1092
  var KIRO_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
974
1093
  function canonicalName5(name) {
@@ -976,9 +1095,9 @@ function canonicalName5(name) {
976
1095
  if (Object.hasOwn(NATIVE_TO_CANONICAL5, name)) return NATIVE_TO_CANONICAL5[name];
977
1096
  if (!name.startsWith(MCP_PREFIX3)) return name;
978
1097
  const rest = name.slice(MCP_PREFIX3.length);
979
- const sep = rest.indexOf(MCP_SEP3);
980
- if (sep <= 0 || sep === rest.length - 1) return name;
981
- return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP3.length);
1098
+ const sep2 = rest.indexOf(MCP_SEP3);
1099
+ if (sep2 <= 0 || sep2 === rest.length - 1) return name;
1100
+ return "mcp:" + rest.slice(0, sep2) + ":" + rest.slice(sep2 + MCP_SEP3.length);
982
1101
  }
983
1102
  function readResult5(resp) {
984
1103
  const text2 = resp === void 0 ? "" : typeof resp === "string" ? resp : JSON.stringify(resp);
@@ -1110,7 +1229,8 @@ var OPENCODE_EVENTS = {
1110
1229
  "step-finish": "Usage"
1111
1230
  };
1112
1231
  var SHELL_TOOL_NAME = "bash";
1113
- var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [SHELL_TOOL_NAME]: "Bash" };
1232
+ var SHELL_TOOL_NAMES5 = Object.freeze([SHELL_TOOL_NAME, "shell"]);
1233
+ var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n3) => [n3, "Bash"])) };
1114
1234
  function toCanonicalTool(name) {
1115
1235
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
1116
1236
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL7, name) ? NATIVE_TO_CANONICAL7[name] : name;
@@ -1158,13 +1278,14 @@ function encode10(ev, d, _extra) {
1158
1278
  // src/adapters/table.ts
1159
1279
  var CLAUDE_EVENTS = { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" };
1160
1280
  var CLAUDE_TOOLS = { shell: ["Bash"], read: ["Read"], grep: ["Grep"], webfetch: ["WebFetch"], edit: ["Write", "Edit", "NotebookEdit"] };
1281
+ var CLAUDE_CODE_TOOLS = { ...CLAUDE_TOOLS, shell: [...SHELL_TOOL_NAMES] };
1161
1282
  var ADAPTERS = Object.freeze([
1162
1283
  {
1163
1284
  id: "claude-code",
1164
1285
  installMode: "marketplace",
1165
1286
  projectSource: "env:CLAUDE_PROJECT_DIR",
1166
1287
  toolNamePrefix: TOOL_NAME_PREFIX,
1167
- nativeTools: CLAUDE_TOOLS,
1288
+ nativeTools: CLAUDE_CODE_TOOLS,
1168
1289
  execReadOnlyHint: false,
1169
1290
  eventMap: CLAUDE_EVENTS,
1170
1291
  compactDelivery: "sessionstart",
@@ -1240,8 +1361,9 @@ var ADAPTERS = Object.freeze([
1240
1361
  installMode: "plugin",
1241
1362
  projectSource: "arg:--agent+cwd",
1242
1363
  toolNamePrefix: TOOL_NAME_PREFIX5,
1243
- nativeTools: { shell: ["bash"] },
1364
+ nativeTools: { shell: [...SHELL_TOOL_NAMES2] },
1244
1365
  execReadOnlyHint: false,
1366
+ // D-PWSH-DUMP-1
1245
1367
  eventMap: { SessionStart: "sessionStart", UserPromptSubmit: "userPromptSubmitted", PreToolUse: "preToolUse", PostToolUse: "postToolUse" },
1246
1368
  compactDelivery: "pending-flag",
1247
1369
  compactSummary: "none",
@@ -1259,7 +1381,7 @@ var ADAPTERS = Object.freeze([
1259
1381
  projectSource: "arg:workspaceFolder",
1260
1382
  toolNamePrefix: TOOL_NAME_PREFIX6,
1261
1383
  // PreCompact sets the pending flag (ADR-0009 §6, DEVIATIONS D-M3-A4-1).
1262
- nativeTools: { shell: [...SHELL_TOOL_NAMES], read: [...READ_TOOL_NAMES], webfetch: [...WEBFETCH_TOOL_NAMES] },
1384
+ nativeTools: { shell: [...SHELL_TOOL_NAMES3], read: [...READ_TOOL_NAMES], webfetch: [...WEBFETCH_TOOL_NAMES] },
1263
1385
  // D-HF-VSCODE-PROJECT-1, D-N7-VSCODE-TOOLS-1
1264
1386
  execReadOnlyHint: false,
1265
1387
  eventMap: { ...CLAUDE_EVENTS, PreCompact: "PreCompact" },
@@ -1278,7 +1400,7 @@ var ADAPTERS = Object.freeze([
1278
1400
  installMode: "mcp-entry",
1279
1401
  projectSource: "arg:--agent+cwd",
1280
1402
  toolNamePrefix: TOOL_NAME_PREFIX7,
1281
- nativeTools: { shell: [...SHELL_TOOL_NAMES2] },
1403
+ nativeTools: { shell: [...SHELL_TOOL_NAMES4] },
1282
1404
  execReadOnlyHint: false,
1283
1405
  // D-HF-KIRO-SHELL-1, D-N7-KIRO-1
1284
1406
  eventMap: { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" },
@@ -1565,11 +1687,11 @@ Examples:
1565
1687
  };
1566
1688
 
1567
1689
  // src/cli/commands.ts
1568
- import { spawnSync as spawnSync3 } from "node:child_process";
1690
+ import { spawnSync as spawnSync5 } from "node:child_process";
1569
1691
  import { createHash as createHash2 } from "node:crypto";
1570
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
1692
+ import { existsSync as existsSync15, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
1571
1693
  import os from "node:os";
1572
- import path7 from "node:path";
1694
+ import path13 from "node:path";
1573
1695
 
1574
1696
  // node_modules/@clack/prompts/dist/index.mjs
1575
1697
  var dist_exports = {};
@@ -4387,13 +4509,14 @@ ${i2}
4387
4509
  }).prompt();
4388
4510
 
4389
4511
  // src/core/project/config-dir.ts
4390
- import { join as join2, posix, win32 } from "node:path";
4512
+ import { basename, dirname as dirname2, join as join2, posix, resolve, win32 } from "node:path";
4391
4513
 
4392
4514
  // src/core/contracts/errors.ts
4393
4515
  var ERROR_TEXT = Object.freeze({
4394
4516
  NODE_TOO_OLD: "Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",
4395
4517
  NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.",
4396
- DB_GONE: "context.db path vanished. Fix: run ctx_doctor.",
4518
+ DB_GONE: "context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",
4519
+ // D-ORPHAN-WAL-1
4397
4520
  NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.",
4398
4521
  UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".',
4399
4522
  TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.",
@@ -4471,6 +4594,10 @@ function homeDirOf(env, platform = process.platform) {
4471
4594
  if (set2(env.HOME)) return env.HOME;
4472
4595
  return set2(env.USERPROFILE) ? env.USERPROFILE : null;
4473
4596
  }
4597
+ function codexDirOf(env, home) {
4598
+ const dir = env[CODEX_HOME_ENV];
4599
+ return dir !== void 0 && dir !== "" ? dir : join2(home, ...AGENT_HOME_DIR.codex);
4600
+ }
4474
4601
  function copilotDirOf(env, home) {
4475
4602
  const dir = env[COPILOT_HOME_ENV];
4476
4603
  return dir !== void 0 && dir !== "" ? dir : join2(home, ...AGENT_HOME_DIR["copilot-cli"]);
@@ -4498,6 +4625,10 @@ function opencodeDirOf(env, home) {
4498
4625
  if (xdg !== void 0 && xdg !== "") return join2(xdg, AGENT_HOME_DIR.opencode[AGENT_HOME_DIR.opencode.length - 1]);
4499
4626
  return join2(home, ...AGENT_HOME_DIR.opencode);
4500
4627
  }
4628
+ function piAgentDirOf(env, home) {
4629
+ const dir = env[PI_AGENT_DIR_ENV];
4630
+ return dir !== void 0 && dir !== "" ? dir : join2(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
4631
+ }
4501
4632
  function vscodeUserDirOf(env, home, platform = process.platform) {
4502
4633
  const set2 = (v) => v !== void 0 && v !== "";
4503
4634
  const p3 = platform === "win32" ? win32 : posix;
@@ -4510,20 +4641,116 @@ function ownMcpFileOf(agent, file, env, home) {
4510
4641
  return agent === "vscode" ? join2(vscodeUserDirOf(env, home), ...file) : join2(home, ...file);
4511
4642
  }
4512
4643
 
4513
- // src/setup/registry.ts
4514
- import path3 from "node:path";
4644
+ // src/core/ops/doctor-issue.ts
4645
+ import { spawnSync } from "node:child_process";
4646
+ import { closeSync, existsSync as existsSync7, fstatSync, mkdirSync as mkdirSync4, openSync, readFileSync as readFileSync4, readSync, realpathSync as realpathSync3, writeFileSync as writeFileSync2 } from "node:fs";
4647
+ import { delimiter, join as join8 } from "node:path";
4648
+
4649
+ // src/core/hooks/fallback.ts
4650
+ import { join as join3, resolve as resolve2 } from "node:path";
4651
+ var fs = process.getBuiltinModule("node:fs");
4652
+
4653
+ // src/core/store/schema.ts
4654
+ var PRAGMAS = `
4655
+ PRAGMA busy_timeout = ${DB_TIMEOUT_MS};
4656
+ PRAGMA journal_mode = WAL;
4657
+ `;
4658
+ var FTS_TOKENIZE = "tokenize = 'porter unicode61 remove_diacritics 2'";
4659
+ var FTS_TOKENIZE_V1 = "tokenize = 'unicode61 remove_diacritics 2'";
4660
+ var DDL = `
4661
+ CREATE TABLE IF NOT EXISTS events (
4662
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
4663
+ session_id TEXT NOT NULL,
4664
+ worktree TEXT NOT NULL,
4665
+ agent TEXT NOT NULL,
4666
+ kind TEXT NOT NULL CHECK (kind IN ('prompt','edit','cmd','toolerr','index','cost','decision')),
4667
+ tool TEXT,
4668
+ key TEXT,
4669
+ path TEXT,
4670
+ ok INTEGER,
4671
+ exit_code INTEGER,
4672
+ bytes INTEGER,
4673
+ body TEXT,
4674
+ turn INTEGER NOT NULL,
4675
+ sandbox_bytes INTEGER NOT NULL DEFAULT 0,
4676
+ returned_bytes INTEGER NOT NULL DEFAULT 0,
4677
+ created_at INTEGER NOT NULL,
4678
+ accessed_at INTEGER NOT NULL
4679
+ );
4680
+ CREATE INDEX IF NOT EXISTS idx_events_session_kind_seq ON events(session_id, kind, seq);
4681
+ CREATE INDEX IF NOT EXISTS idx_events_session_kind_key_seq ON events(session_id, kind, key, seq);
4682
+
4683
+ CREATE TABLE IF NOT EXISTS sources (
4684
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
4685
+ session_id TEXT NOT NULL,
4686
+ worktree TEXT NOT NULL,
4687
+ agent TEXT NOT NULL,
4688
+ kind TEXT NOT NULL CHECK (kind IN ('path','content','url')),
4689
+ label TEXT NOT NULL,
4690
+ bytes_total INTEGER NOT NULL,
4691
+ chunk_count INTEGER NOT NULL,
4692
+ created_ts INTEGER NOT NULL,
4693
+ created_at TEXT NOT NULL,
4694
+ accessed_ts INTEGER NOT NULL
4695
+ );
4696
+ CREATE INDEX IF NOT EXISTS idx_sources_accessed ON sources(accessed_ts);
4697
+
4698
+ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
4699
+ source_id UNINDEXED,
4700
+ session_id UNINDEXED,
4701
+ worktree UNINDEXED,
4702
+ agent UNINDEXED,
4703
+ ord UNINDEXED,
4704
+ body,
4705
+ ${FTS_TOKENIZE_V1}
4706
+ );
4707
+
4708
+ CREATE TABLE IF NOT EXISTS meta (
4709
+ key TEXT PRIMARY KEY,
4710
+ value TEXT NOT NULL
4711
+ );
4712
+ `;
4713
+ var DDL_V3 = `
4714
+ CREATE VIRTUAL TABLE chunks_v3 USING fts5(
4715
+ source_id UNINDEXED,
4716
+ session_id UNINDEXED,
4717
+ worktree UNINDEXED,
4718
+ agent UNINDEXED,
4719
+ ord UNINDEXED,
4720
+ body,
4721
+ title,
4722
+ ${FTS_TOKENIZE}
4723
+ );
4724
+ INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body, title)
4725
+ SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
4726
+ DROP TABLE chunks;
4727
+ ALTER TABLE chunks_v3 RENAME TO chunks;
4728
+ `;
4729
+ var DDL_V5 = `
4730
+ CREATE VIRTUAL TABLE line_units USING fts5(
4731
+ body,
4732
+ source_id UNINDEXED,
4733
+ session_id UNINDEXED,
4734
+ ord UNINDEXED,
4735
+ ${FTS_TOKENIZE}
4736
+ );
4737
+ `;
4738
+
4739
+ // src/core/store/db.ts
4740
+ var { existsSync: existsSync2, linkSync, mkdirSync: mkdirSync2, rmSync } = process.getBuiltinModule("node:fs");
4515
4741
 
4516
4742
  // src/core/ops/doctor-config.ts
4517
- import { join as join6 } from "node:path";
4743
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
4744
+ import { join as join7 } from "node:path";
4518
4745
 
4519
4746
  // src/core/ops/detect-v1.ts
4520
- import { existsSync as existsSync3, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
4747
+ import { existsSync as existsSync4, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
4521
4748
  import { tmpdir } from "node:os";
4522
- import { join as join4 } from "node:path";
4749
+ import { join as join5 } from "node:path";
4523
4750
 
4524
4751
  // src/core/ops/host-config.ts
4525
- import { existsSync as existsSync2, readFileSync } from "node:fs";
4526
- import { dirname as dirname2, join as join3 } from "node:path";
4752
+ import { existsSync as existsSync3, readFileSync } from "node:fs";
4753
+ import { dirname as dirname3, join as join4 } from "node:path";
4527
4754
 
4528
4755
  // node_modules/eslint-visitor-keys/lib/visitor-keys.js
4529
4756
  var KEYS2 = {
@@ -6569,7 +6796,7 @@ function parseTOML(code, options) {
6569
6796
  }
6570
6797
 
6571
6798
  // src/core/ops/atomic-file.ts
6572
- import { mkdirSync as mkdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
6799
+ import { mkdirSync as mkdirSync3, renameSync, unlinkSync, writeFileSync } from "node:fs";
6573
6800
  import path2 from "node:path";
6574
6801
  function sleepSync(ms) {
6575
6802
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -6620,7 +6847,7 @@ function removeTmpFile(tmp, opts = {}) {
6620
6847
  }
6621
6848
  }
6622
6849
  function atomicWriteFile(file, text2, opts = {}) {
6623
- mkdirSync2(path2.dirname(file), { recursive: true });
6850
+ mkdirSync3(path2.dirname(file), { recursive: true });
6624
6851
  const tmp = path2.join(path2.dirname(file), `${ATOMIC_TMP_PREFIX}${path2.basename(file)}${ATOMIC_TMP_MARK}${process.pid}`);
6625
6852
  try {
6626
6853
  writeFileSync(tmp, text2);
@@ -6813,14 +7040,14 @@ function scanToml(text2) {
6813
7040
  continue;
6814
7041
  }
6815
7042
  if (!node.resolvedKey.every((seg) => typeof seg === "string")) continue;
6816
- const path9 = node.resolvedKey;
6817
- for (const kv of node.body) addKey(path9, kv);
7043
+ const path15 = node.resolvedKey;
7044
+ for (const kv of node.body) addKey(path15, kv);
6818
7045
  if (node.kind !== "standard") continue;
6819
7046
  const start = lineStartOf(text2, node.range[0]);
6820
7047
  const headEnd = lineEndOf(text2, node.key.range[1]);
6821
7048
  const last2 = node.body[node.body.length - 1];
6822
7049
  tables.push({
6823
- path: path9,
7050
+ path: path15,
6824
7051
  header: text2.slice(start, text2[headEnd - 1] === "\n" ? headEnd - 1 : headEnd),
6825
7052
  start,
6826
7053
  end: last2 === void 0 ? headEnd : lineEndOf(text2, last2.range[1])
@@ -6831,19 +7058,16 @@ function scanToml(text2) {
6831
7058
  function tomlTableSpans(text2) {
6832
7059
  return scanToml(text2).tables;
6833
7060
  }
6834
- function tomlHeaderText(path9) {
6835
- return "[" + path9.map(tomlHeaderKey).join(".") + "]";
6836
- }
6837
- function parseHostConfig(agent, path9, text2, format) {
7061
+ function parseHostConfig(agent, path15, text2, format) {
6838
7062
  try {
6839
7063
  return format === "toml" ? scanToml(text2).value : scanJson(text2, format).value;
6840
7064
  } catch {
6841
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path9, format });
7065
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path15, format });
6842
7066
  }
6843
7067
  }
6844
- function hostConfigValueAt(value, path9) {
7068
+ function hostConfigValueAt(value, path15) {
6845
7069
  let cur = value;
6846
- for (const seg of path9) {
7070
+ for (const seg of path15) {
6847
7071
  if (!isPlainObject(cur)) return void 0;
6848
7072
  cur = cur[seg];
6849
7073
  }
@@ -6876,32 +7100,32 @@ function indentUnit(root, clean) {
6876
7100
  function render(value, unit, base) {
6877
7101
  return JSON.stringify(value, null, unit).split("\n").join("\n" + base);
6878
7102
  }
6879
- function nest(path9, value) {
7103
+ function nest(path15, value) {
6880
7104
  let out2 = value;
6881
- for (let k = path9.length - 1; k >= 0; k -= 1) out2 = { [path9[k]]: out2 };
7105
+ for (let k = path15.length - 1; k >= 0; k -= 1) out2 = { [path15[k]]: out2 };
6882
7106
  return out2;
6883
7107
  }
6884
- function setJsonText(text2, format, path9, value) {
7108
+ function setJsonText(text2, format, path15, value) {
6885
7109
  const doc = scanJson(text2, format);
6886
7110
  const unit = indentUnit(doc.root, doc.clean);
6887
- if (doc.root === null) return render(nest(path9, value), unit, "") + "\n";
7111
+ if (doc.root === null) return render(nest(path15, value), unit, "") + "\n";
6888
7112
  let node = doc.root;
6889
7113
  let depth = 0;
6890
- while (depth < path9.length && node.kind === "object") {
6891
- const hit = node.members.find((m3) => m3.key === path9[depth]);
7114
+ while (depth < path15.length && node.kind === "object") {
7115
+ const hit = node.members.find((m3) => m3.key === path15[depth]);
6892
7116
  if (hit === void 0) break;
6893
7117
  node = hit.node;
6894
7118
  depth += 1;
6895
7119
  }
6896
- if (depth === path9.length) {
7120
+ if (depth === path15.length) {
6897
7121
  return text2.slice(0, node.start) + render(value, unit, lineIndent(doc.clean, node.start)) + text2.slice(node.end);
6898
7122
  }
6899
- if (node.kind !== "object") throw new SyntaxError("not an object at " + path9.slice(0, depth).join("."));
6900
- const rest = nest(path9.slice(depth + 1), value);
7123
+ if (node.kind !== "object") throw new SyntaxError("not an object at " + path15.slice(0, depth).join("."));
7124
+ const rest = nest(path15.slice(depth + 1), value);
6901
7125
  const last2 = node.members[node.members.length - 1];
6902
7126
  if (last2 === void 0) {
6903
7127
  const base2 = lineIndent(doc.clean, node.start);
6904
- const member2 = "\n" + base2 + unit + JSON.stringify(path9[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
7128
+ const member2 = "\n" + base2 + unit + JSON.stringify(path15[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
6905
7129
  return text2.slice(0, node.start + 1) + member2 + text2.slice(node.end - 1);
6906
7130
  }
6907
7131
  const base = lineIndent(doc.clean, last2.keyStart);
@@ -6909,7 +7133,7 @@ function setJsonText(text2, format, path9, value) {
6909
7133
  while (" \r\n".includes(doc.clean[at])) at += 1;
6910
7134
  const trailing = doc.clean[at] === ",";
6911
7135
  const insertAt = trailing ? at + 1 : last2.node.end;
6912
- const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path9[depth]) + ": " + render(rest, unit, base);
7136
+ const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path15[depth]) + ": " + render(rest, unit, base);
6913
7137
  return text2.slice(0, insertAt) + member + text2.slice(insertAt);
6914
7138
  }
6915
7139
  function tomlScalar(v) {
@@ -6927,17 +7151,17 @@ function tomlHeaderKey(seg) {
6927
7151
  }
6928
7152
  return seg;
6929
7153
  }
6930
- function tomlBlock(path9, value) {
6931
- let out2 = "[" + path9.map(tomlHeaderKey).join(".") + "]\n";
7154
+ function tomlBlock(path15, value) {
7155
+ let out2 = "[" + path15.map(tomlHeaderKey).join(".") + "]\n";
6932
7156
  const subs = [];
6933
7157
  for (const [k, v] of Object.entries(value)) {
6934
- if (isPlainObject(v)) subs.push(tomlBlock([...path9, k], v));
7158
+ if (isPlainObject(v)) subs.push(tomlBlock([...path15, k], v));
6935
7159
  else out2 += tomlHeaderKey(k) + " = " + tomlScalar(v) + "\n";
6936
7160
  }
6937
7161
  return [out2, ...subs].join("\n");
6938
7162
  }
6939
- function under(path9, prefix) {
6940
- return path9.length >= prefix.length && prefix.every((seg, k) => path9[k] === seg);
7163
+ function under(path15, prefix) {
7164
+ return path15.length >= prefix.length && prefix.every((seg, k) => path15[k] === seg);
6941
7165
  }
6942
7166
  function keyLineRange(text2, k) {
6943
7167
  const ls = lineStartOf(text2, k.start);
@@ -6954,40 +7178,40 @@ function withValueAt(root, rel, value) {
6954
7178
  else base[rel[0]] = next;
6955
7179
  return base;
6956
7180
  }
6957
- function replaceToml(text2, doc, path9, value) {
6958
- const block2 = value === void 0 ? "" : tomlBlock(path9, value);
6959
- const owned = doc.tables.filter((t2) => under(t2.path, path9));
6960
- const cuts = doc.keys.filter((k) => under(k.full, path9) && !under(k.base, path9)).map((k) => [...keyLineRange(text2, k), ""]);
7181
+ function replaceToml(text2, doc, path15, value) {
7182
+ const block2 = value === void 0 ? "" : tomlBlock(path15, value);
7183
+ const owned = doc.tables.filter((t2) => under(t2.path, path15));
7184
+ const cuts = doc.keys.filter((k) => under(k.full, path15) && !under(k.base, path15)).map((k) => [...keyLineRange(text2, k), ""]);
6961
7185
  owned.forEach((t2, n3) => cuts.push([t2.start, t2.end, n3 === 0 ? block2 : ""]));
6962
7186
  cuts.sort((a2, b3) => b3[0] - a2[0]);
6963
7187
  let out2 = text2;
6964
7188
  for (const [s, e, put] of cuts) out2 = out2.slice(0, s) + put + out2.slice(e);
6965
7189
  if (owned.length > 0 || block2 === "") return out2;
6966
- const sep = out2 === "" ? "" : out2.endsWith("\n\n") ? "" : out2.endsWith("\n") ? "\n" : "\n\n";
6967
- return out2 + sep + block2;
7190
+ const sep2 = out2 === "" ? "" : out2.endsWith("\n\n") ? "" : out2.endsWith("\n") ? "\n" : "\n\n";
7191
+ return out2 + sep2 + block2;
6968
7192
  }
6969
7193
  var tableLike = (v) => v === void 0 || isPlainObject(v);
6970
- function setTomlText(text2, path9, value) {
7194
+ function setTomlText(text2, path15, value) {
6971
7195
  if (value !== void 0 && !isPlainObject(value)) throw new SyntaxError("TOML edits replace a whole table");
6972
7196
  const doc = scanToml(text2);
6973
- const cur = hostConfigValueAt(doc.value, path9);
7197
+ const cur = hostConfigValueAt(doc.value, path15);
6974
7198
  if (sameValue(cur, value)) return text2;
6975
- const inline = doc.keys.find((k) => k.inline && k.full.length < path9.length && under(path9, k.full));
7199
+ const inline = doc.keys.find((k) => k.inline && k.full.length < path15.length && under(path15, k.full));
6976
7200
  if (inline !== void 0) {
6977
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path9.slice(inline.full.length), value);
7201
+ const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path15.slice(inline.full.length), value);
6978
7202
  return replaceToml(text2, doc, inline.full, whole);
6979
7203
  }
6980
7204
  if (isPlainObject(cur) && isPlainObject(value)) {
6981
7205
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
6982
7206
  if (names.every((k) => tableLike(cur[k]) && tableLike(value[k]))) {
6983
7207
  let out2 = text2;
6984
- for (const k of names) out2 = setTomlText(out2, [...path9, k], value[k]);
7208
+ for (const k of names) out2 = setTomlText(out2, [...path15, k], value[k]);
6985
7209
  return out2;
6986
7210
  }
6987
7211
  }
6988
- return replaceToml(text2, doc, path9, value);
7212
+ return replaceToml(text2, doc, path15, value);
6989
7213
  }
6990
- function setText(agent, path9, text2, format, key, value) {
7214
+ function setText(agent, path15, text2, format, key, value) {
6991
7215
  try {
6992
7216
  if (format !== "toml") return setJsonText(text2, format, key, value);
6993
7217
  const out2 = setTomlText(text2, key, value);
@@ -6996,29 +7220,42 @@ function setText(agent, path9, text2, format, key, value) {
6996
7220
  if (!sameValue(landed, value) && !(emptyTable && landed === void 0)) throw new SyntaxError("edit did not land");
6997
7221
  return out2;
6998
7222
  } catch {
6999
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path9, format });
7223
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path15, format });
7000
7224
  }
7001
7225
  }
7002
- function applyEdits(agent, path9, text2, format, wanted) {
7003
- const parsed = parseHostConfig(agent, path9, text2, format);
7226
+ function isNodeCommand(command) {
7227
+ if (typeof command !== "string") return false;
7228
+ let at = -1;
7229
+ for (const sep2 of V1_PATH_SEPS) at = Math.max(at, command.lastIndexOf(sep2));
7230
+ const exe = command.slice(at + 1).toLowerCase();
7231
+ return exe === HOST_NODE_COMMAND || exe === HOST_NODE_COMMAND + EXE_SUFFIX;
7232
+ }
7233
+ function ownMcpValue(agent, node, server) {
7234
+ const mcp = OWN_MCP_ENTRY[agent];
7235
+ if (mcp === void 0) return void 0;
7236
+ const tail = agent === "vscode" ? [WORKSPACE_FOLDER_FLAG, VSCODE_WORKSPACE_VAR] : [];
7237
+ return { ...mcp.fields, [MCP_COMMAND_FIELD]: node, [MCP_ARGS_FIELD]: [server, AGENT_ARG, agent, ...tail] };
7238
+ }
7239
+ function applyEdits(agent, path15, text2, format, wanted) {
7240
+ const parsed = parseHostConfig(agent, path15, text2, format);
7004
7241
  let out2 = text2;
7005
7242
  const edits = [];
7006
7243
  for (const [key, after] of wanted) {
7007
7244
  const before = hostConfigValueAt(parsed, key);
7008
7245
  if (sameValue(before, after)) continue;
7009
- out2 = setText(agent, path9, out2, format, key, after);
7246
+ out2 = setText(agent, path15, out2, format, key, after);
7010
7247
  edits.push({ path: key.join("."), before, after });
7011
7248
  }
7012
7249
  return { text: out2, format, edits };
7013
7250
  }
7014
- function editHostConfigText(agent, path9, text2, format, wanted) {
7015
- return applyEdits(agent, path9, text2, format, wanted);
7251
+ function editHostConfigText(agent, path15, text2, format, wanted) {
7252
+ return applyEdits(agent, path15, text2, format, wanted);
7016
7253
  }
7017
7254
 
7018
7255
  // src/core/ops/detect-v1.ts
7019
7256
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7020
7257
  var keyPath = (...parts) => parts.join(".");
7021
- var finding = (file, path9, reason) => ({ file, path: path9, reason });
7258
+ var finding = (file, path15, reason) => ({ file, path: path15, reason });
7022
7259
  function stripJsonc(text2) {
7023
7260
  let out2 = "";
7024
7261
  let inStr = false;
@@ -7077,6 +7314,21 @@ function readTomlTables(file) {
7077
7314
  return [];
7078
7315
  }
7079
7316
  }
7317
+ function readTomlValue(file) {
7318
+ try {
7319
+ return parseHostConfig("codex", file, readText(file), "toml");
7320
+ } catch {
7321
+ return {};
7322
+ }
7323
+ }
7324
+ function isV2McpTable(v) {
7325
+ if (!isObj(v) || !isNodeCommand(v[MCP_COMMAND_FIELD])) return false;
7326
+ const first = Array.isArray(v[MCP_ARGS_FIELD]) ? v[MCP_ARGS_FIELD][0] : void 0;
7327
+ if (typeof first !== "string") return false;
7328
+ let at = -1;
7329
+ for (const sep2 of V1_PATH_SEPS) at = Math.max(at, first.lastIndexOf(sep2));
7330
+ return first.slice(at + 1) === SERVER_ENTRY_FILE;
7331
+ }
7080
7332
  var listOf = (v) => Array.isArray(v) ? v : [];
7081
7333
  var commandOf = (v) => isObj(v) && typeof v.command === "string" ? v.command : null;
7082
7334
  function nestedCommands(doc) {
@@ -7105,9 +7357,9 @@ function flatCommands(events2, prefix) {
7105
7357
  return out2;
7106
7358
  }
7107
7359
  var isV1Hook = (cmd) => cmd.includes(SERVER_KEY) && (V1_SCRIPT_NAMES.some((name) => cmd.includes(name)) || cmd.includes(V1_HOOK_COMMAND));
7108
- var isCodexScript = (cmd) => cmd.includes(V1_SCRIPT_EXT) && V1_PATH_SEPS.some((sep) => cmd.includes(V1_CODEX_HOOKS_DIR.join(sep) + sep));
7360
+ var isCodexScript = (cmd) => cmd.includes(V1_SCRIPT_EXT) && V1_PATH_SEPS.some((sep2) => cmd.includes(V1_CODEX_HOOKS_DIR.join(sep2) + sep2));
7109
7361
  function dataDir(dir, reason, out2) {
7110
- if (existsSync3(dir)) out2.push(finding(dir, "", reason));
7362
+ if (existsSync4(dir)) out2.push(finding(dir, "", reason));
7111
7363
  }
7112
7364
  function mcpEntry(file, doc, out2) {
7113
7365
  if (isObj(doc) && isObj(doc[MCP_SERVERS_KEY]) && Object.hasOwn(doc[MCP_SERVERS_KEY], SERVER_KEY)) {
@@ -7115,7 +7367,7 @@ function mcpEntry(file, doc, out2) {
7115
7367
  }
7116
7368
  }
7117
7369
  function claudeShapeSettings(agentHome, out2) {
7118
- const file = join4(agentHome, SETTINGS_FILE);
7370
+ const file = join5(agentHome, SETTINGS_FILE);
7119
7371
  const doc = readJson(file);
7120
7372
  for (const c3 of nestedCommands(doc)) {
7121
7373
  if (c3.command.includes(V1_CACHE_HEAL_NAME)) out2.push(finding(file, c3.path, V1_REASON.cacheHealHook));
@@ -7135,46 +7387,49 @@ function v1HookFile(file, out2) {
7135
7387
  function scanClaudeCode(home, agentHome, out2) {
7136
7388
  claudeShapeSettings(agentHome, out2);
7137
7389
  for (const ext of V1_CACHE_HEAL_EXTS) {
7138
- const file = join4(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
7139
- if (existsSync3(file)) out2.push(finding(file, "", V1_REASON.cacheHealFile));
7390
+ const file = join5(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
7391
+ if (existsSync4(file)) out2.push(finding(file, "", V1_REASON.cacheHealFile));
7140
7392
  }
7141
- const userFile = join4(home, CLAUDE_USER_CONFIG_FILE);
7393
+ const userFile = join5(home, CLAUDE_USER_CONFIG_FILE);
7142
7394
  mcpEntry(userFile, readJson(userFile), out2);
7143
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7395
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7144
7396
  }
7145
7397
  function scanCodex(agentHome, out2) {
7146
- const hooksFile = join4(agentHome, HOOKS_JSON_FILE);
7398
+ const hooksFile = join5(agentHome, HOOKS_JSON_FILE);
7147
7399
  for (const c3 of nestedCommands(readJson(hooksFile))) {
7148
7400
  if (c3.command.includes(V1_CODEX_HOOK_COMMAND) || isCodexScript(c3.command)) {
7149
7401
  out2.push(finding(hooksFile, c3.path, V1_REASON.codexHook));
7150
7402
  }
7151
7403
  }
7152
- const tomlFile = join4(agentHome, CONFIG_TOML_FILE);
7404
+ const tomlFile = join5(agentHome, CONFIG_TOML_FILE);
7405
+ const config = readTomlValue(tomlFile);
7153
7406
  for (const span of readTomlTables(tomlFile)) {
7154
- if (tomlHeaderText(span.path).startsWith(V1_TOML_SECTION_PREFIX)) out2.push(finding(tomlFile, span.header.trim(), V1_REASON.codexToml));
7407
+ if (span.path[0] !== V1_TOML_SECTION_ROOT || span.path[1] !== SERVER_KEY) continue;
7408
+ if (span.path.length === 2 && isV2McpTable(hostConfigValueAt(config, span.path))) continue;
7409
+ out2.push(finding(tomlFile, span.header.trim(), V1_REASON.codexToml));
7155
7410
  }
7156
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7411
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7157
7412
  }
7158
7413
  function scanGemini(agentHome, out2) {
7159
- const file = join4(agentHome, SETTINGS_FILE);
7414
+ const file = join5(agentHome, SETTINGS_FILE);
7160
7415
  for (const c3 of nestedCommands(readJson(file))) {
7161
7416
  if (c3.command.includes(SERVER_KEY)) out2.push(finding(file, c3.path, V1_REASON.hook));
7162
7417
  }
7163
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out2);
7418
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out2);
7164
7419
  }
7165
7420
  function scanVscode(agentHome, project, out2) {
7166
7421
  if (project !== void 0) {
7167
- v1HookFile(join4(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out2);
7168
- const mcpFile = join4(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
7422
+ v1HookFile(join5(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out2);
7423
+ const mcpFile = join5(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
7169
7424
  const doc = readJson(mcpFile);
7170
7425
  const servers = isObj(doc) && isObj(doc[VSCODE_MCP_SERVERS_KEY]) ? doc[VSCODE_MCP_SERVERS_KEY] : {};
7171
7426
  const entry2 = Object.hasOwn(servers, SERVER_KEY) ? servers[SERVER_KEY] : void 0;
7172
7427
  if (isObj(entry2) && (entry2.command === V1_BIN_COMMAND || listOf(entry2.args).some((a2) => a2 === V1_BIN_COMMAND))) {
7173
7428
  out2.push(finding(mcpFile, keyPath(VSCODE_MCP_SERVERS_KEY, SERVER_KEY), V1_REASON.vscodeMcp));
7174
7429
  }
7175
- dataDir(join4(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out2);
7430
+ dataDir(join5(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out2);
7176
7431
  }
7177
- dataDir(join4(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out2);
7432
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out2);
7178
7433
  }
7179
7434
  function jsonFiles(dir) {
7180
7435
  try {
@@ -7184,10 +7439,10 @@ function jsonFiles(dir) {
7184
7439
  }
7185
7440
  }
7186
7441
  function scanKiro(agentHome, project, out2) {
7187
- const agentsDir = join4(agentHome, KIRO_AGENTS_DIR);
7188
- const defaultFile = join4(agentHome, ...KIRO_AGENT_FILE);
7442
+ const agentsDir = join5(agentHome, KIRO_AGENTS_DIR);
7443
+ const defaultFile = join5(agentHome, ...KIRO_AGENT_FILE);
7189
7444
  for (const name of jsonFiles(agentsDir)) {
7190
- const file = join4(agentsDir, name);
7445
+ const file = join5(agentsDir, name);
7191
7446
  const doc = readJson(file);
7192
7447
  if (isObj(doc) && doc[KIRO_AGENT_NAME_KEY] === SERVER_KEY) {
7193
7448
  out2.push(finding(file, "", V1_REASON.kiroAgentFile));
@@ -7198,25 +7453,25 @@ function scanKiro(agentHome, project, out2) {
7198
7453
  if (isV1Hook(c3.command)) out2.push(finding(file, c3.path, V1_REASON.kiroHook));
7199
7454
  }
7200
7455
  }
7201
- const steeringDocs = [join4(agentHome, ...KIRO_STEERING_FILE)];
7202
- if (project !== void 0) steeringDocs.push(join4(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
7456
+ const steeringDocs = [join5(agentHome, ...KIRO_STEERING_FILE)];
7457
+ if (project !== void 0) steeringDocs.push(join5(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
7203
7458
  for (const file of steeringDocs) {
7204
- if (existsSync3(file)) out2.push(finding(file, "", V1_REASON.kiroSteering));
7459
+ if (existsSync4(file)) out2.push(finding(file, "", V1_REASON.kiroSteering));
7205
7460
  }
7206
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7461
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7207
7462
  }
7208
7463
  function scanPi(piAgentDir, agentHome, out2) {
7209
- const file = join4(piAgentDir, SETTINGS_FILE);
7464
+ const file = join5(piAgentDir, SETTINGS_FILE);
7210
7465
  const doc = readJson(file);
7211
7466
  listOf(isObj(doc) ? doc[PI_PACKAGES_KEY] : void 0).forEach((pkg, i2) => {
7212
7467
  const spec = isObj(pkg) ? pkg[PI_PACKAGE_SOURCE_KEY] : pkg;
7213
7468
  if (spec === V1_PI_PACKAGE) out2.push(finding(file, keyPath(PI_PACKAGES_KEY, i2), V1_REASON.piNpm));
7214
7469
  });
7215
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7470
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7216
7471
  }
7217
7472
  function scanOpencode(agentHome, out2) {
7218
7473
  for (const name of OPENCODE_CONFIG_FILES) {
7219
- const file = join4(agentHome, name);
7474
+ const file = join5(agentHome, name);
7220
7475
  const doc = readJson(file);
7221
7476
  if (!isObj(doc) || !Array.isArray(doc[OPENCODE_PLUGIN_KEY])) continue;
7222
7477
  doc[OPENCODE_PLUGIN_KEY].forEach((spec, i2) => {
@@ -7226,13 +7481,13 @@ function scanOpencode(agentHome, out2) {
7226
7481
  }
7227
7482
  }
7228
7483
  function scanZcode(agentHome, out2) {
7229
- const configFile = join4(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
7484
+ const configFile = join5(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
7230
7485
  const config = readJson(configFile);
7231
7486
  const events2 = isObj(config) && isObj(config[HOOKS_KEY]) ? config[HOOKS_KEY][ZCODE_EVENTS_KEY] : void 0;
7232
7487
  for (const c3 of flatCommands(events2, [HOOKS_KEY, ZCODE_EVENTS_KEY])) {
7233
7488
  if (c3.command.includes(V1_HOOK_COMMAND)) out2.push(finding(configFile, c3.path, V1_REASON.zcodeHook));
7234
7489
  }
7235
- const hooksFile = join4(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
7490
+ const hooksFile = join5(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
7236
7491
  for (const c3 of nestedCommands(readJson(hooksFile))) {
7237
7492
  if (c3.command.includes(V1_HOOK_COMMAND)) out2.push(finding(hooksFile, c3.path, V1_REASON.zcodeHook));
7238
7493
  }
@@ -7256,14 +7511,14 @@ function firstTmpMatch(dir) {
7256
7511
  }
7257
7512
  }
7258
7513
  function scanAll(home, tmp, out2) {
7259
- const root = join4(home, DATA_ROOT.slice(1));
7260
- for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join4(root, name), V1_REASON.dataRoot, out2);
7514
+ const root = join5(home, DATA_ROOT.slice(1));
7515
+ for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join5(root, name), V1_REASON.dataRoot, out2);
7261
7516
  if (firstTmpMatch(tmp) !== null) out2.push(finding(tmp, V1_TMP_PREFIX + "*", V1_REASON.tmpFile));
7262
7517
  }
7263
7518
  function detectV1(agent, home, scope = {}) {
7264
7519
  const out2 = [];
7265
7520
  const project = scope.project;
7266
- const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join4(home, ...AGENT_HOME_DIR[agent]);
7521
+ const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "codex" && scope.codexDir !== void 0 ? scope.codexDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join5(home, ...AGENT_HOME_DIR[agent]);
7267
7522
  switch (agent) {
7268
7523
  case "claude-code":
7269
7524
  scanClaudeCode(home, agentHome, out2);
@@ -7276,11 +7531,11 @@ function detectV1(agent, home, scope = {}) {
7276
7531
  break;
7277
7532
  case "qwen":
7278
7533
  claudeShapeSettings(agentHome, out2);
7279
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7534
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7280
7535
  break;
7281
7536
  case "copilot-cli":
7282
- v1HookFile(join4(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out2);
7283
- dataDir(join4(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7537
+ v1HookFile(join5(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out2);
7538
+ dataDir(join5(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out2);
7284
7539
  break;
7285
7540
  case "vscode":
7286
7541
  scanVscode(agentHome, project, out2);
@@ -7289,7 +7544,7 @@ function detectV1(agent, home, scope = {}) {
7289
7544
  scanKiro(agentHome, project, out2);
7290
7545
  break;
7291
7546
  case "pi":
7292
- scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join4(agentHome, PI_AGENT_DIR), agentHome, out2);
7547
+ scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join5(agentHome, PI_AGENT_DIR), agentHome, out2);
7293
7548
  break;
7294
7549
  // D-WIN-PIDIR-1: empty is unset
7295
7550
  case "opencode":
@@ -7304,8 +7559,8 @@ function detectV1(agent, home, scope = {}) {
7304
7559
  }
7305
7560
 
7306
7561
  // src/core/ops/plugin-root.ts
7307
- import { existsSync as existsSync4, readdirSync as readdirSync3, realpathSync as realpathSync2 } from "node:fs";
7308
- import { dirname as dirname3, isAbsolute, join as join5 } from "node:path";
7562
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
7563
+ import { dirname as dirname4, isAbsolute, join as join6, sep } from "node:path";
7309
7564
  import { fileURLToPath } from "node:url";
7310
7565
 
7311
7566
  // src/core/ops/doctor-config.ts
@@ -7318,6 +7573,17 @@ function composeMatcher(row, event) {
7318
7573
  if (event === POST_TOOL_USE && hasReplace(row)) alts.push(MCP_ANY_MATCH);
7319
7574
  return MATCHER_OPEN + alts.join(MATCHER_ALT) + MATCHER_CLOSE;
7320
7575
  }
7576
+ var CODEX_PLUGIN_KEY = `${SERVER_KEY}@${SERVER_KEY}`;
7577
+
7578
+ // src/core/ops/doctor-issue.ts
7579
+ function formUrl(title, summary) {
7580
+ const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
7581
+ const full = `${base}&summary=${encodeURIComponent(summary)}`;
7582
+ return full.length < ISSUE_URL_MAX ? full : base;
7583
+ }
7584
+
7585
+ // src/setup/registry.ts
7586
+ import path3 from "node:path";
7321
7587
 
7322
7588
  // src/setup/hook-shapes.ts
7323
7589
  var MS_PER_SECOND = 1e3;
@@ -7394,7 +7660,6 @@ function configEdits(c3) {
7394
7660
  }
7395
7661
  var COMMAND_SKILLS = Object.freeze(["ctx-doctor", "ctx-stats", "ctx-upgrade"]);
7396
7662
  var SKILL_FILE = "SKILL.md";
7397
- var OPENCODE_PLUGIN = ["opencode", "plugin.js"];
7398
7663
  var CODEX_CONFIG_FILE = "config.toml";
7399
7664
  var CODEX_HOME_ENV2 = "CODEX_HOME";
7400
7665
  var CODEX_DIR = ".codex";
@@ -7438,7 +7703,7 @@ function extensionPlugin(bin, id) {
7438
7703
  };
7439
7704
  }
7440
7705
  var NATIVE_PLUGIN = {
7441
- codex: { bin: "codex", args: ["plugin", "list"], plugin: PLUGIN_ID, hooksVia: ".codex-plugin", skillsVia: path3.join("codex", SKILLS_DIR_NAME), format: "table" },
7706
+ codex: { bin: "codex", args: ["plugin", "list"], plugin: PLUGIN_ID, hooksVia: ".codex-plugin", skillsVia: path3.join("codex", SKILLS_DIR_NAME), format: "table", hookTrust: true },
7442
7707
  qwen: extensionPlugin("qwen", "qwen"),
7443
7708
  gemini: extensionPlugin("gemini", "gemini")
7444
7709
  };
@@ -7447,7 +7712,7 @@ function serverCmd(ctx, id) {
7447
7712
  }
7448
7713
  function hookCommandString(row) {
7449
7714
  const [node, file, flag, id] = row.hookCommand ?? [];
7450
- return `"${node}" "${file}" ${flag} ${id}`;
7715
+ return `${node === HOST_NODE_COMMAND ? node : `"${node}"`} "${file}" ${flag} ${id}`;
7451
7716
  }
7452
7717
  function golden(row, home) {
7453
7718
  const shell = row.nativeTools.shell?.[0];
@@ -7459,16 +7724,14 @@ function golden(row, home) {
7459
7724
  tool_input: { command: "true" }
7460
7725
  };
7461
7726
  }
7462
- var VSCODE_WORKSPACE_VAR = "${workspaceFolder}";
7463
7727
  function configFor(ctx, id) {
7464
7728
  const [node, server, flag, agent] = serverCmd(ctx, id);
7465
7729
  const own2 = OWN_MCP_ENTRY[id];
7466
7730
  if (own2) {
7467
7731
  const file = id === "vscode" ? ownMcpFileOf(id, own2.file, ctx.env, ctx.home) : agentPath(ctx, id, own2.file);
7468
7732
  const format = file.endsWith(".toml") ? "toml" : id === "vscode" ? "jsonc" : "json";
7469
- const args = id === "vscode" ? [server, flag, agent, WORKSPACE_FOLDER_FLAG, VSCODE_WORKSPACE_VAR] : [server, flag, agent];
7470
7733
  const also = own2.also?.map(([k, v]) => [k, v]);
7471
- return { file, format, key: own2.key, value: { ...own2.fields, command: node, args }, ...also ? { also } : {} };
7734
+ return { file, format, key: own2.key, value: ownMcpValue(id, node, server), ...also ? { also } : {} };
7472
7735
  }
7473
7736
  if (id === "opencode") {
7474
7737
  return {
@@ -7502,7 +7765,7 @@ function cliFor(ctx, id) {
7502
7765
  function copyFor(ctx, id) {
7503
7766
  if (id !== "claude-code") return void 0;
7504
7767
  const file = path3.join(claudeDirOf(ctx.env, ctx.home), HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE);
7505
- return { host: "Claude Code", bin: "claude", plugin: PLUGIN_ID, file, refresh: ["plugin", "update", PLUGIN_ID] };
7768
+ return { host: "Claude Code", bin: "claude", plugin: PLUGIN_ID, file, refresh: ["plugin", "update", PLUGIN_ID], enable: ["plugin", "enable", PLUGIN_ID] };
7506
7769
  }
7507
7770
  var LIST = {
7508
7771
  "claude-code": { bin: "claude", args: ["plugin", "list"] },
@@ -7545,7 +7808,7 @@ function hookInstallFor(ctx, row, command) {
7545
7808
  kind: "plugin-list",
7546
7809
  file: path3.join(opencodeDirOf(ctx.env, ctx.home), OPENCODE_BASE_CONFIG_FILE),
7547
7810
  key: ["plugin"],
7548
- entry: path3.join(ctx.pkgDir, ...OPENCODE_PLUGIN)
7811
+ entry: ctx.pkgDir
7549
7812
  };
7550
7813
  }
7551
7814
  return { kind: "package", via: ch.path };
@@ -7571,11 +7834,15 @@ function buildRegistry(ctx) {
7571
7834
  const id = row.id;
7572
7835
  const config = configFor(ctx, id);
7573
7836
  const hookFiles = hookFilesFor(ctx, id);
7574
- const hookCommand = [process.execPath, path3.join(ctx.pkgDir, HOOK_BUNDLE), AGENT_FLAG, id];
7575
- const command = `"${hookCommand[0]}" "${hookCommand[1]}" ${AGENT_FLAG} ${id}`;
7837
+ const runCommand2 = [process.execPath, path3.join(ctx.pkgDir, HOOK_BUNDLE), AGENT_FLAG, id];
7838
+ const bareNode = id === "codex" && (ctx.platform ?? process.platform) === "win32";
7839
+ const hookCommand = bareNode ? [HOST_NODE_COMMAND, ...runCommand2.slice(1)] : runCommand2;
7840
+ const command = `${bareNode ? HOST_NODE_COMMAND : `"${hookCommand[0]}"`} "${hookCommand[1]}" ${AGENT_FLAG} ${id}`;
7576
7841
  const hookInstall = hookInstallFor(ctx, getAdapter(id), command);
7577
7842
  const skillInstall = skillInstallFor(ctx, row);
7843
+ const copilotSettings = id === "copilot-cli" ? agentPath(ctx, id, [COPILOT_DIR, "settings.json"]) : void 0;
7578
7844
  const writes = [
7845
+ ...copilotSettings ? [copilotSettings] : [],
7579
7846
  ...config ? [config.file] : [],
7580
7847
  ...hookFiles.map((h2) => h2.file),
7581
7848
  ...hookInstall.kind === "package" ? [] : [hookInstall.file],
@@ -7592,10 +7859,11 @@ function buildRegistry(ctx) {
7592
7859
  hookFiles,
7593
7860
  hookInstall,
7594
7861
  skillInstall,
7595
- hookRunCommand: hookCommand,
7862
+ hookRunCommand: runCommand2,
7596
7863
  allowedWrites: [...new Set(writes.map((f2) => path3.resolve(f2)))],
7597
7864
  goldenPayload: golden(row, ctx.home)
7598
7865
  };
7866
+ if (copilotSettings) out2.copilotSettings = copilotSettings;
7599
7867
  if (row.installMode !== "in-process") out2.hookCommand = hookCommand;
7600
7868
  const copy = copyFor(ctx, id);
7601
7869
  if (copy) out2.copy = copy;
@@ -7611,20 +7879,354 @@ function assertWritable(row, file) {
7611
7879
  }
7612
7880
  }
7613
7881
 
7882
+ // src/setup/gemini-gate.ts
7883
+ import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7884
+ import path4 from "node:path";
7885
+ var GEMINI_DIR = ".gemini";
7886
+ var SETTINGS_FILE2 = "settings.json";
7887
+ var SYSTEM_PATH_ENV = "GEMINI_CLI_SYSTEM_SETTINGS_PATH";
7888
+ var OWN_AGENT = "gemini";
7889
+ function systemSettingsPath(env) {
7890
+ const set2 = env[SYSTEM_PATH_ENV];
7891
+ if (set2) return set2;
7892
+ if (process.platform === "darwin") return "/Library/Application Support/GeminiCli/settings.json";
7893
+ if (process.platform === "win32") return "C:\\ProgramData\\gemini-cli\\settings.json";
7894
+ return "/etc/gemini-cli/settings.json";
7895
+ }
7896
+ function load(file) {
7897
+ if (!existsSync8(file)) return void 0;
7898
+ try {
7899
+ return { file, doc: parseHostConfig(OWN_AGENT, file, hostText(readFileSync5(file, "utf8")), "jsonc") };
7900
+ } catch {
7901
+ return void 0;
7902
+ }
7903
+ }
7904
+ function sources(env, home, cwd) {
7905
+ return [path4.join(home, GEMINI_DIR, SETTINGS_FILE2), path4.join(cwd, GEMINI_DIR, SETTINGS_FILE2), systemSettingsPath(env)].map(load).filter((s) => s !== void 0);
7906
+ }
7907
+ function ownHookEntry(entry2) {
7908
+ return typeof entry2 === "string" && entry2.includes(HOOK_BUNDLE) && entry2.includes(`${AGENT_FLAG} ${OWN_AGENT}`);
7909
+ }
7910
+ function geminiSettingsGate(env, home, cwd) {
7911
+ const srcs = sources(env, home, cwd);
7912
+ for (const s of srcs) {
7913
+ if (hostConfigValueAt(s.doc, ["admin", "extensions", "enabled"]) === false) {
7914
+ return `${s.file}: admin.extensions.enabled is false, so gemini loads no extension and runs no context-mode hook; an administrator must change it`;
7915
+ }
7916
+ }
7917
+ let winner;
7918
+ for (const s of srcs) if (typeof hostConfigValueAt(s.doc, ["hooksConfig", "enabled"]) === "boolean") winner = s;
7919
+ if (winner && hostConfigValueAt(winner.doc, ["hooksConfig", "enabled"]) === false) {
7920
+ return `${winner.file}: hooksConfig.enabled is false, so gemini runs no hook; set it to true`;
7921
+ }
7922
+ for (const s of srcs) {
7923
+ const off = hostConfigValueAt(s.doc, ["hooksConfig", "disabled"]);
7924
+ const own2 = Array.isArray(off) ? off.find(ownHookEntry) : void 0;
7925
+ if (own2 !== void 0) return `${s.file}: hooksConfig.disabled lists the context-mode hook (${own2}), so gemini skips it; remove that entry`;
7926
+ }
7927
+ return void 0;
7928
+ }
7929
+
7930
+ // src/setup/zcode-gate.ts
7931
+ import { existsSync as existsSync9, readFileSync as readFileSync6 } from "node:fs";
7932
+ import path5 from "node:path";
7933
+ var OWN_AGENT2 = "zcode";
7934
+ var EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "Stop"];
7935
+ var HOOK_TYPES = ["process", "command"];
7936
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7937
+ var isPositive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
7938
+ var isText = (v) => typeof v === "string" && v.length > 0;
7939
+ var isTexts = (v) => Array.isArray(v) && v.every((x2) => typeof x2 === "string");
7940
+ function field(o2, at, name, ok, why) {
7941
+ const v = o2[name];
7942
+ return v === void 0 || ok(v) ? void 0 : { key: `${at}.${name}`, why };
7943
+ }
7944
+ function section(doc, name) {
7945
+ const v = doc[name];
7946
+ if (v === void 0) return {};
7947
+ return isObj2(v) ? { o: v } : { bad: { key: name, why: "must be an object" } };
7948
+ }
7949
+ var oneOf = (allowed) => (v) => allowed.includes(v);
7950
+ var isBool = (v) => typeof v === "boolean";
7951
+ function firstBad(...checks) {
7952
+ return checks.find((c3) => c3 !== void 0);
7953
+ }
7954
+ function simple(doc, name, rules) {
7955
+ const s = section(doc, name);
7956
+ if (s.bad) return s.bad;
7957
+ if (!s.o) return void 0;
7958
+ return firstBad(...rules.map(([k, ok, why]) => field(s.o, name, k, ok, why)));
7959
+ }
7960
+ function hookBad(h2, at) {
7961
+ if (!isObj2(h2)) return { key: at, why: "must be an object" };
7962
+ if (!HOOK_TYPES.includes(h2.type)) return { key: `${at}.type`, why: "must be process or command" };
7963
+ return firstBad(
7964
+ isText(h2.command) ? void 0 : { key: `${at}.command`, why: "must be a non-empty string" },
7965
+ field(h2, at, "enabled", isBool, "must be a boolean"),
7966
+ field(h2, at, "timeoutMs", isPositive, "must be a positive number"),
7967
+ field(h2, at, "timeout", isPositive, "must be a positive number"),
7968
+ field(h2, at, "async", isBool, "must be a boolean"),
7969
+ field(h2, at, "args", isTexts, "must be an array of strings"),
7970
+ field(h2, at, "statusMessage", isText, "must be a non-empty string")
7971
+ );
7972
+ }
7973
+ var GROUP_KEYS = ["matcher", "hooks"];
7974
+ function groupBad(g2, at) {
7975
+ if (!isObj2(g2)) return { key: at, why: "must be an object" };
7976
+ const extra = Object.keys(g2).find((k) => !GROUP_KEYS.includes(k));
7977
+ if (extra !== void 0) return { key: at, why: `has the unknown key ${extra}` };
7978
+ if (!Array.isArray(g2.hooks) || g2.hooks.length === 0) return { key: at, why: "needs a non-empty hooks array" };
7979
+ const m3 = field(g2, at, "matcher", isText, "must be a non-empty string");
7980
+ if (m3) return m3;
7981
+ for (let i2 = 0; i2 < g2.hooks.length; i2++) {
7982
+ const b3 = hookBad(g2.hooks[i2], `${at}.hooks[${i2}]`);
7983
+ if (b3) return b3;
7984
+ }
7985
+ return void 0;
7986
+ }
7987
+ var HOOK_ROOT_KEYS = ["enabled", "timeoutMs", "maxOutputBytes", "events"];
7988
+ function hooksBad(doc) {
7989
+ const s = section(doc, "hooks");
7990
+ if (s.bad) return s.bad;
7991
+ const h2 = s.o;
7992
+ if (!h2) return void 0;
7993
+ const extra = Object.keys(h2).find((k) => !HOOK_ROOT_KEYS.includes(k));
7994
+ if (extra !== void 0) return { key: `hooks.${extra}`, why: "is not a hooks key" };
7995
+ const root = firstBad(field(h2, "hooks", "enabled", isBool, "must be a boolean"), field(h2, "hooks", "timeoutMs", isPositive, "must be a positive number"), field(h2, "hooks", "maxOutputBytes", isPositive, "must be a positive number"));
7996
+ if (root || h2.events === void 0) return root;
7997
+ if (!isObj2(h2.events)) return { key: "hooks.events", why: "must be an object" };
7998
+ for (const [ev, groups] of Object.entries(h2.events)) {
7999
+ if (!EVENTS.includes(ev)) return { key: `hooks.events.${ev}`, why: "is not a zcode hook event" };
8000
+ if (!Array.isArray(groups)) return { key: `hooks.events.${ev}`, why: "must be an array of matcher groups" };
8001
+ for (let i2 = 0; i2 < groups.length; i2++) {
8002
+ const b3 = groupBad(groups[i2], `hooks.events.${ev}[${i2}]`);
8003
+ if (b3) return b3;
8004
+ }
8005
+ }
8006
+ return void 0;
8007
+ }
8008
+ function zcodeSchemaBad(doc) {
8009
+ if (!isObj2(doc)) return { key: "(root)", why: "must be a JSON object" };
8010
+ return firstBad(
8011
+ simple(doc, "modelStream", [["idleTimeoutMs", isPositive, "must be a positive number"]]),
8012
+ simple(doc, "permission", [["mode", oneOf(["plan", "build", "edit", "yolo", "guarded", "auto"]), "must be plan, build, edit, yolo, guarded or auto"], ["allowedTools", isTexts, "must be an array of strings"], ["disallowedTools", isTexts, "must be an array of strings"], ["autoApproveHighRisk", isBool, "must be a boolean"], ["allowMediumRiskInAuto", isBool, "must be a boolean"]]),
8013
+ simple(doc, "features", ["compact", "rewind", "subagent", "memory", "skill", "mcp"].map((k) => [k, isBool, "must be a boolean"])),
8014
+ simple(doc, "memory", [["use", isBool, "must be a boolean"]]),
8015
+ simple(doc, "logging", [["level", oneOf(["debug", "info", "warn", "error"]), "must be debug, info, warn or error"], ["format", oneOf(["text", "json"]), "must be text or json"]]),
8016
+ simple(doc, "ui", [["locale", oneOf(["auto", "en-US", "zh-CN"]), "must be auto, en-US or zh-CN"], ["theme", oneOf(["auto", "dark", "light"]), "must be auto, dark or light"]]),
8017
+ simple(doc, "toolConcurrency", [["maxConcurrency", isPositive, "must be a positive number"]]),
8018
+ hooksBad(doc)
8019
+ );
8020
+ }
8021
+ function zcodeConfigGate(home) {
8022
+ const file = path5.join(home, ".zcode", "cli", "config.json");
8023
+ if (!existsSync9(file)) return void 0;
8024
+ let doc;
8025
+ try {
8026
+ doc = parseHostConfig(OWN_AGENT2, file, hostText(readFileSync6(file, "utf8")), "json");
8027
+ } catch {
8028
+ return void 0;
8029
+ }
8030
+ const bad = zcodeSchemaBad(doc);
8031
+ if (!bad) return void 0;
8032
+ return `${file}: ${bad.key} ${bad.why}, so zcode drops the whole config.json and runs no context-mode hook; fix or remove that key`;
8033
+ }
8034
+
8035
+ // src/setup/pi-gate.ts
8036
+ import { existsSync as existsSync10, readFileSync as readFileSync7, realpathSync as realpathSync4 } from "node:fs";
8037
+ import path6 from "node:path";
8038
+ var OWN_FILE = "pi/index.js";
8039
+ var EXTENSIONS_KEY = "extensions";
8040
+ var PROJECT_DIR = ".pi";
8041
+ var TRUST_FILE = "trust.json";
8042
+ var ALWAYS = "always";
8043
+ var SOURCE_PREFIXES = ["npm:", "git:"];
8044
+ function load2(file) {
8045
+ if (!existsSync10(file)) return void 0;
8046
+ try {
8047
+ return { file, doc: parseHostConfig("pi", file, hostText(readFileSync7(file, "utf8")), "json") };
8048
+ } catch {
8049
+ return void 0;
8050
+ }
8051
+ }
8052
+ var real = (p3) => {
8053
+ try {
8054
+ return realpathSync4(p3);
8055
+ } catch {
8056
+ return path6.resolve(p3);
8057
+ }
8058
+ };
8059
+ function sourceName(source) {
8060
+ let s = source;
8061
+ for (const p3 of SOURCE_PREFIXES) if (s.startsWith(p3)) s = s.slice(p3.length);
8062
+ const last2 = s.split("/").pop() ?? "";
8063
+ const at = last2.indexOf("@", 1);
8064
+ const name = at > 0 ? last2.slice(0, at) : last2;
8065
+ return name.endsWith(".git") ? name.slice(0, -4) : name;
8066
+ }
8067
+ function isOwn(source, pkgDir) {
8068
+ if (typeof source !== "string") return false;
8069
+ return real(source) === real(pkgDir) || sourceName(source) === SERVER_KEY;
8070
+ }
8071
+ function ownEntries(src, pkgDir) {
8072
+ const list2 = hostConfigValueAt(src.doc, [PI_PACKAGES_KEY]);
8073
+ if (!Array.isArray(list2)) return [];
8074
+ const out2 = [];
8075
+ for (const e of list2) {
8076
+ const obj = typeof e === "object" && e !== null && !Array.isArray(e) ? e : void 0;
8077
+ if (!isOwn(obj ? obj[PI_PACKAGE_SOURCE_KEY] : e, pkgDir)) continue;
8078
+ const ext = obj?.[EXTENSIONS_KEY];
8079
+ out2.push({ source: src, patterns: Array.isArray(ext) ? ext.filter((x2) => typeof x2 === "string") : void 0 });
8080
+ }
8081
+ return out2;
8082
+ }
8083
+ function matchesAny(patterns, pkgDir) {
8084
+ const abs = path6.join(pkgDir, OWN_FILE).split(path6.sep).join("/");
8085
+ return patterns.some((p3) => {
8086
+ const g2 = p3.startsWith("./") ? p3.slice(2) : p3;
8087
+ return [OWN_FILE, path6.posix.basename(OWN_FILE), abs].some((c3) => path6.posix.matchesGlob(c3, g2));
8088
+ });
8089
+ }
8090
+ var exactAny = (patterns, pkgDir) => {
8091
+ const abs = path6.join(pkgDir, OWN_FILE).split(path6.sep).join("/");
8092
+ return patterns.some((p3) => {
8093
+ const g2 = p3.startsWith("./") ? p3.slice(2) : p3;
8094
+ return g2 === OWN_FILE || g2 === abs;
8095
+ });
8096
+ };
8097
+ function loads(patterns, pkgDir) {
8098
+ if (patterns.length === 0) return false;
8099
+ const by = (c3) => patterns.filter((p3) => p3.startsWith(c3)).map((p3) => p3.slice(1));
8100
+ const includes = patterns.filter((p3) => !"+-!".includes(p3[0] ?? ""));
8101
+ let on = includes.length === 0 || matchesAny(includes, pkgDir);
8102
+ if (matchesAny(by("!"), pkgDir)) on = false;
8103
+ if (exactAny(by("+"), pkgDir)) on = true;
8104
+ if (exactAny(by("-"), pkgDir)) on = false;
8105
+ return on;
8106
+ }
8107
+ function projectTrusted(agentDir, userDoc, cwd) {
8108
+ const trust = load2(path6.join(agentDir, TRUST_FILE));
8109
+ const entries = /* @__PURE__ */ new Map();
8110
+ if (trust && typeof trust.doc === "object" && trust.doc !== null) for (const [k, v] of Object.entries(trust.doc)) entries.set(real(k), v);
8111
+ let dir = real(cwd);
8112
+ for (; ; ) {
8113
+ const v = entries.get(dir);
8114
+ if (v === true || v === false) return v;
8115
+ const up = path6.dirname(dir);
8116
+ if (up === dir) break;
8117
+ dir = up;
8118
+ }
8119
+ return hostConfigValueAt(userDoc, ["defaultProjectTrust"]) === ALWAYS;
8120
+ }
8121
+ function piSettingsGate(env, home, pkgDir, cwd) {
8122
+ const agentDir = piAgentDirOf(env, home);
8123
+ const user = load2(path6.join(agentDir, SETTINGS_FILE));
8124
+ const project = load2(path6.join(cwd, PROJECT_DIR, SETTINGS_FILE));
8125
+ const projectOwn = project && projectTrusted(agentDir, user?.doc, cwd) ? ownEntries(project, pkgDir) : [];
8126
+ const effective = projectOwn.length ? projectOwn : user ? ownEntries(user, pkgDir) : [];
8127
+ for (const e of effective) {
8128
+ if (e.patterns !== void 0 && !loads(e.patterns, pkgDir)) {
8129
+ return `${e.source.file}: the packages[] entry for context-mode has extensions ${JSON.stringify(e.patterns)}, which leaves out ${OWN_FILE}, so pi loads no hook; remove the "extensions" filter from that entry`;
8130
+ }
8131
+ }
8132
+ return void 0;
8133
+ }
8134
+
8135
+ // src/setup/vscode-gate.ts
8136
+ import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
8137
+ import path7 from "node:path";
8138
+ var SETTINGS_FILE3 = "settings.json";
8139
+ var WORKSPACE_DIR = ".vscode";
8140
+ var USE_HOOKS_KEY = "chat.useHooks";
8141
+ var LOCATIONS_KEY = "chat.hookFilesLocations";
8142
+ var OWN_LOCATION = "~/.copilot/hooks";
8143
+ var MANAGED_KEYS = ["allowManagedHooksOnly", "strictPluginOnlyCustomization"];
8144
+ function load3(file) {
8145
+ if (!existsSync11(file)) return void 0;
8146
+ try {
8147
+ return { file, doc: parseHostConfig("vscode", file, hostText(readFileSync8(file, "utf8")), "jsonc") };
8148
+ } catch {
8149
+ return void 0;
8150
+ }
8151
+ }
8152
+ function managedSettingsPath(env) {
8153
+ if (process.platform === "darwin") return "/Library/Application Support/GitHubCopilot/managed-settings.json";
8154
+ if (process.platform === "win32") return path7.join(env.ProgramFiles || "C:\\Program Files", "GitHubCopilot", "managed-settings.json");
8155
+ return "/etc/github-copilot/managed-settings.json";
8156
+ }
8157
+ function vscodeSettingsGate(env, home, cwd, managedFile = managedSettingsPath(env)) {
8158
+ const managed = load3(managedFile);
8159
+ if (managed) {
8160
+ for (const key of MANAGED_KEYS) {
8161
+ if (hostConfigValueAt(managed.doc, [key]) === true) {
8162
+ return `${managed.file}: ${key} is true, so VS Code runs no user hook file; an administrator must change it`;
8163
+ }
8164
+ }
8165
+ }
8166
+ const srcs = [path7.join(vscodeUserDirOf(env, home), SETTINGS_FILE3), path7.join(cwd, WORKSPACE_DIR, SETTINGS_FILE3)].map(load3).filter((s) => s !== void 0);
8167
+ let hooks;
8168
+ let locations;
8169
+ for (const s of srcs) {
8170
+ if (typeof hostConfigValueAt(s.doc, [USE_HOOKS_KEY]) === "boolean") hooks = s;
8171
+ const v = hostConfigValueAt(s.doc, [LOCATIONS_KEY]);
8172
+ if (typeof v === "object" && v !== null && !Array.isArray(v)) locations = s;
8173
+ }
8174
+ if (hooks && hostConfigValueAt(hooks.doc, [USE_HOOKS_KEY]) === false) {
8175
+ return `${hooks.file}: ${USE_HOOKS_KEY} is false, so VS Code runs no hook; set it to true`;
8176
+ }
8177
+ if (locations) {
8178
+ const v = hostConfigValueAt(locations.doc, [LOCATIONS_KEY]);
8179
+ if (v[OWN_LOCATION] !== true) {
8180
+ return `${locations.file}: ${LOCATIONS_KEY} leaves out "${OWN_LOCATION}", so VS Code does not read the context-mode hook file; add "${OWN_LOCATION}": true`;
8181
+ }
8182
+ }
8183
+ return void 0;
8184
+ }
8185
+
8186
+ // src/setup/qwen-gate.ts
8187
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
8188
+ import path8 from "node:path";
8189
+ var KEY = "disableAllHooks";
8190
+ var SETTINGS = "settings.json";
8191
+ var SYSTEM_ENV = "QWEN_CODE_SYSTEM_SETTINGS_PATH";
8192
+ var HOME_ENV = "QWEN_HOME";
8193
+ var DARWIN_SYSTEM = "/Library/Application Support/QwenCode/settings.json";
8194
+ var WIN_SYSTEM = "C:\\ProgramData\\qwen-code\\settings.json";
8195
+ var LINUX_SYSTEM = "/etc/qwen-code/settings.json";
8196
+ function settingsFiles(env, home, cwd, platform) {
8197
+ const sys = env[SYSTEM_ENV] || (platform === "darwin" ? DARWIN_SYSTEM : platform === "win32" ? WIN_SYSTEM : LINUX_SYSTEM);
8198
+ const userDir = env[HOME_ENV] || path8.join(home, ".qwen");
8199
+ return [sys, path8.join(userDir, SETTINGS), path8.join(cwd, ".qwen", SETTINGS)];
8200
+ }
8201
+ function qwenHooksOff(env, home, cwd = process.cwd(), platform = process.platform) {
8202
+ for (const file of settingsFiles(env, home, cwd, platform)) {
8203
+ if (!existsSync12(file)) continue;
8204
+ let value;
8205
+ try {
8206
+ value = hostConfigValueAt(parseHostConfig("qwen", file, hostText(readFileSync9(file, "utf8")), "jsonc"), [KEY]);
8207
+ } catch {
8208
+ continue;
8209
+ }
8210
+ if (value === true) return `qwen runs no hook: "${KEY}" is true in ${file}; set it to false`;
8211
+ }
8212
+ return void 0;
8213
+ }
8214
+
7614
8215
  // src/setup/codex-trust.ts
7615
8216
  import { createHash } from "node:crypto";
7616
- import { existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
7617
- import path5 from "node:path";
8217
+ import { existsSync as existsSync13, realpathSync as realpathSync5 } from "node:fs";
8218
+ import path10 from "node:path";
8219
+ import { spawn, spawnSync as spawnSync3 } from "node:child_process";
7618
8220
 
7619
8221
  // src/setup/spawn-bin.ts
7620
- import { spawnSync } from "node:child_process";
8222
+ import { spawnSync as spawnSync2 } from "node:child_process";
7621
8223
  import { accessSync, constants as fsc, statSync } from "node:fs";
7622
- import path4 from "node:path";
8224
+ import path9 from "node:path";
7623
8225
 
7624
8226
  // src/core/sandbox/path-entries.ts
7625
- function pathEntries(value, platform = process.platform, delimiter = platform === "win32" ? ";" : ":") {
8227
+ function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
7626
8228
  const win = platform === "win32";
7627
- return value.split(delimiter).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
8229
+ return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
7628
8230
  }
7629
8231
 
7630
8232
  // src/setup/spawn-bin.ts
@@ -7638,10 +8240,10 @@ function whichBin(bin, env, platform = process.platform) {
7638
8240
  const get = (k) => envGet(env, k);
7639
8241
  const win = platform === "win32";
7640
8242
  const exts = win ? (get("PATHEXT") || WIN_EXT).split(";").filter(Boolean) : [""];
7641
- const names = win && path4.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
8243
+ const names = win && path9.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
7642
8244
  for (const dir of pathEntries(get("PATH") ?? "", platform)) {
7643
8245
  for (const n3 of names) {
7644
- const f2 = path4.join(dir, n3);
8246
+ const f2 = path9.join(dir, n3);
7645
8247
  try {
7646
8248
  accessSync(f2, fsc.X_OK);
7647
8249
  if (statSync(f2).isFile()) return f2;
@@ -7682,7 +8284,7 @@ function winCmdLine(file, args, env = {}) {
7682
8284
  return `"${[file, ...args].map(q).join(" ")}"`;
7683
8285
  }
7684
8286
  function spawnForm(file, args, env, platform = process.platform) {
7685
- if (platform === "win32" && WIN_SHIM_EXTS.includes(path4.extname(file).toLowerCase())) {
8287
+ if (platform === "win32" && WIN_SHIM_EXTS.includes(path9.extname(file).toLowerCase())) {
7686
8288
  return { command: envGet(env, "COMSPEC") || DEFAULT_COMSPEC, args: ["/d", "/v:off", "/s", "/c", winCmdLine(file, args, env)], windowsVerbatimArguments: true };
7687
8289
  }
7688
8290
  return { command: file, args, windowsVerbatimArguments: false };
@@ -7695,18 +8297,18 @@ function spawnShim(file, args, env, opts, platform = process.platform) {
7695
8297
  const error = e instanceof Error ? e : new Error(String(e));
7696
8298
  return { pid: 0, output: [null, "", error.message], stdout: "", stderr: error.message, status: null, signal: null, error };
7697
8299
  }
7698
- return spawnSync(f2.command, f2.args, { ...opts, env, windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
8300
+ return spawnSync2(f2.command, f2.args, { ...opts, env, windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
7699
8301
  }
7700
8302
 
7701
8303
  // src/setup/codex-trust.ts
7702
- var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8304
+ var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7703
8305
  var TRUST_KEY = ["hooks", "state"];
7704
8306
  var CODEX_TRUST_PATH = TRUST_KEY.join(".") + ".";
7705
8307
  var HASH_FIELD = "trusted_hash";
7706
8308
  var HASH_PREFIX = "sha256:";
7707
8309
  function sortKeys(v) {
7708
8310
  if (Array.isArray(v)) return v.map(sortKeys);
7709
- if (!isObj2(v)) return v;
8311
+ if (!isObj3(v)) return v;
7710
8312
  return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
7711
8313
  }
7712
8314
  function snake(name) {
@@ -7718,13 +8320,13 @@ function snake(name) {
7718
8320
  return out2;
7719
8321
  }
7720
8322
  function realFile(file) {
7721
- let dir = path5.resolve(file);
8323
+ let dir = path10.resolve(file);
7722
8324
  const rest = [];
7723
- while (!existsSync5(dir) && path5.dirname(dir) !== dir) {
7724
- rest.unshift(path5.basename(dir));
7725
- dir = path5.dirname(dir);
8325
+ while (!existsSync13(dir) && path10.dirname(dir) !== dir) {
8326
+ rest.unshift(path10.basename(dir));
8327
+ dir = path10.dirname(dir);
7726
8328
  }
7727
- return path5.join(realpathSync3(dir), ...rest);
8329
+ return path10.join(realpathSync5(dir), ...rest);
7728
8330
  }
7729
8331
  var ASK_TIMEOUT_MS = 1e4;
7730
8332
  var ASK_TRIES = 3;
@@ -7737,7 +8339,7 @@ function codexHomeFromReply(out2) {
7737
8339
  } catch {
7738
8340
  continue;
7739
8341
  }
7740
- if (isObj2(m3) && isObj2(m3.result) && typeof m3.result.codexHome === "string" && m3.result.codexHome !== "") return m3.result.codexHome;
8342
+ if (isObj3(m3) && isObj3(m3.result) && typeof m3.result.codexHome === "string" && m3.result.codexHome !== "") return m3.result.codexHome;
7741
8343
  }
7742
8344
  return void 0;
7743
8345
  }
@@ -7752,11 +8354,11 @@ function askCodexHome(env) {
7752
8354
  }
7753
8355
  return void 0;
7754
8356
  }
7755
- function sameDir(a2, b3, platform) {
7756
- if (platform !== "win32") return path5.posix.normalize(a2) === path5.posix.normalize(b3);
8357
+ function sameDir(a2, b3, platform = process.platform) {
8358
+ if (platform !== "win32") return path10.posix.normalize(a2) === path10.posix.normalize(b3);
7757
8359
  const norm = (p3) => {
7758
8360
  const bare = p3.startsWith(WIN_VERBATIM_PREFIX) ? p3.slice(WIN_VERBATIM_PREFIX.length) : p3;
7759
- const n3 = path5.win32.normalize(bare).toLowerCase();
8361
+ const n3 = path10.win32.normalize(bare).toLowerCase();
7760
8362
  return n3.length > 3 && n3.endsWith("\\") ? n3.slice(0, -1) : n3;
7761
8363
  };
7762
8364
  return norm(a2) === norm(b3);
@@ -7766,31 +8368,246 @@ function codexKeyDir(o2, platform = process.platform) {
7766
8368
  }
7767
8369
  function codexTrustEntries(hooksFile, doc, command, env) {
7768
8370
  const out2 = [];
7769
- if (!isObj2(doc) || !isObj2(doc.hooks)) return out2;
7770
- const abs = path5.resolve(hooksFile);
7771
- const dir = codexKeyDir({ dir: path5.dirname(abs), asked: env ? askCodexHome(env) : void 0, real: env && !env.CODEX_HOME ? (p3) => path5.resolve(p3) : realFile });
7772
- const real = (dir.startsWith(WIN_VERBATIM_PREFIX) ? path5.win32 : path5).join(dir, path5.basename(abs));
8371
+ if (!isObj3(doc) || !isObj3(doc.hooks)) return out2;
8372
+ const abs = path10.resolve(hooksFile);
8373
+ const dir = codexKeyDir({ dir: path10.dirname(abs), asked: env ? askCodexHome(env) : void 0, real: env && !env.CODEX_HOME ? (p3) => path10.resolve(p3) : realFile });
8374
+ const real2 = (dir.startsWith(WIN_VERBATIM_PREFIX) ? path10.win32 : path10).join(dir, path10.basename(abs));
7773
8375
  for (const [event, groups] of Object.entries(doc.hooks)) {
7774
8376
  if (!Array.isArray(groups)) continue;
7775
8377
  groups.forEach((g2, gi) => {
7776
- if (!isObj2(g2) || !Array.isArray(g2.hooks)) return;
8378
+ if (!isObj3(g2) || !Array.isArray(g2.hooks)) return;
7777
8379
  g2.hooks.forEach((h2, hi) => {
7778
- if (!isObj2(h2) || h2.command !== command) return;
8380
+ if (!isObj3(h2) || h2.command !== command) return;
7779
8381
  const id = { event_name: snake(event), hooks: [{ ...h2, async: false }] };
7780
8382
  if (g2.matcher !== void 0) id.matcher = g2.matcher;
7781
8383
  const hash = HASH_PREFIX + createHash("sha256").update(JSON.stringify(sortKeys(id))).digest("hex");
7782
- out2.push([[...TRUST_KEY, `${real}:${snake(event)}:${gi}:${hi}`], { [HASH_FIELD]: hash }]);
8384
+ out2.push([[...TRUST_KEY, `${real2}:${snake(event)}:${gi}:${hi}`], { [HASH_FIELD]: hash }]);
7783
8385
  });
7784
8386
  });
7785
8387
  }
7786
8388
  return out2;
7787
8389
  }
8390
+ var LIST_TIMEOUT_MS = 15e3;
8391
+ var EXIT_GRACE_MS = 5e3;
8392
+ var PLUGIN_SOURCE = "plugin";
8393
+ var TRUSTED = "trusted";
8394
+ function pluginHooksFromReply(m3, pluginId) {
8395
+ const out2 = [];
8396
+ if (!isObj3(m3) || !isObj3(m3.result) || !Array.isArray(m3.result.data)) return out2;
8397
+ for (const d of m3.result.data) {
8398
+ if (!isObj3(d) || !Array.isArray(d.hooks)) continue;
8399
+ for (const h2 of d.hooks) {
8400
+ if (!isObj3(h2) || h2.source !== PLUGIN_SOURCE || h2.pluginId !== pluginId) continue;
8401
+ if (typeof h2.key !== "string" || typeof h2.currentHash !== "string") continue;
8402
+ if (out2.some((x2) => x2.key === h2.key)) continue;
8403
+ out2.push({ key: h2.key, hash: h2.currentHash, trusted: h2.trustStatus === TRUSTED });
8404
+ }
8405
+ }
8406
+ return out2;
8407
+ }
8408
+ async function listPluginHooks(env, pluginId, cwd) {
8409
+ const r2 = await askPluginHooks(env, pluginId, cwd);
8410
+ return r2.kind === "list" ? r2.hooks : void 0;
8411
+ }
8412
+ function askPluginHooks(env, pluginId, cwd) {
8413
+ const bin = whichBin("codex", env);
8414
+ if (!bin) return Promise.resolve({ kind: "absent" });
8415
+ return new Promise((resolve3) => {
8416
+ let asked;
8417
+ const done_ = (hooks) => hooks === void 0 ? { kind: "silent" } : { kind: "list", hooks, codexHome: asked };
8418
+ let f2;
8419
+ try {
8420
+ f2 = spawnForm(bin, ["app-server"], env);
8421
+ } catch {
8422
+ resolve3({ kind: "silent" });
8423
+ return;
8424
+ }
8425
+ const child = spawn(f2.command, f2.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
8426
+ let buf = "";
8427
+ let done = false;
8428
+ let exited = false;
8429
+ let result;
8430
+ const settle = () => {
8431
+ clearTimeout(grace);
8432
+ resolve3(done_(result));
8433
+ };
8434
+ let grace;
8435
+ const finish2 = (v) => {
8436
+ if (done) return;
8437
+ done = true;
8438
+ clearTimeout(timer);
8439
+ result = v;
8440
+ child.stdin.destroy();
8441
+ if (exited) {
8442
+ settle();
8443
+ return;
8444
+ }
8445
+ grace = setTimeout(settle, EXIT_GRACE_MS);
8446
+ stopTree(child.pid, () => child.kill());
8447
+ };
8448
+ const timer = setTimeout(() => finish2(void 0), LIST_TIMEOUT_MS);
8449
+ const send = (o2) => {
8450
+ try {
8451
+ child.stdin.write(JSON.stringify(o2) + "\n");
8452
+ } catch {
8453
+ finish2(void 0);
8454
+ }
8455
+ };
8456
+ child.on("error", () => finish2(void 0));
8457
+ child.on("close", () => {
8458
+ exited = true;
8459
+ if (done) settle();
8460
+ else finish2(void 0);
8461
+ });
8462
+ child.stdin.on("error", () => finish2(void 0));
8463
+ child.stdout.setEncoding("utf8");
8464
+ child.stdout.on("data", (d) => {
8465
+ buf += d;
8466
+ const lines = buf.split("\n");
8467
+ buf = lines.pop() ?? "";
8468
+ for (const line of lines) {
8469
+ let m3;
8470
+ try {
8471
+ m3 = JSON.parse(line);
8472
+ } catch {
8473
+ continue;
8474
+ }
8475
+ if (!isObj3(m3)) continue;
8476
+ if (m3.id === 1) {
8477
+ asked = codexHomeFromReply(line);
8478
+ send({ method: "initialized" });
8479
+ send({ id: 2, method: "hooks/list", params: { cwds: [cwd] } });
8480
+ } else if (m3.id === 2) finish2(pluginHooksFromReply(m3, pluginId));
8481
+ }
8482
+ });
8483
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "context-mode-setup", version: "2.0.0" } } });
8484
+ });
8485
+ }
8486
+ function stopTree(pid, kill) {
8487
+ if (process.platform === "win32" && pid !== void 0) {
8488
+ try {
8489
+ spawnSync3("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 5e3 });
8490
+ } catch {
8491
+ }
8492
+ }
8493
+ kill();
8494
+ }
8495
+ var HASH_PART_SEP = "/";
8496
+ function hookHashOf(currentHash) {
8497
+ const cut = currentHash.indexOf(HASH_PART_SEP);
8498
+ return cut < 0 ? currentHash : currentHash.slice(0, cut);
8499
+ }
8500
+ function pluginTrustEntries(hooks) {
8501
+ return hooks.filter((h2) => !h2.trusted).map((h2) => [[...TRUST_KEY, h2.key], { [HASH_FIELD]: hookHashOf(h2.hash) }]);
8502
+ }
8503
+ var CODEX_PLUGIN_ID = `${SERVER_KEY}@${SERVER_KEY}`;
8504
+ var CODEX_UNTRUSTED_FIX = "run: context-mode setup";
8505
+ function untrustedPluginHooksDetail(hooks) {
8506
+ const bad = hooks.filter((h2) => !h2.trusted);
8507
+ if (!bad.length) return void 0;
8508
+ return `codex lists ${bad.length} of ${hooks.length} context-mode plugin hooks untrusted, so they do not run; ${CODEX_UNTRUSTED_FIX}`;
8509
+ }
8510
+
8511
+ // src/setup/copilot-hooks.ts
8512
+ import { spawn as spawn2 } from "node:child_process";
8513
+ import { realpathSync as realpathSync6 } from "node:fs";
8514
+ import path11 from "node:path";
8515
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8516
+ var ASK_TIMEOUT_MS2 = 15e3;
8517
+ var HEADER_END = "\r\n\r\n";
8518
+ var LENGTH_HEADER = "content-length";
8519
+ var USER_ORIGIN = "user";
8520
+ function canon(p3) {
8521
+ let r2 = path11.resolve(p3);
8522
+ try {
8523
+ r2 = realpathSync6(r2);
8524
+ } catch {
8525
+ }
8526
+ return process.platform === "win32" ? r2.toLowerCase() : r2;
8527
+ }
8528
+ function copilotHooksFromReply(m3, file) {
8529
+ const out2 = [];
8530
+ if (!isObj4(m3) || !isObj4(m3.result) || !Array.isArray(m3.result.hooks)) return out2;
8531
+ const want = canon(file);
8532
+ const base = path11.dirname(path11.dirname(path11.resolve(file)));
8533
+ for (const h2 of m3.result.hooks) {
8534
+ if (!isObj4(h2) || h2.origin !== USER_ORIGIN || typeof h2.source !== "string" || typeof h2.hookType !== "string" || typeof h2.enabled !== "boolean") continue;
8535
+ if (canon(path11.isAbsolute(h2.source) ? h2.source : path11.join(base, h2.source)) !== want) continue;
8536
+ out2.push({ event: h2.hookType, source: h2.source, enabled: h2.enabled, ...typeof h2.disableKey === "string" ? { disableKey: h2.disableKey } : {} });
8537
+ }
8538
+ return out2;
8539
+ }
8540
+ function frame(buf) {
8541
+ const end = buf.indexOf(HEADER_END);
8542
+ if (end < 0) return void 0;
8543
+ let len = -1;
8544
+ for (const line of buf.subarray(0, end).toString("latin1").split("\r\n")) {
8545
+ const at = line.indexOf(":");
8546
+ if (at > 0 && line.slice(0, at).trim().toLowerCase() === LENGTH_HEADER) len = Number(line.slice(at + 1).trim());
8547
+ }
8548
+ if (!Number.isInteger(len) || len < 0) return void 0;
8549
+ const start = end + HEADER_END.length;
8550
+ if (buf.length < start + len) return void 0;
8551
+ return { body: buf.subarray(start, start + len).toString("utf8"), rest: buf.subarray(start + len) };
8552
+ }
8553
+ function listCopilotHooks(env, file, cwd) {
8554
+ const bin = whichBin("copilot", env);
8555
+ if (!bin) return Promise.resolve(void 0);
8556
+ return new Promise((resolve3) => {
8557
+ let f2;
8558
+ try {
8559
+ f2 = spawnForm(bin, ["--server", "--stdio", "--no-auto-update"], env);
8560
+ } catch {
8561
+ resolve3(void 0);
8562
+ return;
8563
+ }
8564
+ const child = spawn2(f2.command, f2.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
8565
+ let buf = Buffer.alloc(0);
8566
+ let done = false;
8567
+ const finish2 = (v) => {
8568
+ if (done) return;
8569
+ done = true;
8570
+ clearTimeout(timer);
8571
+ child.stdin.destroy();
8572
+ child.kill();
8573
+ resolve3(v);
8574
+ };
8575
+ const timer = setTimeout(() => finish2(void 0), ASK_TIMEOUT_MS2);
8576
+ child.on("error", () => finish2(void 0));
8577
+ child.on("close", () => finish2(void 0));
8578
+ child.stdin.on("error", () => finish2(void 0));
8579
+ child.stdout.on("data", (d) => {
8580
+ buf = Buffer.concat([buf, d]);
8581
+ const m3 = frame(buf);
8582
+ if (!m3) return;
8583
+ buf = Buffer.from(m3.rest);
8584
+ let reply;
8585
+ try {
8586
+ reply = JSON.parse(m3.body);
8587
+ } catch {
8588
+ finish2(void 0);
8589
+ return;
8590
+ }
8591
+ if (!isObj4(reply) || !isObj4(reply.result) || !Array.isArray(reply.result.hooks)) {
8592
+ finish2(void 0);
8593
+ return;
8594
+ }
8595
+ finish2(copilotHooksFromReply(reply, file));
8596
+ });
8597
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "hooks.discover", params: {} });
8598
+ try {
8599
+ child.stdin.write(`Content-Length: ${Buffer.byteLength(body)}${HEADER_END}${body}`);
8600
+ } catch {
8601
+ finish2(void 0);
8602
+ }
8603
+ });
8604
+ }
7788
8605
 
7789
8606
  // src/setup/engine.ts
7790
- import { spawn, spawnSync as spawnSync2 } from "node:child_process";
7791
- import { closeSync, existsSync as existsSync6, mkdirSync as mkdirSync3, mkdtempSync, openSync, readFileSync as readFileSync3, readSync, readdirSync as readdirSync4, realpathSync as realpathSync4, rmSync, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
8607
+ import { spawn as spawn3, spawnSync as spawnSync4 } from "node:child_process";
8608
+ import { closeSync as closeSync2, existsSync as existsSync14, mkdirSync as mkdirSync5, mkdtempSync, openSync as openSync2, readFileSync as readFileSync10, readSync as readSync2, readdirSync as readdirSync5, realpathSync as realpathSync7, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
7792
8609
  import { tmpdir as tmpdir2 } from "node:os";
7793
- import path6 from "node:path";
8610
+ import path12 from "node:path";
7794
8611
 
7795
8612
  // src/setup/hook-sample.ts
7796
8613
  var SAMPLE_FILE = "big.log";
@@ -7862,6 +8679,7 @@ var HOOK_SAMPLES = 9;
7862
8679
  var HOOK_ROUNDS = 5;
7863
8680
  var P95 = 0.95;
7864
8681
  var VERIFY_TIMEOUT_MS = 1e4;
8682
+ var INSTALL_TIMEOUT_MS = 12e4;
7865
8683
  var MANIFEST = "manifest.json";
7866
8684
  var MANIFEST_DONE = "manifest.removed.json";
7867
8685
  var FILES = "files";
@@ -7873,39 +8691,39 @@ var REAL_HOST = Object.freeze({
7873
8691
  var BINARY_MAGICS = Object.freeze(["cffaedfe", "cefaedfe", "7f454c46", "4d5a"]);
7874
8692
  function isNativeBinary(file) {
7875
8693
  const head = Buffer.alloc(4);
7876
- const fd = openSync(file, "r");
8694
+ const fd = openSync2(file, "r");
7877
8695
  try {
7878
- readSync(fd, head, 0, 4, 0);
8696
+ readSync2(fd, head, 0, 4, 0);
7879
8697
  } finally {
7880
- closeSync(fd);
8698
+ closeSync2(fd);
7881
8699
  }
7882
8700
  const hex = head.toString("hex");
7883
8701
  return BINARY_MAGICS.some((m3) => hex.startsWith(m3));
7884
8702
  }
7885
8703
  function owningPackage(dir) {
7886
- for (let d = dir; ; d = path6.dirname(d)) {
7887
- const f2 = path6.join(d, "package.json");
7888
- if (existsSync6(f2)) {
8704
+ for (let d = dir; ; d = path12.dirname(d)) {
8705
+ const f2 = path12.join(d, "package.json");
8706
+ if (existsSync14(f2)) {
7889
8707
  try {
7890
- return String(JSON.parse(hostText(readFileSync3(f2, "utf8"))).name);
8708
+ return String(JSON.parse(hostText(readFileSync10(f2, "utf8"))).name);
7891
8709
  } catch {
7892
8710
  return void 0;
7893
8711
  }
7894
8712
  }
7895
- if (path6.dirname(d) === d) return void 0;
8713
+ if (path12.dirname(d) === d) return void 0;
7896
8714
  }
7897
8715
  }
7898
8716
  function hostBin(bin, env, platform = process.platform) {
7899
- const real = REAL_HOST[bin];
7900
- if (!real) return { file: which(bin, env, platform), shims: [] };
8717
+ const real2 = REAL_HOST[bin];
8718
+ if (!real2) return { file: which(bin, env, platform), shims: [] };
7901
8719
  const get = (k) => env[Object.keys(env).find((x2) => x2.toUpperCase() === k) ?? k];
7902
8720
  const shims = [];
7903
8721
  for (const dir of pathEntries(get("PATH") ?? "", platform)) {
7904
8722
  const own2 = which(bin, { PATH: dir, ...get("PATHEXT") ? { PATHEXT: get("PATHEXT") } : {} }, platform);
7905
- for (const f2 of [own2, ...real.extra.map((p3) => path6.join(dir, ...p3))]) {
7906
- if (!f2 || !existsSync6(f2) || !statSync2(f2).isFile()) continue;
7907
- const file = realpathSync4(f2);
7908
- if (isNativeBinary(file) || owningPackage(path6.dirname(file)) === real.pkg) return { file, shims };
8723
+ for (const f2 of [own2, ...real2.extra.map((p3) => path12.join(dir, ...p3))]) {
8724
+ if (!f2 || !existsSync14(f2) || !statSync2(f2).isFile()) continue;
8725
+ const file = realpathSync7(f2);
8726
+ if (isNativeBinary(file) || owningPackage(path12.dirname(file)) === real2.pkg) return { file, shims };
7909
8727
  shims.push(f2);
7910
8728
  }
7911
8729
  }
@@ -7916,14 +8734,14 @@ function installExitOk(status, listed, platform = process.platform) {
7916
8734
  if (status === 0) return true;
7917
8735
  return platform === "win32" && status === WIN_EXIT_CRASH && listed;
7918
8736
  }
7919
- function runBin(bin, args, env, input) {
7920
- return spawnShim(hostBin(bin, env).file ?? bin, args, env, { encoding: "utf8", input, timeout: VERIFY_TIMEOUT_MS });
8737
+ function runBin(bin, args, env, input, timeout = VERIFY_TIMEOUT_MS) {
8738
+ return spawnShim(hostBin(bin, env).file ?? bin, args, env, { encoding: "utf8", input, timeout });
7921
8739
  }
7922
8740
  function readOr(file) {
7923
- return existsSync6(file) ? hostText(readFileSync3(file, "utf8")) : void 0;
8741
+ return existsSync14(file) ? hostText(readFileSync10(file, "utf8")) : void 0;
7924
8742
  }
7925
8743
  function readRaw(file) {
7926
- return existsSync6(file) ? readFileSync3(file, "utf8") : void 0;
8744
+ return existsSync14(file) ? readFileSync10(file, "utf8") : void 0;
7927
8745
  }
7928
8746
  var atomicWrite = atomicWriteFile;
7929
8747
  function pidAlive(pid) {
@@ -7941,7 +8759,7 @@ function p95(xs) {
7941
8759
  function parseFail(_row, file) {
7942
8760
  return `${file} does not parse; left as is. Fix the file, then re-run setup`;
7943
8761
  }
7944
- var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8762
+ var isObj5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7945
8763
  function planHookFile(row, hf) {
7946
8764
  const before = readOr(hf.file);
7947
8765
  if (before === void 0) return void 0;
@@ -7951,14 +8769,14 @@ function planHookFile(row, hf) {
7951
8769
  } catch {
7952
8770
  throw new Error(parseFail(row, hf.file));
7953
8771
  }
7954
- if (!isObj3(doc) || !isObj3(doc.hooks)) return void 0;
8772
+ if (!isObj5(doc) || !isObj5(doc.hooks)) return void 0;
7955
8773
  const changes = [];
7956
8774
  const want = hookCommandString(row);
7957
8775
  for (const [event, groups] of Object.entries(doc.hooks)) {
7958
8776
  if (!Array.isArray(groups)) continue;
7959
8777
  for (let g2 = groups.length - 1; g2 >= 0; g2--) {
7960
8778
  const group2 = groups[g2];
7961
- if (isObj3(group2) && typeof group2.command === "string" && !Array.isArray(group2.hooks)) {
8779
+ if (isObj5(group2) && typeof group2.command === "string" && !Array.isArray(group2.hooks)) {
7962
8780
  if (!group2.command.includes(V1_HOOK_MARK)) continue;
7963
8781
  const at = `hooks.${event}[${g2}].command`;
7964
8782
  if (hf.mode === "rewrite") {
@@ -7970,10 +8788,10 @@ function planHookFile(row, hf) {
7970
8788
  }
7971
8789
  continue;
7972
8790
  }
7973
- const list2 = isObj3(group2) ? group2.hooks : void 0;
8791
+ const list2 = isObj5(group2) ? group2.hooks : void 0;
7974
8792
  if (!Array.isArray(list2)) continue;
7975
8793
  for (let h2 = list2.length - 1; h2 >= 0; h2--) {
7976
- const cmd = isObj3(list2[h2]) ? list2[h2].command : void 0;
8794
+ const cmd = isObj5(list2[h2]) ? list2[h2].command : void 0;
7977
8795
  if (typeof cmd !== "string" || !cmd.includes(V1_HOOK_MARK)) continue;
7978
8796
  const at = `hooks.${event}[${g2}].hooks[${h2}].command`;
7979
8797
  if (hf.mode === "rewrite") {
@@ -7998,11 +8816,11 @@ function isOwnHookCommand(cmd, agent) {
7998
8816
  if (tail.startsWith('"')) tail = tail.slice(1);
7999
8817
  return tail.trim() === `${AGENT_FLAG} ${agent}`;
8000
8818
  }
8001
- var holdsOwn = (v, agent) => typeof v === "string" ? isOwnHookCommand(v, agent) : Array.isArray(v) ? v.some((x2) => holdsOwn(x2, agent)) : isObj3(v) ? Object.values(v).some((x2) => holdsOwn(x2, agent)) : false;
8819
+ var holdsOwn = (v, agent) => typeof v === "string" ? isOwnHookCommand(v, agent) : Array.isArray(v) ? v.some((x2) => holdsOwn(x2, agent)) : isObj5(v) ? Object.values(v).some((x2) => holdsOwn(x2, agent)) : false;
8002
8820
  var same = (a2, b3) => JSON.stringify(a2) === JSON.stringify(b3);
8003
8821
  function mergeOwn(cur, want, agent) {
8004
- if (isObj3(want)) {
8005
- const base = isObj3(cur) ? { ...cur } : {};
8822
+ if (isObj5(want)) {
8823
+ const base = isObj5(cur) ? { ...cur } : {};
8006
8824
  for (const [k, v] of Object.entries(want)) base[k] = mergeOwn(base[k], v, agent);
8007
8825
  return base;
8008
8826
  }
@@ -8025,7 +8843,7 @@ function planJsonKeys(row, edits, file, format, want) {
8025
8843
  throw new Error(parseFail(row, file));
8026
8844
  }
8027
8845
  }
8028
- if (!isObj3(doc)) throw new Error(parseFail(row, file));
8846
+ if (!isObj5(doc)) throw new Error(parseFail(row, file));
8029
8847
  let res;
8030
8848
  try {
8031
8849
  res = editHostConfigText(row.id, file, text2 ?? "", format, want(doc));
@@ -8061,6 +8879,58 @@ function planCodexTrust(row, edits, hooksFile, file, command, env) {
8061
8879
  prior.changes.push(...changes);
8062
8880
  } else edits.push({ file, before: text2, after: res.text, changes });
8063
8881
  }
8882
+ var NATIVE_PLUGIN_PREFIX = "context-mode@";
8883
+ function isNativeSpec(e) {
8884
+ return typeof e === "string" && e.startsWith(NATIVE_PLUGIN_PREFIX);
8885
+ }
8886
+ function isStaleOwnPlugin(e, entry2) {
8887
+ if (typeof e !== "string" || e === entry2 || !path12.isAbsolute(e)) return false;
8888
+ if (e === path12.join(entry2, ...OPENCODE_PLUGIN_PATH)) return true;
8889
+ if (existsSync14(e)) return false;
8890
+ const seg = e.split("\\").join("/").split("/");
8891
+ const n3 = seg.length;
8892
+ if (n3 >= 3 && seg[n3 - 1] === "plugin.js" && seg[n3 - 2] === "opencode" && seg[n3 - 3] === "context-mode") return true;
8893
+ return n3 >= 2 && seg[n3 - 1] === "context-mode" && seg[n3 - 2] === "node_modules";
8894
+ }
8895
+ function wantedPluginList(list2, entry2, nativeElsewhere = false) {
8896
+ const native = nativeElsewhere || list2.some(isNativeSpec);
8897
+ const kept = list2.filter((e) => !(native && e === entry2) && !isStaleOwnPlugin(e, entry2));
8898
+ return native || kept.includes(entry2) ? kept : [...kept, entry2];
8899
+ }
8900
+ var OC2_NATIVE_KEY = "plugins";
8901
+ function nativePluginsKey(doc) {
8902
+ const v = isObj5(doc) ? doc[OC2_NATIVE_KEY] : void 0;
8903
+ return Array.isArray(v) && v.some(isNativeSpec);
8904
+ }
8905
+ function pluginListIssue(h2) {
8906
+ const text2 = readOr(h2.file);
8907
+ if (text2 === void 0) return void 0;
8908
+ let doc;
8909
+ try {
8910
+ doc = parseHostConfig("opencode", h2.file, text2, fileFormat({ id: "opencode" }, h2.file));
8911
+ } catch {
8912
+ return void 0;
8913
+ }
8914
+ const cur = isObj5(doc) ? doc[h2.key[0]] : void 0;
8915
+ const list2 = Array.isArray(cur) ? cur : [];
8916
+ if ((list2.some(isNativeSpec) || nativePluginsKey(doc)) && list2.includes(h2.entry)) return `${h2.file}: context-mode loads twice (native entry and ${h2.entry}), every hook fires twice; run: context-mode setup`;
8917
+ const stale = list2.find((e) => isStaleOwnPlugin(e, h2.entry));
8918
+ if (stale !== void 0) return `${h2.file}: plugin file missing, so OpenCode never loads the hooks (${String(stale)}); run: context-mode setup`;
8919
+ return void 0;
8920
+ }
8921
+ function kiroDisabledIssue(h2) {
8922
+ const text2 = readOr(h2.file);
8923
+ if (text2 === void 0) return void 0;
8924
+ let doc;
8925
+ try {
8926
+ doc = parseHostConfig("kiro", h2.file, text2, "json");
8927
+ } catch {
8928
+ return void 0;
8929
+ }
8930
+ const hooks = isObj5(doc) && Array.isArray(doc.hooks) ? doc.hooks : [];
8931
+ const off = hooks.filter((e) => isObj5(e) && e.enabled === false && isObj5(e.action) && isOwnHookCommand(e.action.command, "kiro")).map((e) => String(e.name));
8932
+ return off.length ? `${h2.file}: kiro skips the disabled context-mode hook${off.length > 1 ? "s" : ""} (${off.join(", ")}); set "enabled" to true or run: context-mode setup` : void 0;
8933
+ }
8064
8934
  function planHookInstall(row, edits, env) {
8065
8935
  const h2 = row.hookInstall;
8066
8936
  if (h2.kind === "file") {
@@ -8070,7 +8940,9 @@ function planHookInstall(row, edits, env) {
8070
8940
  planJsonKeys(row, edits, h2.file, fileFormat(row, h2.file), (doc) => {
8071
8941
  const cur = doc[h2.key[0]];
8072
8942
  const list2 = Array.isArray(cur) ? cur : [];
8073
- return [[h2.key, list2.includes(h2.entry) ? list2 : [...list2, h2.entry]]];
8943
+ const want = wantedPluginList(list2, h2.entry, nativePluginsKey(doc));
8944
+ if (cur === void 0 && want.length === 0) return [];
8945
+ return [[h2.key, want.length === list2.length && want.every((e, i2) => e === list2[i2]) ? list2 : want]];
8074
8946
  });
8075
8947
  }
8076
8948
  }
@@ -8078,13 +8950,13 @@ function planSkills(row, edits) {
8078
8950
  const s = row.skillInstall;
8079
8951
  if (s.kind !== "dir") return;
8080
8952
  for (const f2 of s.files) {
8081
- if (!existsSync6(f2.src)) throw new Error(`preflight: ${f2.src} is missing`);
8082
- const after = renderSkill(readFileSync3(f2.src, "utf8"), s.prefixes);
8953
+ if (!existsSync14(f2.src)) throw new Error(`preflight: ${f2.src} is missing`);
8954
+ const after = renderSkill(readFileSync10(f2.src, "utf8"), s.prefixes);
8083
8955
  const before = readRaw(f2.file);
8084
8956
  if (before !== after) edits.push({ plain: true, file: f2.file, before, after, changes: [{ file: f2.file, path: f2.name, before: before === void 0 ? null : "old", after: "SKILL.md" }] });
8085
8957
  }
8086
8958
  }
8087
- function planRow(row, listed, stale, env) {
8959
+ function planRow(row, listed, stale, env, disabled = false) {
8088
8960
  const edits = [];
8089
8961
  if (row.config) {
8090
8962
  const c3 = row.config;
@@ -8106,18 +8978,83 @@ function planRow(row, listed, stale, env) {
8106
8978
  planSkills(row, edits);
8107
8979
  const cli = row.config || !row.cli || listed ? [] : row.cli.install;
8108
8980
  const refresh = listed && stale && row.copy ? [row.copy.refresh] : [];
8981
+ if (listed && disabled && row.copy) refresh.push(row.copy.enable);
8109
8982
  return { edits, cli, refresh };
8110
8983
  }
8111
8984
  function listCheck(row, env) {
8112
- const l2 = row.listCommand;
8113
- if (!l2 || !hostBin(l2.bin, env).file) return void 0;
8985
+ return listState(row, env).check;
8986
+ }
8987
+ var STATUS_KEY = "Status:";
8988
+ var DISABLED_WORD = "disabled";
8989
+ function statusOf(row, text2) {
8990
+ const c3 = row.copy;
8991
+ if (!c3) return void 0;
8992
+ let mine = false;
8993
+ for (const raw of text2.split("\n")) {
8994
+ const t2 = raw.trim();
8995
+ if (raw.length && !raw.startsWith(" ")) {
8996
+ mine = false;
8997
+ continue;
8998
+ }
8999
+ if (t2.split(" ").includes(c3.plugin)) {
9000
+ mine = true;
9001
+ continue;
9002
+ }
9003
+ if (mine && t2.startsWith(STATUS_KEY)) return t2.split(" ").includes(DISABLED_WORD) ? "disabled" : "enabled";
9004
+ }
9005
+ return void 0;
9006
+ }
9007
+ function opencodeMajor(bin, env) {
9008
+ const r2 = runBin(bin, ["--version"], env);
9009
+ const text2 = `${r2.stdout}${r2.stderr}`;
9010
+ const digits = text2.split("").filter((c3) => c3 >= "0" && c3 <= "9" || c3 === ".").join("");
9011
+ return Number(digits.split(".")[0]);
9012
+ }
9013
+ function opencodeListArgs(bin, env) {
9014
+ return opencodeMajor(bin, env) >= 2 ? ["mcp", "list", "--standalone"] : ["mcp", "list", "--pure"];
9015
+ }
9016
+ function listState(row, env) {
9017
+ const l0 = row.listCommand;
9018
+ if (!l0 || !hostBin(l0.bin, env).file) return { status: void 0 };
9019
+ const l2 = row.id === "opencode" ? { bin: l0.bin, args: opencodeListArgs(l0.bin, env) } : l0;
8114
9020
  const r2 = runBin(l2.bin, l2.args, env);
8115
9021
  const ok = r2.status === 0 && `${r2.stdout}${r2.stderr}`.includes("context-mode");
8116
- return { name: "list", ok, detail: ok ? void 0 : `${l2.bin} ${l2.args.join(" ")} does not list context-mode` };
9022
+ const check = { name: "list", ok, detail: ok ? void 0 : `${l2.bin} ${l2.args.join(" ")} does not list context-mode` };
9023
+ return { check, status: r2.status === 0 ? statusOf(row, `${r2.stdout}`) : void 0 };
9024
+ }
9025
+ var DISABLE_ALL_HOOKS = "disableAllHooks";
9026
+ var SETTINGS_FILES = ["settings.json", "settings.local.json"];
9027
+ function disabledBySettings(row) {
9028
+ const c3 = row.copy;
9029
+ if (!c3) return void 0;
9030
+ const dirs = [path12.dirname(path12.dirname(c3.file)), path12.join(process.cwd(), ".claude")];
9031
+ for (const dir of dirs) {
9032
+ for (const name of SETTINGS_FILES) {
9033
+ const file = path12.join(dir, name);
9034
+ const text2 = readOr(file);
9035
+ if (text2 === void 0) continue;
9036
+ let doc;
9037
+ try {
9038
+ doc = JSON.parse(text2);
9039
+ } catch {
9040
+ continue;
9041
+ }
9042
+ if (isObj5(doc) && doc[DISABLE_ALL_HOOKS] === true) return file;
9043
+ }
9044
+ }
9045
+ return void 0;
9046
+ }
9047
+ function hookEnabledCheck(row, status) {
9048
+ const c3 = row.copy;
9049
+ if (!c3) return void 0;
9050
+ if (status === "disabled") return { name: "hook-enabled", ok: false, detail: `${c3.plugin} is installed but disabled in ${c3.bin}, so its hooks do not run; run: ${c3.bin} ${c3.enable.join(" ")}` };
9051
+ const file = disabledBySettings(row);
9052
+ if (file) return { name: "hook-enabled", ok: false, detail: `${file} sets ${DISABLE_ALL_HOOKS}, so ${c3.host} runs no hooks; remove "${DISABLE_ALL_HOOKS}" from it` };
9053
+ return { name: "hook-enabled", ok: true };
8117
9054
  }
8118
9055
  function packageVersion(pkgDir) {
8119
9056
  try {
8120
- const v = JSON.parse(hostText(readFileSync3(path6.join(pkgDir, "package.json"), "utf8"))).version;
9057
+ const v = JSON.parse(hostText(readFileSync10(path12.join(pkgDir, "package.json"), "utf8"))).version;
8121
9058
  return typeof v === "string" ? v : void 0;
8122
9059
  } catch {
8123
9060
  return void 0;
@@ -8131,20 +9068,20 @@ function copyCheck(row, pkgDir) {
8131
9068
  let entries;
8132
9069
  try {
8133
9070
  const doc = JSON.parse(text2);
8134
- entries = isObj3(doc) && isObj3(doc.plugins) ? doc.plugins[c3.plugin] : void 0;
9071
+ entries = isObj5(doc) && isObj5(doc.plugins) ? doc.plugins[c3.plugin] : void 0;
8135
9072
  } catch {
8136
9073
  return { name: "copy", ok: false, detail: `${c3.file} is not valid JSON; run ${c3.bin} ${c3.refresh.join(" ")}` };
8137
9074
  }
8138
9075
  if (!Array.isArray(entries)) return void 0;
8139
- const versions = entries.filter(isObj3).map((e) => e.version).filter((v) => typeof v === "string");
9076
+ const versions = entries.filter(isObj5).map((e) => e.version).filter((v) => typeof v === "string");
8140
9077
  if (!versions.length) return void 0;
8141
9078
  const old = versions.find((v) => v !== pkg);
8142
9079
  if (old === void 0) return { name: "copy", ok: true };
8143
9080
  return { name: "copy", ok: false, detail: `${c3.host} runs context-mode ${old}, the installed package is ${pkg}; run ${c3.bin} ${c3.refresh.join(" ")}` };
8144
9081
  }
8145
9082
  function mcpCheck(cmd, env) {
8146
- return new Promise((resolve) => {
8147
- const child = spawn(cmd[0], cmd.slice(1), { env, stdio: ["pipe", "pipe", "ignore"], detached: process.platform !== "win32", windowsHide: true });
9083
+ return new Promise((resolve3) => {
9084
+ const child = spawn3(cmd[0], cmd.slice(1), { env, stdio: ["pipe", "pipe", "ignore"], detached: process.platform !== "win32", windowsHide: true });
8148
9085
  const reap = () => {
8149
9086
  child.kill();
8150
9087
  };
@@ -8155,11 +9092,12 @@ function mcpCheck(cmd, env) {
8155
9092
  clearTimeout(timer);
8156
9093
  process.off("exit", reap);
8157
9094
  child.kill();
8158
- resolve({ name: "mcp", ok, detail });
9095
+ resolve3({ name: "mcp", ok, detail });
8159
9096
  };
8160
9097
  const timer = setTimeout(() => done(false, "no MCP answer before timeout"), VERIFY_TIMEOUT_MS);
8161
9098
  child.on("error", (e) => done(false, e.message));
8162
9099
  child.on("exit", (code) => done(false, `server exited (${code}) before tools/list`));
9100
+ child.stdin.on("error", (e) => done(false, `server closed its input: ${e.message}`));
8163
9101
  child.stdout.on("data", (d) => {
8164
9102
  buf += d.toString();
8165
9103
  let nl;
@@ -8177,7 +9115,7 @@ function mcpCheck(cmd, env) {
8177
9115
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
8178
9116
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }) + "\n");
8179
9117
  } else if (m3.id === 2) {
8180
- const tools = isObj3(m3.result) && Array.isArray(m3.result.tools) ? m3.result.tools.map((t2) => t2.name) : [];
9118
+ const tools = isObj5(m3.result) && Array.isArray(m3.result.tools) ? m3.result.tools.map((t2) => t2.name) : [];
8181
9119
  const want = [...TOOL_ORDER].sort();
8182
9120
  const got = [...tools].sort();
8183
9121
  const ok = JSON.stringify(got) === JSON.stringify(want);
@@ -8193,13 +9131,13 @@ function mcpCheck(cmd, env) {
8193
9131
  });
8194
9132
  }
8195
9133
  function hookRound(row, env) {
8196
- const cmd = row.hookCommand;
9134
+ const cmd = row.hookRunCommand;
8197
9135
  const input = JSON.stringify(row.goldenPayload);
8198
9136
  const wall = [];
8199
9137
  const bare = [];
8200
9138
  for (let i2 = 0; i2 < HOOK_SAMPLES; i2++) {
8201
9139
  let t2 = performance.now();
8202
- const r2 = spawnSync2(cmd[0], cmd.slice(1), { env, input, encoding: "utf8", timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
9140
+ const r2 = spawnSync4(cmd[0], cmd.slice(1), { env, input, encoding: "utf8", timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
8203
9141
  wall.push(performance.now() - t2);
8204
9142
  if (r2.status !== 0) return { name: "hook", ok: false, detail: `hook exited ${r2.status}: ${`${r2.stderr}`.trim()}` };
8205
9143
  const out2 = `${r2.stdout}`.trim();
@@ -8209,10 +9147,10 @@ function hookRound(row, env) {
8209
9147
  j2 = JSON.parse(out2);
8210
9148
  } catch {
8211
9149
  }
8212
- if (!isObj3(j2)) return { name: "hook", ok: false, detail: `hook answer is not a JSON object: ${out2.slice(0, 200)}` };
9150
+ if (!isObj5(j2)) return { name: "hook", ok: false, detail: `hook answer is not a JSON object: ${out2.slice(0, 200)}` };
8213
9151
  }
8214
9152
  t2 = performance.now();
8215
- spawnSync2(cmd[0], ["-e", ""], { env, timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
9153
+ spawnSync4(cmd[0], ["-e", ""], { env, timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
8216
9154
  bare.push(performance.now() - t2);
8217
9155
  }
8218
9156
  const wallP95Ms = Math.round(p95(wall));
@@ -8259,33 +9197,35 @@ function hookRegisteredCheck(row, env, list2) {
8259
9197
  if (!edits.length) return { name: "hook-registered", ok: true };
8260
9198
  const trust = h2.kind === "file" ? h2.trust : void 0;
8261
9199
  if (trust && edits.every((e) => e.file === trust && e.changes.every((c3) => isTrust(row, c3)))) return { name: "hook-registered", ok: false, detail: `${h2.file}: the context-mode hooks are not trusted in ${trust}; re-run setup` };
8262
- return { name: "hook-registered", ok: false, detail: `${h2.file} lacks the context-mode hook entry` };
9200
+ const issue = h2.kind === "plugin-list" ? pluginListIssue(h2) : h2.kind === "file" && row.id === "kiro" ? kiroDisabledIssue(h2) : void 0;
9201
+ const oc2 = issue === void 0 && row.id === "opencode" && h2.kind === "plugin-list" && hostBin("opencode", env).file !== void 0 && opencodeMajor("opencode", env) >= 2;
9202
+ return { name: "hook-registered", ok: false, detail: issue ?? `${h2.file} lacks the context-mode hook entry${oc2 ? "; run: opencode plugin add context-mode@next" : ""}` };
8263
9203
  }
8264
9204
  function hookRunsCheck(row, env) {
8265
- const root = mkdtempSync(path6.join(tmpdir2(), "cm-doctor-runs-"));
9205
+ const root = mkdtempSync(path12.join(tmpdir2(), "cm-doctor-runs-"));
8266
9206
  try {
8267
- const home = path6.join(root, "home");
8268
- const proj = path6.join(root, "proj");
8269
- mkdirSync3(home);
8270
- mkdirSync3(proj);
9207
+ const home = path12.join(root, "home");
9208
+ const proj = path12.join(root, "proj");
9209
+ mkdirSync5(home);
9210
+ mkdirSync5(proj);
8271
9211
  const text2 = sampleText();
8272
- writeFileSync2(path6.join(proj, SAMPLE_FILE), text2);
9212
+ writeFileSync3(path12.join(proj, SAMPLE_FILE), text2);
8273
9213
  const { effect, payload } = hookSample(row.id, proj, text2);
8274
9214
  const sampleEnv = { ...env, HOME: home, USERPROFILE: home };
8275
9215
  delete sampleEnv.CLAUDE_PROJECT_DIR;
8276
9216
  const cmd = row.hookRunCommand;
8277
- const r2 = spawnSync2(cmd[0], cmd.slice(1), { env: sampleEnv, cwd: proj, input: JSON.stringify(payload), encoding: "utf8", timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
9217
+ const r2 = spawnSync4(cmd[0], cmd.slice(1), { env: sampleEnv, cwd: proj, input: JSON.stringify(payload), encoding: "utf8", timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
8278
9218
  const bad = sampleVerdict(row.id, effect, text2, { status: r2.status, stdout: `${r2.stdout ?? ""}`, stderr: `${r2.stderr ?? ""}` });
8279
9219
  return bad === null ? { name: "hook-runs", ok: true } : { name: "hook-runs", ok: false, detail: bad };
8280
9220
  } finally {
8281
- rmSync(root, { recursive: true, force: true });
9221
+ rmSync2(root, { recursive: true, force: true });
8282
9222
  }
8283
9223
  }
8284
9224
  var SEEN_SQL = "SELECT 1 FROM events WHERE agent = ? LIMIT 1";
8285
9225
  var NOT_SEEN_LINE = "not seen yet, run one tool call";
8286
9226
  function hookSeenCheck(row, home) {
8287
- const base = path6.join(home, STATE_DIR, PROJECTS_DIR_NAME);
8288
- const dirs = existsSync6(base) ? readdirSync4(base) : [];
9227
+ const base = path12.join(home, STATE_DIR, PROJECTS_DIR_NAME);
9228
+ const dirs = existsSync14(base) ? readdirSync5(base) : [];
8289
9229
  let sqlite;
8290
9230
  try {
8291
9231
  sqlite = process.getBuiltinModule("node:sqlite");
@@ -8293,8 +9233,8 @@ function hookSeenCheck(row, home) {
8293
9233
  sqlite = void 0;
8294
9234
  }
8295
9235
  for (const d of dirs) {
8296
- const file = path6.join(base, d, DB_FILE_NAME);
8297
- if (!sqlite || !existsSync6(file)) continue;
9236
+ const file = path12.join(base, d, DB_FILE_NAME);
9237
+ if (!sqlite || !existsSync14(file)) continue;
8298
9238
  let db;
8299
9239
  try {
8300
9240
  db = new sqlite.DatabaseSync(file, { readOnly: true });
@@ -8309,15 +9249,17 @@ function hookSeenCheck(row, home) {
8309
9249
  function skillsCheck(row, pkgDir) {
8310
9250
  const s = row.skillInstall;
8311
9251
  if (s.kind === "package") {
8312
- const miss = COMMAND_SKILLS.map((n3) => path6.join(pkgDir, s.via, n3, SKILL_FILE)).filter((f2) => !existsSync6(f2));
9252
+ const miss = COMMAND_SKILLS.map((n3) => path12.join(pkgDir, s.via, n3, SKILL_FILE)).filter((f2) => !existsSync14(f2));
8313
9253
  return { name: "skills", ok: miss.length === 0, detail: miss.length ? `missing ${miss.join(", ")}` : void 0 };
8314
9254
  }
8315
- const bad = s.files.filter((f2) => readRaw(f2.file) !== (existsSync6(f2.src) ? renderSkill(readFileSync3(f2.src, "utf8"), s.prefixes) : void 0));
9255
+ const bad = s.files.filter((f2) => readRaw(f2.file) !== (existsSync14(f2.src) ? renderSkill(readFileSync10(f2.src, "utf8"), s.prefixes) : void 0));
8316
9256
  return { name: "skills", ok: bad.length === 0, detail: bad.length ? `${bad.map((f2) => f2.file).join(", ")} missing or without the ${s.prefixes.join(" / ") || "plain"} tool prefix` : void 0 };
8317
9257
  }
8318
9258
  var PLUGIN_ENABLED = "enabled";
8319
9259
  var WORD_TRIM = ",;";
9260
+ var CODEX_CONFIG_FILE2 = "config.toml";
8320
9261
  var EXT_ENABLED_USER = "Enabled (User):";
9262
+ var EXT_ENABLED_WORKSPACE = "Enabled (Workspace):";
8321
9263
  var EXT_TRUE = "true";
8322
9264
  function tableState(n3, text2) {
8323
9265
  const line = text2.split("\n").find((l2) => l2.split(" ").includes(n3.plugin));
@@ -8326,6 +9268,8 @@ function tableState(n3, text2) {
8326
9268
  }
8327
9269
  function extensionState(n3, text2) {
8328
9270
  let mine = false;
9271
+ let state;
9272
+ let workspaceOff = false;
8329
9273
  for (const raw of text2.split("\n")) {
8330
9274
  const line = raw.trimEnd();
8331
9275
  if (line.length && !line.startsWith(" ")) {
@@ -8333,16 +9277,19 @@ function extensionState(n3, text2) {
8333
9277
  continue;
8334
9278
  }
8335
9279
  const t2 = line.trim();
8336
- if (mine && t2.startsWith(EXT_ENABLED_USER)) return t2.slice(EXT_ENABLED_USER.length).trim() === EXT_TRUE ? "enabled" : "disabled";
9280
+ if (!mine) continue;
9281
+ if (t2.startsWith(EXT_ENABLED_USER)) state = t2.slice(EXT_ENABLED_USER.length).trim() === EXT_TRUE ? "enabled" : "disabled";
9282
+ if (t2.startsWith(EXT_ENABLED_WORKSPACE)) workspaceOff = t2.slice(EXT_ENABLED_WORKSPACE.length).trim() !== EXT_TRUE;
8337
9283
  }
8338
- return void 0;
9284
+ return { state, workspaceOff };
8339
9285
  }
8340
9286
  function nativeState(row, env) {
9287
+ const none = { state: void 0, workspaceOff: false };
8341
9288
  const n3 = row.nativePlugin;
8342
- if (!n3 || !hostBin(n3.bin, env).file) return void 0;
9289
+ if (!n3 || !hostBin(n3.bin, env).file) return none;
8343
9290
  const r2 = runBin(n3.bin, n3.args, env);
8344
- if (r2.status !== 0) return void 0;
8345
- return n3.format === "extension" ? extensionState(n3, `${r2.stdout}${r2.stderr}`) : tableState(n3, `${r2.stdout}`);
9291
+ if (r2.status !== 0) return none;
9292
+ return n3.format === "extension" ? extensionState(n3, `${r2.stdout}${r2.stderr}`) : { state: tableState(n3, `${r2.stdout}`), workspaceOff: false };
8346
9293
  }
8347
9294
  function nativeRow(row, n3) {
8348
9295
  return {
@@ -8363,9 +9310,9 @@ function trimChars(w, chars) {
8363
9310
  while (b3 > a2 && chars.includes(w.charAt(b3 - 1))) b3--;
8364
9311
  return w.slice(a2, b3);
8365
9312
  }
8366
- async function nativeResult(row, ctx) {
9313
+ async function nativeResult(row, ctx, apply2) {
8367
9314
  const n3 = row.nativePlugin;
8368
- const state = nativeState(row, ctx.env);
9315
+ const { state, workspaceOff } = nativeState(row, ctx.env);
8369
9316
  if (!n3 || state === void 0) return void 0;
8370
9317
  const bin = hostBin(n3.bin, ctx.env).file;
8371
9318
  if (state === "disabled") {
@@ -8380,25 +9327,144 @@ async function nativeResult(row, ctx) {
8380
9327
  reason: `context-mode is installed but disabled in ${n3.bin}, run ${n3.bin} ${n3.enable.join(" ")}`
8381
9328
  };
8382
9329
  }
8383
- const res = { id: row.id, status: "PASS", v1: [], changes: [], checks: await verifyRow(nativeRow(row, n3), ctx), bin };
9330
+ const res = { id: row.id, status: "PASS", v1: [], changes: [], checks: [], bin };
9331
+ let hooks = n3.hookTrust ? await listPluginHooks(ctx.env, n3.plugin, ctx.home) : void 0;
9332
+ if (apply2 && hooks?.some((h2) => !h2.trusted)) {
9333
+ try {
9334
+ const done = trustPluginHooks(row, ctx, apply2, hooks);
9335
+ res.changes.push(...done);
9336
+ if (done.length && !apply2.dryRun) hooks = await listPluginHooks(ctx.env, n3.plugin, ctx.home);
9337
+ } catch (e) {
9338
+ apply2.run.rollback(row.id, ctx.env);
9339
+ return { ...res, status: "FAIL", reason: e.message, rolledBack: true };
9340
+ }
9341
+ }
9342
+ res.checks = await verifyRow(nativeRow(row, n3), ctx);
9343
+ if (n3.hookTrust) res.checks = withHookTrust(res.checks, hooks, !!apply2?.dryRun);
9344
+ if (n3.format === "extension") res.checks = withHookGate(res.checks, geminiGate(n3, ctx, workspaceOff));
8384
9345
  const bad = res.checks.filter((c3) => !c3.ok);
8385
9346
  if (bad.length) {
8386
9347
  res.status = "FAIL";
8387
9348
  res.reason = bad.map((c3) => `${c3.name}: ${c3.detail}`).join("; ");
9349
+ if (apply2 && !apply2.dryRun && res.changes.length) {
9350
+ apply2.run.rollback(row.id, ctx.env);
9351
+ res.rolledBack = true;
9352
+ }
8388
9353
  }
8389
9354
  return res;
8390
9355
  }
9356
+ function trustPluginHooks(row, ctx, apply2, hooks) {
9357
+ const file = path12.join(codexDirOf(ctx.env, ctx.home), CODEX_CONFIG_FILE2);
9358
+ const text2 = readOr(file);
9359
+ let edit;
9360
+ try {
9361
+ edit = editHostConfigText(row.id, file, text2 ?? "", "toml", pluginTrustEntries(hooks));
9362
+ } catch (e) {
9363
+ if (e instanceof CtxError) throw new Error(parseFail(row, file));
9364
+ throw e;
9365
+ }
9366
+ if (!edit.edits.length) return [];
9367
+ if (!apply2.dryRun) {
9368
+ assertWritable(row, file);
9369
+ const raw = readRaw(file);
9370
+ apply2.run.record({ agent: row.id, file, existed: raw !== void 0 }, raw);
9371
+ atomicWrite(file, raw === void 0 ? edit.text : withLayout(edit.text, hostLayout(raw)));
9372
+ }
9373
+ return edit.edits.map((e) => ({ file, ...e }));
9374
+ }
9375
+ function geminiGate(n3, ctx, workspaceOff) {
9376
+ if (n3.bin === "qwen") {
9377
+ if (workspaceOff && n3.enable) return `qwen runs no hook: context-mode is disabled for this workspace; run ${n3.bin} ${n3.enable.join(" ")}`;
9378
+ return qwenHooksOff(ctx.env, ctx.home, process.cwd());
9379
+ }
9380
+ if (n3.bin !== "gemini") return void 0;
9381
+ if (workspaceOff && n3.enable) return `gemini lists context-mode disabled for this workspace, so it runs no hook; run ${n3.bin} ${n3.enable.join(" ")} --scope workspace`;
9382
+ return geminiSettingsGate(ctx.env, ctx.home, process.cwd());
9383
+ }
9384
+ function withHookGate(checks, detail) {
9385
+ if (detail === void 0) return checks;
9386
+ return checks.map((c3) => c3.name === "hook-registered" ? { name: c3.name, ok: false, detail } : c3);
9387
+ }
9388
+ var UNTRUSTED_FIX = CODEX_UNTRUSTED_FIX;
9389
+ function withHookTrust(checks, hooks, dryRun) {
9390
+ if (hooks === void 0) return [...checks, { name: "hook-trust", ok: true, warn: true, detail: "codex did not report hook trust (codex app-server hooks/list)" }];
9391
+ const detail = untrustedPluginHooksDetail(hooks);
9392
+ if (detail === void 0 || dryRun) return checks;
9393
+ return checks.map((c3) => c3.name === "hook-registered" ? { name: c3.name, ok: false, detail } : c3);
9394
+ }
9395
+ async function copilotEnabledCheck(row, ctx) {
9396
+ const name = "hook-enabled";
9397
+ const h2 = row.hookInstall;
9398
+ const settings2 = row.copilotSettings;
9399
+ if (h2.kind !== "file" || !settings2) return { name, ok: true };
9400
+ const hooks = await listCopilotHooks(ctx.env, h2.file, ctx.home);
9401
+ if (hooks === void 0) return { name, ok: true, warn: true, detail: "copilot did not report hook state (copilot --server --stdio hooks.discover)" };
9402
+ if (!hooks.length) return { name, ok: false, detail: `copilot lists no context-mode hook from ${h2.file}; ${UNTRUSTED_FIX}` };
9403
+ const bad = hooks.filter((x2) => !x2.enabled);
9404
+ if (!bad.length) return { name, ok: true };
9405
+ let doc;
9406
+ try {
9407
+ const t2 = readOr(settings2);
9408
+ doc = t2 === void 0 ? {} : parseHostConfig(row.id, settings2, t2, "jsonc");
9409
+ } catch {
9410
+ doc = {};
9411
+ }
9412
+ if (isObjSetup(doc) && doc.disableAllHooks === true) return { name, ok: false, detail: `${settings2} sets disableAllHooks, so copilot runs no hook; set it to false` };
9413
+ if (bad.every((x2) => x2.disableKey !== void 0)) return { name, ok: false, detail: `${bad.length} of ${hooks.length} context-mode hooks disabled in ${settings2} disabledHooks, so they do not run; ${UNTRUSTED_FIX}` };
9414
+ return { name, ok: false, detail: `copilot lists ${bad.length} of ${hooks.length} context-mode hooks disabled by a policy, so they do not run` };
9415
+ }
9416
+ async function enableCopilotHooks(row, ctx, run) {
9417
+ const h2 = row.hookInstall;
9418
+ const settings2 = row.copilotSettings;
9419
+ if (h2.kind !== "file" || !settings2) return [];
9420
+ const listed = await listCopilotHooks(ctx.env, h2.file, ctx.home);
9421
+ const keys = (listed ?? []).flatMap((x2) => !x2.enabled && x2.disableKey !== void 0 ? [x2.disableKey] : []);
9422
+ if (!keys.length) return [];
9423
+ const text2 = readOr(settings2);
9424
+ let doc = {};
9425
+ if (text2 !== void 0 && text2.trim() !== "") {
9426
+ try {
9427
+ doc = parseHostConfig(row.id, settings2, text2, "jsonc");
9428
+ } catch {
9429
+ throw new Error(parseFail(row, settings2));
9430
+ }
9431
+ }
9432
+ if (!isObjSetup(doc)) throw new Error(parseFail(row, settings2));
9433
+ const cur = Array.isArray(doc.disabledHooks) ? doc.disabledHooks : [];
9434
+ const next = cur.filter((k) => !keys.includes(k));
9435
+ if (next.length === cur.length) return [];
9436
+ let edit;
9437
+ try {
9438
+ edit = editHostConfigText(row.id, settings2, text2 ?? "", "jsonc", [[["disabledHooks"], next]]);
9439
+ } catch (e) {
9440
+ if (e instanceof CtxError) throw new Error(parseFail(row, settings2));
9441
+ throw e;
9442
+ }
9443
+ assertWritable(row, settings2);
9444
+ const raw = readRaw(settings2);
9445
+ run.record({ agent: row.id, file: settings2, existed: raw !== void 0 }, raw);
9446
+ atomicWrite(settings2, raw === void 0 ? edit.text : withLayout(edit.text, hostLayout(raw)));
9447
+ return edit.edits.map((e) => ({ file: settings2, ...e }));
9448
+ }
9449
+ var isObjSetup = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8391
9450
  async function verifyRow(row, ctx) {
8392
9451
  const env = ctx.env;
8393
9452
  const checks = [parseCheck(row)];
8394
- const l2 = listCheck(row, env);
9453
+ const ls = listState(row, env);
9454
+ const l2 = ls.check;
8395
9455
  if (l2) checks.push(l2);
8396
9456
  const cp = copyCheck(row, ctx.pkgDir);
8397
9457
  if (cp) checks.push(cp);
8398
9458
  checks.push(await mcpCheck(row.serverCommand, env));
8399
9459
  if (row.hookCommand) checks.push(hookCheck(row, env));
8400
- checks.push(hookRegisteredCheck(row, env, l2), hookRunsCheck(row, env), hookSeenCheck(row, ctx.home), skillsCheck(row, ctx.pkgDir));
8401
- return checks;
9460
+ checks.push(hookRegisteredCheck(row, env, l2));
9461
+ const en = hookEnabledCheck(row, ls.status);
9462
+ if (en) checks.push(en);
9463
+ if (row.copilotSettings) checks.push(await copilotEnabledCheck(row, ctx));
9464
+ checks.push(hookRunsCheck(row, env), hookSeenCheck(row, ctx.home), skillsCheck(row, ctx.pkgDir));
9465
+ if (row.id === "pi") return withHookGate(checks, piSettingsGate(env, ctx.home, ctx.pkgDir, process.cwd()));
9466
+ if (row.id === "vscode") return withHookGate(checks, vscodeSettingsGate(env, ctx.home, process.cwd()));
9467
+ return row.id === "zcode" ? withHookGate(checks, zcodeConfigGate(ctx.home)) : checks;
8402
9468
  }
8403
9469
  var Run = class {
8404
9470
  manifest;
@@ -8409,16 +9475,16 @@ var Run = class {
8409
9475
  this.runId = runId;
8410
9476
  }
8411
9477
  get dir() {
8412
- return path6.join(this.root, BACKUP_DIR, this.runId);
9478
+ return path12.join(this.root, BACKUP_DIR, this.runId);
8413
9479
  }
8414
9480
  save() {
8415
- if (this.manifest) atomicWrite(path6.join(this.dir, MANIFEST), JSON.stringify(this.manifest, null, 2));
9481
+ if (this.manifest) atomicWrite(path12.join(this.dir, MANIFEST), JSON.stringify(this.manifest, null, 2));
8416
9482
  }
8417
9483
  record(e, bytes) {
8418
9484
  if (!this.manifest) this.manifest = { runId: this.runId, path: this.dir, entries: [] };
8419
9485
  if (bytes !== void 0) {
8420
- const rel = path6.join(FILES, String(this.manifest.entries.length));
8421
- atomicWrite(path6.join(this.dir, rel), bytes);
9486
+ const rel = path12.join(FILES, String(this.manifest.entries.length));
9487
+ atomicWrite(path12.join(this.dir, rel), bytes);
8422
9488
  e.backup = rel;
8423
9489
  }
8424
9490
  this.manifest.entries.push(e);
@@ -8438,26 +9504,26 @@ function undo(dir, entries, env) {
8438
9504
  continue;
8439
9505
  }
8440
9506
  if (!e.file) continue;
8441
- if (e.existed && e.backup) atomicWrite(e.file, readFileSync3(path6.join(dir, e.backup), "utf8"));
9507
+ if (e.existed && e.backup) atomicWrite(e.file, readFileSync10(path12.join(dir, e.backup), "utf8"));
8442
9508
  else unlinkWithRetry(e.file);
8443
9509
  }
8444
9510
  }
8445
9511
  function takeLock(root, runId) {
8446
- const file = path6.join(root, LOCK_FILE);
8447
- mkdirSync3(root, { recursive: true });
9512
+ const file = path12.join(root, LOCK_FILE);
9513
+ mkdirSync5(root, { recursive: true });
8448
9514
  for (let attempt = 0; attempt < 2; attempt++) {
8449
9515
  try {
8450
- writeFileSync2(file, JSON.stringify({ pid: process.pid, runId }), { flag: "wx" });
9516
+ writeFileSync3(file, JSON.stringify({ pid: process.pid, runId }), { flag: "wx" });
8451
9517
  return void 0;
8452
9518
  } catch (e) {
8453
9519
  if (e.code !== "EEXIST") throw e;
8454
9520
  let pid = 0;
8455
9521
  try {
8456
- pid = Number(JSON.parse(readFileSync3(file, "utf8")).pid);
9522
+ pid = Number(JSON.parse(readFileSync10(file, "utf8")).pid);
8457
9523
  } catch {
8458
9524
  }
8459
9525
  if (pid && pidAlive(pid)) return `setup lock ${file} is held by pid ${pid}; wait for that run or remove the lock`;
8460
- rmSync(file, { force: true });
9526
+ rmSync2(file, { force: true });
8461
9527
  }
8462
9528
  }
8463
9529
  return `setup lock ${file} could not be taken`;
@@ -8467,20 +9533,20 @@ function agentHomeDir(id, ctx) {
8467
9533
  if (id === "copilot-cli") return copilotDirOf(ctx.env, ctx.home);
8468
9534
  if (id === "kiro") return kiroDirOf(ctx.env, ctx.home);
8469
9535
  if (id === "opencode") return opencodeDirOf(ctx.env, ctx.home);
8470
- return path6.join(ctx.home, ...AGENT_HOME_DIR[id]);
9536
+ return path12.join(ctx.home, ...AGENT_HOME_DIR[id]);
8471
9537
  }
8472
9538
  function detectAgents(reg, ctx) {
8473
- return reg.filter((r2) => existsSync6(agentHomeDir(r2.id, ctx)) || r2.listCommand && which(r2.listCommand.bin, ctx.env)).map((r2) => r2.id);
9539
+ return reg.filter((r2) => existsSync14(agentHomeDir(r2.id, ctx)) || r2.listCommand && which(r2.listCommand.bin, ctx.env)).map((r2) => r2.id);
8474
9540
  }
8475
9541
  async function runSetup(opts) {
8476
9542
  const ctx = { home: opts.home, pkgDir: opts.pkgDir, env: opts.env };
8477
9543
  const runId = opts.runId ?? (/* @__PURE__ */ new Date()).toISOString().split(":").join("-").split(".").join("-");
8478
9544
  const reg = buildRegistry(ctx);
8479
9545
  for (const f2 of ["server.mjs", "hook.mjs"]) {
8480
- if (!existsSync6(path6.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path6.join(ctx.pkgDir, f2)} is missing` };
9546
+ if (!existsSync14(path12.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path12.join(ctx.pkgDir, f2)} is missing` };
8481
9547
  }
8482
9548
  const ids = opts.agents ?? detectAgents(reg, ctx);
8483
- const root = path6.join(ctx.home, STATE_DIR);
9549
+ const root = path12.join(ctx.home, STATE_DIR);
8484
9550
  if (!opts.dryRun) {
8485
9551
  const held = takeLock(root, runId);
8486
9552
  if (held) return { exitCode: 1, agents: [], error: held };
@@ -8490,7 +9556,7 @@ async function runSetup(opts) {
8490
9556
  let current;
8491
9557
  const onAbort = () => {
8492
9558
  if (current !== void 0 && !opts.dryRun) run.rollback(current, ctx.env);
8493
- if (!opts.dryRun) rmSync(path6.join(root, LOCK_FILE), { force: true });
9559
+ if (!opts.dryRun) rmSync2(path12.join(root, LOCK_FILE), { force: true });
8494
9560
  };
8495
9561
  opts.signal?.addEventListener("abort", onAbort, { once: true });
8496
9562
  try {
@@ -8502,14 +9568,14 @@ async function runSetup(opts) {
8502
9568
  }
8503
9569
  current = id;
8504
9570
  opts.onAgent?.(id, "start");
8505
- const res = await nativeResult(row, ctx) ?? await setupRow(row, ctx, run, !!opts.dryRun);
9571
+ const res = await nativeResult(row, ctx, { run, dryRun: !!opts.dryRun }) ?? await setupRow(row, ctx, run, !!opts.dryRun);
8506
9572
  current = void 0;
8507
9573
  agents.push(res);
8508
9574
  opts.onAgent?.(id, "done", res);
8509
9575
  }
8510
9576
  } finally {
8511
9577
  opts.signal?.removeEventListener("abort", onAbort);
8512
- if (!opts.dryRun) rmSync(path6.join(root, LOCK_FILE), { force: true });
9578
+ if (!opts.dryRun) rmSync2(path12.join(root, LOCK_FILE), { force: true });
8513
9579
  }
8514
9580
  return { exitCode: agents.some((a2) => a2.status === "FAIL") ? 1 : 0, agents, backupDir: run.manifest ? run.dir : void 0 };
8515
9581
  }
@@ -8525,13 +9591,14 @@ async function setupRow(row, ctx, run, dryRun) {
8525
9591
  if (!row.config && !row.cli) return { ...res, status: "SKIPPED", reason: `${row.id}: no setup path in the registry` };
8526
9592
  let plan;
8527
9593
  try {
8528
- const listed = needsBin ? listCheck(row, ctx.env)?.ok === true : false;
8529
- plan = planRow(row, listed, copyCheck(row, ctx.pkgDir)?.ok === false, ctx.env);
9594
+ const ls = needsBin ? listState(row, ctx.env) : { status: void 0, check: void 0 };
9595
+ const listed = ls.check?.ok === true;
9596
+ plan = planRow(row, listed, copyCheck(row, ctx.pkgDir)?.ok === false, ctx.env, listed && ls.status === "disabled");
8530
9597
  } catch (e) {
8531
9598
  return { ...res, status: "FAIL", reason: e.message };
8532
9599
  }
8533
9600
  const configEdited = (file) => plan.edits.some((e) => e.file === file && e.changes.some((c3) => !isTrust(row, c3)));
8534
- res.v1 = detectV1(row.id, ctx.home, { claudeDir: claudeDirOf(ctx.env, ctx.home), copilotDir: copilotDirOf(ctx.env, ctx.home), kiroDir: kiroDirOf(ctx.env, ctx.home), opencodeDir: opencodeDirOf(ctx.env, ctx.home) }).filter((f2) => !(row.config && f2.file === row.config.file && !configEdited(f2.file)));
9601
+ res.v1 = detectV1(row.id, ctx.home, { claudeDir: claudeDirOf(ctx.env, ctx.home), codexDir: codexDirOf(ctx.env, ctx.home), copilotDir: copilotDirOf(ctx.env, ctx.home), kiroDir: kiroDirOf(ctx.env, ctx.home), opencodeDir: opencodeDirOf(ctx.env, ctx.home) }).filter((f2) => !(row.config && f2.file === row.config.file && !configEdited(f2.file)));
8535
9602
  res.changes = [...plan.edits.flatMap((e) => e.changes), ...[...plan.cli, ...plan.refresh].map((args) => ({ command: [row.cli.bin, ...args] }))];
8536
9603
  if (dryRun) return res;
8537
9604
  try {
@@ -8542,15 +9609,16 @@ async function setupRow(row, ctx, run, dryRun) {
8542
9609
  atomicWrite(e.file, e.plain || raw === void 0 ? e.after : withLayout(e.after, hostLayout(raw)));
8543
9610
  }
8544
9611
  for (const args of plan.cli) {
8545
- const r2 = runBin(row.cli.bin, args, ctx.env, row.cli.input ?? "");
9612
+ const r2 = runBin(row.cli.bin, args, ctx.env, row.cli.input ?? "", INSTALL_TIMEOUT_MS);
8546
9613
  if (!installExitOk(r2.status, r2.status === WIN_EXIT_CRASH && listCheck(row, ctx.env)?.ok === true)) throw new Error(`${row.cli.bin} ${args.join(" ")} exited ${r2.status}: ${`${r2.stderr}`.trim()}`);
8547
9614
  }
8548
9615
  if (plan.cli.length) for (const args of row.cli.remove) run.record({ agent: row.id, undo: { bin: row.cli.bin, args } });
8549
9616
  for (const args of plan.refresh) {
8550
- const r2 = runBin(row.cli.bin, args, ctx.env);
9617
+ const r2 = runBin(row.cli.bin, args, ctx.env, void 0, INSTALL_TIMEOUT_MS);
8551
9618
  if (r2.status !== 0) throw new Error(`${row.cli.bin} ${args.join(" ")} exited ${r2.status}: ${`${r2.stderr}`.trim()}`);
8552
9619
  run.record({ agent: row.id, ran: { bin: row.cli.bin, args } });
8553
9620
  }
9621
+ res.changes.push(...await enableCopilotHooks(row, ctx, run));
8554
9622
  res.checks = await verifyRow(row, ctx);
8555
9623
  const bad = res.checks.filter((c3) => !c3.ok);
8556
9624
  if (bad.length) throw new Error(bad.map((c3) => `${c3.name}: ${c3.detail}`).join("; "));
@@ -8566,10 +9634,10 @@ async function runDoctor(opts) {
8566
9634
  const ctx = { home: opts.home, pkgDir: opts.pkgDir, env: opts.env };
8567
9635
  const reg = buildRegistry(ctx);
8568
9636
  for (const f2 of ["server.mjs", "hook.mjs"]) {
8569
- if (!existsSync6(path6.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path6.join(ctx.pkgDir, f2)} is missing` };
9637
+ if (!existsSync14(path12.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path12.join(ctx.pkgDir, f2)} is missing` };
8570
9638
  }
8571
9639
  const ids = opts.agents ?? detectAgents(reg, ctx);
8572
- const run = new Run(path6.join(ctx.home, STATE_DIR), "doctor");
9640
+ const run = new Run(path12.join(ctx.home, STATE_DIR), "doctor");
8573
9641
  const agents = [];
8574
9642
  for (const id of ids) {
8575
9643
  const row = reg.find((r2) => r2.id === id);
@@ -8589,9 +9657,9 @@ async function runDoctor(opts) {
8589
9657
  if (res.v1.some((f2) => !UPGRADE_REPORT_ONLY_REASONS.includes(f2.reason))) {
8590
9658
  res.status = "FAIL";
8591
9659
  res.reason = V1_FORM_REASON;
8592
- } else if (res.changes.length && !onlyTrust(row, res.changes)) {
9660
+ } else if (res.changes.length && !onlyTrust(row, res.changes) && !hasPluginIssue(row)) {
8593
9661
  res.status = "FAIL";
8594
- res.reason = NOT_SET_UP_REASON;
9662
+ res.reason = notSetUpReason(row, res, ctx.env);
8595
9663
  } else {
8596
9664
  res.checks = await verifyRow(row, ctx);
8597
9665
  const bad = res.checks.filter((c3) => !c3.ok);
@@ -8606,12 +9674,25 @@ async function runDoctor(opts) {
8606
9674
  }
8607
9675
  return { exitCode: agents.some((a2) => a2.status === "FAIL") ? 1 : 0, agents };
8608
9676
  }
9677
+ function notSetUpReason(row, res, env) {
9678
+ const h2 = row.hookInstall;
9679
+ const missing = row.id === "opencode" && h2.kind === "plugin-list" && res.changes.some((c3) => c3.path === h2.key[0]);
9680
+ const oc2 = missing && hostBin("opencode", env).file !== void 0 && opencodeMajor("opencode", env) >= 2;
9681
+ return oc2 ? `${NOT_SET_UP_REASON}, or run: opencode plugin add context-mode@next` : NOT_SET_UP_REASON;
9682
+ }
9683
+ function hasPluginIssue(row) {
9684
+ const h2 = row.hookInstall;
9685
+ if (h2.kind === "file") return row.id === "kiro" && kiroDisabledIssue(h2) !== void 0;
9686
+ return h2.kind === "plugin-list" && pluginListIssue(h2) !== void 0;
9687
+ }
8609
9688
  function onlyTrust(row, changes) {
8610
9689
  return changes.every((c3) => isTrust(row, c3) || isRefresh(row, c3));
8611
9690
  }
8612
9691
  function isRefresh(row, c3) {
8613
9692
  const r2 = row.copy;
8614
- return r2 !== void 0 && c3.command !== void 0 && c3.command.join(" ") === [r2.bin, ...r2.refresh].join(" ");
9693
+ if (r2 === void 0 || c3.command === void 0) return false;
9694
+ const cmd = c3.command.join(" ");
9695
+ return cmd === [r2.bin, ...r2.refresh].join(" ") || cmd === [r2.bin, ...r2.enable].join(" ");
8615
9696
  }
8616
9697
  function isTrust(row, c3) {
8617
9698
  const h2 = row.hookInstall;
@@ -8619,28 +9700,28 @@ function isTrust(row, c3) {
8619
9700
  }
8620
9701
  function runRemove(opts) {
8621
9702
  const env = opts.env ?? process.env;
8622
- const root = path6.join(opts.home, STATE_DIR);
8623
- const base = path6.join(root, BACKUP_DIR);
8624
- if (!existsSync6(base)) return { exitCode: 0, restored: 0 };
9703
+ const root = path12.join(opts.home, STATE_DIR);
9704
+ const base = path12.join(root, BACKUP_DIR);
9705
+ if (!existsSync14(base)) return { exitCode: 0, restored: 0 };
8625
9706
  const held = takeLock(root, "remove");
8626
9707
  if (held) return { exitCode: 1, restored: 0, error: held };
8627
9708
  let restored = 0;
8628
9709
  try {
8629
- const runs = readdirSync4(base).map((r2) => path6.join(base, r2)).filter((d) => existsSync6(path6.join(d, MANIFEST))).sort().reverse();
9710
+ const runs = readdirSync5(base).map((r2) => path12.join(base, r2)).filter((d) => existsSync14(path12.join(d, MANIFEST))).sort().reverse();
8630
9711
  for (const dir of runs) {
8631
- const m3 = JSON.parse(readFileSync3(path6.join(dir, MANIFEST), "utf8"));
9712
+ const m3 = JSON.parse(readFileSync10(path12.join(dir, MANIFEST), "utf8"));
8632
9713
  undo(dir, m3.entries, env);
8633
9714
  restored += m3.entries.length;
8634
- renameWithRetry(path6.join(dir, MANIFEST), path6.join(dir, MANIFEST_DONE));
9715
+ renameWithRetry(path12.join(dir, MANIFEST), path12.join(dir, MANIFEST_DONE));
8635
9716
  }
8636
9717
  } finally {
8637
- rmSync(path6.join(root, LOCK_FILE), { force: true });
9718
+ rmSync2(path12.join(root, LOCK_FILE), { force: true });
8638
9719
  }
8639
9720
  return { exitCode: 0, restored };
8640
9721
  }
8641
9722
 
8642
9723
  // src/setup/print.ts
8643
- import { readFileSync as readFileSync4 } from "node:fs";
9724
+ import { readFileSync as readFileSync11 } from "node:fs";
8644
9725
  var SHELL_SAFE_PUNCT = "@%+=:,./-_";
8645
9726
  function isShellSafe(s) {
8646
9727
  if (s === "") return false;
@@ -8668,7 +9749,7 @@ function printPlan(row, env) {
8668
9749
  else if (h2.kind === "plugin-list") steps.push({ kind: "hook", file: h2.file, block: JSON.stringify({ [h2.key[0]]: [h2.entry] }, null, 2) + "\n" });
8669
9750
  const sk = row.skillInstall;
8670
9751
  if (sk.kind === "dir") {
8671
- for (const f2 of sk.files) steps.push({ kind: "skill", file: f2.file, block: renderSkill(readFileSync4(f2.src, "utf8"), sk.prefixes) });
9752
+ for (const f2 of sk.files) steps.push({ kind: "skill", file: f2.file, block: renderSkill(readFileSync11(f2.src, "utf8"), sk.prefixes) });
8672
9753
  }
8673
9754
  return { agent: row.id, steps, verify: `context-mode doctor --agents ${row.id}` };
8674
9755
  }
@@ -8829,23 +9910,22 @@ function buildIssueReport(command, res, ui) {
8829
9910
  return { text: redact(lines.join("\n"), ui.ctx), title };
8830
9911
  }
8831
9912
  function ghReady(env) {
8832
- const r2 = spawnSync3("gh", ["auth", "status"], { env, stdio: "ignore", timeout: 1e4, windowsHide: true });
9913
+ const r2 = spawnSync5("gh", ["auth", "status"], { env, stdio: "ignore", timeout: 1e4, windowsHide: true });
8833
9914
  return r2.status === 0;
8834
9915
  }
8835
- function issueUrl(title, body) {
8836
- const b3 = body.length > URL_BODY_MAX ? body.slice(0, URL_BODY_MAX) + "\n(cut; attach the report file)" : body;
8837
- return `https://github.com/${ISSUE_REPO}/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(b3)}`;
9916
+ function issueUrl(title, summary) {
9917
+ return formUrl(title, summary.length > URL_BODY_MAX ? summary.slice(0, URL_BODY_MAX) : summary);
8838
9918
  }
8839
9919
  async function report(ui, command, res, write) {
8840
9920
  const { text: text2, title } = buildIssueReport(command, res, ui);
8841
9921
  let file = "";
8842
9922
  if (write) {
8843
- const dir = path7.join(ui.ctx.home, STATE_DIR, REPORT_DIR);
8844
- mkdirSync4(dir, { recursive: true });
8845
- file = path7.join(dir, `${command}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
8846
- writeFileSync3(file, text2);
9923
+ const dir = path13.join(ui.ctx.home, STATE_DIR, REPORT_DIR);
9924
+ mkdirSync6(dir, { recursive: true });
9925
+ file = path13.join(dir, `${command}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
9926
+ writeFileSync4(file, text2);
8847
9927
  }
8848
- const gh = `gh issue create --repo ${ISSUE_REPO} --title ${JSON.stringify(title)} --body-file ${JSON.stringify(file || "<report>")}`;
9928
+ const gh = `gh issue create --repo ${ISSUE_REPO} --title ${JSON.stringify(title)} --label bug --body-file ${JSON.stringify(file || "<report>")}`;
8849
9929
  const p3 = ui.clack;
8850
9930
  if (!p3) {
8851
9931
  if (ui.f.debug) err(text2);
@@ -8860,15 +9940,15 @@ async function report(ui, command, res, write) {
8860
9940
  return;
8861
9941
  }
8862
9942
  if (file && ghReady(ui.ctx.env)) {
8863
- const r2 = spawnSync3("gh", ["issue", "create", "--repo", ISSUE_REPO, "--title", title, "--body-file", file], { env: ui.ctx.env, encoding: "utf8", timeout: 6e4, windowsHide: true });
9943
+ const r2 = spawnSync5("gh", ["issue", "create", "--repo", ISSUE_REPO, "--title", title, "--label", "bug", "--body-file", file], { env: ui.ctx.env, encoding: "utf8", timeout: 6e4, windowsHide: true });
8864
9944
  if (r2.status === 0) {
8865
9945
  p3.log.success(`Issue opened: ${`${r2.stdout}`.trim()}`);
8866
9946
  return;
8867
9947
  }
8868
9948
  p3.log.warn(`gh issue create failed: ${`${r2.stderr}`.trim()}`);
8869
9949
  }
8870
- p3.log.info(`Open this URL to file the issue:
8871
- ${issueUrl(title, text2)}`);
9950
+ p3.log.info(`Open this URL to file the issue (paste the report file into the form):
9951
+ ${issueUrl(title, title)}`);
8872
9952
  }
8873
9953
  async function apply(ui, agents, dryRun) {
8874
9954
  const ac = new AbortController();
@@ -8921,7 +10001,8 @@ function list(ui) {
8921
10001
  const detected = new Set(detectAgents(reg, ui.ctx));
8922
10002
  const rows = ADAPTERS.map((a2) => ({
8923
10003
  id: a2.id,
8924
- level: Object.keys(a2.eventMap).length ? "full" : "MCP only",
10004
+ hooks: a2.hookChannel.kind,
10005
+ // ADR-0020: every agent has a hook channel
8925
10006
  installMode: a2.installMode,
8926
10007
  detected: detected.has(a2.id)
8927
10008
  }));
@@ -8929,8 +10010,8 @@ function list(ui) {
8929
10010
  out(JSON.stringify({ agents: rows }));
8930
10011
  return EXIT_OK;
8931
10012
  }
8932
- out(`${"AGENT".padEnd(13)} ${"SUPPORT".padEnd(9)} ${"FOUND".padEnd(9)} INSTALL`);
8933
- for (const r2 of rows) out(`${r2.id.padEnd(13)} ${r2.level.padEnd(9)} ${(r2.detected ? "detected" : "-").padEnd(9)} ${r2.installMode}`);
10013
+ out(`${"AGENT".padEnd(13)} ${"HOOKS".padEnd(11)} ${"FOUND".padEnd(9)} INSTALL`);
10014
+ for (const r2 of rows) out(`${r2.id.padEnd(13)} ${r2.hooks.padEnd(11)} ${(r2.detected ? "detected" : "-").padEnd(9)} ${r2.installMode}`);
8934
10015
  return EXIT_OK;
8935
10016
  }
8936
10017
  async function remove(ui) {
@@ -8950,7 +10031,7 @@ async function remove(ui) {
8950
10031
  }
8951
10032
  }
8952
10033
  if (ui.f.dryRun) {
8953
- out(`Would restore every file recorded under ${path7.join(ui.ctx.home, STATE_DIR, "backups")}`);
10034
+ out(`Would restore every file recorded under ${path13.join(ui.ctx.home, STATE_DIR, "backups")}`);
8954
10035
  return EXIT_OK;
8955
10036
  }
8956
10037
  const r2 = runRemove({ home: ui.ctx.home, env: ui.ctx.env });
@@ -9082,20 +10163,20 @@ async function upgrade(ui) {
9082
10163
  }
9083
10164
  const shell = process.platform === "win32";
9084
10165
  progress2(ui, `running ${install}`);
9085
- const r2 = spawnSync3(npm, ["i", "-g", spec], { env: ui.ctx.env, encoding: "utf8", shell, windowsHide: true });
10166
+ const r2 = spawnSync5(npm, ["i", "-g", spec], { env: ui.ctx.env, encoding: "utf8", shell, windowsHide: true });
9086
10167
  if (r2.status !== 0) {
9087
10168
  const why = (`${r2.stderr ?? ""}`.trim().split("\n").pop() ?? "") || (r2.error?.message ?? "");
9088
10169
  err(`FAIL upgrade: ${install} exited ${r2.status ?? "?"}${why ? `: ${why}` : ""}. Fix: ${install}`);
9089
10170
  return EXIT_FAIL;
9090
10171
  }
9091
- const root = `${spawnSync3(npm, ["root", "-g"], { env: ui.ctx.env, encoding: "utf8", shell, windowsHide: true }).stdout ?? ""}`.trim();
9092
- const cli = path7.join(root, "context-mode", "cli.mjs");
9093
- if (!root || !existsSync7(cli)) {
10172
+ const root = `${spawnSync5(npm, ["root", "-g"], { env: ui.ctx.env, encoding: "utf8", shell, windowsHide: true }).stdout ?? ""}`.trim();
10173
+ const cli = path13.join(root, "context-mode", "cli.mjs");
10174
+ if (!root || !existsSync15(cli)) {
9094
10175
  err(`FAIL upgrade: ${cli} not found after ${install}. Fix: ${install}`);
9095
10176
  return EXIT_FAIL;
9096
10177
  }
9097
10178
  progress2(ui, `running context-mode ${repairArgs.join(" ")}`);
9098
- const c3 = spawnSync3(process.execPath, [cli, ...repairArgs], { env: ui.ctx.env, stdio: "inherit", windowsHide: true });
10179
+ const c3 = spawnSync5(process.execPath, [cli, ...repairArgs], { env: ui.ctx.env, stdio: "inherit", windowsHide: true });
9099
10180
  return c3.status ?? (c3.signal === "SIGINT" ? EXIT_SIGINT : EXIT_FAIL);
9100
10181
  }
9101
10182
  async function runCommand(cmd, args, env) {
@@ -9128,6 +10209,18 @@ Run context-mode ${cmd} --help.`);
9128
10209
  }
9129
10210
  }
9130
10211
 
10212
+ // src/entries/is-entry.ts
10213
+ import { realpathSync as realpathSync8 } from "node:fs";
10214
+ function isEntry(main2, argv1, self) {
10215
+ if (main2 !== void 0) return main2;
10216
+ if (argv1 === void 0 || argv1 === "") return false;
10217
+ try {
10218
+ return realpathSync8(argv1) === realpathSync8(self);
10219
+ } catch {
10220
+ return false;
10221
+ }
10222
+ }
10223
+
9131
10224
  // src/entries/cli.ts
9132
10225
  var EXIT_OK2 = 0;
9133
10226
  var EXIT_FAIL2 = 1;
@@ -9173,10 +10266,10 @@ function route(argv, version) {
9173
10266
  ` };
9174
10267
  }
9175
10268
  function main() {
9176
- const dir = path8.dirname(realpathSync5(fileURLToPath2(import.meta.url)));
10269
+ const dir = path14.dirname(realpathSync9(fileURLToPath2(import.meta.url)));
9177
10270
  let version = "";
9178
10271
  try {
9179
- version = String(JSON.parse(readFileSync5(path8.join(dir, PACKAGE_FILE), "utf8")).version);
10272
+ version = String(JSON.parse(readFileSync12(path14.join(dir, PACKAGE_FILE), "utf8")).version);
9180
10273
  } catch (err2) {
9181
10274
  process.stderr.write(`${SERVER_KEY}: cannot read ${PACKAGE_FILE}: ${err2.message}
9182
10275
  `);
@@ -9200,7 +10293,7 @@ function main() {
9200
10293
  process.exitCode = r2.code;
9201
10294
  return;
9202
10295
  }
9203
- const child = spawn2(process.execPath, [path8.join(dir, r2.file), ...r2.args], { stdio: "inherit", windowsHide: true });
10296
+ const child = spawn4(process.execPath, [path14.join(dir, r2.file), ...r2.args], { stdio: "inherit", windowsHide: true });
9204
10297
  process.on("SIGINT", () => {
9205
10298
  });
9206
10299
  child.on("error", (err2) => {
@@ -9212,7 +10305,7 @@ function main() {
9212
10305
  process.exitCode = signal === "SIGINT" ? EXIT_SIGINT2 : code ?? EXIT_FAIL2;
9213
10306
  });
9214
10307
  }
9215
- if (import.meta.main) main();
10308
+ if (isEntry(import.meta.main, process.argv[1], fileURLToPath2(import.meta.url))) main();
9216
10309
  export {
9217
10310
  HELP2 as HELP,
9218
10311
  V1_PLATFORM_AGENT,