cc-pets 2.1.0 → 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 (58) hide show
  1. package/CC_BRIDGE.md +11 -6
  2. package/CC_BRIDGE.zh-CN.md +8 -4
  3. package/CHANGELOG.md +59 -1
  4. package/CHANGELOG.zh-CN.md +59 -1
  5. package/README.md +60 -12
  6. package/README.zh-CN.md +58 -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 +17 -16
  17. package/Sources/CCPets/CCPetsAppDelegate.m +74 -2406
  18. package/Sources/CCPets/CCPetsCleanup.h +4 -0
  19. package/Sources/CCPets/CCPetsCleanup.m +35 -2
  20. package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
  21. package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
  22. package/Sources/CCPets/CCPetsEvents.m +1 -1
  23. package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
  24. package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
  25. package/Sources/CCPets/CCPetsGlassView.h +31 -0
  26. package/Sources/CCPets/CCPetsGlassView.m +246 -0
  27. package/Sources/CCPets/CCPetsPaths.h +7 -1
  28. package/Sources/CCPets/CCPetsPaths.m +14 -1
  29. package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
  30. package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
  31. package/Sources/CCPets/CCPetsUsage.h +2 -1
  32. package/Sources/CCPets/CCPetsUsage.m +69 -21
  33. package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
  34. package/Sources/CCPets/CCPetsVersion.h +7 -0
  35. package/Sources/CCPets/CCPetsVersion.m +82 -0
  36. package/Sources/CCPets/MenuChoiceRow.h +19 -0
  37. package/Sources/CCPets/MenuChoiceRow.m +96 -0
  38. package/Sources/CCPets/MenuHintView.h +15 -0
  39. package/Sources/CCPets/MenuHintView.m +128 -0
  40. package/Sources/CCPets/PetView.h +2 -0
  41. package/Sources/CCPets/PetView.m +121 -53
  42. package/Sources/CCPets/QuotaDashboardView.h +3 -4
  43. package/Sources/CCPets/QuotaDashboardView.m +222 -146
  44. package/Sources/CCPets/main.m +29 -0
  45. package/bin/cc-pets +39 -1
  46. package/bin/codex-with-pet +2 -0
  47. package/package.json +3 -2
  48. package/scripts/bridge/cli.mjs +9 -2
  49. package/scripts/bridge/core.mjs +1 -1
  50. package/scripts/bridge/install.mjs +23 -1
  51. package/scripts/bridge/process.mjs +22 -0
  52. package/scripts/doctor.mjs +456 -0
  53. package/scripts/install-claude-hooks.mjs +12 -18
  54. package/scripts/install-codex-hooks.mjs +3 -9
  55. package/scripts/integration-markers.mjs +51 -0
  56. package/scripts/pet-store.mjs +2 -1
  57. package/scripts/uninstall-integrations.mjs +16 -44
  58. package/scripts/uninstall-shell-integration.sh +3 -3
package/bin/cc-pets CHANGED
@@ -7,6 +7,38 @@ PET_BIN="${PROJECT_DIR}/.build/release/cc-pets"
7
7
  BUILD_APP="${PROJECT_DIR}/.build/release/CC Pets.app"
8
8
  INSTALLED_APP="${CC_PETS_APPLICATIONS_DIR:-${HOME}/Applications}/CC Pets.app"
9
9
 
10
+ # 只列面向用户的命令。--hook / --claude-usage / --provider-event / --render-* 等是
11
+ # hooks、statusline 和测试调用的内部入口,列出来只会让人误用。
12
+ print_usage() {
13
+ cat <<'USAGE'
14
+ 用法:cc-pets [命令]
15
+
16
+ cc-pets 启动桌宠(优先使用 ~/Applications 里安装的版本)
17
+ cc-pets install 安装或修复 shell / Claude Code / Codex 集成
18
+ cc-pets uninstall 移除集成并恢复 status line
19
+ cc-pets uninstall --purge 同时删除 App、应用数据和偏好(会先确认;保留 ~/.cc-pets 的素材与台词)
20
+ cc-pets uninstall-app 只删除 ~/Applications/CC Pets.app
21
+ cc-pets build 重新构建
22
+ cc-pets clean 清理缓存(需先退出桌宠)
23
+ cc-pets doctor 检查安装与各项集成是否正常,并给出修复建议
24
+ cc-pets paths [--json] 列出配置、缓存与数据的存放位置和大小
25
+ cc-pets pet <命令> 管理桌宠素材,详见 cc-pets pet help
26
+ cc-pets bridge <命令> CC Bridge 跨会话消息,详见 cc-pets bridge --help
27
+ cc-pets --status 输出 Codex 当前额度
28
+ cc-pets --history 输出额度历史(JSON)
29
+ cc-pets --foreground 在前台运行桌宠(调试用)
30
+ cc-pets -v, --version 显示版本
31
+ cc-pets -h, --help 显示本帮助
32
+
33
+ codex-with-pet / claude-with-pet 会在启动 CLI 的同时拉起桌宠。
34
+ USAGE
35
+ }
36
+
37
+ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" || "${1:-}" == "help" ]]; then
38
+ print_usage
39
+ exit 0
40
+ fi
41
+
10
42
  if [[ "${1:-}" == "install" ]]; then
