cc-pets 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CC_BRIDGE.md +239 -0
  2. package/CC_BRIDGE.zh-CN.md +210 -0
  3. package/CHANGELOG.md +39 -0
  4. package/CHANGELOG.zh-CN.md +39 -0
  5. package/PROVIDER_PROTOCOL.md +6 -0
  6. package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
  7. package/README.md +26 -0
  8. package/README.zh-CN.md +25 -2
  9. package/Resources/Info.plist +2 -0
  10. package/Sources/CCPets/CCPetsAppDelegate.h +25 -0
  11. package/Sources/CCPets/CCPetsAppDelegate.m +751 -29
  12. package/Sources/CCPets/CCPetsBridge.h +43 -0
  13. package/Sources/CCPets/CCPetsBridge.m +198 -0
  14. package/Sources/CCPets/CCPetsEvents.m +7 -2
  15. package/Sources/CCPets/CCPetsPaths.h +4 -0
  16. package/Sources/CCPets/CCPetsPaths.m +6 -0
  17. package/Sources/CCPets/CCPetsQuotaHistory.m +9 -2
  18. package/Sources/CCPets/CCPetsTerminalFocus.h +11 -0
  19. package/Sources/CCPets/CCPetsTerminalFocus.m +150 -0
  20. package/Sources/CCPets/PetView.m +86 -1
  21. package/Sources/CCPets/QuotaDashboardView.m +17 -4
  22. package/Sources/CCPets/main.m +5 -0
  23. package/bin/cc-pets +5 -0
  24. package/bin/claude-with-pet +8 -2
  25. package/bin/codex-with-pet +8 -3
  26. package/package.json +3 -1
  27. package/scripts/bridge/cli.mjs +229 -0
  28. package/scripts/bridge/core.mjs +227 -0
  29. package/scripts/bridge/hook.mjs +149 -0
  30. package/scripts/bridge/install.mjs +288 -0
  31. package/scripts/bridge/mcp-server.mjs +300 -0
  32. package/scripts/bridge/options.mjs +86 -0
  33. package/scripts/bridge/process.mjs +129 -0
  34. package/scripts/bridge/reservations.mjs +247 -0
  35. package/scripts/bridge/store.mjs +432 -0
  36. package/scripts/bridge/watch.mjs +69 -0
  37. package/scripts/install-shell-integration.sh +3 -0
  38. package/scripts/uninstall-integrations.mjs +10 -0
