cc-pets 2.2.0 → 2.3.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 (173) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +85 -0
  4. package/CHANGELOG.zh-CN.md +85 -0
  5. package/CONTRIBUTING.md +28 -11
  6. package/CONTRIBUTING.zh-CN.md +23 -11
  7. package/README.md +127 -27
  8. package/README.zh-CN.md +104 -30
  9. package/Resources/zh-Hans.lproj/Localizable.strings +573 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +89 -31
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +18 -4
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +90 -21
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +269 -0
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +13 -7
  19. package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +71 -47
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +16 -2
  22. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +110 -12
  23. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  24. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  25. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  26. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  27. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  37. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  39. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  43. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  44. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  45. package/Sources/CCPets/Pet/CCPetsImageLoader.h +5 -0
  46. package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +10 -2
  47. package/Sources/CCPets/Pet/CCPetsPetSize.h +10 -0
  48. package/Sources/CCPets/Pet/CCPetsPetSize.m +21 -0
  49. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  50. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  51. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +18 -2
  52. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +53 -22
  53. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +42 -2
  54. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  55. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  56. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  57. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  58. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  59. package/Sources/CCPets/Pet/PetView.m +635 -0
  60. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  61. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  62. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  63. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  64. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  65. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  67. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  68. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  69. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  70. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  71. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  72. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  73. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  74. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  75. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  76. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  77. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  78. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  79. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  80. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  81. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  82. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  83. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  84. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  85. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  86. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  87. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  88. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  89. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  90. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  91. package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +3 -0
  92. package/Sources/CCPets/UI/MenuPetSizeView.h +5 -0
  93. package/Sources/CCPets/UI/MenuPetSizeView.m +73 -0
  94. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  95. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  96. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  97. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  98. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  99. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  100. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  101. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  102. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  103. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  104. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  105. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  106. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  107. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  108. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  109. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  110. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  111. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  112. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  113. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  114. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  115. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  116. package/THIRD_PARTY_NOTICES.md +1 -1
  117. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  118. package/bin/cc-pets +8 -6
  119. package/bin/claude-with-pet +10 -2
  120. package/bin/codex-with-pet +13 -5
  121. package/package.json +1 -1
  122. package/scripts/build.sh +7 -3
  123. package/scripts/i18n.zsh +9 -52
  124. package/scripts/install-app.sh +4 -0
  125. package/scripts/install-shell-integration.sh +17 -10
  126. package/scripts/uninstall-shell-integration.sh +6 -1
  127. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +0 -226
  128. package/Sources/CCPets/CCPetsEvents.h +0 -10
  129. package/Sources/CCPets/CCPetsImageLoader.h +0 -4
  130. package/Sources/CCPets/CCPetsUsage.h +0 -36
  131. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  132. package/Sources/CCPets/PetView.m +0 -1806
  133. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  134. package/scripts/bridge/cli.mjs +0 -237
  135. package/scripts/bridge/core.mjs +0 -228
  136. package/scripts/bridge/hook.mjs +0 -150
  137. package/scripts/bridge/install.mjs +0 -311
  138. package/scripts/bridge/mcp-server.mjs +0 -308
  139. package/scripts/bridge/options.mjs +0 -87
  140. package/scripts/bridge/process.mjs +0 -151
  141. package/scripts/bridge/reservations.mjs +0 -248
  142. package/scripts/bridge/store.mjs +0 -433
  143. package/scripts/bridge/watch.mjs +0 -69
  144. package/scripts/check-l10n.mjs +0 -168
  145. package/scripts/configure-updater.mjs +0 -43
  146. package/scripts/detect-cli.mjs +0 -68
  147. package/scripts/doctor.mjs +0 -470
  148. package/scripts/i18n.mjs +0 -122
  149. package/scripts/install-claude-hooks.mjs +0 -253
  150. package/scripts/install-codex-hooks.mjs +0 -78
  151. package/scripts/integration-markers.mjs +0 -51
  152. package/scripts/locales/zh-Hans.json +0 -366
  153. package/scripts/pet-store.mjs +0 -415
  154. package/scripts/uninstall-integrations.mjs +0 -205
  155. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  156. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  157. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  159. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  161. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  162. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  163. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  164. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  165. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  166. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  167. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  168. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  169. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  170. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  171. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  172. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  173. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