11
43
  exec "${PROJECT_DIR}/scripts/install-shell-integration.sh"
12
44
  fi
@@ -21,8 +53,14 @@ if [[ "${1:-}" == "bridge" ]]; then
21
53
  exec node "${PROJECT_DIR}/scripts/bridge/cli.mjs" "$@"
22
54
  fi
23
55
 
56
+ if [[ "${1:-}" == "doctor" || "${1:-}" == "paths" ]]; then
57
+ exec node "${PROJECT_DIR}/scripts/doctor.mjs" "$@"
58
+ fi
59
+
24
60
  if [[ "${1:-}" == "uninstall" ]]; then
25
- exec "${PROJECT_DIR}/scripts/uninstall-shell-integration.sh"
61
+ shift
62
+ # --purge / --yes 要传下去;原先这里吞掉了参数,README 里的 uninstall --purge 实际不生效。
63
+ exec "${PROJECT_DIR}/scripts/uninstall-shell-integration.sh" "$@"
26
64
  fi
27
65
 
28
66
  if [[ "${1:-}" == "uninstall-app" ]]; then
@@ -49,6 +49,8 @@ mkdir -p "${CLIENT_DIR}"
49
49
  # 第一行记录 provider,第二行记录 TTY;桌宠据此判断具体 Agent 会话是否仍在线。
50
50
  printf '%s\n%s\n' 'Codex' "${CC_PETS_TERMINAL_TTY:t}" > "${CLIENT_FILE}"
51
51
 
52
+ # 新版 Codex 的 hook 由共享后台服务拉起,拿不到这里的终端环境;先登记,hook 再按会话配对。
53
+ "${PET_BIN}" --codex-launch >/dev/null 2>&1 || true
52
54
  print -rn -- '{"schemaVersion":1,"provider":"Codex","state":"starting"}' | \
53
55
  "${PET_BIN}" --provider-event >/dev/null 2>&1 || true
54
56
  # 桌宠是常驻进程,会一直带着这里的环境。CLAUDE_CONFIG_DIR 是会话级的(claude-nw
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "2.1.0",
3
+ "version": "2.1.2",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": {
6
6
  "name": "Sunnyshiny",
@@ -62,7 +62,8 @@
62
62
  "test": "./tests/test.sh",
63
63
  "version": "npm test",
64
64
  "postinstall": "./scripts/install-shell-integration.sh",
65
- "prepack": "npm test"
65
+ "prepack": "npm test",
66
+ "prepublish:check": "npm whoami && if npm view $npm_package_name@$npm_package_version version 2>/dev/null | grep -q .; then echo \"error: $npm_package_name@$npm_package_version is already published; bump the version first\" >&2; exit 1; fi && npm publish --dry-run"
66
67
  },