@@ -0,0 +1,149 @@
1
+ // 同步 hook:维护会话注册表,并在用户输入时兜底注入信箱里的待处理消息。
2
+ //
3
+ // 安装时以 `CC_BRIDGE_HOOK=<Claude|Codex> node …/cli.mjs hook` 注册到两边的
4
+ // SessionStart / UserPromptSubmit / Stop / SessionEnd。任何异常都吞掉并 exit 0:
5
+ // 这是别人 CLI 的关键路径,CC Bridge 出错不能拖垮对方的一轮对话。
6
+
7
+ import { spawn } from "node:child_process";
8
+ import fs from "node:fs";
9
+ import { fileURLToPath } from "node:url";
10
+ import { PROVIDERS, formatEnvelope, liveSessions } from "./core.mjs";
11
+ import { currentOptions } from "./options.mjs";
12
+ import { findAgentAncestor, processTty } from "./process.mjs";
13
+ import {
14
+ acknowledgeReservation, describeReservation, editedFilesFromToolInput, findForeignReservations, isAcknowledged,
15
+ releaseSessionReservations
16
+ } from "./reservations.mjs";
17
+ import {
18
+ abandonInbox, claimInbox, hasIdleSubscriptions, isBridgeEnabled, pruneReceipts, readSession, removeSession,
19
+ safeSessionId, updateReceipt, upsertSession
20
+ } from "./store.mjs";
21
+
22
+ const cliPath = fileURLToPath(new URL("./cli.mjs", import.meta.url));
23
+
24
+ const STATUS_BY_EVENT = {
25
+ SessionStart: "idle",
26
+ UserPromptSubmit: "busy",
27
+ Stop: "idle"
28
+ };
29
+
30
+ const agentPid = (provider) => {
31
+ const ancestor = findAgentAncestor();
32
+ return ancestor && ancestor.provider === provider ? ancestor.pid : undefined;
33
+ };
34
+
35
+ // 用户开口时把信箱里的消息一并带进这一轮。Claude 平时由 watcher 负责投递,这里只是
36
+ // watcher 超时退出后的空窗期兜底;Codex 平时走 codex queue,这里兜的是 queue 不可用
37
+ // 时退回信箱的消息。
38
+ const injectPending = (sessionId, eventName) => {
39
+ const messages = claimInbox(sessionId);
40
+ if (messages.length === 0) return null;
41
+ for (const message of messages) {
42
+ updateReceipt(message.id, { status: "delivered", transport: { kind: "prompt-inject" } });
43
+ }
44
+ return {
45
+ hookSpecificOutput: {
46
+ hookEventName: eventName,
47
+ additionalContext: messages.map(formatEnvelope).join("\n\n")
48
+ }
49
+ };
50
+ };
51
+
52
+ // 首次拦截、重试放行:本会话第一次编辑某处他人预留的文件时返回 deny 并说明原因,同时记下
53
+ // "已提醒";重试同一操作时这处预留已确认,直接放行。用 deny 而不是只注入 additionalContext:
54
+ // 实测 Codex 的 additionalContext 在工具调用发出之后才到达,拦不住这次编辑,模型也会忽略。
55
+ // 不用 "ask":Codex 的 PreToolUse 只支持 allow / deny,两边行为要一致。
56
+ const checkReservations = (payload, sessionId) => {
57
+ const files = editedFilesFromToolInput(payload.tool_input);
58
+ const cwd = typeof payload.cwd === "string" ? payload.cwd : readSession(sessionId)?.cwd;
59
+ if (files.length === 0 || !cwd) return null;
60
+ const pending = findForeignReservations({ sessionId, cwd, filePaths: files })
61
+ .filter((hit) => !isAcknowledged(hit.reservation, sessionId));
62
+ if (pending.length === 0) return null;
63
+ for (const hit of pending) acknowledgeReservation(hit.reservation.id, sessionId);
64
+ const lines = pending.map((hit) => `- ${hit.file}:${describeReservation(hit.reservation)}`);
65
+ return {
66
+ hookSpecificOutput: {
67
+ hookEventName: "PreToolUse",
68
+ permissionDecision: "deny",
69
+ permissionDecisionReason: [
70
+ "[cc-bridge 文件预留] 这次编辑先暂停一次:以下文件已被本机另一个 Agent 会话预留。",
71
+ ...lines,
72
+ "这不是权限拒绝,而是一次性提醒:如果这次修改是用户明确要求的,直接重试同一操作即可放行," +
73
+ "之后不会再因这处预留拦你;否则请先用 send_message 与对方协调,或改做其他部分。",
74
+ // 实测 Codex 重试放行后只回复"已创建",用户不知道自己改的是别人正在改的区域。
75
+ "如果重试放行,请在给用户的回复里说明:这些文件正被上面的会话预留(写明会话名和原因)," +
76
+ "以便用户判断是否需要与对方协调。"
77
+ ].join("\n")
78
+ }
79
+ };
80
+ };
81
+
82
+ // 空闲通知可能要调 codex queue(秒级),放到脱离的子进程里做,
83
+ // 不让 Stop hook 拖慢对方回合的收尾。
84
+ const notifyIdleInBackground = (sessionId) => {
85
+ const child = spawn(process.execPath, [cliPath, "notify-idle", sessionId], {
86
+ detached: true, stdio: "ignore", env: process.env
87
+ });
88
+ child.unref();
89
+ };
90
+
91
+ export const runHook = (rawInput, environment = process.env) => {
92
+ if (!isBridgeEnabled()) return null;
93
+ const provider = environment.CC_BRIDGE_HOOK;
94
+ if (!PROVIDERS.includes(provider)) return null;
95
+ let payload;
96
+ try {
97
+ payload = JSON.parse(rawInput);
98
+ } catch {
99
+ return null;
100
+ }
101
+ const event = payload?.hook_event_name;
102
+ const sessionId = safeSessionId(payload?.session_id);
103
+ if (!event || !sessionId) return null;
104
+
105
+ if (event === "SessionEnd") {
106
+ removeSession(sessionId);
107
+ abandonInbox(sessionId);
108
+ releaseSessionReservations(sessionId);
109
+ return null;
110
+ }
111
+
112
+ // 编辑前检查文件预留(首次拦截、重试放行)。不更新注册表——这个 hook 每次编辑都会跑,保持最轻。
113
+ if (event === "PreToolUse") return currentOptions().editGuard ? checkReservations(payload, sessionId) : null;
114
+
115
+ const status = STATUS_BY_EVENT[event];
116
+ const known = readSession(sessionId);
117
+ // 每次都重新探测:`claude --resume` 会在新进程里沿用同一个 session id。
118
+ const pid = agentPid(provider) ?? known?.pid;
119
+ upsertSession({
120
+ sessionId,
121
+ provider,
122
+ pid,
123
+ cwd: typeof payload.cwd === "string" ? payload.cwd : undefined,
124
+ tty: processTty(pid) ?? undefined,
125
+ status,
126
+ // hook 继承宿主 CLI 的环境:`CC_BRIDGE_NAME=frontend claude` 即以 frontend 注册。
127
+ // 只在首次注册时生效,之后改名走 set_name。
128
+ preferredName: environment.CC_BRIDGE_NAME,
129
+ liveSessions: known ? [] : liveSessions()
130
+ });
131
+
132
+ if (event === "SessionStart") {
133
+ pruneReceipts();
134
+ return null;
135
+ }
136
+ if (event === "UserPromptSubmit") return injectPending(sessionId, event);
137
+ if (event === "Stop" && hasIdleSubscriptions(sessionId)) notifyIdleInBackground(sessionId);
138
+ return null;
139
+ };
140
+
141
+ export const main = () => {
142
+ try {
143
+ const output = runHook(fs.readFileSync(0, "utf8"));
144
+ if (output) process.stdout.write(JSON.stringify(output));
145
+ } catch {
146
+ // 见文件头:绝不因为 CC Bridge 的问题让对方 CLI 的 hook 失败。
147
+ }
148
+ return 0;
149
+ };
@@ -0,0 +1,288 @@
1
+ // CC Bridge 的接入与移除:hooks、MCP 注册、Codex 工具审批与 Claude 工具放行(可选)。
2
+ //
3
+ // 与 install-claude-hooks.mjs / install-codex-hooks.mjs 同一套约定:
4
+ // - 只追加带标记的条目,移除时只认自己的标记,不碰用户其他配置;
5
+ // - 配置文件先写临时文件再 rename;
6
+ // - 没装的 CLI 不写(不凭空创建 ~/.claude、~/.codex)。
7
+ // MCP 用各自官方的 `claude mcp add` / `codex mcp add` 注册,而不是手改它们的内部文件。
8
+
9
+ import { execFileSync } from "node:child_process";
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import { detectClaudeCLI, detectCodexCLI } from "../detect-cli.mjs";
15
+ import { DEFAULT_OPTIONS, normalizeOptions } from "./options.mjs";
16
+ import { resolveRealExecutable } from "./process.mjs";
17
+
18
+ export const HOOK_MARKER = "CC_BRIDGE_HOOK=";
19
+ export const MCP_NAME = "cc-bridge";
20
+ const TOML_START = "# >>> cc-bridge >>>";
21
+ const TOML_END = "# <<< cc-bridge <<<";
22
+
23
+ // 正式发布前这个功能叫过 "Agent Bus"(cc-pets bus)。启用过旧版的机器上还留着旧标记的
24
+ // hooks、旧名字的 MCP 注册和旧审批块,安装 / 卸载时一并识别清理,不留两套。
25
+ const LEGACY_HOOK_MARKERS = ["CC_PETS_BUS_HOOK="];
26
+ const LEGACY_MCP_NAMES = ["cc-pets-bus"];
27
+ const LEGACY_TOML_BLOCKS = [["# >>> cc-pets-bus >>>", "# <<< cc-pets-bus <<<"]];
28
+
29
+ const cliPath = fileURLToPath(new URL("./cli.mjs", import.meta.url));
30
+ const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
31
+
32
+ const claudeHome = () => process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
33
+ const codexHome = () => process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
34
+
35
+ // node 用绝对路径:hook 的 PATH 不一定带 nvm 之类的目录。
36
+ const bridgeCommand = (provider, subcommand) =>
37
+ `${HOOK_MARKER}${provider} ${shellQuote(process.execPath)} ${shellQuote(cliPath)} ${subcommand}`;
38
+
39
+ const isBridgeHook = (handler) =>
40
+ typeof handler?.command === "string" &&
41
+ [HOOK_MARKER, ...LEGACY_HOOK_MARKERS].some((marker) => handler.command.startsWith(marker));
42
+
43
+ const readJsonConfig = (file) => {
44
+ if (!fs.existsSync(file)) return {};
45
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
46
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
47
+ throw new Error(`${file} 不是 JSON 对象`);
48
+ }
49
+ return parsed;
50
+ };
51
+
52
+ const writeJsonConfig = (file, value) => {
53
+ const temporary = `${file}.cc-bridge.tmp`;
54
+ const mode = fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600;
55
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode });
56
+ fs.renameSync(temporary, file);
57
+ };
58
+
59
+ const stripBridgeHooks = (config) => {
60
+ if (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)) return config;
61
+ for (const [event, groups] of Object.entries(config.hooks)) {
62
+ if (!Array.isArray(groups)) continue;
63
+ const kept = groups.flatMap((group) => {
64
+ if (!group || !Array.isArray(group.hooks)) return [group];
65
+ const handlers = group.hooks.filter((handler) => !isBridgeHook(handler));
66
+ return handlers.length > 0 ? [{ ...group, hooks: handlers }] : [];
67
+ });
68
+ if (kept.length > 0) {
69
+ config.hooks[event] = kept;
70
+ } else {
71
+ delete config.hooks[event];
72
+ }
73
+ }
74
+ if (Object.keys(config.hooks).length === 0) delete config.hooks;
75
+ return config;
76
+ };
77
+
78
+ const addHook = (config, event, handler, matcher) => {
79
+ if (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)) config.hooks = {};
80
+ if (!Array.isArray(config.hooks[event])) config.hooks[event] = [];
81
+ config.hooks[event].push(matcher ? { matcher, hooks: [handler] } : { hooks: [handler] });
82
+ };
83
+
84
+ // 文件预留提醒只挂在编辑类工具上,避免每次 shell / 读文件都多跑一次 hook。
85
+ // Codex 的补丁工具名以实测为准;匹配不上时只是没有提醒,不影响其他功能。
86
+ const CLAUDE_EDIT_MATCHER = "Edit|Write|MultiEdit|NotebookEdit";
87
+ const CODEX_EDIT_MATCHER = "apply_patch|Edit|Write";
88
+
89
+ // Claude:同步 hook 维护注册表;asyncRewake watcher 负责投递(单例锁保证同时只有一个)。
90
+ // watcher 只挂 SessionStart / Stop,不挂 UserPromptSubmit:由 UserPromptSubmit 拉起的 watcher
91
+ // 在回合中途 exit 2 时,Claude Code 会显示成 "Stop hook blocking error from command
92
+ // UserPromptSubmit",像报错。Stop 拉起的 watcher 会一直活过下一个忙碌回合,中途投递照常,
93
+ // 显示为正常的 "Stop hook feedback";watcher 超时退出后,用户开口时信箱里已有的消息由同步
94
+ // hook 注入,回合中新到的消息在回合结束(Stop 重新挂上 watcher)时投递。
95
+ //
96
+ // 选项决定装哪些:关闭"自动唤醒"时不装 watcher(消息只在用户开口时带入);关闭"编辑前预留拦截"
97
+ // 时不装 PreToolUse(每次编辑少跑一次 hook)。hook / watcher 自己也会再读一次选项兜底。
98
+ export const claudeHookPlan = (options = DEFAULT_OPTIONS) => [
99
+ ...["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"].map((event) => ({
100
+ event, handler: { type: "command", command: bridgeCommand("Claude", "hook"), timeout: 10 }
101
+ })),
102
+ ...(options.editGuard ? [{
103
+ event: "PreToolUse",
104
+ matcher: CLAUDE_EDIT_MATCHER,
105
+ handler: { type: "command", command: bridgeCommand("Claude", "hook"), timeout: 10 }
106
+ }] : []),
107
+ ...(options.wake ? ["SessionStart", "Stop"].map((event) => ({
108
+ event,
109
+ handler: { type: "command", command: bridgeCommand("Claude", "watch"), asyncRewake: true, timeout: 3600 }
110
+ })) : [])
111
+ ];
112
+
113
+ export const codexHookPlan = (options = DEFAULT_OPTIONS) => [
114
+ ...["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"].map((event) => ({
115
+ event, handler: { type: "command", command: bridgeCommand("Codex", "hook"), timeout: 10 }
116
+ })),
117
+ ...(options.editGuard ? [{
118
+ event: "PreToolUse",
119
+ matcher: CODEX_EDIT_MATCHER,
120
+ handler: { type: "command", command: bridgeCommand("Codex", "hook"), timeout: 10 }
121
+ }] : [])
122
+ ];
123
+
124
+ // Claude 的工具放行写在 settings.json 的 permissions.allow 里,条目形如 mcp__cc-bridge__send_message。
125
+ // 只增删这个前缀下的条目(含旧名 cc-pets-bus),不碰用户其他的放行规则。
126
+ const MANAGED_ALLOW = new RegExp(`^mcp__(?:${[MCP_NAME, ...LEGACY_MCP_NAMES].map((name) =>
127
+ name.replace(/[-]/g, "\\-")).join("|")})__[a-z_]+$`);
128
+
129
+ const applyClaudeAllow = (config, tools) => {
130
+ const permissions = config.permissions && typeof config.permissions === "object" && !Array.isArray(config.permissions)
131
+ ? config.permissions : null;
132
+ const current = Array.isArray(permissions?.allow) ? permissions.allow : [];
133
+ const kept = current.filter((entry) => !(typeof entry === "string" && MANAGED_ALLOW.test(entry)));
134
+ const next = [...kept, ...tools.map((tool) => `mcp__${MCP_NAME}__${tool}`)];
135
+ if (next.length > 0) {
136
+ config.permissions = { ...(permissions ?? {}), allow: next };
137
+ } else if (permissions) {
138
+ delete permissions.allow;
139
+ if (Object.keys(permissions).length === 0) delete config.permissions;
140
+ }
141
+ return config;
142
+ };
143
+
144
+ const updateJsonHooks = (file, plan, claudeAllow) => {
145
+ const config = stripBridgeHooks(readJsonConfig(file));
146
+ for (const { event, handler, matcher } of plan) addHook(config, event, handler, matcher);
147
+ if (claudeAllow) applyClaudeAllow(config, claudeAllow);
148
+ writeJsonConfig(file, config);
149
+ };
150
+
151
+ const removeJsonHooks = (file, { claudeAllow = false } = {}) => {
152
+ if (!fs.existsSync(file)) return false;
153
+ const original = fs.readFileSync(file, "utf8");
154
+ const config = stripBridgeHooks(readJsonConfig(file));
155
+ if (claudeAllow) applyClaudeAllow(config, []);
156
+ const updated = `${JSON.stringify(config, null, 2)}\n`;
157
+ if (updated === original) return false;
158
+ writeJsonConfig(file, config);
159
+ return true;
160
+ };
161
+
162
+ const runQuietly = (executable, args) => {
163
+ try {
164
+ execFileSync(executable, args, { stdio: ["ignore", "pipe", "pipe"], timeout: 60_000 });
165
+ return true;
166
+ } catch {
167
+ return false;
168
+ }
169
+ };
170
+
171
+ const mcpCommand = () => ["--", process.execPath, cliPath, "mcp"];
172
+
173
+ // MCP 进程的环境会被 CLI 裁剪,PATH 里不一定找得到 codex;投递到 Codex 需要它,
174
+ // 注册时把安装时解析到的绝对路径固定下来。
175
+ const mcpEnvironment = () => {
176
+ const codex = resolveRealExecutable("codex", "CODEX_REAL_BIN");
177
+ return codex ? [`CODEX_REAL_BIN=${codex}`] : [];
178
+ };
179
+
180
+ const claudeMcpAddArgs = () => [
181
+ "mcp", "add", "--scope", "user", MCP_NAME,
182
+ ...mcpEnvironment().flatMap((pair) => ["-e", pair]),
183
+ ...mcpCommand()
184
+ ];
185
+
186
+ const codexMcpAddArgs = () => [
187
+ "mcp", "add", MCP_NAME,
188
+ ...mcpEnvironment().flatMap((pair) => ["--env", pair]),
189
+ ...mcpCommand()
190
+ ];
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // Codex 工具审批:Codex 默认每次 MCP 调用都要审批,approval_policy=never 时直接报错
194
+ // (实测)。用户选择放开时,只在 config.toml 末尾追加一段带标记的块,移除时整段删掉。
195
+
196
+ const codexApprovalBlock = (tools) => [
197
+ TOML_START,
198
+ "# 由 cc-pets bridge enable / configure 写入;cc-pets bridge disable 会移除。",
199
+ ...tools.flatMap((tool) => [
200
+ `[mcp_servers.${MCP_NAME}.tools.${tool}]`,
201
+ 'approval_mode = "approve"',
202
+ ""
203
+ ]),
204
+ TOML_END
205
+ ].join("\n");
206
+
207
+ const stripTomlBlock = (text) => [[TOML_START, TOML_END], ...LEGACY_TOML_BLOCKS].reduce(
208
+ (current, [start, end]) => current.replace(new RegExp(`\\n?${start}[\\s\\S]*?${end}\\n?`, "g"), "\n"), text)
209
+ .replace(/\n{3,}/g, "\n\n");
210
+
211
+ const setCodexApproval = (tools) => {
212
+ const file = path.join(codexHome(), "config.toml");
213
+ const original = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
214
+ let updated = stripTomlBlock(original).replace(/\s*$/, "\n");
215
+ if (tools.length > 0) updated += `\n${codexApprovalBlock(tools)}\n`;
216
+ if (updated === original) return;
217
+ const temporary = `${file}.cc-bridge.tmp`;
218
+ fs.writeFileSync(temporary, updated, { mode: fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600 });
219
+ fs.renameSync(temporary, file);
220
+ };
221
+
222
+ // ---------------------------------------------------------------------------
223
+
224
+ // registerMcp=false 用于只改选项(桌宠开关、cc-pets bridge configure):不必重跑 claude / codex mcp add。
225
+ export const install = ({ options: rawOptions = DEFAULT_OPTIONS, registerMcp = process.env.CC_BRIDGE_SKIP_MCP !== "1" } = {}) => {
226
+ const options = normalizeOptions(rawOptions);
227
+ const report = [];
228
+ if (detectClaudeCLI()) {
229
+ updateJsonHooks(path.join(claudeHome(), "settings.json"), claudeHookPlan(options), options.claudeAllow);
230
+ report.push(`Claude Code hooks 已写入 ${path.join(claudeHome(), "settings.json")}`);
231
+ report.push(options.claudeAllow.length > 0
232
+ ? `Claude Code 中以下工具免确认:${options.claudeAllow.join(", ")}`
233
+ : "Claude Code 中 cc-bridge 的工具按你的权限设置询问。");
234
+ if (registerMcp) {
235
+ const claude = resolveRealExecutable("claude", "CLAUDE_REAL_BIN");
236
+ for (const name of [MCP_NAME, ...LEGACY_MCP_NAMES]) {
237
+ runQuietly(claude || "claude", ["mcp", "remove", "--scope", "user", name]);
238
+ }
239
+ const ok = claude && runQuietly(claude, claudeMcpAddArgs());
240
+ report.push(ok
241
+ ? `Claude Code MCP 已注册:${MCP_NAME}(首次调用时 Claude 会按你的权限设置询问是否允许)`
242
+ : `Claude Code MCP 注册失败,请手动执行:claude ${claudeMcpAddArgs().map(shellQuote).join(" ")}`);
243
+ }
244
+ } else {
245
+ report.push("未检测到 Claude Code CLI,跳过。");
246
+ }
247
+
248
+ if (detectCodexCLI()) {
249
+ fs.mkdirSync(codexHome(), { recursive: true });
250
+ updateJsonHooks(path.join(codexHome(), "hooks.json"), codexHookPlan(options));
251
+ report.push(`Codex hooks 已写入 ${path.join(codexHome(), "hooks.json")}——下次启动 Codex 后请执行 /hooks 并信任 cc-pets bridge 的 hooks。`);
252
+ if (registerMcp) {
253
+ const codex = resolveRealExecutable("codex", "CODEX_REAL_BIN");
254
+ for (const name of [MCP_NAME, ...LEGACY_MCP_NAMES]) runQuietly(codex || "codex", ["mcp", "remove", name]);
255
+ const ok = codex && runQuietly(codex, codexMcpAddArgs());
256
+ report.push(ok
257
+ ? `Codex MCP 已注册:${MCP_NAME}`
258
+ : `Codex MCP 注册失败,请手动执行:codex ${codexMcpAddArgs().map(shellQuote).join(" ")}`);
259
+ }
260
+ setCodexApproval(options.codexApprove);
261
+ report.push(options.codexApprove.length > 0
262
+ ? `Codex 中以下工具免审批:${options.codexApprove.join(", ")}(需重启 Codex 会话生效)`
263
+ : "Codex 中 cc-bridge 的工具保持默认审批(approval_policy=never 时调用会失败,可用 --codex-approve 放开)。");
264
+ } else {
265
+ report.push("未检测到 Codex CLI,跳过。");
266
+ }
267
+ return report;
268
+ };
269
+
270
+ export const uninstall = ({ unregisterMcp = process.env.CC_BRIDGE_SKIP_MCP !== "1" } = {}) => {
271
+ const report = [];
272
+ if (removeJsonHooks(path.join(claudeHome(), "settings.json"), { claudeAllow: true })) {
273
+ report.push("已移除 Claude Code 中的 cc-bridge hooks 与工具放行规则。");
274
+ }
275
+ if (removeJsonHooks(path.join(codexHome(), "hooks.json"))) report.push("已移除 Codex 中的 cc-bridge hooks。");
276
+ if (fs.existsSync(path.join(codexHome(), "config.toml"))) setCodexApproval([]);
277
+ if (unregisterMcp) {
278
+ const claude = resolveRealExecutable("claude", "CLAUDE_REAL_BIN");
279
+ for (const name of [MCP_NAME, ...LEGACY_MCP_NAMES]) {
280
+ if (claude && runQuietly(claude, ["mcp", "remove", "--scope", "user", name])) report.push(`已移除 Claude Code MCP:${name}。`);
281
+ }
282
+ const codex = resolveRealExecutable("codex", "CODEX_REAL_BIN");
283
+ for (const name of [MCP_NAME, ...LEGACY_MCP_NAMES]) {
284
+ if (codex && runQuietly(codex, ["mcp", "remove", name])) report.push(`已移除 Codex MCP:${name}。`);
285
+ }
286
+ }
287
+ return report;
288
+ };