context-mode 2.0.0-next.13 → 2.0.0-next.15

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
@@ -87,9 +87,9 @@ var require_src = __commonJS({
87
87
  });
88
88
 
89
89
  // src/entries/cli.ts
90
- import { spawn as spawn2 } from "node:child_process";
91
- import { readFileSync as readFileSync6, realpathSync as realpathSync6 } from "node:fs";
92
- import path8 from "node:path";
90
+ import { spawn as spawn4 } from "node:child_process";
91
+ import { readFileSync as readFileSync11, realpathSync as realpathSync8 } from "node:fs";
92
+ import path14 from "node:path";
93
93
  import { fileURLToPath as fileURLToPath2 } from "node:url";
94
94
 
95
95
  // src/core/contracts/constants.ts
@@ -445,6 +445,7 @@ var V1_BIN_COMMAND = SERVER_KEY;
445
445
  var VSCODE_MCP_SERVERS_KEY = "servers";
446
446
  var ZCODE_EVENTS_KEY = "events";
447
447
  var PI_ROLE = "custom";
448
+ var PI_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
448
449
  var PI_PACKAGE_SOURCE_KEY = "source";
449
450
  var V1_PATH_SEPS = Object.freeze(["/", "\\"]);
450
451
  var HOST_SEP_TOKEN = "${/}";
@@ -565,7 +566,7 @@ function readResult(resp) {
565
566
  }
566
567
  return info;
567
568
  }