67
68
  "publishConfig": {
68
69
  "access": "public"
@@ -8,7 +8,9 @@ import {
8
8
  describeSession, identifySelf, liveSessions, receiptSummary, resolveTarget, sendIdleNotices,
9
9
  sendMessage, formatEnvelope
10
10
  } from "./core.mjs";
11
- import { install, uninstall } from "./install.mjs";
11
+ import { describeCodexQueue, install, uninstall } from "./install.mjs";
12
+ import { probeCodexQueue } from "./process.mjs";
13
+ import { detectCodexCLI } from "../detect-cli.mjs";
12
14
  import { DEFAULT_OPTIONS, currentOptions, describeOptions, mergeOptionFlags, normalizeOptions } from "./options.mjs";
13
15
  import { fileURLToPath } from "node:url";
14
16
  import { activeReservations, describeReservation } from "./reservations.mjs";
@@ -127,7 +129,12 @@ const commands = {
127
129
 
128
130
  async status() {
129
131
  console.log(`CC Bridge:${isBridgeEnabled() ? "已开启" : "未开启"}`);
130
- if (isBridgeEnabled()) for (const line of describeOptions(currentOptions())) console.log(` ${line}`);
132
+ if (isBridgeEnabled()) {
133
+ for (const line of describeOptions(currentOptions())) console.log(` ${line}`);
134
+ if (currentOptions().wake && detectCodexCLI()) {
135
+ console.log(` ${describeCodexQueue(probeCodexQueue()) ?? "Codex 支持 codex queue,可自动唤醒。"}`);
136
+ }
137
+ }
131
138
  console.log(`状态目录:${bridgeDirectory()}`);
132
139
  printSessions();
133
140
  const reservations = activeReservations();
@@ -1,6 +1,6 @@
1
1
  // CC Bridge 的业务逻辑:身份识别、目标解析、消息封装、按目标 CLI 选择投递方式。
2
2
  //
3
- // 投递路径(均为官方公开机制,见 CC_BRIDGE_PLAN.md 第 1 节的实测记录):
3
+ // 投递路径(均为官方公开机制):
4
4
  // - 目标是 Codex:`codex queue --thread <id> --message <text>`。空闲时立即唤醒,忙碌时
5
5
  // 排到当前回合之后。发给已关闭会话的消息会被 Codex 持久化并在 resume 时自动执行,
6
6
  // 所以投递前必须确认目标在线。
@@ -13,7 +13,7 @@ import path from "node:path";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { detectClaudeCLI, detectCodexCLI } from "../detect-cli.mjs";
15
15
  import { DEFAULT_OPTIONS, normalizeOptions } from "./options.mjs";
16
- import { resolveRealExecutable } from "./process.mjs";
16
+ import { probeCodexQueue, resolveRealExecutable } from "./process.mjs";
17
17
 
18
18
  export const HOOK_MARKER = "CC_BRIDGE_HOOK=";
19
19
  export const MCP_NAME = "cc-bridge";
@@ -221,6 +221,23 @@ const setCodexApproval = (tools) => {
221
221
 
222
222
  // ---------------------------------------------------------------------------
223
223
 
224
+ // 自动唤醒 Codex 依赖 `codex queue`。不支持时 CC Bridge 照样能用(消息进信箱),只是对方要
225
+ // check_inbox 或等下次输入才收到,开启时就说清楚,免得用户以为"发了没反应"。
226
+ export const describeCodexQueue = (probe) => {
227
+ const version = probe.version ? `(${probe.version})` : "";
228
+ switch (probe.status) {
229
+ case "supported":
230
+ return null;
231
+ case "unsupported":
232
+ return `当前 Codex${version} 不支持 codex queue:发给 Codex 的消息无法自动唤醒对方,会先进信箱,` +
233
+ "由对方调用 check_inbox 或在下次输入时带入。升级 Codex 后即可自动唤醒,无需重新开启。";
234
+ case "missing":
235
+ return "未找到 codex 可执行文件,发给 Codex 的消息只能进信箱;可设置 CODEX_REAL_BIN 后执行 cc-pets bridge enable。";
236
+ default:
237
+ return "无法确认 Codex 是否支持 codex queue;投递失败时会自动退回信箱。";
238
+ }
239
+ };
240
+
224
241
  // registerMcp=false 用于只改选项(桌宠开关、cc-pets bridge configure):不必重跑 claude / codex mcp add。
225
242
  export const install = ({ options: rawOptions = DEFAULT_OPTIONS, registerMcp = process.env.CC_BRIDGE_SKIP_MCP !== "1" } = {}) => {
226
243
  const options = normalizeOptions(rawOptions);
@@ -256,6 +273,11 @@ export const install = ({ options: rawOptions = DEFAULT_OPTIONS, registerMcp = p
256
273
  report.push(ok
257
274
  ? `Codex MCP 已注册:${MCP_NAME}`
258
275
  : `Codex MCP 注册失败,请手动执行:codex ${codexMcpAddArgs().map(shellQuote).join(" ")}`);
276
+ // 只在 enable / refresh 时探测:configure 由桌宠菜单开关触发,不值得每次多拉起两次 codex。
277
+ if (options.wake) {
278
+ const queueNotice = describeCodexQueue(probeCodexQueue(codex));
279
+ if (queueNotice) report.push(queueNotice);
280
+ }
259
281
  }
260
282
  setCodexApproval(options.codexApprove);
261
283
  report.push(options.codexApprove.length > 0
@@ -127,3 +127,25 @@ export const resolveRealExecutable = (name, realBinVariable) => {
127
127
  }
128
128
  return null;
129
129
  };
130
+
131
+ // `codex queue` 是较新的 Codex 才有的子命令。旧版本把不认识的子命令当成交互式启动参数,
132
+ // `--help` 打出的是总帮助而不是报错,所以按帮助里有没有 --thread / --message 判断。
133
+ // 结果只用于提前提示:投递时 queue 失败本来就会退回信箱(core.mjs 的 deliver),
134
+ // 探测失败(超时、找不到 codex)一律算 unknown,不能因此拒绝开启 CC Bridge。
135
+ export const probeCodexQueue = (executable = resolveRealExecutable("codex", "CODEX_REAL_BIN")) => {
136
+ if (!executable || !fs.existsSync(executable)) return { status: "missing", executable: executable ?? null, version: null };
137
+ const run = (args) => {
138
+ try {
139
+ return execFileSync(executable, args,
140
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10_000 });
141
+ } catch (error) {
142
+ if (error.code === "ETIMEDOUT" || error.code === "ENOENT" || error.code === "EACCES") return null;
143
+ return `${error.stdout || ""}${error.stderr || ""}`;
144
+ }
145
+ };
146
+ const version = (run(["--version"]) || "").trim().split("\n")[0] || null;
147
+ const help = run(["queue", "--help"]);
148
+ if (help === null) return { status: "unknown", executable, version };
149
+ const supported = help.includes("--thread") && help.includes("--message");
150
+ return { status: supported ? "supported" : "unsupported", executable, version };
151
+ };
@@ -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
+ }