cc-pets 2.1.1 → 2.1.2

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 (42) hide show
  1. package/CC_BRIDGE.md +5 -0
  2. package/CC_BRIDGE.zh-CN.md +4 -0
  3. package/CHANGELOG.md +23 -1
  4. package/CHANGELOG.zh-CN.md +23 -1
  5. package/README.md +50 -12
  6. package/README.zh-CN.md +49 -13
  7. package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
  8. package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
  9. package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +297 -0
  10. package/Sources/CCPets/CCPetsAppDelegate+Pets.m +187 -0
  11. package/Sources/CCPets/CCPetsAppDelegate+Private.h +322 -0
  12. package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
  13. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +205 -0
  14. package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
  15. package/Sources/CCPets/CCPetsAppDelegate+Update.m +458 -0
  16. package/Sources/CCPets/CCPetsAppDelegate.h +13 -14
  17. package/Sources/CCPets/CCPetsAppDelegate.m +49 -2453
  18. package/Sources/CCPets/CCPetsCleanup.h +4 -0
  19. package/Sources/CCPets/CCPetsCleanup.m +32 -1
  20. package/Sources/CCPets/CCPetsPaths.h +0 -1
  21. package/Sources/CCPets/CCPetsPaths.m +0 -1
  22. package/Sources/CCPets/CCPetsUsage.h +0 -1
  23. package/Sources/CCPets/CCPetsUsage.m +0 -3
  24. package/Sources/CCPets/CCPetsVersion.h +7 -0
  25. package/Sources/CCPets/CCPetsVersion.m +82 -0
  26. package/Sources/CCPets/PetView.h +2 -0
  27. package/Sources/CCPets/PetView.m +16 -4
  28. package/Sources/CCPets/QuotaDashboardView.m +0 -3
  29. package/Sources/CCPets/main.m +13 -0
  30. package/bin/cc-pets +7 -1
  31. package/package.json +3 -2
  32. package/scripts/bridge/cli.mjs +9 -2
  33. package/scripts/bridge/core.mjs +1 -1
  34. package/scripts/bridge/install.mjs +23 -1
  35. package/scripts/bridge/process.mjs +22 -0
  36. package/scripts/doctor.mjs +456 -0
  37. package/scripts/install-claude-hooks.mjs +12 -18
  38. package/scripts/install-codex-hooks.mjs +3 -9
  39. package/scripts/integration-markers.mjs +51 -0
  40. package/scripts/pet-store.mjs +2 -1
  41. package/scripts/uninstall-integrations.mjs +16 -44
  42. package/scripts/uninstall-shell-integration.sh +3 -3
