cc-pets 2.0.3 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CC_BRIDGE.md +239 -0
  2. package/CC_BRIDGE.zh-CN.md +210 -0
  3. package/CHANGELOG.md +49 -0
  4. package/CHANGELOG.zh-CN.md +49 -0
  5. package/PROVIDER_PROTOCOL.md +6 -0
  6. package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
  7. package/README.md +17 -1
  8. package/README.zh-CN.md +18 -2
  9. package/Sources/CCPets/CCPetsAppDelegate.h +17 -2
  10. package/Sources/CCPets/CCPetsAppDelegate.m +478 -56
  11. package/Sources/CCPets/CCPetsBridge.h +43 -0
  12. package/Sources/CCPets/CCPetsBridge.m +198 -0
  13. package/Sources/CCPets/CCPetsCleanup.m +3 -1
  14. package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
  15. package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
  16. package/Sources/CCPets/CCPetsEvents.m +1 -1
  17. package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
  18. package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
  19. package/Sources/CCPets/CCPetsGlassView.h +31 -0
  20. package/Sources/CCPets/CCPetsGlassView.m +246 -0
  21. package/Sources/CCPets/CCPetsPaths.h +7 -0
  22. package/Sources/CCPets/CCPetsPaths.m +14 -0
  23. package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
  24. package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
  25. package/Sources/CCPets/CCPetsUsage.h +2 -0
  26. package/Sources/CCPets/CCPetsUsage.m +69 -18
  27. package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
  28. package/Sources/CCPets/MenuChoiceRow.h +19 -0
  29. package/Sources/CCPets/MenuChoiceRow.m +96 -0
  30. package/Sources/CCPets/MenuHintView.h +15 -0
  31. package/Sources/CCPets/MenuHintView.m +128 -0
  32. package/Sources/CCPets/PetView.m +143 -3
  33. package/Sources/CCPets/QuotaDashboardView.h +3 -4
  34. package/Sources/CCPets/QuotaDashboardView.m +222 -143
  35. package/Sources/CCPets/main.m +16 -0
  36. package/bin/cc-pets +38 -1
  37. package/bin/codex-with-pet +2 -0
  38. package/package.json +3 -1
  39. package/scripts/bridge/cli.mjs +229 -0
  40. package/scripts/bridge/core.mjs +227 -0
  41. package/scripts/bridge/hook.mjs +149 -0
  42. package/scripts/bridge/install.mjs +288 -0
  43. package/scripts/bridge/mcp-server.mjs +300 -0
  44. package/scripts/bridge/options.mjs +86 -0
  45. package/scripts/bridge/process.mjs +129 -0
  46. package/scripts/bridge/reservations.mjs +247 -0
  47. package/scripts/bridge/store.mjs +432 -0
  48. package/scripts/bridge/watch.mjs +69 -0
  49. package/scripts/install-shell-integration.sh +3 -0
  50. package/scripts/uninstall-integrations.mjs +10 -0
