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.
- package/CC_BRIDGE.md +239 -0
- package/CC_BRIDGE.zh-CN.md +210 -0
- package/CHANGELOG.md +39 -0
- package/CHANGELOG.zh-CN.md +39 -0
- package/PROVIDER_PROTOCOL.md +6 -0
- package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
- package/README.md +26 -0
- package/README.zh-CN.md +25 -2
- package/Resources/Info.plist +2 -0
- package/Sources/CCPets/CCPetsAppDelegate.h +25 -0
- package/Sources/CCPets/CCPetsAppDelegate.m +751 -29
- package/Sources/CCPets/CCPetsBridge.h +43 -0
- package/Sources/CCPets/CCPetsBridge.m +198 -0
- package/Sources/CCPets/CCPetsEvents.m +7 -2
- package/Sources/CCPets/CCPetsPaths.h +4 -0
- package/Sources/CCPets/CCPetsPaths.m +6 -0
- package/Sources/CCPets/CCPetsQuotaHistory.m +9 -2
- package/Sources/CCPets/CCPetsTerminalFocus.h +11 -0
- package/Sources/CCPets/CCPetsTerminalFocus.m +150 -0
- package/Sources/CCPets/PetView.m +86 -1
- package/Sources/CCPets/QuotaDashboardView.m +17 -4
- package/Sources/CCPets/main.m +5 -0
- package/bin/cc-pets +5 -0
- package/bin/claude-with-pet +8 -2
- package/bin/codex-with-pet +8 -3
- package/package.json +3 -1
- package/scripts/bridge/cli.mjs +229 -0
- package/scripts/bridge/core.mjs +227 -0
- package/scripts/bridge/hook.mjs +149 -0
- package/scripts/bridge/install.mjs +288 -0
- package/scripts/bridge/mcp-server.mjs +300 -0
- package/scripts/bridge/options.mjs +86 -0
- package/scripts/bridge/process.mjs +129 -0
- package/scripts/bridge/reservations.mjs +247 -0
- package/scripts/bridge/store.mjs +432 -0
- package/scripts/bridge/watch.mjs +69 -0
- package/scripts/install-shell-integration.sh +3 -0
- package/scripts/uninstall-integrations.mjs +10 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// 文件预留:多个 Agent 在同一个仓库里工作时,先声明"我要改哪些文件",避免互相覆盖。
|
|
2
|
+
//
|
|
3
|
+
// 预留是建议性的,不锁文件。其他会话第一次编辑被预留的文件时,PreToolUse hook 会把这次编辑
|
|
4
|
+
// 拦下一次并说明原因;重试同一操作即放行,之后这处预留不再拦它("首次拦截、重试放行")。
|
|
5
|
+
// 只注入提醒不够:实测 Codex 的 additionalContext 在工具调用已经发出之后才到达,拦不住这次
|
|
6
|
+
// 编辑,模型也常常忽略。只记录路径模式和原因,不记录文件内容。
|
|
7
|
+
//
|
|
8
|
+
// 作用域是仓库根目录(git rev-parse --show-toplevel):不同仓库、同一仓库的不同 worktree
|
|
9
|
+
// 各自独立——它们是不同的工作副本,物理上不会互相覆盖。
|
|
10
|
+
|
|
11
|
+
import { execFileSync } from "node:child_process";
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { describeSession, liveSessions } from "./core.mjs";
|
|
16
|
+
import { bridgeSubdirectory, readJson, writeJsonAtomic } from "./store.mjs";
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_TTL_MINUTES = 30;
|
|
19
|
+
export const MAX_TTL_MINUTES = 8 * 60;
|
|
20
|
+
const MAX_PATTERNS = 50;
|
|
21
|
+
const MAX_PATTERN_LENGTH = 300;
|
|
22
|
+
const MAX_REASON_LENGTH = 200;
|
|
23
|
+
|
|
24
|
+
const GLOB_CHARACTERS = /[*?[\]{}]/;
|
|
25
|
+
|
|
26
|
+
export const repoRoot = (directory) => {
|
|
27
|
+
if (!directory) return null;
|
|
28
|
+
try {
|
|
29
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"],
|
|
30
|
+
{ cwd: directory, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || directory;
|
|
31
|
+
} catch {
|
|
32
|
+
return directory;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// 把调用方给的路径(绝对、相对、glob 均可)规范成"相对仓库根、以 / 分隔"的模式。
|
|
37
|
+
// 越出仓库根的路径拒绝,防止预留变成对整个磁盘的声明。
|
|
38
|
+
export const normalizePattern = (root, baseDirectory, raw) => {
|
|
39
|
+
const text = String(raw ?? "").trim();
|
|
40
|
+
if (!text || text.length > MAX_PATTERN_LENGTH) return null;
|
|
41
|
+
const absolute = path.isAbsolute(text) ? path.normalize(text) : path.normalize(path.join(baseDirectory, text));
|
|
42
|
+
const relative = path.relative(root, absolute);
|
|
43
|
+
if (relative === "" ) return "**";
|
|
44
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
|
45
|
+
return relative.split(path.sep).join("/").replace(/\/+$/, "");
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const escapeRegExp = (text) => text.replace(/[.+^${}()|\\]/g, "\\$&");
|
|
49
|
+
|
|
50
|
+
// 支持 **、*、?;不带通配符的模式视为"这个文件,或这个目录下的一切"。
|
|
51
|
+
export const patternToRegExp = (pattern) => {
|
|
52
|
+
if (!GLOB_CHARACTERS.test(pattern)) {
|
|
53
|
+
return new RegExp(`^${escapeRegExp(pattern)}(?:/.*)?$`);
|
|
54
|
+
}
|
|
55
|
+
let source = "";
|
|
56
|
+
for (let index = 0; index < pattern.length; index += 1) {
|
|
57
|
+
const character = pattern[index];
|
|
58
|
+
if (character === "*" && pattern[index + 1] === "*") {
|
|
59
|
+
// "**/" 可以匹配零层目录:src/**/a.ts 也匹配 src/a.ts。
|
|
60
|
+
if (pattern[index + 2] === "/") {
|
|
61
|
+
source += "(?:.*/)?";
|
|
62
|
+
index += 2;
|
|
63
|
+
} else {
|
|
64
|
+
source += ".*";
|
|
65
|
+
index += 1;
|
|
66
|
+
}
|
|
67
|
+
} else if (character === "*") {
|
|
68
|
+
source += "[^/]*";
|
|
69
|
+
} else if (character === "?") {
|
|
70
|
+
source += "[^/]";
|
|
71
|
+
} else if (character === "[" || character === "]" || character === "{" || character === "}") {
|
|
72
|
+
source += `\\${character}`;
|
|
73
|
+
} else {
|
|
74
|
+
source += escapeRegExp(character);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return new RegExp(`^${source}$`);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const staticPrefix = (pattern) => {
|
|
81
|
+
const index = pattern.search(GLOB_CHARACTERS);
|
|
82
|
+
if (index < 0) return pattern;
|
|
83
|
+
const head = pattern.slice(0, index);
|
|
84
|
+
return head.slice(0, head.lastIndexOf("/") + 1);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// 两个模式是否可能指向同一个文件。有一方是具体路径时精确匹配;两个都是 glob 时,
|
|
88
|
+
// 只比较静态目录前缀——宁可多报(src/**/*.ts 与 src/api/* 视为重叠),不能漏报。
|
|
89
|
+
export const patternsOverlap = (left, right) => {
|
|
90
|
+
const leftGlob = GLOB_CHARACTERS.test(left);
|
|
91
|
+
const rightGlob = GLOB_CHARACTERS.test(right);
|
|
92
|
+
if (!leftGlob || !rightGlob) {
|
|
93
|
+
return patternToRegExp(left).test(right) || patternToRegExp(right).test(left);
|
|
94
|
+
}
|
|
95
|
+
const leftPrefix = staticPrefix(left);
|
|
96
|
+
const rightPrefix = staticPrefix(right);
|
|
97
|
+
return leftPrefix.startsWith(rightPrefix) || rightPrefix.startsWith(leftPrefix);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// 存储:一条预留 = 一个 (会话, 仓库, 模式),id 由三者派生,重复预留即续期。
|
|
102
|
+
|
|
103
|
+
const reservationDirectory = () => bridgeSubdirectory("reservations");
|
|
104
|
+
|
|
105
|
+
const reservationId = (session, root, pattern) =>
|
|
106
|
+
`r${crypto.createHash("sha1").update(`${session}\0${root}\0${pattern}`).digest("hex").slice(0, 16)}`;
|
|
107
|
+
|
|
108
|
+
const listAll = () => {
|
|
109
|
+
const directory = reservationDirectory();
|
|
110
|
+
let names;
|
|
111
|
+
try {
|
|
112
|
+
names = fs.readdirSync(directory);
|
|
113
|
+
} catch {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
return names.filter((name) => name.endsWith(".json"))
|
|
117
|
+
.map((name) => readJson(path.join(directory, name))).filter(Boolean);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const removeReservation = (id) => fs.rmSync(path.join(reservationDirectory(), `${id}.json`), { force: true });
|
|
121
|
+
|
|
122
|
+
// 过期的、持有者已不在线的预留顺手清掉,返回仍然有效的。
|
|
123
|
+
export const activeReservations = ({ root, now = Date.now(), sessions } = {}) => {
|
|
124
|
+
// PreToolUse 每次编辑都会走到这里;没有任何预留时不做进程探测。
|
|
125
|
+
const all = listAll();
|
|
126
|
+
if (all.length === 0) return [];
|
|
127
|
+
const live = new Map((sessions ?? liveSessions()).map((session) => [session.session, session]));
|
|
128
|
+
const active = [];
|
|
129
|
+
for (const reservation of all) {
|
|
130
|
+
const holder = live.get(reservation.session);
|
|
131
|
+
if (!holder || reservation.expiresAt <= now) {
|
|
132
|
+
removeReservation(reservation.id);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (root && reservation.root !== root) continue;
|
|
136
|
+
active.push({ ...reservation, holder });
|
|
137
|
+
}
|
|
138
|
+
return active.sort((left, right) => left.createdAt - right.createdAt);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export const releaseSessionReservations = (sessionId) => {
|
|
142
|
+
for (const reservation of listAll()) {
|
|
143
|
+
if (reservation.session === sessionId) removeReservation(reservation.id);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const minutesLeft = (reservation, now = Date.now()) => Math.max(1, Math.round((reservation.expiresAt - now) / 60000));
|
|
148
|
+
|
|
149
|
+
export const describeReservation = (reservation, now = Date.now()) =>
|
|
150
|
+
`${reservation.pattern} · ${describeSession(reservation.holder)} · 剩余 ${minutesLeft(reservation, now)} 分钟` +
|
|
151
|
+
(reservation.reason ? ` · ${reservation.reason}` : "");
|
|
152
|
+
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
export const reserveFiles = ({ self, paths, reason = "", ttlMinutes = DEFAULT_TTL_MINUTES, now = Date.now() }) => {
|
|
156
|
+
const list = Array.isArray(paths) ? paths : [paths];
|
|
157
|
+
if (list.length === 0 || list.length > MAX_PATTERNS) return { error: `一次最多预留 ${MAX_PATTERNS} 个路径,至少 1 个。` };
|
|
158
|
+
const ttl = Number(ttlMinutes);
|
|
159
|
+
if (!Number.isFinite(ttl) || ttl < 1 || ttl > MAX_TTL_MINUTES) {
|
|
160
|
+
return { error: `ttl_minutes 需在 1 到 ${MAX_TTL_MINUTES} 之间。` };
|
|
161
|
+
}
|
|
162
|
+
const root = repoRoot(self.cwd);
|
|
163
|
+
if (!root) return { error: "无法确定当前会话所在的仓库目录。" };
|
|
164
|
+
const patterns = [];
|
|
165
|
+
for (const raw of list) {
|
|
166
|
+
const pattern = normalizePattern(root, self.cwd, raw);
|
|
167
|
+
if (!pattern) return { error: `路径 ${raw} 无效,或不在当前仓库 ${root} 内。` };
|
|
168
|
+
if (!patterns.includes(pattern)) patterns.push(pattern);
|
|
169
|
+
}
|
|
170
|
+
const note = String(reason ?? "").trim().slice(0, MAX_REASON_LENGTH);
|
|
171
|
+
const others = activeReservations({ root, now }).filter((entry) => entry.session !== self.session);
|
|
172
|
+
const conflicts = [];
|
|
173
|
+
for (const pattern of patterns) {
|
|
174
|
+
const id = reservationId(self.session, root, pattern);
|
|
175
|
+
const file = path.join(reservationDirectory(), `${id}.json`);
|
|
176
|
+
// 续期保留已放行名单,否则持有者每续期一次,别人就会被重新拦一次。
|
|
177
|
+
const previous = readJson(file);
|
|
178
|
+
writeJsonAtomic(file, {
|
|
179
|
+
id, session: self.session, root, pattern, reason: note, createdAt: previous?.createdAt ?? now,
|
|
180
|
+
expiresAt: now + ttl * 60000, acknowledgedBy: previous?.acknowledgedBy ?? []
|
|
181
|
+
});
|
|
182
|
+
for (const other of others) {
|
|
183
|
+
if (patternsOverlap(pattern, other.pattern)) conflicts.push({ pattern, other });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return { root, patterns, ttl, conflicts };
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// 记下"这个会话已经被这处预留拦过一次",之后放行。
|
|
190
|
+
export const acknowledgeReservation = (reservationId, sessionId) => {
|
|
191
|
+
const file = path.join(reservationDirectory(), `${reservationId}.json`);
|
|
192
|
+
const record = readJson(file);
|
|
193
|
+
if (!record) return;
|
|
194
|
+
const acknowledged = new Set(record.acknowledgedBy ?? []);
|
|
195
|
+
if (acknowledged.has(sessionId)) return;
|
|
196
|
+
acknowledged.add(sessionId);
|
|
197
|
+
writeJsonAtomic(file, { ...record, acknowledgedBy: [...acknowledged] });
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
export const isAcknowledged = (reservation, sessionId) =>
|
|
201
|
+
Array.isArray(reservation.acknowledgedBy) && reservation.acknowledgedBy.includes(sessionId);
|
|
202
|
+
|
|
203
|
+
export const releaseFiles = ({ self, paths }) => {
|
|
204
|
+
const root = repoRoot(self.cwd);
|
|
205
|
+
const own = listAll().filter((entry) => entry.session === self.session && entry.root === root);
|
|
206
|
+
let targets = own;
|
|
207
|
+
if (Array.isArray(paths) && paths.length > 0) {
|
|
208
|
+
const wanted = new Set(paths.map((raw) => normalizePattern(root, self.cwd, raw)).filter(Boolean));
|
|
209
|
+
targets = own.filter((entry) => wanted.has(entry.pattern));
|
|
210
|
+
}
|
|
211
|
+
for (const entry of targets) removeReservation(entry.id);
|
|
212
|
+
return { root, released: targets.map((entry) => entry.pattern) };
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// PreToolUse 用:这些具体文件是否被其他在线会话预留。
|
|
216
|
+
export const findForeignReservations = ({ sessionId, cwd, filePaths, now = Date.now() }) => {
|
|
217
|
+
const root = repoRoot(cwd);
|
|
218
|
+
const others = activeReservations({ root, now }).filter((entry) => entry.session !== sessionId);
|
|
219
|
+
if (others.length === 0) return [];
|
|
220
|
+
const hits = [];
|
|
221
|
+
for (const filePath of filePaths) {
|
|
222
|
+
const relative = normalizePattern(root, cwd, filePath);
|
|
223
|
+
if (!relative || GLOB_CHARACTERS.test(relative)) continue;
|
|
224
|
+
for (const other of others) {
|
|
225
|
+
if (patternToRegExp(other.pattern).test(relative)) hits.push({ file: relative, reservation: other });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return hits;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// 从编辑类工具的输入里找出要改的文件。
|
|
232
|
+
// - Claude:Edit / Write / MultiEdit 的 file_path,NotebookEdit 的 notebook_path;
|
|
233
|
+
// - Codex:apply_patch 的补丁正文里的 "*** Update/Add/Delete File: <path>" 与 "*** Move to: <path>"。
|
|
234
|
+
// Codex hook 里补丁放在哪个字段没有文档保证,所以对整个 tool_input 做文本匹配。
|
|
235
|
+
export const editedFilesFromToolInput = (toolInput) => {
|
|
236
|
+
const files = new Set();
|
|
237
|
+
if (toolInput && typeof toolInput === "object") {
|
|
238
|
+
for (const key of ["file_path", "notebook_path"]) {
|
|
239
|
+
if (typeof toolInput[key] === "string") files.add(toolInput[key]);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const text = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput ?? "");
|
|
243
|
+
const patch = text.replace(/\\n/g, "\n");
|
|
244
|
+
for (const match of patch.matchAll(/\*\*\* (?:Update|Add|Delete) File: ([^\n"]+)/g)) files.add(match[1].trim());
|
|
245
|
+
for (const match of patch.matchAll(/\*\*\* Move to: ([^\n"]+)/g)) files.add(match[1].trim());
|
|
246
|
+
return [...files];
|
|
247
|
+
};
|
|
@@ -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
|
+
};
|