568
- function decodeClaudeShape(raw, agent, ownPrefix, sources) {
569
+ function decodeClaudeShape(raw, agent, ownPrefix, sources2) {
569
570
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(agent + ": hook payload is not a JSON object");
570
571
  const p3 = raw;
571
572
  const event = CLAUDE_SHAPE_EVENTS.find((e) => e === p3.hook_event_name);
@@ -575,7 +576,7 @@ function decodeClaudeShape(raw, agent, ownPrefix, sources) {
575
576
  ev.agentId = p3.agent_id;
576
577
  if (typeof p3.agent_type === "string") ev.agentType = p3.agent_type;
577
578
  }
578
- if (event === "SessionStart" && typeof p3.source === "string" && sources[p3.source] !== void 0) ev.source = sources[p3.source];
579
+ if (event === "SessionStart" && typeof p3.source === "string" && sources2[p3.source] !== void 0) ev.source = sources2[p3.source];
579
580
  if (event === "UserPromptSubmit" && typeof p3.prompt === "string") ev.prompt = p3.prompt;
580
581
  if (event === "PreToolUse" || event === "PostToolUse") {
581
582
  const name = String(p3.tool_name ?? "");
@@ -1594,9 +1595,9 @@ Examples:
1594
1595
  // src/cli/commands.ts
1595
1596
  import { spawnSync as spawnSync3 } from "node:child_process";
1596
1597
  import { createHash as createHash2 } from "node:crypto";
1597
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
1598
+ import { existsSync as existsSync12, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
1598
1599
  import os from "node:os";
1599
- import path7 from "node:path";
1600
+ import path13 from "node:path";
1600
1601
 
1601
1602
  // node_modules/@clack/prompts/dist/index.mjs
1602
1603
  var dist_exports = {};
@@ -4529,6 +4530,10 @@ function opencodeDirOf(env, home) {
4529
4530
  if (xdg !== void 0 && xdg !== "") return join2(xdg, AGENT_HOME_DIR.opencode[AGENT_HOME_DIR.opencode.length - 1]);
4530
4531
  return join2(home, ...AGENT_HOME_DIR.opencode);
4531
4532
  }
4533
+ function piAgentDirOf(env, home) {
4534
+ const dir = env[PI_AGENT_DIR_ENV];
4535
+ return dir !== void 0 && dir !== "" ? dir : join2(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
4536
+ }
4532
4537
  function vscodeUserDirOf(env, home, platform = process.platform) {
4533
4538
  const set2 = (v) => v !== void 0 && v !== "";
4534
4539
  const p3 = platform === "win32" ? win32 : posix;
@@ -6836,14 +6841,14 @@ function scanToml(text2) {
6836
6841
  continue;
6837
6842
  }
6838
6843
  if (!node.resolvedKey.every((seg) => typeof seg === "string")) continue;
6839
- const path9 = node.resolvedKey;
6840
- for (const kv of node.body) addKey(path9, kv);
6844
+ const path15 = node.resolvedKey;
6845
+ for (const kv of node.body) addKey(path15, kv);
6841
6846
  if (node.kind !== "standard") continue;
6842
6847
  const start = lineStartOf(text2, node.range[0]);
6843
6848
  const headEnd = lineEndOf(text2, node.key.range[1]);
6844
6849
  const last2 = node.body[node.body.length - 1];
6845
6850
  tables.push({
6846
- path: path9,
6851
+ path: path15,
6847
6852
  header: text2.slice(start, text2[headEnd - 1] === "\n" ? headEnd - 1 : headEnd),
6848
6853
  start,
6849
6854
  end: last2 === void 0 ? headEnd : lineEndOf(text2, last2.range[1])
@@ -6854,16 +6859,16 @@ function scanToml(text2) {
6854
6859
  function tomlTableSpans(text2) {
6855
6860
  return scanToml(text2).tables;
6856
6861
  }
6857
- function parseHostConfig(agent, path9, text2, format) {
6862
+ function parseHostConfig(agent, path15, text2, format) {
6858
6863
  try {
6859
6864
  return format === "toml" ? scanToml(text2).value : scanJson(text2, format).value;
6860
6865
  } catch {
6861
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path9, format });
6866
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path15, format });
6862
6867
  }
6863
6868
  }
6864
- function hostConfigValueAt(value, path9) {
6869
+ function hostConfigValueAt(value, path15) {
6865
6870
  let cur = value;
6866
- for (const seg of path9) {
6871
+ for (const seg of path15) {
6867
6872
  if (!isPlainObject(cur)) return void 0;
6868
6873
  cur = cur[seg];
6869
6874
  }
@@ -6896,32 +6901,32 @@ function indentUnit(root, clean) {
6896
6901
  function render(value, unit, base) {
6897
6902
  return JSON.stringify(value, null, unit).split("\n").join("\n" + base);
6898
6903
  }
6899
- function nest(path9, value) {
6904
+ function nest(path15, value) {
6900
6905
  let out2 = value;
6901
- for (let k = path9.length - 1; k >= 0; k -= 1) out2 = { [path9[k]]: out2 };
6906
+ for (let k = path15.length - 1; k >= 0; k -= 1) out2 = { [path15[k]]: out2 };
6902
6907
  return out2;
6903
6908
  }
6904
- function setJsonText(text2, format, path9, value) {
6909
+ function setJsonText(text2, format, path15, value) {
6905
6910
  const doc = scanJson(text2, format);
6906
6911
  const unit = indentUnit(doc.root, doc.clean);
6907
- if (doc.root === null) return render(nest(path9, value), unit, "") + "\n";
6912
+ if (doc.root === null) return render(nest(path15, value), unit, "") + "\n";
6908
6913
  let node = doc.root;
6909
6914
  let depth = 0;
6910
- while (depth < path9.length && node.kind === "object") {
6911
- const hit = node.members.find((m3) => m3.key === path9[depth]);
6915
+ while (depth < path15.length && node.kind === "object") {
6916
+ const hit = node.members.find((m3) => m3.key === path15[depth]);
6912
6917
  if (hit === void 0) break;
6913
6918
  node = hit.node;
6914
6919
  depth += 1;
6915
6920
  }
6916
- if (depth === path9.length) {
6921
+ if (depth === path15.length) {
6917
6922
  return text2.slice(0, node.start) + render(value, unit, lineIndent(doc.clean, node.start)) + text2.slice(node.end);
6918
6923
  }
6919
- if (node.kind !== "object") throw new SyntaxError("not an object at " + path9.slice(0, depth).join("."));
6920
- const rest = nest(path9.slice(depth + 1), value);
6924
+ if (node.kind !== "object") throw new SyntaxError("not an object at " + path15.slice(0, depth).join("."));
6925
+ const rest = nest(path15.slice(depth + 1), value);
6921
6926
  const last2 = node.members[node.members.length - 1];
6922
6927
  if (last2 === void 0) {
6923
6928
  const base2 = lineIndent(doc.clean, node.start);
6924
- const member2 = "\n" + base2 + unit + JSON.stringify(path9[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
6929
+ const member2 = "\n" + base2 + unit + JSON.stringify(path15[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
6925
6930
  return text2.slice(0, node.start + 1) + member2 + text2.slice(node.end - 1);
6926
6931
  }
6927
6932
  const base = lineIndent(doc.clean, last2.keyStart);
@@ -6929,7 +6934,7 @@ function setJsonText(text2, format, path9, value) {
6929
6934
  while (" \r\n".includes(doc.clean[at])) at += 1;
6930
6935
  const trailing = doc.clean[at] === ",";
6931
6936
  const insertAt = trailing ? at + 1 : last2.node.end;
6932
- const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path9[depth]) + ": " + render(rest, unit, base);
6937
+ const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path15[depth]) + ": " + render(rest, unit, base);
6933
6938
  return text2.slice(0, insertAt) + member + text2.slice(insertAt);
6934
6939
  }
6935
6940
  function tomlScalar(v) {
@@ -6947,17 +6952,17 @@ function tomlHeaderKey(seg) {
6947
6952
  }
6948
6953
  return seg;
6949
6954
  }
6950
- function tomlBlock(path9, value) {
6951
- let out2 = "[" + path9.map(tomlHeaderKey).join(".") + "]\n";
6955
+ function tomlBlock(path15, value) {
6956
+ let out2 = "[" + path15.map(tomlHeaderKey).join(".") + "]\n";
6952
6957
  const subs = [];
6953
6958
  for (const [k, v] of Object.entries(value)) {
6954
- if (isPlainObject(v)) subs.push(tomlBlock([...path9, k], v));
6959
+ if (isPlainObject(v)) subs.push(tomlBlock([...path15, k], v));
6955
6960
  else out2 += tomlHeaderKey(k) + " = " + tomlScalar(v) + "\n";
6956
6961
  }
6957
6962
  return [out2, ...subs].join("\n");
6958
6963
  }
6959
- function under(path9, prefix) {
6960
- return path9.length >= prefix.length && prefix.every((seg, k) => path9[k] === seg);
6964
+ function under(path15, prefix) {
6965
+ return path15.length >= prefix.length && prefix.every((seg, k) => path15[k] === seg);
6961
6966
  }
6962
6967
  function keyLineRange(text2, k) {
6963
6968
  const ls = lineStartOf(text2, k.start);
@@ -6974,10 +6979,10 @@ function withValueAt(root, rel, value) {
6974
6979
  else base[rel[0]] = next;
6975
6980
  return base;
6976
6981
  }
6977
- function replaceToml(text2, doc, path9, value) {
6978
- const block2 = value === void 0 ? "" : tomlBlock(path9, value);
6979
- const owned = doc.tables.filter((t2) => under(t2.path, path9));
6980
- const cuts = doc.keys.filter((k) => under(k.full, path9) && !under(k.base, path9)).map((k) => [...keyLineRange(text2, k), ""]);
6982
+ function replaceToml(text2, doc, path15, value) {
6983
+ const block2 = value === void 0 ? "" : tomlBlock(path15, value);
6984
+ const owned = doc.tables.filter((t2) => under(t2.path, path15));
6985
+ const cuts = doc.keys.filter((k) => under(k.full, path15) && !under(k.base, path15)).map((k) => [...keyLineRange(text2, k), ""]);
6981
6986
  owned.forEach((t2, n3) => cuts.push([t2.start, t2.end, n3 === 0 ? block2 : ""]));
6982
6987
  cuts.sort((a2, b3) => b3[0] - a2[0]);
6983
6988
  let out2 = text2;
@@ -6987,27 +6992,27 @@ function replaceToml(text2, doc, path9, value) {
6987
6992
  return out2 + sep2 + block2;
6988
6993
  }
6989
6994
  var tableLike = (v) => v === void 0 || isPlainObject(v);
6990
- function setTomlText(text2, path9, value) {
6995
+ function setTomlText(text2, path15, value) {
6991
6996
  if (value !== void 0 && !isPlainObject(value)) throw new SyntaxError("TOML edits replace a whole table");
6992
6997
  const doc = scanToml(text2);
6993
- const cur = hostConfigValueAt(doc.value, path9);
6998
+ const cur = hostConfigValueAt(doc.value, path15);
6994
6999
  if (sameValue(cur, value)) return text2;
6995
- const inline = doc.keys.find((k) => k.inline && k.full.length < path9.length && under(path9, k.full));
7000
+ const inline = doc.keys.find((k) => k.inline && k.full.length < path15.length && under(path15, k.full));
6996
7001
  if (inline !== void 0) {
6997
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path9.slice(inline.full.length), value);
7002
+ const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path15.slice(inline.full.length), value);
6998
7003
  return replaceToml(text2, doc, inline.full, whole);
6999
7004
  }
7000
7005
  if (isPlainObject(cur) && isPlainObject(value)) {
7001
7006
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
7002
7007
  if (names.every((k) => tableLike(cur[k]) && tableLike(value[k]))) {
7003
7008
  let out2 = text2;
7004
- for (const k of names) out2 = setTomlText(out2, [...path9, k], value[k]);
7009
+ for (const k of names) out2 = setTomlText(out2, [...path15, k], value[k]);
7005
7010
  return out2;
7006
7011
  }
7007
7012
  }
7008
- return replaceToml(text2, doc, path9, value);
7013
+ return replaceToml(text2, doc, path15, value);
7009
7014
  }
7010
- function setText(agent, path9, text2, format, key, value) {
7015
+ function setText(agent, path15, text2, format, key, value) {
7011
7016
  try {
7012
7017
  if (format !== "toml") return setJsonText(text2, format, key, value);
7013
7018
  const out2 = setTomlText(text2, key, value);
@@ -7016,7 +7021,7 @@ function setText(agent, path9, text2, format, key, value) {
7016
7021
  if (!sameValue(landed, value) && !(emptyTable && landed === void 0)) throw new SyntaxError("edit did not land");
7017
7022
  return out2;
7018
7023
  } catch {
7019
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path9, format });
7024
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path15, format });
7020
7025
  }
7021
7026
  }
7022
7027
  function isNodeCommand(command) {
@@ -7032,20 +7037,20 @@ function ownMcpValue(agent, node, server) {
7032
7037
  const tail = agent === "vscode" ? [WORKSPACE_FOLDER_FLAG, VSCODE_WORKSPACE_VAR] : [];
7033
7038
  return { ...mcp.fields, [MCP_COMMAND_FIELD]: node, [MCP_ARGS_FIELD]: [server, AGENT_ARG, agent, ...tail] };
7034
7039
  }
7035
- function applyEdits(agent, path9, text2, format, wanted) {
7036
- const parsed = parseHostConfig(agent, path9, text2, format);
7040
+ function applyEdits(agent, path15, text2, format, wanted) {
7041
+ const parsed = parseHostConfig(agent, path15, text2, format);
7037
7042
  let out2 = text2;
7038
7043
  const edits = [];
7039
7044
  for (const [key, after] of wanted) {
7040
7045
  const before = hostConfigValueAt(parsed, key);
7041
7046
  if (sameValue(before, after)) continue;
7042
- out2 = setText(agent, path9, out2, format, key, after);
7047
+ out2 = setText(agent, path15, out2, format, key, after);
7043
7048
  edits.push({ path: key.join("."), before, after });
7044
7049
  }
7045
7050
  return { text: out2, format, edits };
7046
7051
  }
7047
- function editHostConfigText(agent, path9, text2, format, wanted) {
7048
- return applyEdits(agent, path9, text2, format, wanted);
7052
+ function editHostConfigText(agent, path15, text2, format, wanted) {
7053
+ return applyEdits(agent, path15, text2, format, wanted);
7049
7054
  }
7050
7055
 
7051
7056
  // src/core/ops/doctor-config.ts
@@ -7057,7 +7062,7 @@ import { tmpdir } from "node:os";
7057
7062
  import { join as join4 } from "node:path";
7058
7063
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7059
7064
  var keyPath = (...parts) => parts.join(".");
7060
- var finding = (file, path9, reason) => ({ file, path: path9, reason });
7065
+ var finding = (file, path15, reason) => ({ file, path: path15, reason });
7061
7066
  function stripJsonc(text2) {
7062
7067
  let out2 = "";
7063
7068
  let inStr = false;
@@ -7494,7 +7499,7 @@ function extensionPlugin(bin, id) {
7494
7499
  };
7495
7500
  }
7496
7501
  var NATIVE_PLUGIN = {
7497
- codex: { bin: "codex", args: ["plugin", "list"], plugin: PLUGIN_ID, hooksVia: ".codex-plugin", skillsVia: path3.join("codex", SKILLS_DIR_NAME), format: "table" },
7502
+ codex: { bin: "codex", args: ["plugin", "list"], plugin: PLUGIN_ID, hooksVia: ".codex-plugin", skillsVia: path3.join("codex", SKILLS_DIR_NAME), format: "table", hookTrust: true },
7498
7503
  qwen: extensionPlugin("qwen", "qwen"),
7499
7504
  gemini: extensionPlugin("gemini", "gemini")
7500
7505
  };
@@ -7556,7 +7561,7 @@ function cliFor(ctx, id) {
7556
7561
  function copyFor(ctx, id) {
7557
7562
  if (id !== "claude-code") return void 0;
7558
7563
  const file = path3.join(claudeDirOf(ctx.env, ctx.home), HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE);
7559
- return { host: "Claude Code", bin: "claude", plugin: PLUGIN_ID, file, refresh: ["plugin", "update", PLUGIN_ID] };
7564
+ return { host: "Claude Code", bin: "claude", plugin: PLUGIN_ID, file, refresh: ["plugin", "update", PLUGIN_ID], enable: ["plugin", "enable", PLUGIN_ID] };
7560
7565
  }
7561
7566
  var LIST = {
7562
7567
  "claude-code": { bin: "claude", args: ["plugin", "list"] },
@@ -7629,7 +7634,9 @@ function buildRegistry(ctx) {
7629
7634
  const command = `"${hookCommand[0]}" "${hookCommand[1]}" ${AGENT_FLAG} ${id}`;
7630
7635
  const hookInstall = hookInstallFor(ctx, getAdapter(id), command);
7631
7636
  const skillInstall = skillInstallFor(ctx, row);
7637
+ const copilotSettings = id === "copilot-cli" ? agentPath(ctx, id, [COPILOT_DIR, "settings.json"]) : void 0;
7632
7638
  const writes = [
7639
+ ...copilotSettings ? [copilotSettings] : [],
7633
7640
  ...config ? [config.file] : [],
7634
7641
  ...hookFiles.map((h2) => h2.file),
7635
7642
  ...hookInstall.kind === "package" ? [] : [hookInstall.file],
@@ -7650,6 +7657,7 @@ function buildRegistry(ctx) {
7650
7657
  allowedWrites: [...new Set(writes.map((f2) => path3.resolve(f2)))],
7651
7658
  goldenPayload: golden(row, ctx.home)
7652
7659
  };
7660
+ if (copilotSettings) out2.copilotSettings = copilotSettings;
7653
7661
  if (row.installMode !== "in-process") out2.hookCommand = hookCommand;
7654
7662
  const copy = copyFor(ctx, id);
7655
7663
  if (copy) out2.copy = copy;
@@ -7665,15 +7673,349 @@ function assertWritable(row, file) {
7665
7673
  }
7666
7674
  }
7667
7675
 
7676
+ // src/setup/gemini-gate.ts
7677
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
7678
+ import path4 from "node:path";
7679
+ var GEMINI_DIR = ".gemini";
7680
+ var SETTINGS_FILE2 = "settings.json";
7681
+ var SYSTEM_PATH_ENV = "GEMINI_CLI_SYSTEM_SETTINGS_PATH";
7682
+ var OWN_AGENT = "gemini";
7683
+ function systemSettingsPath(env) {
7684
+ const set2 = env[SYSTEM_PATH_ENV];
7685
+ if (set2) return set2;
7686
+ if (process.platform === "darwin") return "/Library/Application Support/GeminiCli/settings.json";
7687
+ if (process.platform === "win32") return "C:\\ProgramData\\gemini-cli\\settings.json";
7688
+ return "/etc/gemini-cli/settings.json";
7689
+ }
7690
+ function load(file) {
7691
+ if (!existsSync5(file)) return void 0;
7692
+ try {
7693
+ return { file, doc: parseHostConfig(OWN_AGENT, file, hostText(readFileSync4(file, "utf8")), "jsonc") };
7694
+ } catch {
7695
+ return void 0;
7696
+ }
7697
+ }
7698
+ function sources(env, home, cwd) {
7699
+ return [path4.join(home, GEMINI_DIR, SETTINGS_FILE2), path4.join(cwd, GEMINI_DIR, SETTINGS_FILE2), systemSettingsPath(env)].map(load).filter((s) => s !== void 0);
7700
+ }
7701
+ function ownHookEntry(entry2) {
7702
+ return typeof entry2 === "string" && entry2.includes(HOOK_BUNDLE) && entry2.includes(`${AGENT_FLAG} ${OWN_AGENT}`);
7703
+ }
7704
+ function geminiSettingsGate(env, home, cwd) {
7705
+ const srcs = sources(env, home, cwd);
7706
+ for (const s of srcs) {
7707
+ if (hostConfigValueAt(s.doc, ["admin", "extensions", "enabled"]) === false) {
7708
+ return `${s.file}: admin.extensions.enabled is false, so gemini loads no extension and runs no context-mode hook; an administrator must change it`;
7709
+ }
7710
+ }
7711
+ let winner;
7712
+ for (const s of srcs) if (typeof hostConfigValueAt(s.doc, ["hooksConfig", "enabled"]) === "boolean") winner = s;
7713
+ if (winner && hostConfigValueAt(winner.doc, ["hooksConfig", "enabled"]) === false) {
7714
+ return `${winner.file}: hooksConfig.enabled is false, so gemini runs no hook; set it to true`;
7715
+ }
7716
+ for (const s of srcs) {
7717
+ const off = hostConfigValueAt(s.doc, ["hooksConfig", "disabled"]);
7718
+ const own2 = Array.isArray(off) ? off.find(ownHookEntry) : void 0;
7719
+ if (own2 !== void 0) return `${s.file}: hooksConfig.disabled lists the context-mode hook (${own2}), so gemini skips it; remove that entry`;
7720
+ }
7721
+ return void 0;
7722
+ }
7723
+
7724
+ // src/setup/zcode-gate.ts
7725
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
7726
+ import path5 from "node:path";
7727
+ var OWN_AGENT2 = "zcode";
7728
+ var EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "Stop"];
7729
+ var HOOK_TYPES = ["process", "command"];
7730
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7731
+ var isPositive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
7732
+ var isText = (v) => typeof v === "string" && v.length > 0;
7733
+ var isTexts = (v) => Array.isArray(v) && v.every((x2) => typeof x2 === "string");
7734
+ function field(o2, at, name, ok, why) {
7735
+ const v = o2[name];
7736
+ return v === void 0 || ok(v) ? void 0 : { key: `${at}.${name}`, why };
7737
+ }
7738
+ function section(doc, name) {
7739
+ const v = doc[name];
7740
+ if (v === void 0) return {};
7741
+ return isObj2(v) ? { o: v } : { bad: { key: name, why: "must be an object" } };
7742
+ }
7743
+ var oneOf = (allowed) => (v) => allowed.includes(v);
7744
+ var isBool = (v) => typeof v === "boolean";
7745
+ function firstBad(...checks) {
7746
+ return checks.find((c3) => c3 !== void 0);
7747
+ }
7748
+ function simple(doc, name, rules) {
7749
+ const s = section(doc, name);
7750
+ if (s.bad) return s.bad;
7751
+ if (!s.o) return void 0;
7752
+ return firstBad(...rules.map(([k, ok, why]) => field(s.o, name, k, ok, why)));
7753
+ }
7754
+ function hookBad(h2, at) {
7755
+ if (!isObj2(h2)) return { key: at, why: "must be an object" };
7756
+ if (!HOOK_TYPES.includes(h2.type)) return { key: `${at}.type`, why: "must be process or command" };
7757
+ return firstBad(
7758
+ isText(h2.command) ? void 0 : { key: `${at}.command`, why: "must be a non-empty string" },
7759
+ field(h2, at, "enabled", isBool, "must be a boolean"),
7760
+ field(h2, at, "timeoutMs", isPositive, "must be a positive number"),
7761
+ field(h2, at, "timeout", isPositive, "must be a positive number"),
7762
+ field(h2, at, "async", isBool, "must be a boolean"),
7763
+ field(h2, at, "args", isTexts, "must be an array of strings"),
7764
+ field(h2, at, "statusMessage", isText, "must be a non-empty string")
7765
+ );
7766
+ }
7767
+ var GROUP_KEYS = ["matcher", "hooks"];
7768
+ function groupBad(g2, at) {
7769
+ if (!isObj2(g2)) return { key: at, why: "must be an object" };
7770
+ const extra = Object.keys(g2).find((k) => !GROUP_KEYS.includes(k));
7771
+ if (extra !== void 0) return { key: at, why: `has the unknown key ${extra}` };
7772
+ if (!Array.isArray(g2.hooks) || g2.hooks.length === 0) return { key: at, why: "needs a non-empty hooks array" };
7773
+ const m3 = field(g2, at, "matcher", isText, "must be a non-empty string");
7774
+ if (m3) return m3;
7775
+ for (let i2 = 0; i2 < g2.hooks.length; i2++) {
7776
+ const b3 = hookBad(g2.hooks[i2], `${at}.hooks[${i2}]`);
7777
+ if (b3) return b3;
7778
+ }
7779
+ return void 0;
7780
+ }
7781
+ var HOOK_ROOT_KEYS = ["enabled", "timeoutMs", "maxOutputBytes", "events"];
7782
+ function hooksBad(doc) {
7783
+ const s = section(doc, "hooks");
7784
+ if (s.bad) return s.bad;
7785
+ const h2 = s.o;
7786
+ if (!h2) return void 0;
7787
+ const extra = Object.keys(h2).find((k) => !HOOK_ROOT_KEYS.includes(k));
7788
+ if (extra !== void 0) return { key: `hooks.${extra}`, why: "is not a hooks key" };
7789
+ 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"));
7790
+ if (root || h2.events === void 0) return root;
7791
+ if (!isObj2(h2.events)) return { key: "hooks.events", why: "must be an object" };
7792
+ for (const [ev, groups] of Object.entries(h2.events)) {
7793
+ if (!EVENTS.includes(ev)) return { key: `hooks.events.${ev}`, why: "is not a zcode hook event" };
7794
+ if (!Array.isArray(groups)) return { key: `hooks.events.${ev}`, why: "must be an array of matcher groups" };
7795
+ for (let i2 = 0; i2 < groups.length; i2++) {
7796
+ const b3 = groupBad(groups[i2], `hooks.events.${ev}[${i2}]`);
7797
+ if (b3) return b3;
7798
+ }
7799
+ }
7800
+ return void 0;
7801
+ }
7802
+ function zcodeSchemaBad(doc) {
7803
+ if (!isObj2(doc)) return { key: "(root)", why: "must be a JSON object" };
7804
+ return firstBad(
7805
+ simple(doc, "modelStream", [["idleTimeoutMs", isPositive, "must be a positive number"]]),
7806
+ 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"]]),
7807
+ simple(doc, "features", ["compact", "rewind", "subagent", "memory", "skill", "mcp"].map((k) => [k, isBool, "must be a boolean"])),
7808
+ simple(doc, "memory", [["use", isBool, "must be a boolean"]]),
7809
+ 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"]]),
7810
+ 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"]]),
7811
+ simple(doc, "toolConcurrency", [["maxConcurrency", isPositive, "must be a positive number"]]),
7812
+ hooksBad(doc)
7813
+ );
7814
+ }
7815
+ function zcodeConfigGate(home) {
7816
+ const file = path5.join(home, ".zcode", "cli", "config.json");
7817
+ if (!existsSync6(file)) return void 0;
7818
+ let doc;
7819
+ try {
7820
+ doc = parseHostConfig(OWN_AGENT2, file, hostText(readFileSync5(file, "utf8")), "json");
7821
+ } catch {
7822
+ return void 0;
7823
+ }
7824
+ const bad = zcodeSchemaBad(doc);
7825
+ if (!bad) return void 0;
7826
+ return `${file}: ${bad.key} ${bad.why}, so zcode drops the whole config.json and runs no context-mode hook; fix or remove that key`;
7827
+ }
7828
+
7829
+ // src/setup/pi-gate.ts
7830
+ import { existsSync as existsSync7, readFileSync as readFileSync6, realpathSync as realpathSync3 } from "node:fs";
7831
+ import path6 from "node:path";
7832
+ var OWN_FILE = "pi/index.js";
7833
+ var EXTENSIONS_KEY = "extensions";
7834
+ var PROJECT_DIR = ".pi";
7835
+ var TRUST_FILE = "trust.json";
7836
+ var ALWAYS = "always";
7837
+ var SOURCE_PREFIXES = ["npm:", "git:"];
7838
+ function load2(file) {
7839
+ if (!existsSync7(file)) return void 0;
7840
+ try {
7841
+ return { file, doc: parseHostConfig("pi", file, hostText(readFileSync6(file, "utf8")), "json") };
7842
+ } catch {
7843
+ return void 0;
7844
+ }
7845
+ }
7846
+ var real = (p3) => {
7847
+ try {
7848
+ return realpathSync3(p3);
7849
+ } catch {
7850
+ return path6.resolve(p3);
7851
+ }
7852
+ };
7853
+ function sourceName(source) {
7854
+ let s = source;
7855
+ for (const p3 of SOURCE_PREFIXES) if (s.startsWith(p3)) s = s.slice(p3.length);
7856
+ const last2 = s.split("/").pop() ?? "";
7857
+ const at = last2.indexOf("@", 1);
7858
+ const name = at > 0 ? last2.slice(0, at) : last2;
7859
+ return name.endsWith(".git") ? name.slice(0, -4) : name;
7860
+ }
7861
+ function isOwn(source, pkgDir) {
7862
+ if (typeof source !== "string") return false;
7863
+ return real(source) === real(pkgDir) || sourceName(source) === SERVER_KEY;
7864
+ }
7865
+ function ownEntries(src, pkgDir) {
7866
+ const list2 = hostConfigValueAt(src.doc, [PI_PACKAGES_KEY]);
7867
+ if (!Array.isArray(list2)) return [];
7868
+ const out2 = [];
7869
+ for (const e of list2) {
7870
+ const obj = typeof e === "object" && e !== null && !Array.isArray(e) ? e : void 0;
7871
+ if (!isOwn(obj ? obj[PI_PACKAGE_SOURCE_KEY] : e, pkgDir)) continue;
7872
+ const ext = obj?.[EXTENSIONS_KEY];
7873
+ out2.push({ source: src, patterns: Array.isArray(ext) ? ext.filter((x2) => typeof x2 === "string") : void 0 });
7874
+ }
7875
+ return out2;
7876
+ }
7877
+ function matchesAny(patterns, pkgDir) {
7878
+ const abs = path6.join(pkgDir, OWN_FILE).split(path6.sep).join("/");
7879
+ return patterns.some((p3) => {
7880
+ const g2 = p3.startsWith("./") ? p3.slice(2) : p3;
7881
+ return [OWN_FILE, path6.posix.basename(OWN_FILE), abs].some((c3) => path6.posix.matchesGlob(c3, g2));
7882
+ });
7883
+ }
7884
+ var exactAny = (patterns, pkgDir) => {
7885
+ const abs = path6.join(pkgDir, OWN_FILE).split(path6.sep).join("/");
7886
+ return patterns.some((p3) => {
7887
+ const g2 = p3.startsWith("./") ? p3.slice(2) : p3;
7888
+ return g2 === OWN_FILE || g2 === abs;
7889
+ });
7890
+ };
7891
+ function loads(patterns, pkgDir) {
7892
+ if (patterns.length === 0) return false;
7893
+ const by = (c3) => patterns.filter((p3) => p3.startsWith(c3)).map((p3) => p3.slice(1));
7894
+ const includes = patterns.filter((p3) => !"+-!".includes(p3[0] ?? ""));
7895
+ let on = includes.length === 0 || matchesAny(includes, pkgDir);
7896
+ if (matchesAny(by("!"), pkgDir)) on = false;
7897
+ if (exactAny(by("+"), pkgDir)) on = true;
7898
+ if (exactAny(by("-"), pkgDir)) on = false;
7899
+ return on;
7900
+ }
7901
+ function projectTrusted(agentDir, userDoc, cwd) {
7902
+ const trust = load2(path6.join(agentDir, TRUST_FILE));
7903
+ const entries = /* @__PURE__ */ new Map();
7904
+ if (trust && typeof trust.doc === "object" && trust.doc !== null) for (const [k, v] of Object.entries(trust.doc)) entries.set(real(k), v);
7905
+ let dir = real(cwd);
7906
+ for (; ; ) {
7907
+ const v = entries.get(dir);
7908
+ if (v === true || v === false) return v;
7909
+ const up = path6.dirname(dir);
7910
+ if (up === dir) break;
7911
+ dir = up;
7912
+ }
7913
+ return hostConfigValueAt(userDoc, ["defaultProjectTrust"]) === ALWAYS;
7914
+ }
7915
+ function piSettingsGate(env, home, pkgDir, cwd) {
7916
+ const agentDir = piAgentDirOf(env, home);
7917
+ const user = load2(path6.join(agentDir, SETTINGS_FILE));
7918
+ const project = load2(path6.join(cwd, PROJECT_DIR, SETTINGS_FILE));
7919
+ const projectOwn = project && projectTrusted(agentDir, user?.doc, cwd) ? ownEntries(project, pkgDir) : [];
7920
+ const effective = projectOwn.length ? projectOwn : user ? ownEntries(user, pkgDir) : [];
7921
+ for (const e of effective) {
7922
+ if (e.patterns !== void 0 && !loads(e.patterns, pkgDir)) {
7923
+ 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`;
7924
+ }
7925
+ }
7926
+ return void 0;
7927
+ }
7928
+
7929
+ // src/setup/vscode-gate.ts
7930
+ import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
7931
+ import path7 from "node:path";
7932
+ var SETTINGS_FILE3 = "settings.json";
7933
+ var WORKSPACE_DIR = ".vscode";
7934
+ var USE_HOOKS_KEY = "chat.useHooks";
7935
+ var LOCATIONS_KEY = "chat.hookFilesLocations";
7936
+ var OWN_LOCATION = "~/.copilot/hooks";
7937
+ var MANAGED_KEYS = ["allowManagedHooksOnly", "strictPluginOnlyCustomization"];
7938
+ function load3(file) {
7939
+ if (!existsSync8(file)) return void 0;
7940
+ try {
7941
+ return { file, doc: parseHostConfig("vscode", file, hostText(readFileSync7(file, "utf8")), "jsonc") };
7942
+ } catch {
7943
+ return void 0;
7944
+ }
7945
+ }
7946
+ function managedSettingsPath(env) {
7947
+ if (process.platform === "darwin") return "/Library/Application Support/GitHubCopilot/managed-settings.json";
7948
+ if (process.platform === "win32") return path7.join(env.ProgramFiles || "C:\\Program Files", "GitHubCopilot", "managed-settings.json");
7949
+ return "/etc/github-copilot/managed-settings.json";
7950
+ }
7951
+ function vscodeSettingsGate(env, home, cwd, managedFile = managedSettingsPath(env)) {
7952
+ const managed = load3(managedFile);
7953
+ if (managed) {
7954
+ for (const key of MANAGED_KEYS) {
7955
+ if (hostConfigValueAt(managed.doc, [key]) === true) {
7956
+ return `${managed.file}: ${key} is true, so VS Code runs no user hook file; an administrator must change it`;
7957
+ }
7958
+ }
7959
+ }
7960
+ const srcs = [path7.join(vscodeUserDirOf(env, home), SETTINGS_FILE3), path7.join(cwd, WORKSPACE_DIR, SETTINGS_FILE3)].map(load3).filter((s) => s !== void 0);
7961
+ let hooks;
7962
+ let locations;
7963
+ for (const s of srcs) {
7964
+ if (typeof hostConfigValueAt(s.doc, [USE_HOOKS_KEY]) === "boolean") hooks = s;
7965
+ const v = hostConfigValueAt(s.doc, [LOCATIONS_KEY]);
7966
+ if (typeof v === "object" && v !== null && !Array.isArray(v)) locations = s;
7967
+ }
7968
+ if (hooks && hostConfigValueAt(hooks.doc, [USE_HOOKS_KEY]) === false) {
7969
+ return `${hooks.file}: ${USE_HOOKS_KEY} is false, so VS Code runs no hook; set it to true`;
7970
+ }
7971
+ if (locations) {
7972
+ const v = hostConfigValueAt(locations.doc, [LOCATIONS_KEY]);
7973
+ if (v[OWN_LOCATION] !== true) {
7974
+ return `${locations.file}: ${LOCATIONS_KEY} leaves out "${OWN_LOCATION}", so VS Code does not read the context-mode hook file; add "${OWN_LOCATION}": true`;
7975
+ }
7976
+ }
7977
+ return void 0;
7978
+ }
7979
+
7980
+ // src/setup/qwen-gate.ts
7981
+ import { existsSync as existsSync9, readFileSync as readFileSync8 } from "node:fs";
7982
+ import path8 from "node:path";
7983
+ var KEY = "disableAllHooks";
7984
+ var SETTINGS = "settings.json";
7985
+ var SYSTEM_ENV = "QWEN_CODE_SYSTEM_SETTINGS_PATH";
7986
+ var HOME_ENV = "QWEN_HOME";
7987
+ var DARWIN_SYSTEM = "/Library/Application Support/QwenCode/settings.json";
7988
+ var WIN_SYSTEM = "C:\\ProgramData\\qwen-code\\settings.json";
7989
+ var LINUX_SYSTEM = "/etc/qwen-code/settings.json";
7990
+ function settingsFiles(env, home, cwd, platform) {
7991
+ const sys = env[SYSTEM_ENV] || (platform === "darwin" ? DARWIN_SYSTEM : platform === "win32" ? WIN_SYSTEM : LINUX_SYSTEM);
7992
+ const userDir = env[HOME_ENV] || path8.join(home, ".qwen");
7993
+ return [sys, path8.join(userDir, SETTINGS), path8.join(cwd, ".qwen", SETTINGS)];
7994
+ }
7995
+ function qwenHooksOff(env, home, cwd = process.cwd(), platform = process.platform) {
7996
+ for (const file of settingsFiles(env, home, cwd, platform)) {
7997
+ if (!existsSync9(file)) continue;
7998
+ let value;
7999
+ try {
8000
+ value = hostConfigValueAt(parseHostConfig("qwen", file, hostText(readFileSync8(file, "utf8")), "jsonc"), [KEY]);
8001
+ } catch {
8002
+ continue;
8003
+ }
8004
+ if (value === true) return `qwen runs no hook: "${KEY}" is true in ${file}; set it to false`;
8005
+ }
8006
+ return void 0;
8007
+ }
8008
+
7668
8009
  // src/setup/codex-trust.ts
7669
8010
  import { createHash } from "node:crypto";
7670
- import { existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
7671
- import path5 from "node:path";
8011
+ import { existsSync as existsSync10, realpathSync as realpathSync4 } from "node:fs";
8012
+ import path10 from "node:path";
8013
+ import { spawn } from "node:child_process";
7672
8014
 
7673
8015
  // src/setup/spawn-bin.ts
7674
8016
  import { spawnSync } from "node:child_process";
7675
8017
  import { accessSync, constants as fsc, statSync } from "node:fs";
7676
- import path4 from "node:path";
8018
+ import path9 from "node:path";
7677
8019
 
7678
8020
  // src/core/sandbox/path-entries.ts
7679
8021
  function pathEntries(value, platform = process.platform, delimiter = platform === "win32" ? ";" : ":") {
@@ -7692,10 +8034,10 @@ function whichBin(bin, env, platform = process.platform) {
7692
8034
  const get = (k) => envGet(env, k);
7693
8035
  const win = platform === "win32";
7694
8036
  const exts = win ? (get("PATHEXT") || WIN_EXT).split(";").filter(Boolean) : [""];
7695
- const names = win && path4.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
8037
+ const names = win && path9.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
7696
8038
  for (const dir of pathEntries(get("PATH") ?? "", platform)) {
7697
8039
  for (const n3 of names) {
7698
- const f2 = path4.join(dir, n3);
8040
+ const f2 = path9.join(dir, n3);
7699
8041
  try {
7700
8042
  accessSync(f2, fsc.X_OK);
7701
8043
  if (statSync(f2).isFile()) return f2;
@@ -7736,7 +8078,7 @@ function winCmdLine(file, args, env = {}) {
7736
8078
  return `"${[file, ...args].map(q).join(" ")}"`;
7737
8079
  }
7738
8080
  function spawnForm(file, args, env, platform = process.platform) {
7739
- if (platform === "win32" && WIN_SHIM_EXTS.includes(path4.extname(file).toLowerCase())) {
8081
+ if (platform === "win32" && WIN_SHIM_EXTS.includes(path9.extname(file).toLowerCase())) {
7740
8082
  return { command: envGet(env, "COMSPEC") || DEFAULT_COMSPEC, args: ["/d", "/v:off", "/s", "/c", winCmdLine(file, args, env)], windowsVerbatimArguments: true };
7741
8083
  }
7742
8084
  return { command: file, args, windowsVerbatimArguments: false };
@@ -7753,14 +8095,14 @@ function spawnShim(file, args, env, opts, platform = process.platform) {
7753
8095
  }
7754
8096
 
7755
8097
  // src/setup/codex-trust.ts
7756
- var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8098
+ var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7757
8099
  var TRUST_KEY = ["hooks", "state"];
7758
8100
  var CODEX_TRUST_PATH = TRUST_KEY.join(".") + ".";
7759
8101
  var HASH_FIELD = "trusted_hash";
7760
8102
  var HASH_PREFIX = "sha256:";
7761
8103
  function sortKeys(v) {
7762
8104
  if (Array.isArray(v)) return v.map(sortKeys);
7763
- if (!isObj2(v)) return v;
8105
+ if (!isObj3(v)) return v;
7764
8106
  return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
7765
8107
  }
7766
8108
  function snake(name) {
@@ -7772,13 +8114,13 @@ function snake(name) {
7772
8114
  return out2;
7773
8115
  }
7774
8116
  function realFile(file) {
7775
- let dir = path5.resolve(file);
8117
+ let dir = path10.resolve(file);
7776
8118
  const rest = [];
7777
- while (!existsSync5(dir) && path5.dirname(dir) !== dir) {
7778
- rest.unshift(path5.basename(dir));
7779
- dir = path5.dirname(dir);
8119
+ while (!existsSync10(dir) && path10.dirname(dir) !== dir) {
8120
+ rest.unshift(path10.basename(dir));
8121
+ dir = path10.dirname(dir);
7780
8122
  }
7781
- return path5.join(realpathSync3(dir), ...rest);
8123
+ return path10.join(realpathSync4(dir), ...rest);
7782
8124
  }
7783
8125
  var ASK_TIMEOUT_MS = 1e4;
7784
8126
  var ASK_TRIES = 3;
@@ -7791,7 +8133,7 @@ function codexHomeFromReply(out2) {
7791
8133
  } catch {
7792
8134
  continue;
7793
8135
  }
7794
- if (isObj2(m3) && isObj2(m3.result) && typeof m3.result.codexHome === "string" && m3.result.codexHome !== "") return m3.result.codexHome;
8136
+ if (isObj3(m3) && isObj3(m3.result) && typeof m3.result.codexHome === "string" && m3.result.codexHome !== "") return m3.result.codexHome;
7795
8137
  }
7796
8138
  return void 0;
7797
8139
  }
@@ -7807,10 +8149,10 @@ function askCodexHome(env) {
7807
8149
  return void 0;
7808
8150
  }
7809
8151
  function sameDir(a2, b3, platform) {
7810
- if (platform !== "win32") return path5.posix.normalize(a2) === path5.posix.normalize(b3);
8152
+ if (platform !== "win32") return path10.posix.normalize(a2) === path10.posix.normalize(b3);
7811
8153
  const norm = (p3) => {
7812
8154
  const bare = p3.startsWith(WIN_VERBATIM_PREFIX) ? p3.slice(WIN_VERBATIM_PREFIX.length) : p3;
7813
- const n3 = path5.win32.normalize(bare).toLowerCase();
8155
+ const n3 = path10.win32.normalize(bare).toLowerCase();
7814
8156
  return n3.length > 3 && n3.endsWith("\\") ? n3.slice(0, -1) : n3;
7815
8157
  };
7816
8158
  return norm(a2) === norm(b3);
@@ -7820,31 +8162,201 @@ function codexKeyDir(o2, platform = process.platform) {
7820
8162
  }
7821
8163
  function codexTrustEntries(hooksFile, doc, command, env) {
7822
8164
  const out2 = [];
7823
- if (!isObj2(doc) || !isObj2(doc.hooks)) return out2;
7824
- const abs = path5.resolve(hooksFile);
7825
- const dir = codexKeyDir({ dir: path5.dirname(abs), asked: env ? askCodexHome(env) : void 0, real: env && !env.CODEX_HOME ? (p3) => path5.resolve(p3) : realFile });
7826
- const real = (dir.startsWith(WIN_VERBATIM_PREFIX) ? path5.win32 : path5).join(dir, path5.basename(abs));
8165
+ if (!isObj3(doc) || !isObj3(doc.hooks)) return out2;
8166
+ const abs = path10.resolve(hooksFile);
8167
+ const dir = codexKeyDir({ dir: path10.dirname(abs), asked: env ? askCodexHome(env) : void 0, real: env && !env.CODEX_HOME ? (p3) => path10.resolve(p3) : realFile });
8168
+ const real2 = (dir.startsWith(WIN_VERBATIM_PREFIX) ? path10.win32 : path10).join(dir, path10.basename(abs));
7827
8169
  for (const [event, groups] of Object.entries(doc.hooks)) {
7828
8170
  if (!Array.isArray(groups)) continue;
7829
8171
  groups.forEach((g2, gi) => {
7830
- if (!isObj2(g2) || !Array.isArray(g2.hooks)) return;
8172
+ if (!isObj3(g2) || !Array.isArray(g2.hooks)) return;
7831
8173
  g2.hooks.forEach((h2, hi) => {
7832
- if (!isObj2(h2) || h2.command !== command) return;
8174
+ if (!isObj3(h2) || h2.command !== command) return;
7833
8175
  const id = { event_name: snake(event), hooks: [{ ...h2, async: false }] };
7834
8176
  if (g2.matcher !== void 0) id.matcher = g2.matcher;
7835
8177
  const hash = HASH_PREFIX + createHash("sha256").update(JSON.stringify(sortKeys(id))).digest("hex");
7836
- out2.push([[...TRUST_KEY, `${real}:${snake(event)}:${gi}:${hi}`], { [HASH_FIELD]: hash }]);
8178
+ out2.push([[...TRUST_KEY, `${real2}:${snake(event)}:${gi}:${hi}`], { [HASH_FIELD]: hash }]);
7837
8179
  });
7838
8180
  });
7839
8181
  }
7840
8182
  return out2;
7841
8183
  }
8184
+ var LIST_TIMEOUT_MS = 15e3;
8185
+ var PLUGIN_SOURCE = "plugin";
8186
+ var TRUSTED = "trusted";
8187
+ function pluginHooksFromReply(m3, pluginId) {
8188
+ const out2 = [];
8189
+ if (!isObj3(m3) || !isObj3(m3.result) || !Array.isArray(m3.result.data)) return out2;
8190
+ for (const d of m3.result.data) {
8191
+ if (!isObj3(d) || !Array.isArray(d.hooks)) continue;
8192
+ for (const h2 of d.hooks) {
8193
+ if (!isObj3(h2) || h2.source !== PLUGIN_SOURCE || h2.pluginId !== pluginId) continue;
8194
+ if (typeof h2.key !== "string" || typeof h2.currentHash !== "string") continue;
8195
+ if (out2.some((x2) => x2.key === h2.key)) continue;
8196
+ out2.push({ key: h2.key, hash: h2.currentHash, trusted: h2.trustStatus === TRUSTED });
8197
+ }
8198
+ }
8199
+ return out2;
8200
+ }
8201
+ function listPluginHooks(env, pluginId, cwd) {
8202
+ const bin = whichBin("codex", env);
8203
+ if (!bin) return Promise.resolve(void 0);
8204
+ return new Promise((resolve) => {
8205
+ let f2;
8206
+ try {
8207
+ f2 = spawnForm(bin, ["app-server"], env);
8208
+ } catch {
8209
+ resolve(void 0);
8210
+ return;
8211
+ }
8212
+ const child = spawn(f2.command, f2.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
8213
+ let buf = "";
8214
+ let done = false;
8215
+ const finish2 = (v) => {
8216
+ if (done) return;
8217
+ done = true;
8218
+ clearTimeout(timer);
8219
+ child.stdin.destroy();
8220
+ child.kill();
8221
+ resolve(v);
8222
+ };
8223
+ const timer = setTimeout(() => finish2(void 0), LIST_TIMEOUT_MS);
8224
+ const send = (o2) => {
8225
+ try {
8226
+ child.stdin.write(JSON.stringify(o2) + "\n");
8227
+ } catch {
8228
+ finish2(void 0);
8229
+ }
8230
+ };
8231
+ child.on("error", () => finish2(void 0));
8232
+ child.on("close", () => finish2(void 0));
8233
+ child.stdin.on("error", () => finish2(void 0));
8234
+ child.stdout.setEncoding("utf8");
8235
+ child.stdout.on("data", (d) => {
8236
+ buf += d;
8237
+ const lines = buf.split("\n");
8238
+ buf = lines.pop() ?? "";
8239
+ for (const line of lines) {
8240
+ let m3;
8241
+ try {
8242
+ m3 = JSON.parse(line);
8243
+ } catch {
8244
+ continue;
8245
+ }
8246
+ if (!isObj3(m3)) continue;
8247
+ if (m3.id === 1) {
8248
+ send({ method: "initialized" });
8249
+ send({ id: 2, method: "hooks/list", params: { cwds: [cwd] } });
8250
+ } else if (m3.id === 2) finish2(pluginHooksFromReply(m3, pluginId));
8251
+ }
8252
+ });
8253
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "context-mode-setup", version: "2.0.0" } } });
8254
+ });
8255
+ }
8256
+ function pluginTrustEntries(hooks) {
8257
+ return hooks.filter((h2) => !h2.trusted).map((h2) => [[...TRUST_KEY, h2.key], { [HASH_FIELD]: h2.hash }]);
8258
+ }
8259
+
8260
+ // src/setup/copilot-hooks.ts
8261
+ import { spawn as spawn2 } from "node:child_process";
8262
+ import { realpathSync as realpathSync5 } from "node:fs";
8263
+ import path11 from "node:path";
8264
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8265
+ var ASK_TIMEOUT_MS2 = 15e3;
8266
+ var HEADER_END = "\r\n\r\n";
8267
+ var LENGTH_HEADER = "content-length";
8268
+ var USER_ORIGIN = "user";
8269
+ function canon(p3) {
8270
+ let r2 = path11.resolve(p3);
8271
+ try {
8272
+ r2 = realpathSync5(r2);
8273
+ } catch {
8274
+ }
8275
+ return process.platform === "win32" ? r2.toLowerCase() : r2;
8276
+ }
8277
+ function copilotHooksFromReply(m3, file) {
8278
+ const out2 = [];
8279
+ if (!isObj4(m3) || !isObj4(m3.result) || !Array.isArray(m3.result.hooks)) return out2;
8280
+ const want = canon(file);
8281
+ const base = path11.dirname(path11.dirname(path11.resolve(file)));
8282
+ for (const h2 of m3.result.hooks) {
8283
+ if (!isObj4(h2) || h2.origin !== USER_ORIGIN || typeof h2.source !== "string" || typeof h2.hookType !== "string" || typeof h2.enabled !== "boolean") continue;
8284
+ if (canon(path11.isAbsolute(h2.source) ? h2.source : path11.join(base, h2.source)) !== want) continue;
8285
+ out2.push({ event: h2.hookType, source: h2.source, enabled: h2.enabled, ...typeof h2.disableKey === "string" ? { disableKey: h2.disableKey } : {} });
8286
+ }
8287
+ return out2;
8288
+ }
8289
+ function frame(buf) {
8290
+ const end = buf.indexOf(HEADER_END);
8291
+ if (end < 0) return void 0;
8292
+ let len = -1;
8293
+ for (const line of buf.subarray(0, end).toString("latin1").split("\r\n")) {
8294
+ const at = line.indexOf(":");
8295
+ if (at > 0 && line.slice(0, at).trim().toLowerCase() === LENGTH_HEADER) len = Number(line.slice(at + 1).trim());
8296
+ }
8297
+ if (!Number.isInteger(len) || len < 0) return void 0;
8298
+ const start = end + HEADER_END.length;
8299
+ if (buf.length < start + len) return void 0;
8300
+ return { body: buf.subarray(start, start + len).toString("utf8"), rest: buf.subarray(start + len) };
8301
+ }
8302
+ function listCopilotHooks(env, file, cwd) {
8303
+ const bin = whichBin("copilot", env);
8304
+ if (!bin) return Promise.resolve(void 0);
8305
+ return new Promise((resolve) => {
8306
+ let f2;
8307
+ try {
8308
+ f2 = spawnForm(bin, ["--server", "--stdio", "--no-auto-update"], env);
8309
+ } catch {
8310
+ resolve(void 0);
8311
+ return;
8312
+ }
8313
+ const child = spawn2(f2.command, f2.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f2.windowsVerbatimArguments, windowsHide: true });
8314
+ let buf = Buffer.alloc(0);
8315
+ let done = false;
8316
+ const finish2 = (v) => {
8317
+ if (done) return;
8318
+ done = true;
8319
+ clearTimeout(timer);
8320
+ child.stdin.destroy();
8321
+ child.kill();
8322
+ resolve(v);
8323
+ };
8324
+ const timer = setTimeout(() => finish2(void 0), ASK_TIMEOUT_MS2);
8325
+ child.on("error", () => finish2(void 0));
8326
+ child.on("close", () => finish2(void 0));
8327
+ child.stdin.on("error", () => finish2(void 0));
8328
+ child.stdout.on("data", (d) => {
8329
+ buf = Buffer.concat([buf, d]);
8330
+ const m3 = frame(buf);
8331
+ if (!m3) return;
8332
+ buf = Buffer.from(m3.rest);
8333
+ let reply;
8334
+ try {
8335
+ reply = JSON.parse(m3.body);
8336
+ } catch {
8337
+ finish2(void 0);
8338
+ return;
8339
+ }
8340
+ if (!isObj4(reply) || !isObj4(reply.result) || !Array.isArray(reply.result.hooks)) {
8341
+ finish2(void 0);
8342
+ return;
8343
+ }
8344
+ finish2(copilotHooksFromReply(reply, file));
8345
+ });
8346
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "hooks.discover", params: {} });
8347
+ try {
8348
+ child.stdin.write(`Content-Length: ${Buffer.byteLength(body)}${HEADER_END}${body}`);
8349
+ } catch {
8350
+ finish2(void 0);
8351
+ }
8352
+ });
8353
+ }
7842
8354
 
7843
8355
  // src/setup/engine.ts
7844
- import { spawn, spawnSync as spawnSync2 } from "node:child_process";
7845
- import { closeSync, existsSync as existsSync6, mkdirSync as mkdirSync3, mkdtempSync, openSync, readFileSync as readFileSync4, readSync, readdirSync as readdirSync4, realpathSync as realpathSync4, rmSync, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
8356
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
8357
+ import { closeSync, existsSync as existsSync11, mkdirSync as mkdirSync3, mkdtempSync, openSync, readFileSync as readFileSync9, readSync, readdirSync as readdirSync4, realpathSync as realpathSync6, rmSync, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
7846
8358
  import { tmpdir as tmpdir2 } from "node:os";
7847
- import path6 from "node:path";
8359
+ import path12 from "node:path";
7848
8360
 
7849
8361
  // src/setup/hook-sample.ts
7850
8362
  var SAMPLE_FILE = "big.log";
@@ -7937,29 +8449,29 @@ function isNativeBinary(file) {
7937
8449
  return BINARY_MAGICS.some((m3) => hex.startsWith(m3));
7938
8450
  }
7939
8451
  function owningPackage(dir) {
7940
- for (let d = dir; ; d = path6.dirname(d)) {
7941
- const f2 = path6.join(d, "package.json");
7942
- if (existsSync6(f2)) {
8452
+ for (let d = dir; ; d = path12.dirname(d)) {
8453
+ const f2 = path12.join(d, "package.json");
8454
+ if (existsSync11(f2)) {
7943
8455
  try {
7944
- return String(JSON.parse(hostText(readFileSync4(f2, "utf8"))).name);
8456
+ return String(JSON.parse(hostText(readFileSync9(f2, "utf8"))).name);
7945
8457
  } catch {
7946
8458
  return void 0;
7947
8459
  }
7948
8460
  }
7949
- if (path6.dirname(d) === d) return void 0;
8461
+ if (path12.dirname(d) === d) return void 0;
7950
8462
  }
7951
8463
  }
7952
8464
  function hostBin(bin, env, platform = process.platform) {
7953
- const real = REAL_HOST[bin];
7954
- if (!real) return { file: which(bin, env, platform), shims: [] };
8465
+ const real2 = REAL_HOST[bin];
8466
+ if (!real2) return { file: which(bin, env, platform), shims: [] };
7955
8467
  const get = (k) => env[Object.keys(env).find((x2) => x2.toUpperCase() === k) ?? k];
7956
8468
  const shims = [];
7957
8469
  for (const dir of pathEntries(get("PATH") ?? "", platform)) {
7958
8470
  const own2 = which(bin, { PATH: dir, ...get("PATHEXT") ? { PATHEXT: get("PATHEXT") } : {} }, platform);
7959
- for (const f2 of [own2, ...real.extra.map((p3) => path6.join(dir, ...p3))]) {
7960
- if (!f2 || !existsSync6(f2) || !statSync2(f2).isFile()) continue;
7961
- const file = realpathSync4(f2);
7962
- if (isNativeBinary(file) || owningPackage(path6.dirname(file)) === real.pkg) return { file, shims };
8471
+ for (const f2 of [own2, ...real2.extra.map((p3) => path12.join(dir, ...p3))]) {
8472
+ if (!f2 || !existsSync11(f2) || !statSync2(f2).isFile()) continue;
8473
+ const file = realpathSync6(f2);
8474
+ if (isNativeBinary(file) || owningPackage(path12.dirname(file)) === real2.pkg) return { file, shims };
7963
8475
  shims.push(f2);
7964
8476
  }
7965
8477
  }
@@ -7974,10 +8486,10 @@ function runBin(bin, args, env, input) {
7974
8486
  return spawnShim(hostBin(bin, env).file ?? bin, args, env, { encoding: "utf8", input, timeout: VERIFY_TIMEOUT_MS });
7975
8487
  }
7976
8488
  function readOr(file) {
7977
- return existsSync6(file) ? hostText(readFileSync4(file, "utf8")) : void 0;
8489
+ return existsSync11(file) ? hostText(readFileSync9(file, "utf8")) : void 0;
7978
8490
  }
7979
8491
  function readRaw(file) {
7980
- return existsSync6(file) ? readFileSync4(file, "utf8") : void 0;
8492
+ return existsSync11(file) ? readFileSync9(file, "utf8") : void 0;
7981
8493
  }
7982
8494
  var atomicWrite = atomicWriteFile;
7983
8495
  function pidAlive(pid) {
@@ -7995,7 +8507,7 @@ function p95(xs) {
7995
8507
  function parseFail(_row, file) {
7996
8508
  return `${file} does not parse; left as is. Fix the file, then re-run setup`;
7997
8509
  }
7998
- var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8510
+ var isObj5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7999
8511
  function planHookFile(row, hf) {
8000
8512
  const before = readOr(hf.file);
8001
8513
  if (before === void 0) return void 0;
@@ -8005,14 +8517,14 @@ function planHookFile(row, hf) {
8005
8517
  } catch {
8006
8518
  throw new Error(parseFail(row, hf.file));
8007
8519
  }
8008
- if (!isObj3(doc) || !isObj3(doc.hooks)) return void 0;
8520
+ if (!isObj5(doc) || !isObj5(doc.hooks)) return void 0;
8009
8521
  const changes = [];
8010
8522
  const want = hookCommandString(row);
8011
8523
  for (const [event, groups] of Object.entries(doc.hooks)) {
8012
8524
  if (!Array.isArray(groups)) continue;
8013
8525
  for (let g2 = groups.length - 1; g2 >= 0; g2--) {
8014
8526
  const group2 = groups[g2];
8015
- if (isObj3(group2) && typeof group2.command === "string" && !Array.isArray(group2.hooks)) {
8527
+ if (isObj5(group2) && typeof group2.command === "string" && !Array.isArray(group2.hooks)) {
8016
8528
  if (!group2.command.includes(V1_HOOK_MARK)) continue;
8017
8529
  const at = `hooks.${event}[${g2}].command`;
8018
8530
  if (hf.mode === "rewrite") {
@@ -8024,10 +8536,10 @@ function planHookFile(row, hf) {
8024
8536
  }
8025
8537
  continue;
8026
8538
  }
8027
- const list2 = isObj3(group2) ? group2.hooks : void 0;
8539
+ const list2 = isObj5(group2) ? group2.hooks : void 0;
8028
8540
  if (!Array.isArray(list2)) continue;
8029
8541
  for (let h2 = list2.length - 1; h2 >= 0; h2--) {
8030
- const cmd = isObj3(list2[h2]) ? list2[h2].command : void 0;
8542
+ const cmd = isObj5(list2[h2]) ? list2[h2].command : void 0;
8031
8543
  if (typeof cmd !== "string" || !cmd.includes(V1_HOOK_MARK)) continue;
8032
8544
  const at = `hooks.${event}[${g2}].hooks[${h2}].command`;
8033
8545
  if (hf.mode === "rewrite") {
@@ -8052,11 +8564,11 @@ function isOwnHookCommand(cmd, agent) {
8052
8564
  if (tail.startsWith('"')) tail = tail.slice(1);
8053
8565
  return tail.trim() === `${AGENT_FLAG} ${agent}`;
8054
8566
  }
8055
- 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;
8567
+ 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;
8056
8568
  var same = (a2, b3) => JSON.stringify(a2) === JSON.stringify(b3);
8057
8569
  function mergeOwn(cur, want, agent) {
8058
- if (isObj3(want)) {
8059
- const base = isObj3(cur) ? { ...cur } : {};
8570
+ if (isObj5(want)) {
8571
+ const base = isObj5(cur) ? { ...cur } : {};
8060
8572
  for (const [k, v] of Object.entries(want)) base[k] = mergeOwn(base[k], v, agent);
8061
8573
  return base;
8062
8574
  }
@@ -8079,7 +8591,7 @@ function planJsonKeys(row, edits, file, format, want) {
8079
8591
  throw new Error(parseFail(row, file));
8080
8592
  }
8081
8593
  }
8082
- if (!isObj3(doc)) throw new Error(parseFail(row, file));
8594
+ if (!isObj5(doc)) throw new Error(parseFail(row, file));
8083
8595
  let res;
8084
8596
  try {
8085
8597
  res = editHostConfigText(row.id, file, text2 ?? "", format, want(doc));
@@ -8115,6 +8627,50 @@ function planCodexTrust(row, edits, hooksFile, file, command, env) {
8115
8627
  prior.changes.push(...changes);
8116
8628
  } else edits.push({ file, before: text2, after: res.text, changes });
8117
8629
  }
8630
+ var NATIVE_PLUGIN_PREFIX = "context-mode@";
8631
+ function isNativeSpec(e) {
8632
+ return typeof e === "string" && e.startsWith(NATIVE_PLUGIN_PREFIX);
8633
+ }
8634
+ function isStaleOwnPlugin(e, entry2) {
8635
+ if (typeof e !== "string" || e === entry2 || !path12.isAbsolute(e) || existsSync11(e)) return false;
8636
+ const seg = e.split("\\").join("/").split("/");
8637
+ const n3 = seg.length;
8638
+ return n3 >= 3 && seg[n3 - 1] === "plugin.js" && seg[n3 - 2] === "opencode" && seg[n3 - 3] === "context-mode";
8639
+ }
8640
+ function wantedPluginList(list2, entry2) {
8641
+ const native = list2.some(isNativeSpec);
8642
+ const kept = list2.filter((e) => !(native && e === entry2) && !isStaleOwnPlugin(e, entry2));
8643
+ return native || kept.includes(entry2) ? kept : [...kept, entry2];
8644
+ }
8645
+ function pluginListIssue(h2) {
8646
+ const text2 = readOr(h2.file);
8647
+ if (text2 === void 0) return void 0;
8648
+ let doc;
8649
+ try {
8650
+ doc = parseHostConfig("opencode", h2.file, text2, fileFormat({ id: "opencode" }, h2.file));
8651
+ } catch {
8652
+ return void 0;
8653
+ }
8654
+ const cur = isObj5(doc) ? doc[h2.key[0]] : void 0;
8655
+ const list2 = Array.isArray(cur) ? cur : [];
8656
+ if (list2.some(isNativeSpec) && list2.includes(h2.entry)) return `${h2.file}: context-mode loads twice (native entry and ${h2.entry}), every hook fires twice; run: context-mode setup`;
8657
+ const stale = list2.find((e) => isStaleOwnPlugin(e, h2.entry));
8658
+ if (stale !== void 0) return `${h2.file}: plugin file missing, so OpenCode never loads the hooks (${String(stale)}); run: context-mode setup`;
8659
+ return void 0;
8660
+ }
8661
+ function kiroDisabledIssue(h2) {
8662
+ const text2 = readOr(h2.file);
8663
+ if (text2 === void 0) return void 0;
8664
+ let doc;
8665
+ try {
8666
+ doc = parseHostConfig("kiro", h2.file, text2, "json");
8667
+ } catch {
8668
+ return void 0;
8669
+ }
8670
+ const hooks = isObj5(doc) && Array.isArray(doc.hooks) ? doc.hooks : [];
8671
+ const off = hooks.filter((e) => isObj5(e) && e.enabled === false && isObj5(e.action) && isOwnHookCommand(e.action.command, "kiro")).map((e) => String(e.name));
8672
+ 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;
8673
+ }
8118
8674
  function planHookInstall(row, edits, env) {
8119
8675
  const h2 = row.hookInstall;
8120
8676
  if (h2.kind === "file") {
@@ -8124,7 +8680,8 @@ function planHookInstall(row, edits, env) {
8124
8680
  planJsonKeys(row, edits, h2.file, fileFormat(row, h2.file), (doc) => {
8125
8681
  const cur = doc[h2.key[0]];
8126
8682
  const list2 = Array.isArray(cur) ? cur : [];
8127
- return [[h2.key, list2.includes(h2.entry) ? list2 : [...list2, h2.entry]]];
8683
+ const want = wantedPluginList(list2, h2.entry);
8684
+ return [[h2.key, want.length === list2.length && want.every((e, i2) => e === list2[i2]) ? list2 : want]];
8128
8685
  });
8129
8686
  }
8130
8687
  }
@@ -8132,13 +8689,13 @@ function planSkills(row, edits) {
8132
8689
  const s = row.skillInstall;
8133
8690
  if (s.kind !== "dir") return;
8134
8691
  for (const f2 of s.files) {
8135
- if (!existsSync6(f2.src)) throw new Error(`preflight: ${f2.src} is missing`);
8136
- const after = renderSkill(readFileSync4(f2.src, "utf8"), s.prefixes);
8692
+ if (!existsSync11(f2.src)) throw new Error(`preflight: ${f2.src} is missing`);
8693
+ const after = renderSkill(readFileSync9(f2.src, "utf8"), s.prefixes);
8137
8694
  const before = readRaw(f2.file);
8138
8695
  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" }] });
8139
8696
  }
8140
8697
  }
8141
- function planRow(row, listed, stale, env) {
8698
+ function planRow(row, listed, stale, env, disabled = false) {
8142
8699
  const edits = [];
8143
8700
  if (row.config) {
8144
8701
  const c3 = row.config;
@@ -8160,18 +8717,73 @@ function planRow(row, listed, stale, env) {
8160
8717
  planSkills(row, edits);
8161
8718
  const cli = row.config || !row.cli || listed ? [] : row.cli.install;
8162
8719
  const refresh = listed && stale && row.copy ? [row.copy.refresh] : [];
8720
+ if (listed && disabled && row.copy) refresh.push(row.copy.enable);
8163
8721
  return { edits, cli, refresh };
8164
8722
  }
8165
8723
  function listCheck(row, env) {
8724
+ return listState(row, env).check;
8725
+ }
8726
+ var STATUS_KEY = "Status:";
8727
+ var DISABLED_WORD = "disabled";
8728
+ function statusOf(row, text2) {
8729
+ const c3 = row.copy;
8730
+ if (!c3) return void 0;
8731
+ let mine = false;
8732
+ for (const raw of text2.split("\n")) {
8733
+ const t2 = raw.trim();
8734
+ if (raw.length && !raw.startsWith(" ")) {
8735
+ mine = false;
8736
+ continue;
8737
+ }
8738
+ if (t2.split(" ").includes(c3.plugin)) {
8739
+ mine = true;
8740
+ continue;
8741
+ }
8742
+ if (mine && t2.startsWith(STATUS_KEY)) return t2.split(" ").includes(DISABLED_WORD) ? "disabled" : "enabled";
8743
+ }
8744
+ return void 0;
8745
+ }
8746
+ function listState(row, env) {
8166
8747
  const l2 = row.listCommand;
8167
- if (!l2 || !hostBin(l2.bin, env).file) return void 0;
8748
+ if (!l2 || !hostBin(l2.bin, env).file) return { status: void 0 };
8168
8749
  const r2 = runBin(l2.bin, l2.args, env);
8169
8750
  const ok = r2.status === 0 && `${r2.stdout}${r2.stderr}`.includes("context-mode");
8170
- return { name: "list", ok, detail: ok ? void 0 : `${l2.bin} ${l2.args.join(" ")} does not list context-mode` };
8751
+ const check = { name: "list", ok, detail: ok ? void 0 : `${l2.bin} ${l2.args.join(" ")} does not list context-mode` };
8752
+ return { check, status: r2.status === 0 ? statusOf(row, `${r2.stdout}`) : void 0 };
8753
+ }
8754
+ var DISABLE_ALL_HOOKS = "disableAllHooks";
8755
+ var SETTINGS_FILES = ["settings.json", "settings.local.json"];
8756
+ function disabledBySettings(row) {
8757
+ const c3 = row.copy;
8758
+ if (!c3) return void 0;
8759
+ const dirs = [path12.dirname(path12.dirname(c3.file)), path12.join(process.cwd(), ".claude")];
8760
+ for (const dir of dirs) {
8761
+ for (const name of SETTINGS_FILES) {
8762
+ const file = path12.join(dir, name);
8763
+ const text2 = readOr(file);
8764
+ if (text2 === void 0) continue;
8765
+ let doc;
8766
+ try {
8767
+ doc = JSON.parse(text2);
8768
+ } catch {
8769
+ continue;
8770
+ }
8771
+ if (isObj5(doc) && doc[DISABLE_ALL_HOOKS] === true) return file;
8772
+ }
8773
+ }
8774
+ return void 0;
8775
+ }
8776
+ function hookEnabledCheck(row, status) {
8777
+ const c3 = row.copy;
8778
+ if (!c3) return void 0;
8779
+ 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(" ")}` };
8780
+ const file = disabledBySettings(row);
8781
+ 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` };
8782
+ return { name: "hook-enabled", ok: true };
8171
8783
  }
8172
8784
  function packageVersion(pkgDir) {
8173
8785
  try {
8174
- const v = JSON.parse(hostText(readFileSync4(path6.join(pkgDir, "package.json"), "utf8"))).version;
8786
+ const v = JSON.parse(hostText(readFileSync9(path12.join(pkgDir, "package.json"), "utf8"))).version;
8175
8787
  return typeof v === "string" ? v : void 0;
8176
8788
  } catch {
8177
8789
  return void 0;
@@ -8185,12 +8797,12 @@ function copyCheck(row, pkgDir) {
8185
8797
  let entries;
8186
8798
  try {
8187
8799
  const doc = JSON.parse(text2);
8188
- entries = isObj3(doc) && isObj3(doc.plugins) ? doc.plugins[c3.plugin] : void 0;
8800
+ entries = isObj5(doc) && isObj5(doc.plugins) ? doc.plugins[c3.plugin] : void 0;
8189
8801
  } catch {
8190
8802
  return { name: "copy", ok: false, detail: `${c3.file} is not valid JSON; run ${c3.bin} ${c3.refresh.join(" ")}` };
8191
8803
  }
8192
8804
  if (!Array.isArray(entries)) return void 0;
8193
- const versions = entries.filter(isObj3).map((e) => e.version).filter((v) => typeof v === "string");
8805
+ const versions = entries.filter(isObj5).map((e) => e.version).filter((v) => typeof v === "string");
8194
8806
  if (!versions.length) return void 0;
8195
8807
  const old = versions.find((v) => v !== pkg);
8196
8808
  if (old === void 0) return { name: "copy", ok: true };
@@ -8198,7 +8810,7 @@ function copyCheck(row, pkgDir) {
8198
8810
  }
8199
8811
  function mcpCheck(cmd, env) {
8200
8812
  return new Promise((resolve) => {
8201
- const child = spawn(cmd[0], cmd.slice(1), { env, stdio: ["pipe", "pipe", "ignore"], detached: process.platform !== "win32", windowsHide: true });
8813
+ const child = spawn3(cmd[0], cmd.slice(1), { env, stdio: ["pipe", "pipe", "ignore"], detached: process.platform !== "win32", windowsHide: true });
8202
8814
  const reap = () => {
8203
8815
  child.kill();
8204
8816
  };
@@ -8232,7 +8844,7 @@ function mcpCheck(cmd, env) {
8232
8844
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
8233
8845
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }) + "\n");
8234
8846
  } else if (m3.id === 2) {
8235
- const tools = isObj3(m3.result) && Array.isArray(m3.result.tools) ? m3.result.tools.map((t2) => t2.name) : [];
8847
+ const tools = isObj5(m3.result) && Array.isArray(m3.result.tools) ? m3.result.tools.map((t2) => t2.name) : [];
8236
8848
  const want = [...TOOL_ORDER].sort();
8237
8849
  const got = [...tools].sort();
8238
8850
  const ok = JSON.stringify(got) === JSON.stringify(want);
@@ -8264,7 +8876,7 @@ function hookRound(row, env) {
8264
8876
  j2 = JSON.parse(out2);
8265
8877
  } catch {
8266
8878
  }
8267
- if (!isObj3(j2)) return { name: "hook", ok: false, detail: `hook answer is not a JSON object: ${out2.slice(0, 200)}` };
8879
+ if (!isObj5(j2)) return { name: "hook", ok: false, detail: `hook answer is not a JSON object: ${out2.slice(0, 200)}` };
8268
8880
  }
8269
8881
  t2 = performance.now();
8270
8882
  spawnSync2(cmd[0], ["-e", ""], { env, timeout: VERIFY_TIMEOUT_MS, windowsHide: true });
@@ -8314,17 +8926,18 @@ function hookRegisteredCheck(row, env, list2) {
8314
8926
  if (!edits.length) return { name: "hook-registered", ok: true };
8315
8927
  const trust = h2.kind === "file" ? h2.trust : void 0;
8316
8928
  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` };
8317
- return { name: "hook-registered", ok: false, detail: `${h2.file} lacks the context-mode hook entry` };
8929
+ const issue = h2.kind === "plugin-list" ? pluginListIssue(h2) : h2.kind === "file" && row.id === "kiro" ? kiroDisabledIssue(h2) : void 0;
8930
+ return { name: "hook-registered", ok: false, detail: issue ?? `${h2.file} lacks the context-mode hook entry` };
8318
8931
  }
8319
8932
  function hookRunsCheck(row, env) {
8320
- const root = mkdtempSync(path6.join(tmpdir2(), "cm-doctor-runs-"));
8933
+ const root = mkdtempSync(path12.join(tmpdir2(), "cm-doctor-runs-"));
8321
8934
  try {
8322
- const home = path6.join(root, "home");
8323
- const proj = path6.join(root, "proj");
8935
+ const home = path12.join(root, "home");
8936
+ const proj = path12.join(root, "proj");
8324
8937
  mkdirSync3(home);
8325
8938
  mkdirSync3(proj);
8326
8939
  const text2 = sampleText();
8327
- writeFileSync2(path6.join(proj, SAMPLE_FILE), text2);
8940
+ writeFileSync2(path12.join(proj, SAMPLE_FILE), text2);
8328
8941
  const { effect, payload } = hookSample(row.id, proj, text2);
8329
8942
  const sampleEnv = { ...env, HOME: home, USERPROFILE: home };
8330
8943
  delete sampleEnv.CLAUDE_PROJECT_DIR;
@@ -8339,8 +8952,8 @@ function hookRunsCheck(row, env) {
8339
8952
  var SEEN_SQL = "SELECT 1 FROM events WHERE agent = ? LIMIT 1";
8340
8953
  var NOT_SEEN_LINE = "not seen yet, run one tool call";
8341
8954
  function hookSeenCheck(row, home) {
8342
- const base = path6.join(home, STATE_DIR, PROJECTS_DIR_NAME);
8343
- const dirs = existsSync6(base) ? readdirSync4(base) : [];
8955
+ const base = path12.join(home, STATE_DIR, PROJECTS_DIR_NAME);
8956
+ const dirs = existsSync11(base) ? readdirSync4(base) : [];
8344
8957
  let sqlite;
8345
8958
  try {
8346
8959
  sqlite = process.getBuiltinModule("node:sqlite");
@@ -8348,8 +8961,8 @@ function hookSeenCheck(row, home) {
8348
8961
  sqlite = void 0;
8349
8962
  }
8350
8963
  for (const d of dirs) {
8351
- const file = path6.join(base, d, DB_FILE_NAME);
8352
- if (!sqlite || !existsSync6(file)) continue;
8964
+ const file = path12.join(base, d, DB_FILE_NAME);
8965
+ if (!sqlite || !existsSync11(file)) continue;
8353
8966
  let db;
8354
8967
  try {
8355
8968
  db = new sqlite.DatabaseSync(file, { readOnly: true });
@@ -8364,15 +8977,17 @@ function hookSeenCheck(row, home) {
8364
8977
  function skillsCheck(row, pkgDir) {
8365
8978
  const s = row.skillInstall;
8366
8979
  if (s.kind === "package") {
8367
- const miss = COMMAND_SKILLS.map((n3) => path6.join(pkgDir, s.via, n3, SKILL_FILE)).filter((f2) => !existsSync6(f2));
8980
+ const miss = COMMAND_SKILLS.map((n3) => path12.join(pkgDir, s.via, n3, SKILL_FILE)).filter((f2) => !existsSync11(f2));
8368
8981
  return { name: "skills", ok: miss.length === 0, detail: miss.length ? `missing ${miss.join(", ")}` : void 0 };
8369
8982
  }
8370
- const bad = s.files.filter((f2) => readRaw(f2.file) !== (existsSync6(f2.src) ? renderSkill(readFileSync4(f2.src, "utf8"), s.prefixes) : void 0));
8983
+ const bad = s.files.filter((f2) => readRaw(f2.file) !== (existsSync11(f2.src) ? renderSkill(readFileSync9(f2.src, "utf8"), s.prefixes) : void 0));
8371
8984
  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 };
8372
8985
  }
8373
8986
  var PLUGIN_ENABLED = "enabled";
8374
8987
  var WORD_TRIM = ",;";
8988
+ var CODEX_CONFIG_FILE2 = "config.toml";
8375
8989
  var EXT_ENABLED_USER = "Enabled (User):";
8990
+ var EXT_ENABLED_WORKSPACE = "Enabled (Workspace):";
8376
8991
  var EXT_TRUE = "true";
8377
8992
  function tableState(n3, text2) {
8378
8993
  const line = text2.split("\n").find((l2) => l2.split(" ").includes(n3.plugin));
@@ -8381,6 +8996,8 @@ function tableState(n3, text2) {
8381
8996
  }
8382
8997
  function extensionState(n3, text2) {
8383
8998
  let mine = false;
8999
+ let state;
9000
+ let workspaceOff = false;
8384
9001
  for (const raw of text2.split("\n")) {
8385
9002
  const line = raw.trimEnd();
8386
9003
  if (line.length && !line.startsWith(" ")) {
@@ -8388,16 +9005,19 @@ function extensionState(n3, text2) {
8388
9005
  continue;
8389
9006
  }
8390
9007
  const t2 = line.trim();
8391
- if (mine && t2.startsWith(EXT_ENABLED_USER)) return t2.slice(EXT_ENABLED_USER.length).trim() === EXT_TRUE ? "enabled" : "disabled";
9008
+ if (!mine) continue;
9009
+ if (t2.startsWith(EXT_ENABLED_USER)) state = t2.slice(EXT_ENABLED_USER.length).trim() === EXT_TRUE ? "enabled" : "disabled";
9010
+ if (t2.startsWith(EXT_ENABLED_WORKSPACE)) workspaceOff = t2.slice(EXT_ENABLED_WORKSPACE.length).trim() !== EXT_TRUE;
8392
9011
  }
8393
- return void 0;
9012
+ return { state, workspaceOff };
8394
9013
  }
8395
9014
  function nativeState(row, env) {
9015
+ const none = { state: void 0, workspaceOff: false };
8396
9016
  const n3 = row.nativePlugin;
8397
- if (!n3 || !hostBin(n3.bin, env).file) return void 0;
9017
+ if (!n3 || !hostBin(n3.bin, env).file) return none;
8398
9018
  const r2 = runBin(n3.bin, n3.args, env);
8399
- if (r2.status !== 0) return void 0;
8400
- return n3.format === "extension" ? extensionState(n3, `${r2.stdout}${r2.stderr}`) : tableState(n3, `${r2.stdout}`);
9019
+ if (r2.status !== 0) return none;
9020
+ return n3.format === "extension" ? extensionState(n3, `${r2.stdout}${r2.stderr}`) : { state: tableState(n3, `${r2.stdout}`), workspaceOff: false };
8401
9021
  }
8402
9022
  function nativeRow(row, n3) {
8403
9023
  return {
@@ -8418,9 +9038,9 @@ function trimChars(w, chars) {
8418
9038
  while (b3 > a2 && chars.includes(w.charAt(b3 - 1))) b3--;
8419
9039
  return w.slice(a2, b3);
8420
9040
  }
8421
- async function nativeResult(row, ctx) {
9041
+ async function nativeResult(row, ctx, apply2) {
8422
9042
  const n3 = row.nativePlugin;
8423
- const state = nativeState(row, ctx.env);
9043
+ const { state, workspaceOff } = nativeState(row, ctx.env);
8424
9044
  if (!n3 || state === void 0) return void 0;
8425
9045
  const bin = hostBin(n3.bin, ctx.env).file;
8426
9046
  if (state === "disabled") {
@@ -8435,25 +9055,145 @@ async function nativeResult(row, ctx) {
8435
9055
  reason: `context-mode is installed but disabled in ${n3.bin}, run ${n3.bin} ${n3.enable.join(" ")}`
8436
9056
  };
8437
9057
  }
8438
- const res = { id: row.id, status: "PASS", v1: [], changes: [], checks: await verifyRow(nativeRow(row, n3), ctx), bin };
9058
+ const res = { id: row.id, status: "PASS", v1: [], changes: [], checks: [], bin };
9059
+ let hooks = n3.hookTrust ? await listPluginHooks(ctx.env, n3.plugin, ctx.home) : void 0;
9060
+ if (apply2 && hooks?.some((h2) => !h2.trusted)) {
9061
+ try {
9062
+ const done = trustPluginHooks(row, ctx, apply2, hooks);
9063
+ res.changes.push(...done);
9064
+ if (done.length && !apply2.dryRun) hooks = await listPluginHooks(ctx.env, n3.plugin, ctx.home);
9065
+ } catch (e) {
9066
+ apply2.run.rollback(row.id, ctx.env);
9067
+ return { ...res, status: "FAIL", reason: e.message, rolledBack: true };
9068
+ }
9069
+ }
9070
+ res.checks = await verifyRow(nativeRow(row, n3), ctx);
9071
+ if (n3.hookTrust) res.checks = withHookTrust(res.checks, hooks, !!apply2?.dryRun);
9072
+ if (n3.format === "extension") res.checks = withHookGate(res.checks, geminiGate(n3, ctx, workspaceOff));
8439
9073
  const bad = res.checks.filter((c3) => !c3.ok);
8440
9074
  if (bad.length) {
8441
9075
  res.status = "FAIL";
8442
9076
  res.reason = bad.map((c3) => `${c3.name}: ${c3.detail}`).join("; ");
9077
+ if (apply2 && !apply2.dryRun && res.changes.length) {
9078
+ apply2.run.rollback(row.id, ctx.env);
9079
+ res.rolledBack = true;
9080
+ }
8443
9081
  }
8444
9082
  return res;
8445
9083
  }
9084
+ function trustPluginHooks(row, ctx, apply2, hooks) {
9085
+ const file = path12.join(codexDirOf(ctx.env, ctx.home), CODEX_CONFIG_FILE2);
9086
+ const text2 = readOr(file);
9087
+ let edit;
9088
+ try {
9089
+ edit = editHostConfigText(row.id, file, text2 ?? "", "toml", pluginTrustEntries(hooks));
9090
+ } catch (e) {
9091
+ if (e instanceof CtxError) throw new Error(parseFail(row, file));
9092
+ throw e;
9093
+ }
9094
+ if (!edit.edits.length) return [];
9095
+ if (!apply2.dryRun) {
9096
+ assertWritable(row, file);
9097
+ const raw = readRaw(file);
9098
+ apply2.run.record({ agent: row.id, file, existed: raw !== void 0 }, raw);
9099
+ atomicWrite(file, raw === void 0 ? edit.text : withLayout(edit.text, hostLayout(raw)));
9100
+ }
9101
+ return edit.edits.map((e) => ({ file, ...e }));
9102
+ }
9103
+ function geminiGate(n3, ctx, workspaceOff) {
9104
+ if (n3.bin === "qwen") {
9105
+ if (workspaceOff && n3.enable) return `qwen runs no hook: context-mode is disabled for this workspace; run ${n3.bin} ${n3.enable.join(" ")}`;
9106
+ return qwenHooksOff(ctx.env, ctx.home, process.cwd());
9107
+ }
9108
+ if (n3.bin !== "gemini") return void 0;
9109
+ 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`;
9110
+ return geminiSettingsGate(ctx.env, ctx.home, process.cwd());
9111
+ }
9112
+ function withHookGate(checks, detail) {
9113
+ if (detail === void 0) return checks;
9114
+ return checks.map((c3) => c3.name === "hook-registered" ? { name: c3.name, ok: false, detail } : c3);
9115
+ }
9116
+ var UNTRUSTED_FIX = "run: context-mode setup";
9117
+ function withHookTrust(checks, hooks, dryRun) {
9118
+ 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)" }];
9119
+ const bad = hooks.filter((h2) => !h2.trusted);
9120
+ if (!bad.length || dryRun) return checks;
9121
+ const detail = `codex lists ${bad.length} of ${hooks.length} context-mode plugin hooks untrusted, so they do not run; ${UNTRUSTED_FIX}`;
9122
+ return checks.map((c3) => c3.name === "hook-registered" ? { name: c3.name, ok: false, detail } : c3);
9123
+ }
9124
+ async function copilotEnabledCheck(row, ctx) {
9125
+ const name = "hook-enabled";
9126
+ const h2 = row.hookInstall;
9127
+ const settings2 = row.copilotSettings;
9128
+ if (h2.kind !== "file" || !settings2) return { name, ok: true };
9129
+ const hooks = await listCopilotHooks(ctx.env, h2.file, ctx.home);
9130
+ if (hooks === void 0) return { name, ok: true, warn: true, detail: "copilot did not report hook state (copilot --server --stdio hooks.discover)" };
9131
+ if (!hooks.length) return { name, ok: false, detail: `copilot lists no context-mode hook from ${h2.file}; ${UNTRUSTED_FIX}` };
9132
+ const bad = hooks.filter((x2) => !x2.enabled);
9133
+ if (!bad.length) return { name, ok: true };
9134
+ let doc;
9135
+ try {
9136
+ const t2 = readOr(settings2);
9137
+ doc = t2 === void 0 ? {} : parseHostConfig(row.id, settings2, t2, "jsonc");
9138
+ } catch {
9139
+ doc = {};
9140
+ }
9141
+ if (isObjSetup(doc) && doc.disableAllHooks === true) return { name, ok: false, detail: `${settings2} sets disableAllHooks, so copilot runs no hook; set it to false` };
9142
+ 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}` };
9143
+ return { name, ok: false, detail: `copilot lists ${bad.length} of ${hooks.length} context-mode hooks disabled by a policy, so they do not run` };
9144
+ }
9145
+ async function enableCopilotHooks(row, ctx, run) {
9146
+ const h2 = row.hookInstall;
9147
+ const settings2 = row.copilotSettings;
9148
+ if (h2.kind !== "file" || !settings2) return [];
9149
+ const listed = await listCopilotHooks(ctx.env, h2.file, ctx.home);
9150
+ const keys = (listed ?? []).flatMap((x2) => !x2.enabled && x2.disableKey !== void 0 ? [x2.disableKey] : []);
9151
+ if (!keys.length) return [];
9152
+ const text2 = readOr(settings2);
9153
+ let doc = {};
9154
+ if (text2 !== void 0 && text2.trim() !== "") {
9155
+ try {
9156
+ doc = parseHostConfig(row.id, settings2, text2, "jsonc");
9157
+ } catch {
9158
+ throw new Error(parseFail(row, settings2));
9159
+ }
9160
+ }
9161
+ if (!isObjSetup(doc)) throw new Error(parseFail(row, settings2));
9162
+ const cur = Array.isArray(doc.disabledHooks) ? doc.disabledHooks : [];
9163
+ const next = cur.filter((k) => !keys.includes(k));
9164
+ if (next.length === cur.length) return [];
9165
+ let edit;
9166
+ try {
9167
+ edit = editHostConfigText(row.id, settings2, text2 ?? "", "jsonc", [[["disabledHooks"], next]]);
9168
+ } catch (e) {
9169
+ if (e instanceof CtxError) throw new Error(parseFail(row, settings2));
9170
+ throw e;
9171
+ }
9172
+ assertWritable(row, settings2);
9173
+ const raw = readRaw(settings2);
9174
+ run.record({ agent: row.id, file: settings2, existed: raw !== void 0 }, raw);
9175
+ atomicWrite(settings2, raw === void 0 ? edit.text : withLayout(edit.text, hostLayout(raw)));
9176
+ return edit.edits.map((e) => ({ file: settings2, ...e }));
9177
+ }
9178
+ var isObjSetup = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8446
9179
  async function verifyRow(row, ctx) {
8447
9180
  const env = ctx.env;
8448
9181
  const checks = [parseCheck(row)];
8449
- const l2 = listCheck(row, env);
9182
+ const ls = listState(row, env);
9183
+ const l2 = ls.check;
8450
9184
  if (l2) checks.push(l2);
8451
9185
  const cp = copyCheck(row, ctx.pkgDir);
8452
9186
  if (cp) checks.push(cp);
8453
9187
  checks.push(await mcpCheck(row.serverCommand, env));
8454
9188
  if (row.hookCommand) checks.push(hookCheck(row, env));
8455
- checks.push(hookRegisteredCheck(row, env, l2), hookRunsCheck(row, env), hookSeenCheck(row, ctx.home), skillsCheck(row, ctx.pkgDir));
8456
- return checks;
9189
+ checks.push(hookRegisteredCheck(row, env, l2));
9190
+ const en = hookEnabledCheck(row, ls.status);
9191
+ if (en) checks.push(en);
9192
+ if (row.copilotSettings) checks.push(await copilotEnabledCheck(row, ctx));
9193
+ checks.push(hookRunsCheck(row, env), hookSeenCheck(row, ctx.home), skillsCheck(row, ctx.pkgDir));
9194
+ if (row.id === "pi") return withHookGate(checks, piSettingsGate(env, ctx.home, ctx.pkgDir, process.cwd()));
9195
+ if (row.id === "vscode") return withHookGate(checks, vscodeSettingsGate(env, ctx.home, process.cwd()));
9196
+ return row.id === "zcode" ? withHookGate(checks, zcodeConfigGate(ctx.home)) : checks;
8457
9197
  }
8458
9198
  var Run = class {
8459
9199
  manifest;
@@ -8464,16 +9204,16 @@ var Run = class {
8464
9204
  this.runId = runId;
8465
9205
  }
8466
9206
  get dir() {
8467
- return path6.join(this.root, BACKUP_DIR, this.runId);
9207
+ return path12.join(this.root, BACKUP_DIR, this.runId);
8468
9208
  }
8469
9209
  save() {
8470
- if (this.manifest) atomicWrite(path6.join(this.dir, MANIFEST), JSON.stringify(this.manifest, null, 2));
9210
+ if (this.manifest) atomicWrite(path12.join(this.dir, MANIFEST), JSON.stringify(this.manifest, null, 2));
8471
9211
  }
8472
9212
  record(e, bytes) {
8473
9213
  if (!this.manifest) this.manifest = { runId: this.runId, path: this.dir, entries: [] };
8474
9214
  if (bytes !== void 0) {
8475
- const rel = path6.join(FILES, String(this.manifest.entries.length));
8476
- atomicWrite(path6.join(this.dir, rel), bytes);
9215
+ const rel = path12.join(FILES, String(this.manifest.entries.length));
9216
+ atomicWrite(path12.join(this.dir, rel), bytes);
8477
9217
  e.backup = rel;
8478
9218
  }
8479
9219
  this.manifest.entries.push(e);
@@ -8493,12 +9233,12 @@ function undo(dir, entries, env) {
8493
9233
  continue;
8494
9234
  }
8495
9235
  if (!e.file) continue;
8496
- if (e.existed && e.backup) atomicWrite(e.file, readFileSync4(path6.join(dir, e.backup), "utf8"));
9236
+ if (e.existed && e.backup) atomicWrite(e.file, readFileSync9(path12.join(dir, e.backup), "utf8"));
8497
9237
  else unlinkWithRetry(e.file);
8498
9238
  }
8499
9239
  }
8500
9240
  function takeLock(root, runId) {
8501
- const file = path6.join(root, LOCK_FILE);
9241
+ const file = path12.join(root, LOCK_FILE);
8502
9242
  mkdirSync3(root, { recursive: true });
8503
9243
  for (let attempt = 0; attempt < 2; attempt++) {
8504
9244
  try {
@@ -8508,7 +9248,7 @@ function takeLock(root, runId) {
8508
9248
  if (e.code !== "EEXIST") throw e;
8509
9249
  let pid = 0;
8510
9250
  try {
8511
- pid = Number(JSON.parse(readFileSync4(file, "utf8")).pid);
9251
+ pid = Number(JSON.parse(readFileSync9(file, "utf8")).pid);
8512
9252
  } catch {
8513
9253
  }
8514
9254
  if (pid && pidAlive(pid)) return `setup lock ${file} is held by pid ${pid}; wait for that run or remove the lock`;
@@ -8522,20 +9262,20 @@ function agentHomeDir(id, ctx) {
8522
9262
  if (id === "copilot-cli") return copilotDirOf(ctx.env, ctx.home);
8523
9263
  if (id === "kiro") return kiroDirOf(ctx.env, ctx.home);
8524
9264
  if (id === "opencode") return opencodeDirOf(ctx.env, ctx.home);
8525
- return path6.join(ctx.home, ...AGENT_HOME_DIR[id]);
9265
+ return path12.join(ctx.home, ...AGENT_HOME_DIR[id]);
8526
9266
  }
8527
9267
  function detectAgents(reg, ctx) {
8528
- return reg.filter((r2) => existsSync6(agentHomeDir(r2.id, ctx)) || r2.listCommand && which(r2.listCommand.bin, ctx.env)).map((r2) => r2.id);
9268
+ return reg.filter((r2) => existsSync11(agentHomeDir(r2.id, ctx)) || r2.listCommand && which(r2.listCommand.bin, ctx.env)).map((r2) => r2.id);
8529
9269
  }
8530
9270
  async function runSetup(opts) {
8531
9271
  const ctx = { home: opts.home, pkgDir: opts.pkgDir, env: opts.env };
8532
9272
  const runId = opts.runId ?? (/* @__PURE__ */ new Date()).toISOString().split(":").join("-").split(".").join("-");
8533
9273
  const reg = buildRegistry(ctx);
8534
9274
  for (const f2 of ["server.mjs", "hook.mjs"]) {
8535
- if (!existsSync6(path6.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path6.join(ctx.pkgDir, f2)} is missing` };
9275
+ if (!existsSync11(path12.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path12.join(ctx.pkgDir, f2)} is missing` };
8536
9276
  }
8537
9277
  const ids = opts.agents ?? detectAgents(reg, ctx);
8538
- const root = path6.join(ctx.home, STATE_DIR);
9278
+ const root = path12.join(ctx.home, STATE_DIR);
8539
9279
  if (!opts.dryRun) {
8540
9280
  const held = takeLock(root, runId);
8541
9281
  if (held) return { exitCode: 1, agents: [], error: held };
@@ -8545,7 +9285,7 @@ async function runSetup(opts) {
8545
9285
  let current;
8546
9286
  const onAbort = () => {
8547
9287
  if (current !== void 0 && !opts.dryRun) run.rollback(current, ctx.env);
8548
- if (!opts.dryRun) rmSync(path6.join(root, LOCK_FILE), { force: true });
9288
+ if (!opts.dryRun) rmSync(path12.join(root, LOCK_FILE), { force: true });
8549
9289
  };
8550
9290
  opts.signal?.addEventListener("abort", onAbort, { once: true });
8551
9291
  try {
@@ -8557,14 +9297,14 @@ async function runSetup(opts) {
8557
9297
  }
8558
9298
  current = id;
8559
9299
  opts.onAgent?.(id, "start");
8560
- const res = await nativeResult(row, ctx) ?? await setupRow(row, ctx, run, !!opts.dryRun);
9300
+ const res = await nativeResult(row, ctx, { run, dryRun: !!opts.dryRun }) ?? await setupRow(row, ctx, run, !!opts.dryRun);
8561
9301
  current = void 0;
8562
9302
  agents.push(res);
8563
9303
  opts.onAgent?.(id, "done", res);
8564
9304
  }
8565
9305
  } finally {
8566
9306
  opts.signal?.removeEventListener("abort", onAbort);
8567
- if (!opts.dryRun) rmSync(path6.join(root, LOCK_FILE), { force: true });
9307
+ if (!opts.dryRun) rmSync(path12.join(root, LOCK_FILE), { force: true });
8568
9308
  }
8569
9309
  return { exitCode: agents.some((a2) => a2.status === "FAIL") ? 1 : 0, agents, backupDir: run.manifest ? run.dir : void 0 };
8570
9310
  }
@@ -8580,8 +9320,9 @@ async function setupRow(row, ctx, run, dryRun) {
8580
9320
  if (!row.config && !row.cli) return { ...res, status: "SKIPPED", reason: `${row.id}: no setup path in the registry` };
8581
9321
  let plan;
8582
9322
  try {
8583
- const listed = needsBin ? listCheck(row, ctx.env)?.ok === true : false;
8584
- plan = planRow(row, listed, copyCheck(row, ctx.pkgDir)?.ok === false, ctx.env);
9323
+ const ls = needsBin ? listState(row, ctx.env) : { status: void 0, check: void 0 };
9324
+ const listed = ls.check?.ok === true;
9325
+ plan = planRow(row, listed, copyCheck(row, ctx.pkgDir)?.ok === false, ctx.env, listed && ls.status === "disabled");
8585
9326
  } catch (e) {
8586
9327
  return { ...res, status: "FAIL", reason: e.message };
8587
9328
  }
@@ -8606,6 +9347,7 @@ async function setupRow(row, ctx, run, dryRun) {
8606
9347
  if (r2.status !== 0) throw new Error(`${row.cli.bin} ${args.join(" ")} exited ${r2.status}: ${`${r2.stderr}`.trim()}`);
8607
9348
  run.record({ agent: row.id, ran: { bin: row.cli.bin, args } });
8608
9349
  }
9350
+ res.changes.push(...await enableCopilotHooks(row, ctx, run));
8609
9351
  res.checks = await verifyRow(row, ctx);
8610
9352
  const bad = res.checks.filter((c3) => !c3.ok);
8611
9353
  if (bad.length) throw new Error(bad.map((c3) => `${c3.name}: ${c3.detail}`).join("; "));
@@ -8621,10 +9363,10 @@ async function runDoctor(opts) {
8621
9363
  const ctx = { home: opts.home, pkgDir: opts.pkgDir, env: opts.env };
8622
9364
  const reg = buildRegistry(ctx);
8623
9365
  for (const f2 of ["server.mjs", "hook.mjs"]) {
8624
- if (!existsSync6(path6.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path6.join(ctx.pkgDir, f2)} is missing` };
9366
+ if (!existsSync11(path12.join(ctx.pkgDir, f2))) return { exitCode: 1, agents: [], error: `preflight: ${path12.join(ctx.pkgDir, f2)} is missing` };
8625
9367
  }
8626
9368
  const ids = opts.agents ?? detectAgents(reg, ctx);
8627
- const run = new Run(path6.join(ctx.home, STATE_DIR), "doctor");
9369
+ const run = new Run(path12.join(ctx.home, STATE_DIR), "doctor");
8628
9370
  const agents = [];
8629
9371
  for (const id of ids) {
8630
9372
  const row = reg.find((r2) => r2.id === id);
@@ -8644,7 +9386,7 @@ async function runDoctor(opts) {
8644
9386
  if (res.v1.some((f2) => !UPGRADE_REPORT_ONLY_REASONS.includes(f2.reason))) {
8645
9387
  res.status = "FAIL";
8646
9388
  res.reason = V1_FORM_REASON;
8647
- } else if (res.changes.length && !onlyTrust(row, res.changes)) {
9389
+ } else if (res.changes.length && !onlyTrust(row, res.changes) && !hasPluginIssue(row)) {
8648
9390
  res.status = "FAIL";
8649
9391
  res.reason = NOT_SET_UP_REASON;
8650
9392
  } else {
@@ -8661,12 +9403,19 @@ async function runDoctor(opts) {
8661
9403
  }
8662
9404
  return { exitCode: agents.some((a2) => a2.status === "FAIL") ? 1 : 0, agents };
8663
9405
  }
9406
+ function hasPluginIssue(row) {
9407
+ const h2 = row.hookInstall;
9408
+ if (h2.kind === "file") return row.id === "kiro" && kiroDisabledIssue(h2) !== void 0;
9409
+ return h2.kind === "plugin-list" && pluginListIssue(h2) !== void 0;
9410
+ }
8664
9411
  function onlyTrust(row, changes) {
8665
9412
  return changes.every((c3) => isTrust(row, c3) || isRefresh(row, c3));
8666
9413
  }
8667
9414
  function isRefresh(row, c3) {
8668
9415
  const r2 = row.copy;
8669
- return r2 !== void 0 && c3.command !== void 0 && c3.command.join(" ") === [r2.bin, ...r2.refresh].join(" ");
9416
+ if (r2 === void 0 || c3.command === void 0) return false;
9417
+ const cmd = c3.command.join(" ");
9418
+ return cmd === [r2.bin, ...r2.refresh].join(" ") || cmd === [r2.bin, ...r2.enable].join(" ");
8670
9419
  }
8671
9420
  function isTrust(row, c3) {
8672
9421
  const h2 = row.hookInstall;
@@ -8674,28 +9423,28 @@ function isTrust(row, c3) {
8674
9423
  }
8675
9424
  function runRemove(opts) {
8676
9425
  const env = opts.env ?? process.env;
8677
- const root = path6.join(opts.home, STATE_DIR);
8678
- const base = path6.join(root, BACKUP_DIR);
8679
- if (!existsSync6(base)) return { exitCode: 0, restored: 0 };
9426
+ const root = path12.join(opts.home, STATE_DIR);
9427
+ const base = path12.join(root, BACKUP_DIR);
9428
+ if (!existsSync11(base)) return { exitCode: 0, restored: 0 };
8680
9429
  const held = takeLock(root, "remove");
8681
9430
  if (held) return { exitCode: 1, restored: 0, error: held };
8682
9431
  let restored = 0;
8683
9432
  try {
8684
- const runs = readdirSync4(base).map((r2) => path6.join(base, r2)).filter((d) => existsSync6(path6.join(d, MANIFEST))).sort().reverse();
9433
+ const runs = readdirSync4(base).map((r2) => path12.join(base, r2)).filter((d) => existsSync11(path12.join(d, MANIFEST))).sort().reverse();
8685
9434
  for (const dir of runs) {
8686
- const m3 = JSON.parse(readFileSync4(path6.join(dir, MANIFEST), "utf8"));
9435
+ const m3 = JSON.parse(readFileSync9(path12.join(dir, MANIFEST), "utf8"));
8687
9436
  undo(dir, m3.entries, env);
8688
9437
  restored += m3.entries.length;
8689
- renameWithRetry(path6.join(dir, MANIFEST), path6.join(dir, MANIFEST_DONE));
9438
+ renameWithRetry(path12.join(dir, MANIFEST), path12.join(dir, MANIFEST_DONE));
8690
9439
  }
8691
9440
  } finally {
8692
- rmSync(path6.join(root, LOCK_FILE), { force: true });
9441
+ rmSync(path12.join(root, LOCK_FILE), { force: true });
8693
9442
  }
8694
9443
  return { exitCode: 0, restored };
8695
9444
  }
8696
9445
 
8697
9446
  // src/setup/print.ts
8698
- import { readFileSync as readFileSync5 } from "node:fs";
9447
+ import { readFileSync as readFileSync10 } from "node:fs";
8699
9448
  var SHELL_SAFE_PUNCT = "@%+=:,./-_";
8700
9449
  function isShellSafe(s) {
8701
9450
  if (s === "") return false;
@@ -8723,7 +9472,7 @@ function printPlan(row, env) {
8723
9472
  else if (h2.kind === "plugin-list") steps.push({ kind: "hook", file: h2.file, block: JSON.stringify({ [h2.key[0]]: [h2.entry] }, null, 2) + "\n" });
8724
9473
  const sk = row.skillInstall;
8725
9474
  if (sk.kind === "dir") {
8726
- for (const f2 of sk.files) steps.push({ kind: "skill", file: f2.file, block: renderSkill(readFileSync5(f2.src, "utf8"), sk.prefixes) });
9475
+ for (const f2 of sk.files) steps.push({ kind: "skill", file: f2.file, block: renderSkill(readFileSync10(f2.src, "utf8"), sk.prefixes) });
8727
9476
  }
8728
9477
  return { agent: row.id, steps, verify: `context-mode doctor --agents ${row.id}` };
8729
9478
  }
@@ -8895,9 +9644,9 @@ async function report(ui, command, res, write) {
8895
9644
  const { text: text2, title } = buildIssueReport(command, res, ui);
8896
9645
  let file = "";
8897
9646
  if (write) {
8898
- const dir = path7.join(ui.ctx.home, STATE_DIR, REPORT_DIR);
9647
+ const dir = path13.join(ui.ctx.home, STATE_DIR, REPORT_DIR);
8899
9648
  mkdirSync4(dir, { recursive: true });
8900
- file = path7.join(dir, `${command}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
9649
+ file = path13.join(dir, `${command}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
8901
9650
  writeFileSync3(file, text2);
8902
9651
  }
8903
9652
  const gh = `gh issue create --repo ${ISSUE_REPO} --title ${JSON.stringify(title)} --body-file ${JSON.stringify(file || "<report>")}`;
@@ -8976,7 +9725,8 @@ function list(ui) {
8976
9725
  const detected = new Set(detectAgents(reg, ui.ctx));
8977
9726
  const rows = ADAPTERS.map((a2) => ({
8978
9727
  id: a2.id,
8979
- level: Object.keys(a2.eventMap).length ? "full" : "MCP only",
9728
+ hooks: a2.hookChannel.kind,
9729
+ // ADR-0020: every agent has a hook channel
8980
9730
  installMode: a2.installMode,
8981
9731
  detected: detected.has(a2.id)
8982
9732
  }));
@@ -8984,8 +9734,8 @@ function list(ui) {
8984
9734
  out(JSON.stringify({ agents: rows }));
8985
9735
  return EXIT_OK;
8986
9736
  }
8987
- out(`${"AGENT".padEnd(13)} ${"SUPPORT".padEnd(9)} ${"FOUND".padEnd(9)} INSTALL`);
8988
- for (const r2 of rows) out(`${r2.id.padEnd(13)} ${r2.level.padEnd(9)} ${(r2.detected ? "detected" : "-").padEnd(9)} ${r2.installMode}`);
9737
+ out(`${"AGENT".padEnd(13)} ${"HOOKS".padEnd(11)} ${"FOUND".padEnd(9)} INSTALL`);
9738
+ for (const r2 of rows) out(`${r2.id.padEnd(13)} ${r2.hooks.padEnd(11)} ${(r2.detected ? "detected" : "-").padEnd(9)} ${r2.installMode}`);
8989
9739
  return EXIT_OK;
8990
9740
  }
8991
9741
  async function remove(ui) {
@@ -9005,7 +9755,7 @@ async function remove(ui) {
9005
9755
  }
9006
9756
  }
9007
9757
  if (ui.f.dryRun) {
9008
- out(`Would restore every file recorded under ${path7.join(ui.ctx.home, STATE_DIR, "backups")}`);
9758
+ out(`Would restore every file recorded under ${path13.join(ui.ctx.home, STATE_DIR, "backups")}`);
9009
9759
  return EXIT_OK;
9010
9760
  }
9011
9761
  const r2 = runRemove({ home: ui.ctx.home, env: ui.ctx.env });
@@ -9144,8 +9894,8 @@ async function upgrade(ui) {
9144
9894
  return EXIT_FAIL;
9145
9895
  }
9146
9896
  const root = `${spawnSync3(npm, ["root", "-g"], { env: ui.ctx.env, encoding: "utf8", shell, windowsHide: true }).stdout ?? ""}`.trim();
9147
- const cli = path7.join(root, "context-mode", "cli.mjs");
9148
- if (!root || !existsSync7(cli)) {
9897
+ const cli = path13.join(root, "context-mode", "cli.mjs");
9898
+ if (!root || !existsSync12(cli)) {
9149
9899
  err(`FAIL upgrade: ${cli} not found after ${install}. Fix: ${install}`);
9150
9900
  return EXIT_FAIL;
9151
9901
  }
@@ -9184,12 +9934,12 @@ Run context-mode ${cmd} --help.`);
9184
9934
  }
9185
9935
 
9186
9936
  // src/entries/is-entry.ts
9187
- import { realpathSync as realpathSync5 } from "node:fs";
9937
+ import { realpathSync as realpathSync7 } from "node:fs";
9188
9938
  function isEntry(main2, argv1, self) {
9189
9939
  if (main2 !== void 0) return main2;
9190
9940
  if (argv1 === void 0 || argv1 === "") return false;
9191
9941
  try {
9192
- return realpathSync5(argv1) === realpathSync5(self);
9942
+ return realpathSync7(argv1) === realpathSync7(self);
9193
9943
  } catch {
9194
9944
  return false;
9195
9945
  }
@@ -9240,10 +9990,10 @@ function route(argv, version) {
9240
9990
  ` };
9241
9991
  }
9242
9992
  function main() {
9243
- const dir = path8.dirname(realpathSync6(fileURLToPath2(import.meta.url)));
9993
+ const dir = path14.dirname(realpathSync8(fileURLToPath2(import.meta.url)));
9244
9994
  let version = "";
9245
9995
  try {
9246
- version = String(JSON.parse(readFileSync6(path8.join(dir, PACKAGE_FILE), "utf8")).version);
9996
+ version = String(JSON.parse(readFileSync11(path14.join(dir, PACKAGE_FILE), "utf8")).version);
9247
9997
  } catch (err2) {
9248
9998
  process.stderr.write(`${SERVER_KEY}: cannot read ${PACKAGE_FILE}: ${err2.message}
9249
9999
  `);
@@ -9267,7 +10017,7 @@ function main() {
9267
10017
  process.exitCode = r2.code;
9268
10018
  return;
9269
10019
  }
9270
- const child = spawn2(process.execPath, [path8.join(dir, r2.file), ...r2.args], { stdio: "inherit", windowsHide: true });
10020
+ const child = spawn4(process.execPath, [path14.join(dir, r2.file), ...r2.args], { stdio: "inherit", windowsHide: true });
9271
10021
  process.on("SIGINT", () => {
9272
10022
  });
9273
10023
  child.on("error", (err2) => {