package/scripts/i18n.mjs DELETED
@@ -1,122 +0,0 @@
1
- // Node 端(cc-pets 子命令、hook、CC Bridge)的多语言,和 App 端 CCPetsL10n 同一套约定:
2
- // 源码里写英文原文,它就是 scripts/locales/<语言>.json 的 key;英文直接原样输出。
3
- // 参数用 {name} 占位,第二个参数传 { name: 值 }。
4
- //
5
- // 支持哪些语言不写在代码里:英文之外,scripts/locales 下有 <语言>.json 的就算支持。
6
- //
7
- // 语言的来源依次是:
8
- // 1. CC_PETS_LANGUAGE(en / zh-Hans / zh…,测试和临时切换用)
9
- // 2. ~/.cc-pets/language(可用 CC_PETS_HOME 覆盖):桌宠把右键菜单里选定的语言写在这里,
10
- // 这样终端里的输出和桌宠界面是同一种语言
11
- // 3. LC_ALL / LC_MESSAGES / LANG,再退到 Intl 的默认 locale
12
- // 都匹配不上时用英文。匹配规则同 App:先比完整标识或前缀(zh-Hans-CN → zh-Hans),
13
- // 再只比主语言(zh_CN → zh-Hans、ja_JP → ja)。
14
- //
15
- // zsh 脚本通过命令行入口用同一套表:node i18n.mjs <英文原文> [name=value …],见 i18n.zsh。
16
- import fs from "node:fs";
17
- import os from "node:os";
18
- import path from "node:path";
19
- import { fileURLToPath } from "node:url";
20
-
21
- export const SOURCE_LANGUAGE = "en";
22
- const localesDirectory = path.join(path.dirname(fileURLToPath(import.meta.url)), "locales");
23
-
24
- let cachedSupported;
25
- export function supportedLanguages() {
26
- if (cachedSupported) return cachedSupported;
27
- let found = [];
28
- try {
29
- found = fs.readdirSync(localesDirectory)
30
- .filter((name) => name.endsWith(".json"))
31
- .map((name) => name.slice(0, -".json".length))
32
- .filter((language) => language !== SOURCE_LANGUAGE)
33
- .sort();
34
- } catch {
35
- found = [];
36
- }
37
- cachedSupported = [SOURCE_LANGUAGE, ...found];
38
- return cachedSupported;
39
- }
40
-
41
- // zh_CN.UTF-8 → zh-cn
42
- function normalizedTag(value) {
43
- return String(value || "").trim().toLowerCase().replace(/_/g, "-").split(".")[0];
44
- }
45
-
46
- export function matchLanguage(value, supported = supportedLanguages()) {
47
- const tag = normalizedTag(value);
48
- if (!tag || tag === "c" || tag === "posix") return "";
49
- const exact = supported.find((language) => {
50
- const lower = language.toLowerCase();
51
- return tag === lower || tag.startsWith(`${lower}-`);
52
- });
53
- if (exact) return exact;
54
- const base = tag.split("-")[0];
55
- return supported.find((language) => language.toLowerCase().split("-")[0] === base) || "";
56
- }
57
-
58
- function languageFromFile() {
59
- const home = process.env.CC_PETS_HOME || path.join(os.homedir(), ".cc-pets");
60
- try {
61
- return matchLanguage(fs.readFileSync(path.join(home, "language"), "utf8"));
62
- } catch {
63
- return "";
64
- }
65
- }
66
-
67
- function languageFromEnvironment() {
68
- for (const name of ["LC_ALL", "LC_MESSAGES", "LANG"]) {
69
- const language = matchLanguage(process.env[name]);
70
- if (language) return language;
71
- }
72
- try {
73
- return matchLanguage(Intl.DateTimeFormat().resolvedOptions().locale);
74
- } catch {
75
- return "";
76
- }
77
- }
78
-
79
- let cachedLanguage;
80
- export function currentLanguage() {
81
- if (cachedLanguage) return cachedLanguage;
82
- cachedLanguage = matchLanguage(process.env.CC_PETS_LANGUAGE) || languageFromFile() ||
83
- languageFromEnvironment() || SOURCE_LANGUAGE;
84
- return cachedLanguage;
85
- }
86
-
87
- const tables = new Map();
88
- function table(language) {
89
- if (!tables.has(language)) {
90
- try {
91
- tables.set(language, JSON.parse(fs.readFileSync(path.join(localesDirectory, `${language}.json`), "utf8")));
92
- } catch {
93
- tables.set(language, {});
94
- }
95
- }
96
- return tables.get(language);
97
- }
98
-
99
- function interpolate(text, values) {
100
- if (!values) return text;
101
- return text.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (match, name) =>
102
- Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : match);
103
- }
104
-
105
- export function translate(language, text, values) {
106
- const translated = language === SOURCE_LANGUAGE ? text : (table(language)[text] || text);
107
- return interpolate(translated, values);
108
- }
109
-
110
- export function t(text, values) {
111
- return translate(currentLanguage(), text, values);
112
- }
113
-
114
- // node i18n.mjs <英文原文> [name=value …]
115
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
116
- const [text = "", ...pairs] = process.argv.slice(2);
117
- const values = Object.fromEntries(pairs.map((pair) => {
118
- const index = pair.indexOf("=");
119
- return index < 0 ? [pair, ""] : [pair.slice(0, index), pair.slice(index + 1)];
120
- }));
121
- process.stdout.write(`${t(text, values)}\n`);
122
- }
@@ -1,253 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
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";
13
- import { t } from "./i18n.mjs";
14
-
15
- const binary = process.argv[2];
16
- if (!binary) {
17
- console.error(t("Usage: install-claude-hooks.mjs /absolute/path/to/cc-pets"));
18
- process.exit(2);
19
- }
20
-
21
- // 没装 Claude Code 就什么都不写。这里尤其重要:下面的 createStatusLine 分支会创建
22
- // ~/.claude/statusline-command.sh 并把 settings.json 的 statusLine 指过去,
23
- // 对还没装 Claude 的用户等于提前替他决定了状态栏。exit 0 的理由见 install-codex-hooks.mjs。
24
- if (!detectClaudeCLI()) {
25
- console.log(t("Claude Code CLI not detected; skipping Claude hooks and status line setup."));
26
- console.log(t("If you install Claude Code later, run cc-pets install to set it up."));
27
- process.exit(0);
28
- }
29
-
30
- const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
31
- const settingsPath = path.join(claudeHome, "settings.json");
32
- const marker = CLAUDE_HOOK.marker;
33
- const statusLineMarker = STATUS_LINE_MARKER;
34
- const managedHookSignatures = [CLAUDE_HOOK, LEGACY_CLAUDE_HOOK];
35
- const managedStatusLineMarkers = [STATUS_LINE_MARKER, LEGACY_STATUS_LINE_MARKER];
36
- const statusLineStartMarker = STATUS_LINE_START_MARKER;
37
- const statusLineEndMarker = STATUS_LINE_END_MARKER;
38
- const createdStatusLineMarker = CREATED_STATUS_LINE_MARKER;
39
- const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
40
- const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
- const statusLineBlockPattern = new RegExp(
42
- `(?:^|\\n)${escapeRegExp(statusLineStartMarker)}\\n[\\s\\S]*?\\n${escapeRegExp(statusLineEndMarker)}(?=\\n|$)`,
43
- "g"
44
- );
45
- const removeStatusLineBlock = (value) => value
46
- .replace(statusLineBlockPattern, "")
47
- .replace(/^\n+/, "")
48
- .replace(/\n{3,}/g, "\n\n");
49
- // `bash ~/.claude/statusline-command.sh` 指向的仍是一个能就地注入的脚本,只是多了解释器
50
- // 前缀和 `~/`。不剥掉就会被下面的"绝对路径 + 无空格"两条拒掉,白白退化成 base64 包装器,
51
- // 而包装器形态对改 settings.json 的 agent 是黑盒(读不出原命令,容易整条覆盖掉)。
52
- // 带 -c 的形式除外:`-c` 后面是命令串而非脚本路径,不能当路径注入。
53
- const interpreterPattern =
54
- /^(?:\/usr\/bin\/env\s+)?(?:[^\s'"]*\/)?(?:ba|z|k|da)?sh((?:\s+-[A-Za-z]+)*)\s+(.+)$/s;
55
- const unquote = (value) => {
56
- const quoted = value.match(/^(['"])(.*)\1$/s);
57
- return quoted ? quoted[2] : value;
58
- };
59
- // target 保留用户原来的写法(含 `~/`),script 才是展开后用于读写文件的绝对路径。
60
- // 官方形态就是 `~/.claude/statusline.sh`,`~` 是刻意的可移植写法,不能展开后写回配置。
61
- const parseStatusLineCommand = (value) => {
62
- if (typeof value !== "string") return null;
63
- let candidate = unquote(value.trim());
64
- let hasInterpreter = false;
65
- let flags = "";
66
- const interpreted = candidate.match(interpreterPattern);
67
- if (interpreted && !/-[A-Za-z]*c(?=\s|$)/.test(interpreted[1])) {
68
- hasInterpreter = true;
69
- flags = interpreted[1].trim();
70
- candidate = unquote(interpreted[2].trim());
71
- }
72
- let resolved = candidate;
73
- if (resolved.startsWith("~/")) resolved = path.join(os.homedir(), resolved.slice(2));
74
- if (!path.isAbsolute(resolved) || /[\s;&|<>`$()]/.test(resolved)) return null;
75
- return { script: path.resolve(resolved), target: candidate, hasInterpreter, flags };
76
- };
77
- const resolveStatusLineScript = (value) => parseStatusLineCommand(value)?.script ?? null;
78
- const statusLinePrelude = [
79
- statusLineStartMarker,
80
- `CC_PETS_STATUSLINE_INPUT="$(/usr/bin/mktemp "\${TMPDIR:-/tmp}/cc-pets-statusline.XXXXXX")" || exit 1`,
81
- `/bin/cat > "\${CC_PETS_STATUSLINE_INPUT}"`,
82
- `if [ -x ${shellQuote(path.resolve(binary))} ]; then`,
83
- ` ${shellQuote(path.resolve(binary))} --claude-usage < "\${CC_PETS_STATUSLINE_INPUT}" >/dev/null 2>&1 || true`,
84
- "fi",
85
- `exec 0< "\${CC_PETS_STATUSLINE_INPUT}"`,
86
- `/bin/rm -f "\${CC_PETS_STATUSLINE_INPUT}"`,
87
- "unset CC_PETS_STATUSLINE_INPUT",
88
- statusLineEndMarker
89
- ].join("\n");
90
- const installStatusLinePrelude = (scriptPath, createIfMissing = false) => {
91
- let original = "";
92
- let mode = 0o700;
93
- if (fs.existsSync(scriptPath)) {
94
- const stats = fs.statSync(scriptPath);
95
- if (!stats.isFile()) return { installed: false, hadShebang: false };
96
- original = fs.readFileSync(scriptPath, "utf8");
97
- mode = stats.mode;
98
- } else if (createIfMissing) {
99
- fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
100
- original = `#!/bin/zsh\n${createdStatusLineMarker}\n`;
101
- } else {
102
- return { installed: false, hadShebang: false };
103
- }
104
-
105
- const cleaned = removeStatusLineBlock(original);
106
- const firstNewline = cleaned.indexOf("\n");
107
- const hasShebang = cleaned.startsWith("#!");
108
- const shebang = hasShebang
109
- ? cleaned.slice(0, firstNewline === -1 ? cleaned.length : firstNewline)
110
- : "#!/bin/zsh";
111
- const body = hasShebang
112
- ? (firstNewline === -1 ? "" : cleaned.slice(firstNewline + 1))
113
- : cleaned;
114
- const updated = `${shebang}\n${statusLinePrelude}\n${body}`.replace(/\n*$/, "\n");
115
- const temporaryPath = `${scriptPath}.cc-pets.tmp`;
116
- fs.writeFileSync(temporaryPath, updated, { mode });
117
- fs.renameSync(temporaryPath, scriptPath);
118
- fs.chmodSync(scriptPath, mode | 0o100);
119
- return { installed: true, hadShebang: hasShebang };
120
- };
121
- const command = `${marker} ${shellQuote(path.resolve(binary))} --hook`;
122
- const events = [
123
- "SessionStart",
124
- "UserPromptSubmit",
125
- "PreToolUse",
126
- "PermissionRequest",
127
- "PostToolUse",
128
- "PostToolUseFailure",
129
- "Notification",
130
- "SubagentStart",
131
- "SubagentStop",
132
- "TaskCreated",
133
- "TaskCompleted",
134
- "Stop",
135
- "StopFailure",
136
- "SessionEnd"
137
- ];
138
-
139
- fs.mkdirSync(claudeHome, { recursive: true });
140
- let config = {};
141
- if (fs.existsSync(settingsPath)) {
142
- try {
143
- config = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
144
- } catch (error) {
145
- console.error(t("Can't parse {settingsPath}: {message}", { settingsPath, message: error.message }));
146
- process.exit(1);
147
- }
148
- }
149
- if (!config || typeof config !== "object" || Array.isArray(config)) config = {};
150
- if (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)) config.hooks = {};
151
-
152
- for (const [event, groups] of Object.entries(config.hooks)) {
153
- if (!Array.isArray(groups)) continue;
154
- config.hooks[event] = groups.flatMap((group) => {
155
- if (!group || !Array.isArray(group.hooks)) return [group];
156
- const handlers = group.hooks.filter((handler) => {
157
- return !managedHookSignatures.some((signature) => isManagedHookCommand(handler?.command, signature));
158
- });
159
- return handlers.length > 0 ? [{ ...group, hooks: handlers }] : [];
160
- });
161
- }
162
-
163
- for (const event of events) {
164
- if (!Array.isArray(config.hooks[event])) config.hooks[event] = [];
165
- config.hooks[event].push({
166
- hooks: [{ type: "command", command, timeout: 3 }]
167
- });
168
- }
169
-
170
- let originalStatusLineCommand = "";
171
- if (config.statusLine && typeof config.statusLine === "object" && !Array.isArray(config.statusLine)) {
172
- const currentCommand = typeof config.statusLine.command === "string" ? config.statusLine.command : "";
173
- if (managedStatusLineMarkers.some((value) => isManagedStatusLine(currentCommand, value))) {
174
- const match = currentCommand.match(/'([A-Za-z0-9+/=]*)'\s*$/);
175
- if (match) originalStatusLineCommand = Buffer.from(match[1], "base64").toString("utf8");
176
- } else {
177
- originalStatusLineCommand = currentCommand;
178
- }
179
- } else {
180
- config.statusLine = { type: "command" };
181
- }
182
-
183
- let createdStatusLine = false;
184
- if (!originalStatusLineCommand) {
185
- originalStatusLineCommand = path.join(claudeHome, "statusline-command.sh");
186
- createdStatusLine = true;
187
- }
188
- config.statusLine = { ...config.statusLine, type: "command", command: originalStatusLineCommand };
189
-
190
- const parsedStatusLine = parseStatusLineCommand(originalStatusLineCommand);
191
- const statusLineScript = parsedStatusLine?.script ?? null;
192
- const preludeResult = statusLineScript
193
- ? installStatusLinePrelude(statusLineScript, createdStatusLine)
194
- : { installed: false, hadShebang: false };
195
- const statusLineInstalled = preludeResult.installed;
196
-
197
- // 只在原命令带解释器前缀(`bash ~/x.sh`)时才改写 command,去掉那层前缀让 agent 能直接读懂。
198
- // 纯路径形态——包括官方默认的 `~/.claude/statusline.sh`——一个字都不动,写法原样保留。
199
- // 两条额外的闸门,都是为了不改变脚本的执行语义:
200
- // * 带 flag(`sh -e ~/x.sh`)不动,否则 `-e` 这类选项会被悄悄丢掉;
201
- // * 脚本原本没有 shebang 的不动,否则 prelude 补的 `#!/bin/zsh` 会把本来用 bash 跑的
202
- // 脚本换成 zsh 跑。用户写 `bash ~/x.sh` 往往正是因为脚本没有 shebang。
203
- if (
204
- statusLineInstalled &&
205
- parsedStatusLine?.hasInterpreter &&
206
- !parsedStatusLine.flags &&
207
- preludeResult.hadShebang
208
- ) {
209
- config.statusLine = { ...config.statusLine, command: parsedStatusLine.target };
210
- }
211
-
212
- // 就地往用户脚本里插 prelude 只对"能解析出脚本路径的命令"成立。真·第三方状态栏不是这个
213
- // 形态(`bun x ccstatusline`、`npx …`、任何带管道或 `sh -c` 的命令行),
214
- // resolveStatusLineScript 一律拒绝。以前这里只打印一行警告就算了,而 statusline 是 Claude 额度的唯一来源
215
- // (转录 jsonl 和 stats-cache.json 里都没有 rate_limits),于是这类用户的额度永远是 `--`。
216
- // 回退到包装器:command 换成 claude-statusline-with-pet + base64 编码的原命令,它先把 stdin
217
- // 喂给 cc-pets --claude-usage,再原样转发给原命令执行。卸载侧本来就认这个形态(marker +
218
- // 末尾的 base64),能原样还原回去。
219
- const statusLineWrapper = path.resolve(
220
- path.dirname(fileURLToPath(import.meta.url)), "..", "bin", "claude-statusline-with-pet");
221
- let statusLineWrapped = false;
222
- if (!statusLineInstalled && originalStatusLineCommand && fs.existsSync(statusLineWrapper)) {
223
- try {
224
- fs.chmodSync(statusLineWrapper, fs.statSync(statusLineWrapper).mode | 0o100);
225
- } catch {
226
- // 包内文件不可写(只读安装)时权限位通常本来就是对的,交给下面的可执行判断兜底。
227
- }
228
- if (fs.existsSync(statusLineWrapper)) {
229
- const encoded = Buffer.from(originalStatusLineCommand, "utf8").toString("base64");
230
- config.statusLine = {
231
- ...config.statusLine,
232
- type: "command",
233
- command: `${statusLineMarker} ${shellQuote(statusLineWrapper)} '${encoded}'`
234
- };
235
- statusLineWrapped = true;
236
- }
237
- }
238
-
239
- if (!statusLineInstalled && !statusLineWrapped) {
240
- console.warn(t("Claude status line not hooked up: {command}", { command: originalStatusLineCommand || t("(not configured)") }));
241
- console.warn(t("Claude hooks still work, but the pet can't show Claude quota % (token usage is unaffected)."));
242
- }
243
-
244
- const temporaryPath = `${settingsPath}.cc-pets.tmp`;
245
- fs.writeFileSync(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
246
- fs.renameSync(temporaryPath, settingsPath);
247
- fs.chmodSync(settingsPath, 0o600);
248
- console.log(t("Claude Code hooks installed in {settingsPath}", { settingsPath }));
249
- if (statusLineInstalled) {
250
- console.log(t("Claude quota tracking added to your existing status line. The pet shows quota after the first API response."));
251
- } else if (statusLineWrapped) {
252
- console.log(t("Claude quota tracking added to the status line through a wrapper; your original command still runs. The pet shows quota after the first API response."));
253
- }
@@ -1,78 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { detectCodexCLI } from "./detect-cli.mjs";
7
- import { CODEX_HOOK, LEGACY_CODEX_HOOK, isManagedHookCommand } from "./integration-markers.mjs";
8
- import { t } from "./i18n.mjs";
9
-
10
- const binary = process.argv[2];
11
- if (!binary) {
12
- console.error(t("Usage: install-codex-hooks.mjs /absolute/path/to/cc-pets"));
13
- process.exit(2);
14
- }
15
-
16
- // 没装 Codex 就什么都不写。必须 exit 0:install-shell-integration.sh 是 set -eu,
17
- // 这里非零退出会把后面的 Claude Hooks、更新器、shim 和 .zshrc 全部带停,
18
- // 用户会拿到一个装了一半的状态。
19
- if (!detectCodexCLI()) {
20
- console.log(t("Codex CLI not detected; skipping Codex hooks."));
21
- console.log(t("If you install Codex later, run cc-pets install to set it up."));
22
- process.exit(0);
23
- }
24
-
25
- const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
26
- const hooksPath = path.join(codexHome, "hooks.json");
27
- const marker = CODEX_HOOK.marker;
28
- const managedSignatures = [CODEX_HOOK, LEGACY_CODEX_HOOK];
29
- const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
30
- const command = `${marker} ${shellQuote(path.resolve(binary))} --hook`;
31
- const events = [
32
- "SessionStart",
33
- "UserPromptSubmit",
34
- "PreToolUse",
35
- "PermissionRequest",
36
- "PostToolUse",
37
- "SubagentStart",
38
- "SubagentStop",
39
- "Stop"
40
- ];
41
-
42
- fs.mkdirSync(codexHome, { recursive: true });
43
- let config = {};
44
- if (fs.existsSync(hooksPath)) {
45
- try {
46
- config = JSON.parse(fs.readFileSync(hooksPath, "utf8"));
47
- } catch (error) {
48
- console.error(t("Can't parse {hooksPath}: {message}", { hooksPath, message: error.message }));
49
- process.exit(1);
50
- }
51
- }
52
- if (!config || typeof config !== "object" || Array.isArray(config)) config = {};
53
- if (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)) config.hooks = {};
54
-
55
- for (const [event, groups] of Object.entries(config.hooks)) {
56
- if (!Array.isArray(groups)) continue;
57
- config.hooks[event] = groups.flatMap((group) => {
58
- if (!group || !Array.isArray(group.hooks)) return [group];
59
- const handlers = group.hooks.filter((handler) => {
60
- return !managedSignatures.some((signature) => isManagedHookCommand(handler?.command, signature));
61
- });
62
- return handlers.length > 0 ? [{ ...group, hooks: handlers }] : [];
63
- });
64
- }
65
-
66
- for (const event of events) {
67
- if (!Array.isArray(config.hooks[event])) config.hooks[event] = [];
68
- config.hooks[event].push({
69
- hooks: [{ type: "command", command, timeout: 3 }]
70
- });
71
- }
72
-
73
- const temporaryPath = `${hooksPath}.cc-pets.tmp`;
74
- fs.writeFileSync(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
75
- fs.renameSync(temporaryPath, hooksPath);
76
- fs.chmodSync(hooksPath, 0o600);
77
- console.log(t("Codex agent hooks installed in {hooksPath}", { hooksPath }));
78
- console.log(t("Next time you start Codex, run /hooks and trust the CC Pets hooks."));
@@ -1,51 +0,0 @@
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
- };