@@ -0,0 +1,432 @@
1
+ // CC Bridge 的存储层:会话注册表、信箱、回执、订阅、锁。
2
+ //
3
+ // 全部是"一条记录一个文件",状态流转靠同一文件系统内的 rename 完成——rename 是原子的,
4
+ // 多个终端的 hook / watcher / MCP 进程同时抢同一条消息时,只有一个能 rename 成功,
5
+ // 其余拿到 ENOENT 直接跳过,不需要任何守护进程或数据库锁。
6
+ //
7
+ // 目录放在 CC_PETS_STATE_DIR(默认 $TMPDIR)下,与桌宠事件流同级:会话本身活不过重启,
8
+ // 注册表和未投递的消息也没有跨重启保留的意义。启用开关则放在 ~/.cc-pets 里持久保存。
9
+
10
+ import { execFileSync } from "node:child_process";
11
+ import crypto from "node:crypto";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ export const MESSAGE_BODY_LIMIT = 16 * 1024;
17
+ export const MESSAGE_TTL_MS = 24 * 60 * 60 * 1000;
18
+ // 同一对会话 10 分钟内来回超过这个数,基本可以断定是两个 Agent 在互相自动回复。
19
+ export const PAIR_LIMIT_WINDOW_MS = 10 * 60 * 1000;
20
+ export const PAIR_LIMIT_COUNT = 20;
21
+ export const SENDER_LIMIT_COUNT = 40;
22
+
23
+ const uid = () => (typeof process.getuid === "function" ? process.getuid() : 0);
24
+
25
+ // 不能直接用 os.tmpdir():它只认 TMPDIR 环境变量,而 Codex 拉起 MCP server 时会裁剪环境,
26
+ // 拿不到 TMPDIR 就退回 /tmp,与 hook 写入的目录分家。DARWIN_USER_TEMP_DIR 按用户固定、
27
+ // 不依赖环境变量,也正是桌宠原生端 NSTemporaryDirectory() 返回的目录。
28
+ let cachedUserTempDirectory;
29
+ const userTempDirectory = () => {
30
+ if (cachedUserTempDirectory === undefined) {
31
+ cachedUserTempDirectory = null;
32
+ if (process.platform === "darwin") {
33
+ try {
34
+ const value = execFileSync("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"],
35
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
36
+ if (value) cachedUserTempDirectory = value;
37
+ } catch {
38
+ // 退回 os.tmpdir()。
39
+ }
40
+ }
41
+ }
42
+ return cachedUserTempDirectory || os.tmpdir();
43
+ };
44
+
45
+ export const bridgeDirectory = () => path.join(
46
+ process.env.CC_PETS_STATE_DIR || userTempDirectory(), `cc-bridge-${uid()}`);
47
+
48
+ export const bridgeHomeDirectory = () =>
49
+ process.env.CC_PETS_HOME || path.join(os.homedir(), ".cc-pets");
50
+
51
+ const enabledFlagPath = () => path.join(bridgeHomeDirectory(), "bridge-enabled");
52
+
53
+ export const isBridgeEnabled = () => fs.existsSync(enabledFlagPath());
54
+
55
+ // 桌宠(~/Applications 下的 App)不知道 cc-pets 包装在哪,菜单开关要靠这个文件找到 node 与 CLI。
56
+ // 每次安装(bridge refresh)、enable、configure 都会重写,包路径随升级变化也能跟上。
57
+ export const writeCliLocator = (cliPath) => {
58
+ fs.mkdirSync(bridgeHomeDirectory(), { recursive: true, mode: 0o700 });
59
+ const file = path.join(bridgeHomeDirectory(), "bridge-cli.json");
60
+ const temporary = `${file}.${process.pid}.tmp`;
61
+ fs.writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, node: process.execPath, cli: cliPath }, null, 2)}\n`,
62
+ { mode: 0o600 });
63
+ fs.renameSync(temporary, file);
64
+ };
65
+
66
+ // 正式发布前叫过 "Agent Bus",开关文件是 bus-enabled。迁移成新名字并保留当时的选项,
67
+ // 这样 refresh / 卸载能认出"用户开启过",把旧集成清掉后按原选项重写。
68
+ export const migrateLegacyFlag = () => {
69
+ const legacy = path.join(bridgeHomeDirectory(), "bus-enabled");
70
+ if (!fs.existsSync(legacy)) return false;
71
+ if (fs.existsSync(enabledFlagPath())) {
72
+ fs.rmSync(legacy, { force: true });
73
+ } else {
74
+ fs.renameSync(legacy, enabledFlagPath());
75
+ }
76
+ return true;
77
+ };
78
+
79
+ // 开关文件同时保存 enable 时的选项:重装 / 升级后包路径会变,安装流程要用同样的选项
80
+ // 重写一遍 hooks 与 MCP 注册(见 cli.mjs 的 refresh)。
81
+ export const readBridgeOptions = () => {
82
+ try {
83
+ const parsed = JSON.parse(fs.readFileSync(enabledFlagPath(), "utf8"));
84
+ return parsed && typeof parsed === "object" ? parsed : {};
85
+ } catch {
86
+ return {};
87
+ }
88
+ };
89
+
90
+ export const setBridgeEnabled = (enabled, options = {}) => {
91
+ if (enabled) {
92
+ fs.mkdirSync(bridgeHomeDirectory(), { recursive: true, mode: 0o700 });
93
+ fs.writeFileSync(enabledFlagPath(),
94
+ `${JSON.stringify({ ...options, enabledAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
95
+ } else {
96
+ fs.rmSync(enabledFlagPath(), { force: true });
97
+ }
98
+ };
99
+
100
+ // 目录一律 0700:信箱里是消息正文,同机其他用户不能读,也不能往里塞"任务"。
101
+ // 已存在的目录也要校正权限并确认归属,防止有人提前在共享 /tmp 里抢建同名目录。
102
+ const ensureDirectory = (directory) => {
103
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
104
+ const status = fs.lstatSync(directory);
105
+ if (!status.isDirectory() || status.isSymbolicLink()) {
106
+ throw new Error(`${directory} 不是普通目录`);
107
+ }
108
+ if (status.uid !== uid()) throw new Error(`${directory} 不属于当前用户`);
109
+ if ((status.mode & 0o077) !== 0) fs.chmodSync(directory, 0o700);
110
+ return directory;
111
+ };
112
+
113
+ export const bridgePath = (...parts) => {
114
+ const root = ensureDirectory(bridgeDirectory());
115
+ if (parts.length === 0) return root;
116
+ const directory = path.join(root, ...parts.slice(0, -1));
117
+ if (parts.length > 1) ensureDirectory(directory);
118
+ return path.join(directory, parts[parts.length - 1]);
119
+ };
120
+
121
+ export const bridgeSubdirectory = (...parts) => ensureDirectory(path.join(bridgePath(), ...parts));
122
+
123
+ // session id 会拼进文件路径,只放行 UUID 一类的安全字符,杜绝 ../ 之类的路径穿越。
124
+ export const safeSessionId = (value) =>
125
+ typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value) && !/^\.+$/.test(value)
126
+ ? value : null;
127
+
128
+ // 先写同目录临时文件再 rename:读取端永远看不到写了一半的 JSON。
129
+ export const writeJsonAtomic = (file, value) => {
130
+ const temporary = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
131
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
132
+ fs.renameSync(temporary, file);
133
+ };
134
+
135
+ export const readJson = (file) => {
136
+ try {
137
+ return JSON.parse(fs.readFileSync(file, "utf8"));
138
+ } catch {
139
+ return null;
140
+ }
141
+ };
142
+
143
+ const listJson = (directory) => {
144
+ let entries;
145
+ try {
146
+ entries = fs.readdirSync(directory);
147
+ } catch {
148
+ return [];
149
+ }
150
+ return entries.filter((name) => name.endsWith(".json")).sort();
151
+ };
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // 会话注册表
155
+
156
+ export const sessionRef = (sessionId) =>
157
+ crypto.createHash("sha1").update(sessionId).digest("hex").slice(0, 6);
158
+
159
+ const sessionFile = (sessionId) => path.join(bridgeSubdirectory("sessions"), `${sessionId}.json`);
160
+
161
+ export const readSession = (sessionId) => {
162
+ const safe = safeSessionId(sessionId);
163
+ return safe ? readJson(sessionFile(safe)) : null;
164
+ };
165
+
166
+ export const listSessions = () => {
167
+ const directory = bridgeSubdirectory("sessions");
168
+ return listJson(directory).map((name) => readJson(path.join(directory, name))).filter(Boolean);
169
+ };
170
+
171
+ export const removeSession = (sessionId) => {
172
+ const safe = safeSessionId(sessionId);
173
+ if (safe) fs.rmSync(sessionFile(safe), { force: true });
174
+ };
175
+
176
+ const projectSlug = (cwd) => {
177
+ const base = path.basename(cwd || "") || "session";
178
+ const slug = base.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
179
+ return (slug || "session").slice(0, 32);
180
+ };
181
+
182
+ // 名字是给 Agent 和人看的地址:<provider>-<项目目录名>-<n>。n 取同前缀下在线会话
183
+ // 未占用的最小正整数,会话结束后编号可以被复用;ref 由 session id 派生,永不变化,
184
+ // 用于重名时消歧。
185
+ const allocateName = (provider, cwd, sessionId, liveSessions) => {
186
+ const prefix = `${provider.toLowerCase()}-${projectSlug(cwd)}`;
187
+ const taken = new Set(liveSessions
188
+ .filter((entry) => entry.session !== sessionId)
189
+ .map((entry) => entry.name));
190
+ for (let index = 1; ; index += 1) {
191
+ const candidate = `${prefix}-${index}`;
192
+ if (!taken.has(candidate)) return candidate;
193
+ }
194
+ };
195
+
196
+ // 自定义名字:启动时用 CC_BRIDGE_NAME 指定,或会话里调用 set_name 修改。
197
+ // 只允许小写字母、数字和 . _ -,首字符必须是字母或数字,最长 40 个字符——名字会出现在消息头
198
+ // 和 Agent 的工具参数里,不能带空格、方括号(与 "名字 [ref]" 语法冲突)或控制字符。
199
+ export const normalizeSessionName = (value) => {
200
+ const name = String(value ?? "").trim().toLowerCase();
201
+ return /^[a-z0-9][a-z0-9._-]{0,39}$/.test(name) ? name : null;
202
+ };
203
+
204
+ const nameTakenBy = (name, sessionId, liveSessions) =>
205
+ liveSessions.find((entry) => entry.session !== sessionId && entry.name === name) || null;
206
+
207
+ // 启动时指定的名字被占用就追加序号(frontend → frontend-2),不让会话因此注册失败。
208
+ const allocateCustomName = (name, sessionId, liveSessions) => {
209
+ if (!nameTakenBy(name, sessionId, liveSessions)) return name;
210
+ for (let index = 2; ; index += 1) {
211
+ const candidate = `${name}-${index}`.slice(0, 40);
212
+ if (!nameTakenBy(candidate, sessionId, liveSessions)) return candidate;
213
+ }
214
+ };
215
+
216
+ // liveSessions 由调用方传入(需要进程探测,放在 process.mjs 里做),避免存储层依赖 ps。
217
+ export const upsertSession = ({
218
+ sessionId, provider, pid, cwd, tty, status, preferredName, liveSessions = []
219
+ }) => {
220
+ const safe = safeSessionId(sessionId);
221
+ if (!safe) return null;
222
+ const now = Date.now();
223
+ const existing = readSession(safe);
224
+ const record = existing || {
225
+ session: safe,
226
+ provider,
227
+ ref: sessionRef(safe),
228
+ startedAt: now
229
+ };
230
+ record.provider = provider || record.provider;
231
+ if (Number.isInteger(pid) && pid > 1) record.pid = pid;
232
+ if (cwd) record.cwd = cwd;
233
+ if (tty) record.tty = tty;
234
+ if (!record.name) {
235
+ const custom = normalizeSessionName(preferredName);
236
+ record.name = custom
237
+ ? allocateCustomName(custom, safe, liveSessions)
238
+ : allocateName(record.provider, record.cwd, safe, liveSessions);
239
+ }
240
+ if (status) record.status = status;
241
+ record.updatedAt = now;
242
+ writeJsonAtomic(sessionFile(safe), record);
243
+ return record;
244
+ };
245
+
246
+ // 会话内改名:名字被其他在线会话占用时直接报错,由调用方换一个,不自动追加序号。
247
+ export const renameSession = (sessionId, requestedName, liveSessions) => {
248
+ const record = readSession(sessionId);
249
+ if (!record) return { error: "当前会话尚未注册。" };
250
+ const name = normalizeSessionName(requestedName);
251
+ if (!name) {
252
+ return { error: "名字只能包含小写字母、数字和 . _ -,以字母或数字开头,最长 40 个字符。" };
253
+ }
254
+ const holder = nameTakenBy(name, record.session, liveSessions);
255
+ if (holder) return { error: `名字 ${name} 已被 ${holder.name} [${holder.ref}] 使用,请换一个。` };
256
+ const previous = record.name;
257
+ record.name = name;
258
+ record.updatedAt = Date.now();
259
+ writeJsonAtomic(sessionFile(record.session), record);
260
+ return { session: record, previous };
261
+ };
262
+
263
+ // ---------------------------------------------------------------------------
264
+ // 消息
265
+
266
+ export const newMessageId = () =>
267
+ `m${Date.now().toString(36)}${crypto.randomBytes(5).toString("hex")}`;
268
+
269
+ const inboxDirectory = (sessionId) => bridgeSubdirectory("inbox", sessionId);
270
+ const claimedDirectory = (sessionId) => bridgeSubdirectory("claimed", sessionId);
271
+ const receiptFile = (messageId) => path.join(bridgeSubdirectory("sent"), `${messageId}.json`);
272
+
273
+ export const readReceipt = (messageId) =>
274
+ /^[a-z0-9]+$/.test(messageId || "") ? readJson(receiptFile(messageId)) : null;
275
+
276
+ export const writeReceipt = (message) => writeJsonAtomic(receiptFile(message.id), message);
277
+
278
+ export const updateReceipt = (messageId, patch) => {
279
+ const current = readReceipt(messageId);
280
+ if (!current) return null;
281
+ const next = { ...current, ...patch, updatedAt: Date.now() };
282
+ writeReceipt(next);
283
+ return next;
284
+ };
285
+
286
+ export const listReceipts = () => {
287
+ const directory = bridgeSubdirectory("sent");
288
+ return listJson(directory).map((name) => readJson(path.join(directory, name))).filter(Boolean);
289
+ };
290
+
291
+ // 发送前的配额检查。返回 null 表示放行,否则返回拒绝原因。
292
+ export const checkSendLimits = (fromSession, toSession, now = Date.now()) => {
293
+ const recent = listReceipts().filter((entry) => now - (entry.createdAt || 0) < PAIR_LIMIT_WINDOW_MS);
294
+ const pair = recent.filter((entry) =>
295
+ (entry.from?.session === fromSession && entry.to?.session === toSession) ||
296
+ (entry.from?.session === toSession && entry.to?.session === fromSession));
297
+ if (pair.length >= PAIR_LIMIT_COUNT) {
298
+ return `这两个会话 10 分钟内已往来 ${pair.length} 条消息,疑似互相自动回复形成循环,已暂停发送。请让用户确认后再继续。`;
299
+ }
300
+ const sent = recent.filter((entry) => entry.from?.session === fromSession);
301
+ if (sent.length >= SENDER_LIMIT_COUNT) {
302
+ return `当前会话 10 分钟内已发送 ${sent.length} 条消息,超过上限,已暂停发送。`;
303
+ }
304
+ return null;
305
+ };
306
+
307
+ export const enqueueInbox = (message) => {
308
+ const target = safeSessionId(message.to?.session);
309
+ if (!target) throw new Error("目标会话 id 无效");
310
+ writeJsonAtomic(path.join(inboxDirectory(target), `${message.id}.json`), message);
311
+ };
312
+
313
+ // 认领:inbox → claimed。rename 失败(被别的进程抢先认领)就跳过。
314
+ // 过期消息顺手标记 expired 并丢弃,不再投递。
315
+ export const claimInbox = (sessionId, now = Date.now()) => {
316
+ const safe = safeSessionId(sessionId);
317
+ if (!safe) return [];
318
+ const inbox = inboxDirectory(safe);
319
+ const claimed = claimedDirectory(safe);
320
+ const messages = [];
321
+ for (const name of listJson(inbox)) {
322
+ const source = path.join(inbox, name);
323
+ const destination = path.join(claimed, name);
324
+ try {
325
+ fs.renameSync(source, destination);
326
+ } catch {
327
+ continue;
328
+ }
329
+ const message = readJson(destination);
330
+ fs.rmSync(destination, { force: true });
331
+ if (!message) continue;
332
+ if (now - (message.createdAt || 0) > MESSAGE_TTL_MS) {
333
+ updateReceipt(message.id, { status: "expired" });
334
+ continue;
335
+ }
336
+ messages.push(message);
337
+ }
338
+ return messages;
339
+ };
340
+
341
+ export const pendingCount = (sessionId) => {
342
+ const safe = safeSessionId(sessionId);
343
+ return safe ? listJson(inboxDirectory(safe)).length : 0;
344
+ };
345
+
346
+ // 会话结束:信箱里还没投出去的消息标记为 undeliverable,回执里能看到。
347
+ export const abandonInbox = (sessionId) => {
348
+ const safe = safeSessionId(sessionId);
349
+ if (!safe) return;
350
+ const inbox = inboxDirectory(safe);
351
+ for (const name of listJson(inbox)) {
352
+ const file = path.join(inbox, name);
353
+ const message = readJson(file);
354
+ fs.rmSync(file, { force: true });
355
+ if (message) updateReceipt(message.id, { status: "undeliverable", reason: "目标会话已结束" });
356
+ }
357
+ };
358
+
359
+ // 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。
360
+ export const pruneReceipts = (now = Date.now()) => {
361
+ const directory = bridgeSubdirectory("sent");
362
+ for (const name of listJson(directory)) {
363
+ const file = path.join(directory, name);
364
+ const receipt = readJson(file);
365
+ if (!receipt || now - (receipt.createdAt || 0) > MESSAGE_TTL_MS * 2) fs.rmSync(file, { force: true });
366
+ }
367
+ };
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // 空闲订阅:subscriptions/<target>/<subscriber>.json,一次性。
371
+
372
+ export const addIdleSubscription = (targetSession, subscriberSession) => {
373
+ const target = safeSessionId(targetSession);
374
+ const subscriber = safeSessionId(subscriberSession);
375
+ if (!target || !subscriber) return;
376
+ writeJsonAtomic(path.join(bridgeSubdirectory("subscriptions", target), `${subscriber}.json`),
377
+ { subscriber, createdAt: Date.now() });
378
+ };
379
+
380
+ export const hasIdleSubscriptions = (targetSession) => {
381
+ const target = safeSessionId(targetSession);
382
+ return target ? listJson(path.join(bridgeDirectory(), "subscriptions", target)).length > 0 : false;
383
+ };
384
+
385
+ export const takeIdleSubscriptions = (targetSession) => {
386
+ const target = safeSessionId(targetSession);
387
+ if (!target) return [];
388
+ const directory = bridgeSubdirectory("subscriptions", target);
389
+ const subscribers = [];
390
+ for (const name of listJson(directory)) {
391
+ const file = path.join(directory, name);
392
+ const claimed = `${file}.taken`;
393
+ try {
394
+ fs.renameSync(file, claimed);
395
+ } catch {
396
+ continue;
397
+ }
398
+ const entry = readJson(claimed);
399
+ fs.rmSync(claimed, { force: true });
400
+ if (entry?.subscriber) subscribers.push(entry.subscriber);
401
+ }
402
+ return subscribers;
403
+ };
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // 锁:O_EXCL 创建,内容是持有者 pid。持有者已死的锁视为陈旧,可以抢占。
407
+
408
+ export const acquireLock = (name, isHolderAlive) => {
409
+ const file = path.join(bridgeSubdirectory("locks"), `${name}.pid`);
410
+ for (let attempt = 0; attempt < 2; attempt += 1) {
411
+ try {
412
+ const descriptor = fs.openSync(file, "wx", 0o600);
413
+ fs.writeSync(descriptor, String(process.pid));
414
+ fs.closeSync(descriptor);
415
+ return () => {
416
+ const holder = Number.parseInt(fs.readFileSync(file, "utf8"), 10);
417
+ if (holder === process.pid) fs.rmSync(file, { force: true });
418
+ };
419
+ } catch (error) {
420
+ if (error.code !== "EEXIST") throw error;
421
+ let holder = 0;
422
+ try {
423
+ holder = Number.parseInt(fs.readFileSync(file, "utf8"), 10);
424
+ } catch {
425
+ // 锁文件刚被释放,下一轮重试。
426
+ }
427
+ if (holder > 0 && isHolderAlive(holder)) return null;
428
+ fs.rmSync(file, { force: true });
429
+ }
430
+ }
431
+ return null;
432
+ };
@@ -0,0 +1,69 @@
1
+ // Claude 端的投递者:以 asyncRewake hook 运行,等信箱来消息后 exit 2 唤醒会话。
2
+ //
3
+ // 实测(Claude Code 2.1.281):
4
+ // - asyncRewake hook 以 exit 2 退出时,stderr 作为系统提醒进入会话;会话空闲会被唤醒,
5
+ // 忙碌则注入当前回合;
6
+ // - hook 的 timeout 会被强制执行,所以 watcher 在超时前主动退出,下一次 SessionStart /
7
+ // UserPromptSubmit / Stop 事件再重新挂上;
8
+ // - 会话退出时 hook 子进程会被清理。
9
+ //
10
+ // 每个会话只保留一个 watcher(锁文件),否则多个 watcher 会抢同一个信箱、重复唤醒。
11
+
12
+ import fs from "node:fs";
13
+ import { formatEnvelope } from "./core.mjs";
14
+ import { currentOptions } from "./options.mjs";
15
+ import { isProcessAlive } from "./process.mjs";
16
+ import { acquireLock, claimInbox, isBridgeEnabled, safeSessionId, updateReceipt } from "./store.mjs";
17
+
18
+ // 安装时 hook 的 timeout 是 3600 秒,这里留 5 分钟余量主动退出,保证锁由自己释放。
19
+ const DEFAULT_WATCH_SECONDS = 3300;
20
+ const DEFAULT_POLL_MS = 1000;
21
+
22
+ const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
23
+
24
+ export const runWatch = async (rawInput, environment = process.env) => {
25
+ // 关闭"自动唤醒"后 watcher 本不会被安装;配置还没刷新到对方 CLI 时在这里兜底。
26
+ if (!isBridgeEnabled() || !currentOptions().wake) return 0;
27
+ let payload;
28
+ try {
29
+ payload = JSON.parse(rawInput);
30
+ } catch {
31
+ return 0;
32
+ }
33
+ const sessionId = safeSessionId(payload?.session_id);
34
+ if (!sessionId) return 0;
35
+
36
+ const release = acquireLock(`watch-${sessionId}`, isProcessAlive);
37
+ if (!release) return 0;
38
+
39
+ const seconds = Number(environment.CC_BRIDGE_WATCH_SECONDS) || DEFAULT_WATCH_SECONDS;
40
+ const pollMs = Number(environment.CC_BRIDGE_POLL_MS) || DEFAULT_POLL_MS;
41
+ const deadline = Date.now() + seconds * 1000;
42
+ const parent = process.ppid;
43
+ try {
44
+ while (Date.now() < deadline) {
45
+ // 宿主会话已经没了(被 kill -9 等,没来得及清理子进程)就别再占着锁。
46
+ if (!isProcessAlive(parent)) return 0;
47
+ const messages = claimInbox(sessionId);
48
+ if (messages.length > 0) {
49
+ for (const message of messages) {
50
+ updateReceipt(message.id, { status: "delivered", transport: { kind: "claude-rewake" } });
51
+ }
52
+ process.stderr.write(`${messages.map(formatEnvelope).join("\n\n")}\n`);
53
+ return 2;
54
+ }
55
+ await sleep(pollMs);
56
+ }
57
+ return 0;
58
+ } finally {
59
+ release();
60
+ }
61
+ };
62
+
63
+ export const main = async () => {
64
+ try {
65
+ return await runWatch(fs.readFileSync(0, "utf8"));
66
+ } catch {
67
+ return 0;
68
+ }
69
+ };
@@ -27,6 +27,9 @@ export PATH="${NODE_EXECUTABLE:h}:${PATH:-/usr/bin:/bin:/usr/sbin:/sbin}"
27
27
  "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/install-claude-hooks.mjs" \