@@ -0,0 +1,456 @@
1
+ #!/usr/bin/env node
2
+ // `cc-pets paths` 与 `cc-pets doctor`。
3
+ //
4
+ // 两者都只读:不改任何配置、不拉起桌宠。输出常被贴进 issue,所以 home 一律显示成 `~`,
5
+ // 不打印 status line 原命令、会话内容或 token。
6
+ // 桌宠自己的数据路径以原生程序 `--paths` 为准(与运行时同一套函数、同样认环境变量覆盖),
7
+ // 这里只补上 Node 侧才知道的部分(CC Bridge、shim、各 CLI 的配置文件)。
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 {
16
+ CLAUDE_HOOK, CODEX_HOOK, LEGACY_CLAUDE_HOOK, LEGACY_CODEX_HOOK, SHIM_START_MARKER,
17
+ STATUS_LINE_MARKER, STATUS_LINE_START_MARKER, isManagedHookCommand, isManagedStatusLine,
18
+ resolveStatusLineScript
19
+ } from "./integration-markers.mjs";
20
+ import { HOOK_MARKER, describeCodexQueue } from "./bridge/install.mjs";
21
+ import { currentOptions } from "./bridge/options.mjs";
22
+ import { probeCodexQueue, resolveRealExecutable } from "./bridge/process.mjs";
23
+ import { bridgeDirectory, bridgeHomeDirectory, isBridgeEnabled } from "./bridge/store.mjs";
24
+
25
+ const projectDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
26
+ const petBinary = path.join(projectDir, ".build/release/cc-pets");
27
+ const packageVersion = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).version;
28
+ const home = os.homedir();
29
+ const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
30
+ const codexHome = process.env.CODEX_HOME || path.join(home, ".codex");
31
+ const shimDirectory = path.resolve(process.env.CC_PETS_SHIM_DIR || path.join(home, ".cc-pets/shims"));
32
+ const shellRC = path.join(process.env.ZDOTDIR || home, ".zshrc");
33
+ const installedApp = path.join(process.env.CC_PETS_APPLICATIONS_DIR || path.join(home, "Applications"), "CC Pets.app");
34
+
35
+ const tilde = (value) => {
36
+ if (typeof value !== "string") return value;
37
+ if (value === home) return "~";
38
+ return value.startsWith(`${home}/`) ? `~${value.slice(home.length)}` : value;
39
+ };
40
+
41
+ const run = (executable, args) => {
42
+ try {
43
+ return execFileSync(executable, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 });
44
+ } catch {
45
+ return null;
46
+ }
47
+ };
48
+
49
+ const nativePaths = () => {
50
+ const output = fs.existsSync(petBinary) ? run(petBinary, ["--paths"]) : null;
51
+ try {
52
+ return output ? JSON.parse(output) : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ };
57
+
58
+ const sizeOf = (target) => {
59
+ let stats;
60
+ try {
61
+ stats = fs.lstatSync(target);
62
+ } catch {
63
+ return null;
64
+ }
65
+ if (!stats.isDirectory()) return stats.size;
66
+ let total = 0;
67
+ for (const entry of fs.readdirSync(target)) total += sizeOf(path.join(target, entry)) ?? 0;
68
+ return total;
69
+ };
70
+
71
+ const formatSize = (bytes) => {
72
+ if (bytes === null) return "不存在";
73
+ if (bytes < 1024) return `${bytes} B`;
74
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
75
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
76
+ };
77
+
78
+ // 终端里中文占两列,按 length 对齐会错位。
79
+ const displayWidth = (text) => [...text].reduce((width, character) =>
80
+ width + (/[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(character) ? 2 : 1), 0);
81
+
82
+ const readJson = (file) => {
83
+ try {
84
+ return { value: JSON.parse(fs.readFileSync(file, "utf8")) };
85
+ } catch (error) {
86
+ return { error: error.code === "ENOENT" ? "missing" : "invalid" };
87
+ }
88
+ };
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // cc-pets paths
92
+
93
+ const pathGroups = (native) => {
94
+ const ccPetsHome = bridgeHomeDirectory();
95
+ const groups = [
96
+ {
97
+ title: "设置(--purge 会删除)",
98
+ items: native ? [["偏好设置", native.preferences]] : []
99
+ },
100
+ {
101
+ title: "用户内容(clean 与 --purge 都保留)",
102
+ items: [
103
+ ...(native ? [
104
+ ["桌宠素材", native.pets],
105
+ ["通用台词", native.phrases],
106
+ ["宠物专属台词", native.petPhrases]
107
+ ] : []),
108
+ ["CC Bridge 开关", path.join(ccPetsHome, "bridge-enabled")],
109
+ ["codex / claude shim", shimDirectory]
110
+ ]
111
+ },
112
+ {
113
+ title: "应用数据(--purge 会删除;clean 只清其中的 Token 缓存与更新日志)",
114
+ items: native ? [
115
+ ["应用数据目录", native.applicationSupport],
116
+ ["额度历史", native.quotaHistory],
117
+ ["自动更新配置", path.join(native.applicationSupport, "updater.json")]
118
+ ] : []
119
+ },
120
+ {
121
+ title: "缓存与运行时状态(clean 会清理,丢失不影响使用)",
122
+ items: [
123
+ ...(native ? [
124
+ ["素材清单缓存", native.petStoreCache],
125
+ ["Agent 事件流", native.agentEvents],
126
+ ["Claude 额度快照", native.claudeUsage],
127
+ ["Codex 实时额度", native.codexLiveUsage],
128
+ ["Codex 启动记录", native.codexLaunches],
129
+ ["在线客户端记录", native.clients]
130
+ ] : []),
131
+ ["CC Bridge 状态目录", bridgeDirectory()]
132
+ ]
133
+ },
134
+ {
135
+ title: "程序与集成",
136
+ items: [
137
+ ["npm 包", projectDir],
138
+ ["已安装的 App", installedApp],
139
+ ["Claude Code 配置", path.join(claudeHome, "settings.json")],
140
+ ["Codex Hooks", path.join(codexHome, "hooks.json")],
141
+ ["Shell 配置", shellRC]
142
+ ]
143
+ }
144
+ ];
145
+ return groups.filter((group) => group.items.length > 0);
146
+ };
147
+
148
+ const printPaths = (asJson) => {
149
+ const native = nativePaths();
150
+ const groups = pathGroups(native);
151
+ if (asJson) {
152
+ const document = {
153
+ version: packageVersion,
154
+ running: native?.running ?? null,
155
+ groups: groups.map((group) => ({
156
+ title: group.title,
157
+ items: group.items.map(([label, target]) => ({ label, path: tilde(target), bytes: sizeOf(target) }))
158
+ }))
159
+ };
160
+ console.log(JSON.stringify(document, null, 2));
161
+ return 0;
162
+ }
163
+ if (!native) {
164
+ console.log("⚠️ 原生程序未构建或无法运行,桌宠自身的数据路径无法确定;执行 cc-pets install 后重试。\n");
165
+ }
166
+ const width = Math.max(...groups.flatMap((group) => group.items.map(([label]) => displayWidth(label))));
167
+ groups.forEach((group, index) => {
168
+ if (index > 0) console.log("");
169
+ console.log(group.title);
170
+ for (const [label, target] of group.items) {
171
+ console.log(` ${label}${" ".repeat(width - displayWidth(label) + 2)}${tilde(target)} (${formatSize(sizeOf(target))})`);
172
+ }
173
+ });
174
+ return 0;
175
+ };
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // cc-pets doctor
179
+
180
+ const ICONS = { ok: "✅", warn: "⚠️ ", fail: "❌", info: "ℹ️ " };
181
+
182
+ const versionOfApp = (appPath) => {
183
+ const plist = path.join(appPath, "Contents/Info.plist");
184
+ if (!fs.existsSync(plist)) return null;
185
+ return (run("/usr/bin/plutil", ["-extract", "CFBundleShortVersionString", "raw", "-o", "-", plist]) || "").trim() || null;
186
+ };
187
+
188
+ // 认出配置里属于 CC Pets 的 hook,并区分"指向当前安装"和"指向别处"(包被挪走、换了 node 版本重装后
189
+ // 常见,hook 每次触发都会失败)。
190
+ const inspectHooks = (configFile, signature, legacySignature) => {
191
+ const { value, error } = readJson(configFile);
192
+ if (error === "invalid") return { error: "invalid" };
193
+ const commands = Object.values(value?.hooks ?? {})
194
+ .filter(Array.isArray).flat()
195
+ .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
196
+ .map((handler) => handler?.command);
197
+ const managed = commands.filter((command) => isManagedHookCommand(command, signature));
198
+ const current = managed.filter((command) => command.includes(`'${petBinary}'`));
199
+ return {
200
+ total: managed.length,
201
+ stale: managed.length - current.length,
202
+ legacy: commands.filter((command) => isManagedHookCommand(command, legacySignature)).length,
203
+ bridge: commands.filter((command) => typeof command === "string" && command.startsWith(HOOK_MARKER)).length
204
+ };
205
+ };
206
+
207
+ const hookChecks = (name, configFile, signature, legacySignature) => {
208
+ const hooks = inspectHooks(configFile, signature, legacySignature);
209
+ if (hooks.error) {
210
+ return {
211
+ results: [{ level: "fail", title: `${name} 配置无法解析:${tilde(configFile)}`, fix: "修正该 JSON 文件后执行 cc-pets install" }],
212
+ bridgeHooks: 0
213
+ };
214
+ }
215
+ const results = [];
216
+ if (hooks.total === 0) {
217
+ results.push({ level: "fail", title: `${name} Hooks 未安装`, fix: "cc-pets install" });
218
+ } else if (hooks.stale > 0) {
219
+ results.push({
220
+ level: "warn",
221
+ title: `${name} Hooks 中有 ${hooks.stale} 条指向其他位置的 cc-pets(包被移动或重装过)`,
222
+ fix: "cc-pets install"
223
+ });
224
+ } else {
225
+ results.push({ level: "ok", title: `${name} Hooks 已安装(${hooks.total} 个事件)` });
226
+ }
227
+ if (hooks.legacy > 0) {
228
+ results.push({ level: "warn", title: `${name} 配置里残留 ${hooks.legacy} 条旧版 codex-pet Hooks`, fix: "cc-pets install" });
229
+ }
230
+ return { results, bridgeHooks: hooks.bridge };
231
+ };
232
+
233
+ const statusLineCheck = () => {
234
+ const { value } = readJson(path.join(claudeHome, "settings.json"));
235
+ const command = typeof value?.statusLine?.command === "string" ? value.statusLine.command : "";
236
+ if (isManagedStatusLine(command, STATUS_LINE_MARKER)) {
237
+ return { level: "ok", title: "Claude status line 已通过包装器接入额度采集" };
238
+ }
239
+ const script = resolveStatusLineScript(command);
240
+ let content = "";
241
+ try {
242
+ content = script ? fs.readFileSync(script, "utf8") : "";
243
+ } catch {
244
+ content = "";
245
+ }
246
+ if (content.includes(STATUS_LINE_START_MARKER)) {
247
+ return content.includes(`'${petBinary}'`)
248
+ ? { level: "ok", title: `Claude status line 已接入额度采集(${tilde(script)})` }
249
+ : { level: "warn", title: "Claude status line 里的额度采集指向其他位置的 cc-pets", fix: "cc-pets install" };
250
+ }
251
+ return {
252
+ level: "warn",
253
+ title: command ? "Claude status line 未接入额度采集,桌宠拿不到 Claude 额度百分比" : "未配置 Claude status line,桌宠拿不到 Claude 额度百分比",
254
+ fix: "cc-pets install"
255
+ };
256
+ };
257
+
258
+ const shimChecks = () => {
259
+ const results = [];
260
+ let rc = "";
261
+ try {
262
+ rc = fs.readFileSync(shellRC, "utf8");
263
+ } catch {
264
+ rc = "";
265
+ }
266
+ results.push(rc.includes(SHIM_START_MARKER)
267
+ ? { level: "ok", title: `${tilde(shellRC)} 已加入 shim 目录` }
268
+ : { level: "fail", title: `${tilde(shellRC)} 中没有 CC Pets 的 shim 配置`, fix: "cc-pets install" });
269
+
270
+ const broken = [];
271
+ for (const name of ["codex", "claude"]) {
272
+ const shim = path.join(shimDirectory, name);
273
+ let link = null;
274
+ try {
275
+ link = fs.readlinkSync(shim);
276
+ } catch {
277
+ broken.push(`${name}(缺失)`);
278
+ continue;
279
+ }
280
+ if (!fs.existsSync(path.resolve(shimDirectory, link))) broken.push(`${name}(指向的文件不存在)`);
281
+ }
282
+ results.push(broken.length === 0
283
+ ? { level: "ok", title: `shim 完整:${tilde(shimDirectory)}` }
284
+ : { level: "warn", title: `shim 异常:${broken.join("、")}`, fix: "cc-pets install" });
285
+
286
+ const entries = (process.env.PATH || "").split(path.delimiter).filter(Boolean).map((entry) => path.resolve(entry));
287
+ const index = entries.indexOf(shimDirectory);
288
+ if (index < 0) {
289
+ results.push({ level: "warn", title: "当前终端的 PATH 里没有 shim 目录,直接敲 codex / claude 不会拉起桌宠", fix: `source ${tilde(shellRC)},或新开一个终端` });
290
+ } else if (index > 0) {
291
+ const shadowing = entries.slice(0, index).find((entry) =>
292
+ ["codex", "claude"].some((name) => fs.existsSync(path.join(entry, name))));
293
+ results.push(shadowing
294
+ ? { level: "warn", title: `PATH 中 ${tilde(shadowing)} 排在 shim 目录之前,会绕过桌宠`, fix: `source ${tilde(shellRC)},或新开一个终端` }
295
+ : { level: "ok", title: "PATH 中 shim 目录优先于真实的 codex / claude" });
296
+ } else {
297
+ results.push({ level: "ok", title: "PATH 中 shim 目录排在最前" });
298
+ }
299
+ return results;
300
+ };
301
+
302
+ const realBinaryCheck = (name, variable) => {
303
+ const real = resolveRealExecutable(name, variable);
304
+ return real && fs.existsSync(real)
305
+ ? { level: "ok", title: `找到真实的 ${name}:${tilde(real)}` }
306
+ : { level: "warn", title: `PATH 中找不到真实的 ${name},shim 无法转发`, fix: `export ${variable}=/absolute/path/to/${name}` };
307
+ };
308
+
309
+ const updaterCheck = (native) => {
310
+ if (!native) return null;
311
+ const file = path.join(native.applicationSupport, "updater.json");
312
+ const { value, error } = readJson(file);
313
+ if (error) {
314
+ return { level: "warn", title: "自动更新未配置,应用内无法一键更新", fix: "npm install -g cc-pets@latest --allow-scripts=cc-pets" };
315
+ }
316
+ const missing = ["nodePath", "npmCliPath"].filter((key) => !value?.[key] || !fs.existsSync(value[key]));
317
+ return missing.length === 0
318
+ ? { level: "ok", title: "自动更新配置有效" }
319
+ : { level: "warn", title: `自动更新记录的 ${missing.join("、")} 已不存在(换过 Node 版本?)`, fix: "npm install -g cc-pets@latest --allow-scripts=cc-pets" };
320
+ };
321
+
322
+ const formatAge = (milliseconds) => {
323
+ const minutes = Math.round(milliseconds / 60_000);
324
+ if (minutes < 60) return `${minutes} 分钟前`;
325
+ const hours = Math.round(minutes / 60);
326
+ return hours < 48 ? `${hours} 小时前` : `${Math.round(hours / 24)} 天前`;
327
+ };
328
+
329
+ const runDoctor = () => {
330
+ const native = nativePaths();
331
+ const sections = [];
332
+ const claudeDetected = detectClaudeCLI();
333
+ const codexDetected = detectCodexCLI();
334
+
335
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
336
+ const program = [
337
+ nodeMajor >= 18
338
+ ? { level: "ok", title: `Node.js ${process.versions.node}` }
339
+ : { level: "fail", title: `Node.js ${process.versions.node} 过旧,需要 18 或更高版本` },
340
+ { level: "info", title: `npm 包 ${packageVersion}:${tilde(projectDir)}` }
341
+ ];
342
+ const binaryVersion = fs.existsSync(petBinary) ? (run(petBinary, ["--version"]) || "").trim().replace(/^cc-pets\s+/, "") : null;
343
+ if (!binaryVersion) {
344
+ program.push({ level: "fail", title: "原生程序未构建或无法运行", fix: "cc-pets install" });
345
+ } else if (binaryVersion !== packageVersion) {
346
+ program.push({ level: "warn", title: `原生程序版本 ${binaryVersion} 与 npm 包 ${packageVersion} 不一致`, fix: "cc-pets install" });
347
+ } else {
348
+ program.push({ level: "ok", title: `原生程序 ${binaryVersion}` });
349
+ }
350
+ const appVersion = versionOfApp(installedApp);
351
+ if (!appVersion) {
352
+ program.push({ level: "warn", title: `未找到已安装的 App:${tilde(installedApp)}`, fix: "cc-pets install" });
353
+ } else if (appVersion !== packageVersion) {
354
+ program.push({ level: "warn", title: `已安装的 App 版本 ${appVersion} 与 npm 包 ${packageVersion} 不一致`, fix: "cc-pets install" });
355
+ } else {
356
+ program.push({ level: "ok", title: `已安装的 App ${appVersion}` });
357
+ }
358
+ if (native) program.push({ level: "info", title: native.running ? "桌宠正在运行" : "桌宠未运行" });
359
+ const updater = updaterCheck(native);
360
+ if (updater) program.push(updater);
361
+ sections.push({ title: "程序", results: program });
362
+
363
+ let claudeBridgeHooks = 0;
364
+ if (claudeDetected) {
365
+ const { results, bridgeHooks } = hookChecks("Claude Code", path.join(claudeHome, "settings.json"), CLAUDE_HOOK, LEGACY_CLAUDE_HOOK);
366
+ claudeBridgeHooks = bridgeHooks;
367
+ const claude = [...results, statusLineCheck()];
368
+ if (native) {
369
+ let modified = null;
370
+ try {
371
+ modified = fs.statSync(native.claudeUsage).mtimeMs;
372
+ } catch {
373
+ modified = null;
374
+ }
375
+ claude.push(modified
376
+ ? { level: "info", title: `Claude 额度快照更新于 ${formatAge(Date.now() - modified)}` }
377
+ : { level: "info", title: "暂无 Claude 额度快照(Claude Code 首次收到 API 响应后生成)" });
378
+ }
379
+ sections.push({ title: "Claude Code", results: claude });
380
+ } else {
381
+ sections.push({ title: "Claude Code", results: [{ level: "info", title: "未检测到 Claude Code CLI,跳过" }] });
382
+ }
383
+
384
+ let codexBridgeHooks = 0;
385
+ if (codexDetected) {
386
+ const { results, bridgeHooks } = hookChecks("Codex", path.join(codexHome, "hooks.json"), CODEX_HOOK, LEGACY_CODEX_HOOK);
387
+ codexBridgeHooks = bridgeHooks;
388
+ sections.push({
389
+ title: "Codex",
390
+ results: [
391
+ ...results,
392
+ { level: "info", title: "Codex 需要在 /hooks 中信任 CC Pets Hooks 后才会触发(无法自动检测)" }
393
+ ]
394
+ });
395
+ } else {
396
+ sections.push({ title: "Codex", results: [{ level: "info", title: "未检测到 Codex CLI,跳过" }] });
397
+ }
398
+
399
+ sections.push({
400
+ title: "Shell 集成",
401
+ results: [
402
+ ...shimChecks(),
403
+ ...(codexDetected ? [realBinaryCheck("codex", "CODEX_REAL_BIN")] : []),
404
+ ...(claudeDetected ? [realBinaryCheck("claude", "CLAUDE_REAL_BIN")] : [])
405
+ ]
406
+ });
407
+
408
+ if (!isBridgeEnabled()) {
409
+ sections.push({ title: "CC Bridge", results: [{ level: "info", title: "未开启(可选功能,cc-pets bridge enable 开启)" }] });
410
+ } else {
411
+ const bridge = [{ level: "ok", title: "已开启" }];
412
+ if (claudeDetected) {
413
+ bridge.push(claudeBridgeHooks > 0
414
+ ? { level: "ok", title: "Claude Code 中的 CC Bridge Hooks 已安装" }
415
+ : { level: "warn", title: "Claude Code 中缺少 CC Bridge Hooks", fix: "cc-pets bridge enable" });
416
+ }
417
+ if (codexDetected) {
418
+ bridge.push(codexBridgeHooks > 0
419
+ ? { level: "ok", title: "Codex 中的 CC Bridge Hooks 已安装" }
420
+ : { level: "warn", title: "Codex 中缺少 CC Bridge Hooks", fix: "cc-pets bridge enable" });
421
+ if (currentOptions().wake) {
422
+ const notice = describeCodexQueue(probeCodexQueue());
423
+ bridge.push(notice
424
+ ? { level: "warn", title: notice }
425
+ : { level: "ok", title: "Codex 支持 codex queue,可自动唤醒" });
426
+ }
427
+ }
428
+ sections.push({ title: "CC Bridge", results: bridge });
429
+ }
430
+
431
+ console.log(`CC Pets 诊断(npm 包 ${packageVersion},${os.platform()} ${os.release()})`);
432
+ const counts = { ok: 0, warn: 0, fail: 0, info: 0 };
433
+ for (const section of sections) {
434
+ console.log(`\n${section.title}`);
435
+ for (const result of section.results) {
436
+ counts[result.level] += 1;
437
+ console.log(` ${ICONS[result.level]} ${result.title}`);
438
+ if (result.fix) console.log(` → ${result.fix}`);
439
+ }
440
+ }
441
+ console.log(`\n结果:${counts.ok} 项正常,${counts.warn} 项警告,${counts.fail} 项错误。`);
442
+ if (counts.fail + counts.warn > 0) console.log("多数问题执行 cc-pets install 即可修复;数据位置见 cc-pets paths。");
443
+ return counts.fail > 0 ? 1 : 0;
444
+ };
445
+
446
+ // ---------------------------------------------------------------------------
447
+
448
+ const [command, ...args] = process.argv.slice(2);
449
+ if (command === "paths") {
450
+ process.exitCode = printPaths(args.includes("--json"));
451
+ } else if (command === "doctor") {
452
+ process.exitCode = runDoctor();
453
+ } else {
454
+ console.error("用法: doctor.mjs paths [--json] | doctor");
455
+ process.exitCode = 2;
456
+ }
@@ -5,6 +5,11 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { detectClaudeCLI } from "./detect-cli.mjs";
8
+ import {
9
+ CLAUDE_HOOK, CREATED_STATUS_LINE_MARKER, LEGACY_CLAUDE_HOOK, LEGACY_STATUS_LINE_MARKER,
10
+ STATUS_LINE_END_MARKER, STATUS_LINE_MARKER, STATUS_LINE_START_MARKER,
11
+ isManagedHookCommand, isManagedStatusLine
12
+ } from "./integration-markers.mjs";
8
13
 
9
14
  const binary = process.argv[2];
10
15
  if (!binary) {
@@ -23,24 +28,13 @@ if (!detectClaudeCLI()) {
23
28
 
24
29
  const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
25
30
  const settingsPath = path.join(claudeHome, "settings.json");
26
- const marker = "CC_PETS_CLAUDE_AGENT_HOOK=1";
27
- const statusLineMarker = "CC_PETS_CLAUDE_STATUS_LINE=1";
28
- const managedHookSignatures = [
29
- { marker, executable: "cc-pets" },
30
- { marker: "CLAUDE_PET_AGENT_HOOK=1", executable: "codex-pet" }
31
- ];
32
- const managedStatusLineMarkers = [statusLineMarker, "CLAUDE_PET_STATUS_LINE=1"];
33
- const statusLineStartMarker = "# >>> cc-pets-statusline >>>";
34
- const statusLineEndMarker = "# <<< cc-pets-statusline <<<";
35
- const createdStatusLineMarker = "# CC Pets created this status line script";
36
- const isManagedHookCommand = (value, signature) =>
37
- typeof value === "string" &&
38
- value.startsWith(`${signature.marker} `) &&
39
- value.endsWith(`/.build/release/${signature.executable}' --hook`);
40
- const isManagedStatusLine = (value, candidateMarker) =>
41
- typeof value === "string" &&
42
- value.startsWith(`${candidateMarker} `) &&
43
- /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
31
+ const marker = CLAUDE_HOOK.marker;
32
+ const statusLineMarker = STATUS_LINE_MARKER;
33
+ const managedHookSignatures = [CLAUDE_HOOK, LEGACY_CLAUDE_HOOK];
34
+ const managedStatusLineMarkers = [STATUS_LINE_MARKER, LEGACY_STATUS_LINE_MARKER];
35
+ const statusLineStartMarker = STATUS_LINE_START_MARKER;
36
+ const statusLineEndMarker = STATUS_LINE_END_MARKER;
37
+ const createdStatusLineMarker = CREATED_STATUS_LINE_MARKER;
44
38
  const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
45
39
  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46
40
  const statusLineBlockPattern = new RegExp(
@@ -4,6 +4,7 @@ import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { detectCodexCLI } from "./detect-cli.mjs";
7
+ import { CODEX_HOOK, LEGACY_CODEX_HOOK, isManagedHookCommand } from "./integration-markers.mjs";
7
8
 
8
9
  const binary = process.argv[2];
9
10
  if (!binary) {
@@ -22,15 +23,8 @@ if (!detectCodexCLI()) {
22
23
 
23
24
  const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
24
25
  const hooksPath = path.join(codexHome, "hooks.json");
25
- const marker = "CC_PETS_CODEX_AGENT_HOOK=1";
26
- const managedSignatures = [
27
- { marker, executable: "cc-pets" },
28
- { marker: "CODEX_PET_AGENT_HOOK=1", executable: "codex-pet" }
29
- ];
30
- const isManagedHookCommand = (value, signature) =>
31
- typeof value === "string" &&
32
- value.startsWith(`${signature.marker} `) &&
33
- value.endsWith(`/.build/release/${signature.executable}' --hook`);
26
+ const marker = CODEX_HOOK.marker;
27
+ const managedSignatures = [CODEX_HOOK, LEGACY_CODEX_HOOK];
34
28
  const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
35
29
  const command = `${marker} ${shellQuote(path.resolve(binary))} --hook`;
36
30
  const events = [
@@ -0,0 +1,51 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ // CC Pets 写进 Claude Code / Codex 配置里的条目怎么认。安装、卸载、cc-pets doctor 共用这一份,
5
+ // 以免哪天改了写法,doctor 还按旧规则说"一切正常"。
6
+
7
+ export const CODEX_HOOK = { marker: "CC_PETS_CODEX_AGENT_HOOK=1", executable: "cc-pets" };
8
+ export const LEGACY_CODEX_HOOK = { marker: "CODEX_PET_AGENT_HOOK=1", executable: "codex-pet" };
9
+ export const CLAUDE_HOOK = { marker: "CC_PETS_CLAUDE_AGENT_HOOK=1", executable: "cc-pets" };
10
+ export const LEGACY_CLAUDE_HOOK = { marker: "CLAUDE_PET_AGENT_HOOK=1", executable: "codex-pet" };
11
+
12
+ export const STATUS_LINE_MARKER = "CC_PETS_CLAUDE_STATUS_LINE=1";
13
+ export const LEGACY_STATUS_LINE_MARKER = "CLAUDE_PET_STATUS_LINE=1";
14
+ export const STATUS_LINE_START_MARKER = "# >>> cc-pets-statusline >>>";
15
+ export const STATUS_LINE_END_MARKER = "# <<< cc-pets-statusline <<<";
16
+ export const CREATED_STATUS_LINE_MARKER = "# CC Pets created this status line script";
17
+
18
+ export const SHIM_START_MARKER = "# >>> cc-pets-shims >>>";
19
+ export const SHIM_END_MARKER = "# <<< cc-pets-shims <<<";
20
+
21
+ export const isManagedHookCommand = (value, signature) =>
22
+ typeof value === "string" &&
23
+ value.startsWith(`${signature.marker} `) &&
24
+ value.endsWith(`/.build/release/${signature.executable}' --hook`);
25
+
26
+ export const isManagedStatusLine = (value, marker) =>
27
+ typeof value === "string" &&
28
+ value.startsWith(`${marker} `) &&
29
+ /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
30
+
31
+ // `bash ~/x.sh` 这类带解释器前缀的命令同样指向一个被就地注入过的脚本;带 -c 的不算,
32
+ // `-c` 后面是命令串而非脚本路径。install-claude-hooks.mjs 另有一份返回更多字段的解析,规则一致。
33
+ const interpreterPattern =
34
+ /^(?:\/usr\/bin\/env\s+)?(?:[^\s'"]*\/)?(?:ba|z|k|da)?sh((?:\s+-[A-Za-z]+)*)\s+(.+)$/s;
35
+
36
+ const unquote = (value) => {
37
+ const quoted = value.match(/^(['"])(.*)\1$/s);
38
+ return quoted ? quoted[2] : value;
39
+ };
40
+
41
+ export const resolveStatusLineScript = (value) => {
42
+ if (typeof value !== "string") return null;
43
+ let candidate = unquote(value.trim());
44
+ const interpreted = candidate.match(interpreterPattern);
45
+ if (interpreted && !/-[A-Za-z]*c(?=\s|$)/.test(interpreted[1])) {
46
+ candidate = unquote(interpreted[2].trim());
47
+ }
48
+ if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
49
+ if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
50
+ return path.resolve(candidate);
51
+ };
@@ -51,8 +51,9 @@ const petsRoot = () => {
51
51
  if (override && override.length > 0) return path.resolve(untilde(override));
52
52
  return path.join(os.homedir(), ".cc-pets", "pets");
53
53
  };
54
+ // 与 CC Bridge、cc-pets clean 一致:CC_PETS_HOME 可覆盖 ~/.cc-pets。
54
55
  const cachePath = (sourceName) =>
55
- path.join(os.homedir(), ".cc-pets", "cache", `manifest-${sourceName}.json`);
56
+ path.join(process.env.CC_PETS_HOME || path.join(os.homedir(), ".cc-pets"), "cache", `manifest-${sourceName}.json`);
56
57
  // 每个源都可以单独用环境变量改清单地址,主要给测试和自建源的本地联调用。
57
58
  const manifestUrlFor = (sourceName) =>
58
59
  process.env[`CC_PETS_MANIFEST_URL_${sourceName.toUpperCase()}`] || SOURCES[sourceName].manifestUrl;
@@ -3,55 +3,27 @@
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import {
7
+ CLAUDE_HOOK, CODEX_HOOK, CREATED_STATUS_LINE_MARKER, LEGACY_CLAUDE_HOOK, LEGACY_CODEX_HOOK,
8
+ LEGACY_STATUS_LINE_MARKER, SHIM_END_MARKER, SHIM_START_MARKER, STATUS_LINE_END_MARKER,
9
+ STATUS_LINE_MARKER, STATUS_LINE_START_MARKER, isManagedHookCommand, isManagedStatusLine,
10
+ resolveStatusLineScript
11
+ } from "./integration-markers.mjs";
6
12
 
7
13
  const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
8
14
  const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
9
15
  const preparingInstall = process.argv[2] === "--prepare-install";
10
16
  const shellRC = process.argv[preparingInstall ? 3 : 2];
11
17
 
12
- const currentCodexHook = { marker: "CC_PETS_CODEX_AGENT_HOOK=1", executable: "cc-pets" };
13
- const legacyCodexHook = { marker: "CODEX_PET_AGENT_HOOK=1", executable: "codex-pet" };
14
- const currentClaudeHook = { marker: "CC_PETS_CLAUDE_AGENT_HOOK=1", executable: "cc-pets" };
15
- const legacyClaudeHook = { marker: "CLAUDE_PET_AGENT_HOOK=1", executable: "codex-pet" };
16
- const currentStatusLineMarker = "CC_PETS_CLAUDE_STATUS_LINE=1";
17
- const legacyStatusLineMarker = "CLAUDE_PET_STATUS_LINE=1";
18
- const statusLineStartMarker = "# >>> cc-pets-statusline >>>";
19
- const statusLineEndMarker = "# <<< cc-pets-statusline <<<";
20
- const createdStatusLineMarker = "# CC Pets created this status line script";
21
-
22
- function isManagedHookCommand(value, signature) {
23
- return typeof value === "string" &&
24
- value.startsWith(`${signature.marker} `) &&
25
- value.endsWith(`/.build/release/${signature.executable}' --hook`);
26
- }
27
-
28
- function isManagedStatusLine(value, marker) {
29
- return typeof value === "string" &&
30
- value.startsWith(`${marker} `) &&
31
- /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
32
- }
33
-
34
- // 与 install-claude-hooks.mjs 保持一致:`bash ~/x.sh` 这类带解释器前缀的命令同样指向一个
35
- // 被就地注入过的脚本,卸载时也要能解析出来,否则 prelude 会残留在脚本里。
36
- const interpreterPattern =
37
- /^(?:\/usr\/bin\/env\s+)?(?:[^\s'"]*\/)?(?:ba|z|k|da)?sh((?:\s+-[A-Za-z]+)*)\s+(.+)$/s;
38
-
39
- function unquote(value) {
40
- const quoted = value.match(/^(['"])(.*)\1$/s);
41
- return quoted ? quoted[2] : value;
42
- }
43
-
44
- function resolveStatusLineScript(value) {
45
- if (typeof value !== "string") return null;
46
- let candidate = unquote(value.trim());
47
- const interpreted = candidate.match(interpreterPattern);
48
- if (interpreted && !/-[A-Za-z]*c(?=\s|$)/.test(interpreted[1])) {
49
- candidate = unquote(interpreted[2].trim());
50
- }
51
- if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
52
- if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
53
- return path.resolve(candidate);
54
- }
18
+ const currentCodexHook = CODEX_HOOK;
19
+ const legacyCodexHook = LEGACY_CODEX_HOOK;
20
+ const currentClaudeHook = CLAUDE_HOOK;
21
+ const legacyClaudeHook = LEGACY_CLAUDE_HOOK;
22
+ const currentStatusLineMarker = STATUS_LINE_MARKER;
23
+ const legacyStatusLineMarker = LEGACY_STATUS_LINE_MARKER;
24
+ const statusLineStartMarker = STATUS_LINE_START_MARKER;
25
+ const statusLineEndMarker = STATUS_LINE_END_MARKER;
26
+ const createdStatusLineMarker = CREATED_STATUS_LINE_MARKER;
55
27
 
56
28
  function removeStatusLinePrelude(scriptPath) {
57
29
  if (!scriptPath || !fs.existsSync(scriptPath)) return { changed: false, created: false };
@@ -175,7 +147,7 @@ if (shellRC && fs.existsSync(shellRC)) {
175
147
  // cc-pets-codex / cc-pets-claude 是 alias 时代的段落。alias 区分大小写,挡不住
176
148
  // Claude / CODEX 这类写法,已被 cc-pets-shims 的 PATH shim 取代;安装前的
177
149
  // --prepare-install 会走到这里,顺带把老段落迁移掉。
178
- let updated = removeMarkedBlock(original, "# >>> cc-pets-shims >>>", "# <<< cc-pets-shims <<<");
150
+ let updated = removeMarkedBlock(original, SHIM_START_MARKER, SHIM_END_MARKER);
179
151
  updated = removeMarkedBlock(updated, "# >>> cc-pets-codex >>>", "# <<< cc-pets-codex <<<");
180
152
  updated = removeMarkedBlock(updated, "# >>> cc-pets-claude >>>", "# <<< cc-pets-claude <<<");
181
153
  updated = removeMarkedBlock(updated, "# >>> codex-pet >>>", "# <<< codex-pet <<<");