cc-pets 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CC_BRIDGE.md +5 -0
  2. package/CC_BRIDGE.zh-CN.md +4 -0
  3. package/CHANGELOG.md +40 -1
  4. package/CHANGELOG.zh-CN.md +40 -1
  5. package/CONTRIBUTING.md +54 -0
  6. package/CONTRIBUTING.zh-CN.md +45 -0
  7. package/README.md +57 -14
  8. package/README.zh-CN.md +56 -14
  9. package/Resources/Info.plist +3 -1
  10. package/Resources/en.lproj/InfoPlist.strings +1 -0
  11. package/Resources/phrases.default.en.txt +182 -0
  12. package/Resources/zh-Hans.lproj/InfoPlist.strings +1 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +332 -0
  14. package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
  15. package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
  16. package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +299 -0
  17. package/Sources/CCPets/CCPetsAppDelegate+Pets.m +185 -0
  18. package/Sources/CCPets/CCPetsAppDelegate+Private.h +325 -0
  19. package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
  20. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +226 -0
  21. package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
  22. package/Sources/CCPets/CCPetsAppDelegate+Update.m +459 -0
  23. package/Sources/CCPets/CCPetsAppDelegate.h +13 -14
  24. package/Sources/CCPets/CCPetsAppDelegate.m +68 -2466
  25. package/Sources/CCPets/CCPetsCleanup.h +4 -0
  26. package/Sources/CCPets/CCPetsCleanup.m +41 -7
  27. package/Sources/CCPets/CCPetsEvents.m +4 -3
  28. package/Sources/CCPets/CCPetsL10n.h +55 -0
  29. package/Sources/CCPets/CCPetsL10n.m +219 -0
  30. package/Sources/CCPets/CCPetsPaths.h +0 -1
  31. package/Sources/CCPets/CCPetsPaths.m +0 -1
  32. package/Sources/CCPets/CCPetsPhrases.h +7 -1
  33. package/Sources/CCPets/CCPetsPhrases.m +86 -31
  34. package/Sources/CCPets/CCPetsPhrasesEditor.m +62 -64
  35. package/Sources/CCPets/CCPetsPreviews.m +7 -6
  36. package/Sources/CCPets/CCPetsUsage.h +0 -1
  37. package/Sources/CCPets/CCPetsUsage.m +0 -3
  38. package/Sources/CCPets/CCPetsVersion.h +10 -0
  39. package/Sources/CCPets/CCPetsVersion.m +92 -2
  40. package/Sources/CCPets/MenuToggleSwitch.m +3 -2
  41. package/Sources/CCPets/PetView.h +2 -0
  42. package/Sources/CCPets/PetView.m +115 -74
  43. package/Sources/CCPets/QuotaDashboardView.m +122 -88
  44. package/Sources/CCPets/main.m +16 -1
  45. package/bin/cc-pets +25 -20
  46. package/bin/claude-with-pet +2 -1
  47. package/bin/codex-with-pet +2 -1
  48. package/package.json +5 -3
  49. package/scripts/bridge/cli.mjs +47 -39
  50. package/scripts/bridge/core.mjs +28 -27
  51. package/scripts/bridge/hook.mjs +7 -6
  52. package/scripts/bridge/install.mjs +42 -19
  53. package/scripts/bridge/mcp-server.mjs +79 -71
  54. package/scripts/bridge/options.mjs +7 -6
  55. package/scripts/bridge/process.mjs +22 -0
  56. package/scripts/bridge/reservations.mjs +6 -5
  57. package/scripts/bridge/store.mjs +10 -9
  58. package/scripts/build.sh +24 -5
  59. package/scripts/check-l10n.mjs +168 -0
  60. package/scripts/configure-updater.mjs +4 -3
  61. package/scripts/doctor.mjs +470 -0
  62. package/scripts/i18n.mjs +122 -0
  63. package/scripts/i18n.zsh +66 -0
  64. package/scripts/install-app.sh +3 -2
  65. package/scripts/install-claude-hooks.mjs +22 -27
  66. package/scripts/install-codex-hooks.mjs +10 -15
  67. package/scripts/install-shell-integration.sh +6 -5
  68. package/scripts/integration-markers.mjs +51 -0
  69. package/scripts/locales/zh-Hans.json +366 -0
  70. package/scripts/pet-store.mjs +47 -45
  71. package/scripts/uninstall-app.sh +4 -3
  72. package/scripts/uninstall-integrations.mjs +24 -51
  73. package/scripts/uninstall-shell-integration.sh +8 -7
  74. /package/Resources/{phrases.default.txt → phrases.default.zh-Hans.txt} +0 -0
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ // 多语言自检。源码里写英文原文,它就是各语言表的 key:
3
+ // - App:L(@"…")(见 Sources/CCPets/CCPetsL10n.h)↔ Resources/<语言>.lproj/Localizable.strings
4
+ // - CLI:Node 的 t("…")(见 scripts/i18n.mjs)和 zsh 的 cc_pets_t "…"(见 scripts/i18n.zsh)
5
+ // ↔ scripts/locales/<语言>.json
6
+ // 改了英文原文却忘了改表,那种语言的界面就会漏出英文,而且不报任何错。这里把每种语言的表
7
+ // 都和源码逐条对上(有几张表就查几张,加语言不用改这里):
8
+ // - 缺翻译:代码里有、表里没有 → 失败
9
+ // - 多余:表里有、代码里已经没有 → 失败(多半是英文原文改过了,旧 key 成了孤儿)
10
+ // - 占位符对不上:%@ / %ld / {name} 的个数或名字不一致 → 失败
11
+ // - App 表缺元信息(语言名、Release 段落标题)→ 失败
12
+ // - App 和 CLI 支持的语言不一致 → 失败
13
+ //
14
+ // node scripts/check-l10n.mjs 检查,有问题时退出码 1
15
+ // node scripts/check-l10n.mjs --missing <语言> 只把这种语言缺的 key 按 JSON 打出来,方便补表
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ import { execFileSync } from "node:child_process";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ const projectDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
22
+ const sourceDir = path.join(projectDir, "Sources", "CCPets");
23
+ const resourcesDir = path.join(projectDir, "Resources");
24
+ const localesDir = path.join(projectDir, "scripts", "locales");
25
+ // 与 CCPetsL10n.h 里的 CCPetsLanguageNameKey / CCPetsReleaseNotesSectionKey 一致。
26
+ const APP_META_KEYS = ["Language Name", "Release Notes Section"];
27
+ const SKIPPED_SCRIPTS = new Set(["check-l10n.mjs", "i18n.mjs", "i18n.zsh"]);
28
+
29
+ function unescapeC(text) {
30
+ return text.replace(/\\(["\\nt])/g, (_, ch) => ({ n: "\n", t: "\t" })[ch] ?? ch);
31
+ }
32
+
33
+ function lineOf(text, index) {
34
+ return text.slice(0, index).split("\n").length;
35
+ }
36
+
37
+ // L(@"a" "b" @"c") 这类跨行拼接也算一个 key。
38
+ function objcKeys() {
39
+ const keys = new Map();
40
+ const call = /\bL\(\s*((?:@?"(?:[^"\\]|\\.)*"\s*)+)\)/g;
41
+ const piece = /@?"((?:[^"\\]|\\.)*)"/g;
42
+ for (const name of fs.readdirSync(sourceDir).filter((file) => file.endsWith(".m")).sort()) {
43
+ const text = fs.readFileSync(path.join(sourceDir, name), "utf8");
44
+ for (const match of text.matchAll(call)) {
45
+ const key = [...match[1].matchAll(piece)].map((part) => unescapeC(part[1])).join("");
46
+ if (!keys.has(key)) keys.set(key, `${name}:${lineOf(text, match.index)}`);
47
+ }
48
+ }
49
+ return keys;
50
+ }
51
+
52
+ function walk(dir) {
53
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
54
+ const full = path.join(dir, entry.name);
55
+ if (entry.isDirectory()) return entry.name === "locales" ? [] : walk(full);
56
+ return [full];
57
+ });
58
+ }
59
+
60
+ // Node 端只认 t("…") / t('…') / t(`…`)(模板串里不许有 ${}),第一个参数必须是字面量。
61
+ // zsh 端只认 cc_pets_t "…",第一个参数必须是不含变量的双引号字面量。
62
+ function cliKeys() {
63
+ const keys = new Map();
64
+ const nodeCall = /\bt\(\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\$]|\\.)*`)/g;
65
+ const zshCall = /\bcc_pets_t\s+"((?:[^"\\$`]|\\.)*)"/g;
66
+ const files = [...walk(path.join(projectDir, "scripts")), ...walk(path.join(projectDir, "bin"))]
67
+ .filter((file) => !SKIPPED_SCRIPTS.has(path.basename(file)))
68
+ .sort();
69
+ for (const file of files) {
70
+ const text = fs.readFileSync(file, "utf8");
71
+ const relative = path.relative(projectDir, file);
72
+ const node = /\.(mjs|js)$/.test(file);
73
+ for (const match of text.matchAll(node ? nodeCall : zshCall)) {
74
+ const key = node
75
+ ? unescapeC(match[1].slice(1, -1).replace(/\\'/g, "'").replace(/\\`/g, "`"))
76
+ : match[1].replace(/\\(["\\$`])/g, "$1");
77
+ if (!keys.has(key)) keys.set(key, `${relative}:${lineOf(text, match.index)}`);
78
+ }
79
+ }
80
+ return keys;
81
+ }
82
+
83
+ function readStrings(file) {
84
+ return JSON.parse(execFileSync("/usr/bin/plutil", ["-convert", "json", "-o", "-", file], {
85
+ encoding: "utf8"
86
+ }));
87
+ }
88
+
89
+ // %1$@ 和 %@ 视为同一个占位符,只比较类型的多重集合;{name} 比较名字的集合。
90
+ function placeholders(text) {
91
+ const printf = [...text.matchAll(/%(?:\d+\$)?(?:[-+ #0]*\d*(?:\.\d+)?)(l{0,2}[dufsx@]|%)/g)]
92
+ .map((match) => match[1]).filter((type) => type !== "%").sort();
93
+ const slots = [...text.matchAll(/\{([A-Za-z][A-Za-z0-9]*)\}/g)].map((match) => match[1]).sort();
94
+ return JSON.stringify([printf, [...new Set(slots)]]);
95
+ }
96
+
97
+ function check(label, keys, table, metaKeys = []) {
98
+ const problems = [];
99
+ const missing = {};
100
+ for (const key of metaKeys) {
101
+ if (!String(table[key] ?? "").trim()) problems.push(`${label} 缺元信息: ${JSON.stringify(key)}`);
102
+ }
103
+ for (const [key, where] of keys) {
104
+ if (!(key in table)) {
105
+ problems.push(`${label} 缺翻译 (${where}): ${JSON.stringify(key)}`);
106
+ missing[key] = "";
107
+ } else if (placeholders(key) !== placeholders(table[key])) {
108
+ problems.push(`${label} 占位符不一致 (${where}): ${JSON.stringify(key)} → ${JSON.stringify(table[key])}`);
109
+ }
110
+ }
111
+ for (const key of Object.keys(table)) {
112
+ if (!keys.has(key) && !metaKeys.includes(key)) problems.push(`${label} 多余的条目: ${JSON.stringify(key)}`);
113
+ }
114
+ return { problems, missing };
115
+ }
116
+
117
+ const appLanguages = fs.readdirSync(resourcesDir)
118
+ .filter((entry) => entry.endsWith(".lproj"))
119
+ .filter((entry) => fs.existsSync(path.join(resourcesDir, entry, "Localizable.strings")))
120
+ .map((entry) => entry.slice(0, -".lproj".length))
121
+ .sort();
122
+ const cliLanguages = fs.readdirSync(localesDir)
123
+ .filter((entry) => entry.endsWith(".json"))
124
+ .map((entry) => entry.slice(0, -".json".length))
125
+ .sort();
126
+
127
+ const appKeys = objcKeys();
128
+ const scriptKeys = cliKeys();
129
+ const results = {};
130
+ for (const language of appLanguages) {
131
+ results[`App ${language}`] = check(`App ${language}`, appKeys,
132
+ readStrings(path.join(resourcesDir, `${language}.lproj`, "Localizable.strings")), APP_META_KEYS);
133
+ }
134
+ for (const language of cliLanguages) {
135
+ results[`CLI ${language}`] = check(`CLI ${language}`, scriptKeys,
136
+ JSON.parse(fs.readFileSync(path.join(localesDir, `${language}.json`), "utf8")));
137
+ }
138
+
139
+ const missingIndex = process.argv.indexOf("--missing");
140
+ if (missingIndex >= 0) {
141
+ const language = process.argv[missingIndex + 1];
142
+ if (!language) {
143
+ console.error("用法: check-l10n.mjs --missing <语言>");
144
+ process.exit(2);
145
+ }
146
+ // 还没建表的新语言:缺的就是全部 key。
147
+ const all = (keys) => Object.fromEntries([...keys.keys()].map((key) => [key, ""]));
148
+ const app = results[`App ${language}`]?.missing ?? all(appKeys);
149
+ const cli = results[`CLI ${language}`]?.missing ?? all(scriptKeys);
150
+ process.stdout.write(`${JSON.stringify({ app, cli }, null, 2)}\n`);
151
+ process.exit(0);
152
+ }
153
+
154
+ const problems = [];
155
+ // App 和 CLI 支持的语言要一致,否则切到某种语言后桌宠和终端各说各的。
156
+ for (const language of appLanguages) {
157
+ if (!cliLanguages.includes(language)) problems.push(`缺 scripts/locales/${language}.json(App 已支持 ${language})`);
158
+ }
159
+ for (const language of cliLanguages) {
160
+ if (!appLanguages.includes(language)) problems.push(`缺 Resources/${language}.lproj/Localizable.strings(CLI 已支持 ${language})`);
161
+ }
162
+ for (const result of Object.values(results)) problems.push(...result.problems);
163
+ if (problems.length > 0) {
164
+ for (const problem of problems) console.error(problem);
165
+ console.error(`\n共 ${problems.length} 处多语言问题。`);
166
+ process.exit(1);
167
+ }
168
+ console.log(`多语言检查通过(en 为源语言,另有 ${appLanguages.join("、")})。`);
@@ -3,12 +3,13 @@
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { t } from "./i18n.mjs";
6
7
 
7
8
  const nodeCandidate = process.env.npm_node_execpath || process.execPath;
8
9
  const npmCandidate = process.env.npm_execpath;
9
10
 
10
11
  if (!nodeCandidate || !npmCandidate) {
11
- console.warn("未记录自动更新配置:npm 没有提供 node/npm-cli 路径。");
12
+ console.warn(t("Auto-update config not saved: npm didn't provide the node/npm-cli paths."));
12
13
  process.exit(0);
13
14
  }
14
15
 
@@ -18,12 +19,12 @@ try {
18
19
  nodePath = fs.realpathSync(nodeCandidate);
19
20
  npmCliPath = fs.realpathSync(npmCandidate);
20
21
  } catch {
21
- console.warn("未记录自动更新配置:node/npm-cli 路径不存在。");
22
+ console.warn(t("Auto-update config not saved: the node/npm-cli paths don't exist."));
22
23
  process.exit(0);
23
24
  }
24
25
 
25
26
  if (!path.isAbsolute(nodePath) || !path.isAbsolute(npmCliPath)) {
26
- console.warn("未记录自动更新配置:node/npm-cli 路径不是绝对路径。");
27
+ console.warn(t("Auto-update config not saved: the node/npm-cli paths aren't absolute."));
27
28
  process.exit(0);
28
29
  }
29
30
 
@@ -0,0 +1,470 @@
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
+ import { t } from "./i18n.mjs";
25
+
26
+ const projectDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
27
+ const petBinary = path.join(projectDir, ".build/release/cc-pets");
28
+ const packageVersion = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).version;
29
+ const home = os.homedir();
30
+ const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
31
+ const codexHome = process.env.CODEX_HOME || path.join(home, ".codex");
32
+ const shimDirectory = path.resolve(process.env.CC_PETS_SHIM_DIR || path.join(home, ".cc-pets/shims"));
33
+ const shellRC = path.join(process.env.ZDOTDIR || home, ".zshrc");
34
+ const installedApp = path.join(process.env.CC_PETS_APPLICATIONS_DIR || path.join(home, "Applications"), "CC Pets.app");
35
+
36
+ const tilde = (value) => {
37
+ if (typeof value !== "string") return value;
38
+ if (value === home) return "~";
39
+ return value.startsWith(`${home}/`) ? `~${value.slice(home.length)}` : value;
40
+ };
41
+
42
+ const run = (executable, args) => {
43
+ try {
44
+ return execFileSync(executable, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 });
45
+ } catch {
46
+ return null;
47
+ }
48
+ };
49
+
50
+ const nativePaths = () => {
51
+ const output = fs.existsSync(petBinary) ? run(petBinary, ["--paths"]) : null;
52
+ try {
53
+ return output ? JSON.parse(output) : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ };
58
+
59
+ const sizeOf = (target) => {
60
+ let stats;
61
+ try {
62
+ stats = fs.lstatSync(target);
63
+ } catch {
64
+ return null;
65
+ }
66
+ if (!stats.isDirectory()) return stats.size;
67
+ let total = 0;
68
+ for (const entry of fs.readdirSync(target)) total += sizeOf(path.join(target, entry)) ?? 0;
69
+ return total;
70
+ };
71
+
72
+ const formatSize = (bytes) => {
73
+ if (bytes === null) return t("missing");
74
+ if (bytes < 1024) return `${bytes} B`;
75
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
76
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
77
+ };
78
+
79
+ // 终端里中文占两列,按 length 对齐会错位。
80
+ const displayWidth = (text) => [...text].reduce((width, character) =>
81
+ width + (/[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(character) ? 2 : 1), 0);
82
+
83
+ const readJson = (file) => {
84
+ try {
85
+ return { value: JSON.parse(fs.readFileSync(file, "utf8")) };
86
+ } catch (error) {
87
+ return { error: error.code === "ENOENT" ? "missing" : "invalid" };
88
+ }
89
+ };
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // cc-pets paths
93
+
94
+ const pathGroups = (native) => {
95
+ const ccPetsHome = bridgeHomeDirectory();
96
+ const groups = [
97
+ {
98
+ title: t("Settings (removed by --purge)"),
99
+ items: native ? [[t("Preferences"), native.preferences]] : []
100
+ },
101
+ {
102
+ title: t("Your content (kept by both clean and --purge)"),
103
+ items: [
104
+ ...(native ? [
105
+ [t("Pet sprites"), native.pets],
106
+ [t("Shared lines"), native.phrases],
107
+ [t("Per-pet lines"), native.petPhrases]
108
+ ] : []),
109
+ [t("CC Bridge switch"), path.join(ccPetsHome, "bridge-enabled")],
110
+ ["codex / claude shim", shimDirectory]
111
+ ]
112
+ },
113
+ {
114
+ title: t("App data (removed by --purge; clean only clears the token cache and update log)"),
115
+ items: native ? [
116
+ [t("App data directory"), native.applicationSupport],
117
+ [t("Quota history"), native.quotaHistory],
118
+ [t("Auto-update config"), path.join(native.applicationSupport, "updater.json")]
119
+ ] : []
120
+ },
121
+ {
122
+ title: t("Caches and runtime state (cleared by clean; safe to lose)"),
123
+ items: [
124
+ ...(native ? [
125
+ [t("Pet store manifest cache"), native.petStoreCache],
126
+ [t("Agent event stream"), native.agentEvents],
127
+ [t("Claude quota snapshot"), native.claudeUsage],
128
+ [t("Codex live quota"), native.codexLiveUsage],
129
+ [t("Codex launch records"), native.codexLaunches],
130
+ [t("Online client records"), native.clients]
131
+ ] : []),
132
+ [t("CC Bridge state directory"), bridgeDirectory()]
133
+ ]
134
+ },
135
+ {
136
+ title: t("Program and integrations"),
137
+ items: [
138
+ [t("npm package"), projectDir],
139
+ [t("Installed app"), installedApp],
140
+ [t("Claude Code settings"), path.join(claudeHome, "settings.json")],
141
+ ["Codex Hooks", path.join(codexHome, "hooks.json")],
142
+ [t("Shell config"), shellRC]
143
+ ]
144
+ }
145
+ ];
146
+ return groups.filter((group) => group.items.length > 0);
147
+ };
148
+
149
+ const printPaths = (asJson) => {
150
+ const native = nativePaths();
151
+ const groups = pathGroups(native);
152
+ if (asJson) {
153
+ const document = {
154
+ version: packageVersion,
155
+ running: native?.running ?? null,
156
+ groups: groups.map((group) => ({
157
+ title: group.title,
158
+ items: group.items.map(([label, target]) => ({ label, path: tilde(target), bytes: sizeOf(target) }))
159
+ }))
160
+ };
161
+ console.log(JSON.stringify(document, null, 2));
162
+ return 0;
163
+ }
164
+ if (!native) {
165
+ console.log(t(`⚠️ The native binary isn't built or can't run, so the pet's own data paths are unknown; run cc-pets install and try again.
166
+ `));
167
+ }
168
+ const width = Math.max(...groups.flatMap((group) => group.items.map(([label]) => displayWidth(label))));
169
+ groups.forEach((group, index) => {
170
+ if (index > 0) console.log("");
171
+ console.log(group.title);
172
+ for (const [label, target] of group.items) {
173
+ console.log(` ${label}${" ".repeat(width - displayWidth(label) + 2)}${tilde(target)} (${formatSize(sizeOf(target))})`);
174
+ }
175
+ });
176
+ return 0;
177
+ };
178
+
179
+ // ---------------------------------------------------------------------------
180
+ // cc-pets doctor
181
+
182
+ const ICONS = { ok: "✅", warn: "⚠️ ", fail: "❌", info: "ℹ️ " };
183
+
184
+ const versionOfApp = (appPath) => {
185
+ const plist = path.join(appPath, "Contents/Info.plist");
186
+ if (!fs.existsSync(plist)) return null;
187
+ return (run("/usr/bin/plutil", ["-extract", "CFBundleShortVersionString", "raw", "-o", "-", plist]) || "").trim() || null;
188
+ };
189
+
190
+ // 认出配置里属于 CC Pets 的 hook,并区分"指向当前安装"和"指向别处"(包被挪走、换了 node 版本重装后
191
+ // 常见,hook 每次触发都会失败)。
192
+ const inspectHooks = (configFile, signature, legacySignature) => {
193
+ const { value, error } = readJson(configFile);
194
+ if (error === "invalid") return { error: "invalid" };
195
+ const commands = Object.values(value?.hooks ?? {})
196
+ .filter(Array.isArray).flat()
197
+ .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
198
+ .map((handler) => handler?.command);
199
+ const managed = commands.filter((command) => isManagedHookCommand(command, signature));
200
+ const current = managed.filter((command) => command.includes(`'${petBinary}'`));
201
+ return {
202
+ total: managed.length,
203
+ stale: managed.length - current.length,
204
+ legacy: commands.filter((command) => isManagedHookCommand(command, legacySignature)).length,
205
+ bridge: commands.filter((command) => typeof command === "string" && command.startsWith(HOOK_MARKER)).length
206
+ };
207
+ };
208
+
209
+ const hookChecks = (name, configFile, signature, legacySignature) => {
210
+ const hooks = inspectHooks(configFile, signature, legacySignature);
211
+ if (hooks.error) {
212
+ return {
213
+ results: [{ level: "fail", title: t("Can't parse {name} config: {configFile}", { name, configFile: tilde(configFile) }), fix: t("Fix that JSON file, then run cc-pets install") }],
214
+ bridgeHooks: 0
215
+ };
216
+ }
217
+ const results = [];
218
+ if (hooks.total === 0) {
219
+ results.push({ level: "fail", title: t("{name} hooks not installed", { name }), fix: "cc-pets install" });
220
+ } else if (hooks.stale > 0) {
221
+ results.push({
222
+ level: "warn",
223
+ title: hooks.stale !== 1
224
+ ? t("{stale} {name} hooks point to cc-pets elsewhere (the package was moved or reinstalled)", { name, stale: hooks.stale })
225
+ : t("{stale} {name} hook points to cc-pets elsewhere (the package was moved or reinstalled)", { name, stale: hooks.stale }),
226
+ fix: "cc-pets install"
227
+ });
228
+ } else {
229
+ results.push({ level: "ok", title: t("{name} hooks installed ({total} events)", { name, total: hooks.total }) });
230
+ }
231
+ if (hooks.legacy > 0) {
232
+ results.push({
233
+ level: "warn",
234
+ title: hooks.legacy !== 1
235
+ ? t("{name} config still has {legacy} old codex-pet hooks", { name, legacy: hooks.legacy })
236
+ : t("{name} config still has {legacy} old codex-pet hook", { name, legacy: hooks.legacy }),
237
+ fix: "cc-pets install"
238
+ });
239
+ }
240
+ return { results, bridgeHooks: hooks.bridge };
241
+ };
242
+
243
+ const statusLineCheck = () => {
244
+ const { value } = readJson(path.join(claudeHome, "settings.json"));
245
+ const command = typeof value?.statusLine?.command === "string" ? value.statusLine.command : "";
246
+ if (isManagedStatusLine(command, STATUS_LINE_MARKER)) {
247
+ return { level: "ok", title: t("Claude status line feeds quota data through the wrapper") };
248
+ }
249
+ const script = resolveStatusLineScript(command);
250
+ let content = "";
251
+ try {
252
+ content = script ? fs.readFileSync(script, "utf8") : "";
253
+ } catch {
254
+ content = "";
255
+ }
256
+ if (content.includes(STATUS_LINE_START_MARKER)) {
257
+ return content.includes(`'${petBinary}'`)
258
+ ? { level: "ok", title: t("Claude status line feeds quota data ({script})", { script: tilde(script) }) }
259
+ : { level: "warn", title: t("The quota hook in the Claude status line points to cc-pets elsewhere"), fix: "cc-pets install" };
260
+ }
261
+ return {
262
+ level: "warn",
263
+ title: command ? t("Claude status line doesn't feed quota data, so the pet can't show Claude quota %") : t("No Claude status line configured, so the pet can't show Claude quota %"),
264
+ fix: "cc-pets install"
265
+ };
266
+ };
267
+
268
+ const shimChecks = () => {
269
+ const results = [];
270
+ let rc = "";
271
+ try {
272
+ rc = fs.readFileSync(shellRC, "utf8");
273
+ } catch {
274
+ rc = "";
275
+ }
276
+ results.push(rc.includes(SHIM_START_MARKER)
277
+ ? { level: "ok", title: t("{shellRC} adds the shim directory", { shellRC: tilde(shellRC) }) }
278
+ : { level: "fail", title: t("{shellRC} has no CC Pets shim setup", { shellRC: tilde(shellRC) }), fix: "cc-pets install" });
279
+
280
+ const broken = [];
281
+ for (const name of ["codex", "claude"]) {
282
+ const shim = path.join(shimDirectory, name);
283
+ let link = null;
284
+ try {
285
+ link = fs.readlinkSync(shim);
286
+ } catch {
287
+ broken.push(t("{name} (missing)", { name }));
288
+ continue;
289
+ }
290
+ if (!fs.existsSync(path.resolve(shimDirectory, link))) broken.push(t("{name} (target doesn't exist)", { name }));
291
+ }
292
+ results.push(broken.length === 0
293
+ ? { level: "ok", title: t("Shims complete: {shimDirectory}", { shimDirectory: tilde(shimDirectory) }) }
294
+ : { level: "warn", title: t("Shim problems: {broken}", { broken: broken.join(t(", ")) }), fix: "cc-pets install" });
295
+
296
+ const entries = (process.env.PATH || "").split(path.delimiter).filter(Boolean).map((entry) => path.resolve(entry));
297
+ const index = entries.indexOf(shimDirectory);
298
+ if (index < 0) {
299
+ results.push({ level: "warn", title: t("This terminal's PATH lacks the shim directory, so typing codex / claude won't start the pet"), fix: t("source {shellRC}, or open a new terminal", { shellRC: tilde(shellRC) }) });
300
+ } else if (index > 0) {
301
+ const shadowing = entries.slice(0, index).find((entry) =>
302
+ ["codex", "claude"].some((name) => fs.existsSync(path.join(entry, name))));
303
+ results.push(shadowing
304
+ ? { level: "warn", title: t("{shadowing} comes before the shim directory in PATH and bypasses the pet", { shadowing: tilde(shadowing) }), fix: t("source {shellRC}, or open a new terminal", { shellRC: tilde(shellRC) }) }
305
+ : { level: "ok", title: t("The shim directory comes before the real codex / claude in PATH") });
306
+ } else {
307
+ results.push({ level: "ok", title: t("The shim directory is first in PATH") });
308
+ }
309
+ return results;
310
+ };
311
+
312
+ const realBinaryCheck = (name, variable) => {
313
+ const real = resolveRealExecutable(name, variable);
314
+ return real && fs.existsSync(real)
315
+ ? { level: "ok", title: t("Found the real {name}: {real}", { name, real: tilde(real) }) }
316
+ : { level: "warn", title: t("The real {name} isn't in PATH, so the shim can't forward to it", { name }), fix: `export ${variable}=/absolute/path/to/${name}` };
317
+ };
318
+
319
+ const updaterCheck = (native) => {
320
+ if (!native) return null;
321
+ const file = path.join(native.applicationSupport, "updater.json");
322
+ const { value, error } = readJson(file);
323
+ if (error) {
324
+ return { level: "warn", title: t("Auto-update isn't configured, so in-app updates won't work"), fix: "npm install -g cc-pets@latest --allow-scripts=cc-pets" };
325
+ }
326
+ const missing = ["nodePath", "npmCliPath"].filter((key) => !value?.[key] || !fs.existsSync(value[key]));
327
+ return missing.length === 0
328
+ ? { level: "ok", title: t("Auto-update config is valid") }
329
+ : { level: "warn", title: t("The {missing} recorded for auto-update no longer exist (changed Node versions?)", { missing: missing.join(t(", ")) }), fix: "npm install -g cc-pets@latest --allow-scripts=cc-pets" };
330
+ };
331
+
332
+ const formatAge = (milliseconds) => {
333
+ const minutes = Math.round(milliseconds / 60_000);
334
+ if (minutes < 60) return t("{minutes} min ago", { minutes });
335
+ const hours = Math.round(minutes / 60);
336
+ return hours < 48 ? t("{hours} h ago", { hours }) : t("{days} days ago", { days: Math.round(hours / 24) });
337
+ };
338
+
339
+ const runDoctor = () => {
340
+ const native = nativePaths();
341
+ const sections = [];
342
+ const claudeDetected = detectClaudeCLI();
343
+ const codexDetected = detectCodexCLI();
344
+
345
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
346
+ const program = [
347
+ nodeMajor >= 18
348
+ ? { level: "ok", title: `Node.js ${process.versions.node}` }
349
+ : { level: "fail", title: t("Node.js {node} is too old; 18 or later is required", { node: process.versions.node }) },
350
+ { level: "info", title: t("npm package {packageVersion}: {projectDir}", { packageVersion, projectDir: tilde(projectDir) }) }
351
+ ];
352
+ const binaryVersion = fs.existsSync(petBinary) ? (run(petBinary, ["--version"]) || "").trim().replace(/^cc-pets\s+/, "") : null;
353
+ if (!binaryVersion) {
354
+ program.push({ level: "fail", title: t("Native binary isn't built or can't run"), fix: "cc-pets install" });
355
+ } else if (binaryVersion !== packageVersion) {
356
+ program.push({ level: "warn", title: t("Native binary {binaryVersion} doesn't match npm package {packageVersion}", { binaryVersion, packageVersion }), fix: "cc-pets install" });
357
+ } else {
358
+ program.push({ level: "ok", title: t("Native binary {binaryVersion}", { binaryVersion }) });
359
+ }
360
+ const appVersion = versionOfApp(installedApp);
361
+ if (!appVersion) {
362
+ program.push({ level: "warn", title: t("Installed app not found: {installedApp}", { installedApp: tilde(installedApp) }), fix: "cc-pets install" });
363
+ } else if (appVersion !== packageVersion) {
364
+ program.push({ level: "warn", title: t("Installed app {appVersion} doesn't match npm package {packageVersion}", { appVersion, packageVersion }), fix: "cc-pets install" });
365
+ } else {
366
+ program.push({ level: "ok", title: t("Installed app {appVersion}", { appVersion }) });
367
+ }
368
+ if (native) program.push({ level: "info", title: native.running ? t("The pet is running") : t("The pet isn't running") });
369
+ const updater = updaterCheck(native);
370
+ if (updater) program.push(updater);
371
+ sections.push({ title: t("Program"), results: program });
372
+
373
+ let claudeBridgeHooks = 0;
374
+ if (claudeDetected) {
375
+ const { results, bridgeHooks } = hookChecks("Claude Code", path.join(claudeHome, "settings.json"), CLAUDE_HOOK, LEGACY_CLAUDE_HOOK);
376
+ claudeBridgeHooks = bridgeHooks;
377
+ const claude = [...results, statusLineCheck()];
378
+ if (native) {
379
+ let modified = null;
380
+ try {
381
+ modified = fs.statSync(native.claudeUsage).mtimeMs;
382
+ } catch {
383
+ modified = null;
384
+ }
385
+ claude.push(modified
386
+ ? { level: "info", title: t("Claude quota snapshot updated {age}", { age: formatAge(Date.now() - modified) }) }
387
+ : { level: "info", title: t("No Claude quota snapshot yet (created after Claude Code's first API response)") });
388
+ }
389
+ sections.push({ title: "Claude Code", results: claude });
390
+ } else {
391
+ sections.push({ title: "Claude Code", results: [{ level: "info", title: t("Claude Code CLI not detected, skipped") }] });
392
+ }
393
+
394
+ let codexBridgeHooks = 0;
395
+ if (codexDetected) {
396
+ const { results, bridgeHooks } = hookChecks("Codex", path.join(codexHome, "hooks.json"), CODEX_HOOK, LEGACY_CODEX_HOOK);
397
+ codexBridgeHooks = bridgeHooks;
398
+ sections.push({
399
+ title: "Codex",
400
+ results: [
401
+ ...results,
402
+ { level: "info", title: t("Codex only runs CC Pets hooks after you trust them in /hooks (can't be checked automatically)") }
403
+ ]
404
+ });
405
+ } else {
406
+ sections.push({ title: "Codex", results: [{ level: "info", title: t("Codex CLI not detected, skipped") }] });
407
+ }
408
+
409
+ sections.push({
410
+ title: t("Shell integration"),
411
+ results: [
412
+ ...shimChecks(),
413
+ ...(codexDetected ? [realBinaryCheck("codex", "CODEX_REAL_BIN")] : []),
414
+ ...(claudeDetected ? [realBinaryCheck("claude", "CLAUDE_REAL_BIN")] : [])
415
+ ]
416
+ });
417
+
418
+ if (!isBridgeEnabled()) {
419
+ sections.push({ title: "CC Bridge", results: [{ level: "info", title: t("Off (optional; turn on with cc-pets bridge enable)") }] });
420
+ } else {
421
+ const bridge = [{ level: "ok", title: t("Enabled") }];
422
+ if (claudeDetected) {
423
+ bridge.push(claudeBridgeHooks > 0
424
+ ? { level: "ok", title: t("CC Bridge hooks installed in Claude Code") }
425
+ : { level: "warn", title: t("CC Bridge hooks missing in Claude Code"), fix: "cc-pets bridge enable" });
426
+ }
427
+ if (codexDetected) {
428
+ bridge.push(codexBridgeHooks > 0
429
+ ? { level: "ok", title: t("CC Bridge hooks installed in Codex") }
430
+ : { level: "warn", title: t("CC Bridge hooks missing in Codex"), fix: "cc-pets bridge enable" });
431
+ if (currentOptions().wake) {
432
+ const notice = describeCodexQueue(probeCodexQueue());
433
+ bridge.push(notice
434
+ ? { level: "warn", title: notice }
435
+ : { level: "ok", title: t("Codex supports codex queue, so it can be woken automatically") });
436
+ }
437
+ }
438
+ sections.push({ title: "CC Bridge", results: bridge });
439
+ }
440
+
441
+ console.log(t("CC Pets diagnostics (npm package {packageVersion}, {platform} {release})", { packageVersion, platform: os.platform(), release: os.release() }));
442
+ const counts = { ok: 0, warn: 0, fail: 0, info: 0 };
443
+ for (const section of sections) {
444
+ console.log(`\n${section.title}`);
445
+ for (const result of section.results) {
446
+ counts[result.level] += 1;
447
+ console.log(` ${ICONS[result.level]} ${result.title}`);
448
+ if (result.fix) console.log(` → ${result.fix}`);
449
+ }
450
+ }
451
+ const warnings = counts.warn !== 1
452
+ ? t("{count} warnings", { count: counts.warn }) : t("{count} warning", { count: counts.warn });
453
+ const errors = counts.fail !== 1
454
+ ? t("{count} errors", { count: counts.fail }) : t("{count} error", { count: counts.fail });
455
+ console.log(t("\nResult: {ok} OK, {warnings}, {errors}.", { ok: counts.ok, warnings, errors }));
456
+ if (counts.fail + counts.warn > 0) console.log(t("Most problems are fixed by cc-pets install; see cc-pets paths for data locations."));
457
+ return counts.fail > 0 ? 1 : 0;
458
+ };
459
+
460
+ // ---------------------------------------------------------------------------
461
+
462
+ const [command, ...args] = process.argv.slice(2);
463
+ if (command === "paths") {
464
+ process.exitCode = printPaths(args.includes("--json"));
465
+ } else if (command === "doctor") {
466
+ process.exitCode = runDoctor();
467
+ } else {
468
+ console.error(t("Usage: doctor.mjs paths [--json] | doctor"));
469
+ process.exitCode = 2;
470
+ }