28
28
  "${PROJECT_DIR}/.build/release/cc-pets"
29
29
  "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/configure-updater.mjs"
30
+ # CC Bridge 默认关闭;用户开启过的话,包路径可能随升级变化,按原选项重写一遍集成。
31
+ "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/bridge/cli.mjs" refresh || \
32
+ print -u2 "CC Bridge 集成刷新失败,可稍后执行 cc-pets bridge enable 重试。"
30
33
 
31
34
  PET_APP="${PROJECT_DIR}/.build/release/CC Pets.app"
32
35
  PET_APP_EXECUTABLE="${PET_APP}/Contents/MacOS/cc-pets"
@@ -212,6 +212,16 @@ if (!preparingInstall && fs.existsSync(shimDirectory)) {
212
212
  if (fs.readdirSync(shimDirectory).length === 0) fs.rmdirSync(shimDirectory);
213
213
  }
214
214
 
215
+ // CC Bridge 只在真正卸载时移除;重装时由 install-shell-integration.sh 的 bridge refresh 接管。
216
+ // MCP 注册只在确实开启过时才去调用 claude / codex 注销,避免卸载时无谓地拉起它们的 CLI。
217
+ if (!preparingInstall) {
218
+ const bridge = await import("./bridge/install.mjs");
219
+ const bridgeStore = await import("./bridge/store.mjs");
220
+ bridgeStore.migrateLegacyFlag();
221
+ for (const line of bridge.uninstall({ unregisterMcp: bridgeStore.isBridgeEnabled() })) console.log(line);
222
+ bridgeStore.setBridgeEnabled(false);
223
+ }
224
+
215
225
  const action = preparingInstall ? "已迁移" : "已移除";
216
226
  if (codexChanged) console.log(`${action} ${codexHooksPath} 中的 CC Pets Hooks。`);
217
227
  if (claudeChanged) console.log(`${action} ${claudeSettingsPath} 中的 CC Pets Hooks,并恢复原 status line。`);