cc-pets 2.2.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CC_BRIDGE.md +24 -2
- package/CC_BRIDGE.zh-CN.md +19 -2
- package/CHANGELOG.md +111 -0
- package/CHANGELOG.zh-CN.md +111 -0
- package/CONTRIBUTING.md +35 -10
- package/CONTRIBUTING.zh-CN.md +28 -10
- package/README.md +212 -32
- package/README.zh-CN.md +167 -36
- package/Resources/AgentIcons/claude.png +0 -0
- package/Resources/AgentIcons/codex.icns +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
- package/Resources/zh-Hans.lproj/Localizable.strings +699 -20
- package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
- package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +90 -25
- package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
- package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
- package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +71 -23
- package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
- package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
- package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +87 -102
- package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +121 -51
- package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
- package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +17 -2
- package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
- package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
- package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
- package/Sources/CCPets/{main.m → App/main.m} +74 -1
- package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
- package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +43 -23
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +832 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +59 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +576 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +507 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +106 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +897 -0
- package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
- package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
- package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
- package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
- package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +2 -1
- package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +148 -36
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
- package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
- package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
- package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
- package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
- package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
- package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
- package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
- package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
- package/Sources/CCPets/Pet/PetView+Private.h +81 -0
- package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
- package/Sources/CCPets/Pet/PetView.m +635 -0
- package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
- package/Sources/CCPets/Support/CCPetsDoctor.m +646 -0
- package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
- package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
- package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
- package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
- package/Sources/CCPets/Support/CCPetsPreferences.h +33 -0
- package/Sources/CCPets/Support/CCPetsPreferences.m +117 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.h +44 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.m +279 -0
- package/Sources/CCPets/UI/CCPetsGlassView.h +57 -0
- package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +60 -11
- package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
- package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.h +64 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.m +1412 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.h +135 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.m +865 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.m +288 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.m +712 -0
- package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
- package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
- package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
- package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
- package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
- package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
- package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
- package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
- package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
- package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
- package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
- package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
- package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
- package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
- package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
- package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +97 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Models.m +323 -0
- package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
- package/Sources/CCPets/Usage/CCPetsUsage.h +58 -0
- package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
- package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
- package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
- package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
- package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +174 -19
- package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
- package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
- package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +598 -0
- package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
- package/Sources/CCPets/Usage/QuotaDashboardView.m +713 -0
- package/THIRD_PARTY_NOTICES.md +8 -4
- package/THIRD_PARTY_NOTICES.zh-CN.md +6 -2
- package/bin/cc-pets +8 -6
- package/bin/claude-with-pet +12 -2
- package/bin/codex-with-pet +15 -5
- package/package.json +5 -1
- package/plugins/jetbrains/README.md +62 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
- package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
- package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
- package/plugins/vscode/README.md +63 -0
- package/plugins/vscode/extension.js +210 -0
- package/plugins/vscode/package.json +18 -0
- package/scripts/build-idea-plugin.sh +101 -0
- package/scripts/build-vscode-extension.sh +112 -0
- package/scripts/build.sh +31 -5
- package/scripts/compile-cached.zsh +133 -0
- package/scripts/i18n.zsh +9 -52
- package/scripts/install-app.sh +4 -0
- package/scripts/install-shell-integration.sh +17 -10
- package/scripts/uninstall-shell-integration.sh +6 -1
- package/Sources/CCPets/CCPetsEvents.h +0 -10
- package/Sources/CCPets/CCPetsGlassView.h +0 -31
- package/Sources/CCPets/CCPetsUsage.h +0 -36
- package/Sources/CCPets/CCPetsUsage.m +0 -2069
- package/Sources/CCPets/PetView.m +0 -1839
- package/Sources/CCPets/QuotaDashboardView.m +0 -1145
- package/scripts/bridge/cli.mjs +0 -237
- package/scripts/bridge/core.mjs +0 -228
- package/scripts/bridge/hook.mjs +0 -150
- package/scripts/bridge/install.mjs +0 -311
- package/scripts/bridge/mcp-server.mjs +0 -308
- package/scripts/bridge/options.mjs +0 -87
- package/scripts/bridge/process.mjs +0 -151
- package/scripts/bridge/reservations.mjs +0 -248
- package/scripts/bridge/store.mjs +0 -433
- package/scripts/bridge/watch.mjs +0 -69
- package/scripts/check-l10n.mjs +0 -168
- package/scripts/configure-updater.mjs +0 -43
- package/scripts/detect-cli.mjs +0 -68
- package/scripts/doctor.mjs +0 -470
- package/scripts/i18n.mjs +0 -122
- package/scripts/install-claude-hooks.mjs +0 -253
- package/scripts/install-codex-hooks.mjs +0 -78
- package/scripts/integration-markers.mjs +0 -51
- package/scripts/locales/zh-Hans.json +0 -366
- package/scripts/pet-store.mjs +0 -415
- package/scripts/uninstall-integrations.mjs +0 -205
- /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
- /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
- /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
- /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
- /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
- /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
- /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
- /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
- /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
- /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
package/scripts/bridge/store.mjs
DELETED
|
@@ -1,433 +0,0 @@
|
|
|
1
|
-
// CC Bridge 的存储层:会话注册表、信箱、回执、订阅、锁。
|
|
2
|
-
//
|
|
3
|
-
// 全部是"一条记录一个文件",状态流转靠同一文件系统内的 rename 完成——rename 是原子的,
|
|
4
|
-
// 多个终端的 hook / watcher / MCP 进程同时抢同一条消息时,只有一个能 rename 成功,
|
|
5
|
-
// 其余拿到 ENOENT 直接跳过,不需要任何守护进程或数据库锁。
|
|
6
|
-
//
|
|
7
|
-
// 目录放在 CC_PETS_STATE_DIR(默认 $TMPDIR)下,与桌宠事件流同级:会话本身活不过重启,
|
|
8
|
-
// 注册表和未投递的消息也没有跨重启保留的意义。启用开关则放在 ~/.cc-pets 里持久保存。
|
|
9
|
-
|
|
10
|
-
import { execFileSync } from "node:child_process";
|
|
11
|
-
import crypto from "node:crypto";
|
|
12
|
-
import fs from "node:fs";
|
|
13
|
-
import os from "node:os";
|
|
14
|
-
import path from "node:path";
|
|
15
|
-
import { t } from "../i18n.mjs";
|
|
16
|
-
|
|
17
|
-
export const MESSAGE_BODY_LIMIT = 16 * 1024;
|
|
18
|
-
export const MESSAGE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
19
|
-
// 同一对会话 10 分钟内来回超过这个数,基本可以断定是两个 Agent 在互相自动回复。
|
|
20
|
-
export const PAIR_LIMIT_WINDOW_MS = 10 * 60 * 1000;
|
|
21
|
-
export const PAIR_LIMIT_COUNT = 20;
|
|
22
|
-
export const SENDER_LIMIT_COUNT = 40;
|
|
23
|
-
|
|
24
|
-
const uid = () => (typeof process.getuid === "function" ? process.getuid() : 0);
|
|
25
|
-
|
|
26
|
-
// 不能直接用 os.tmpdir():它只认 TMPDIR 环境变量,而 Codex 拉起 MCP server 时会裁剪环境,
|
|
27
|
-
// 拿不到 TMPDIR 就退回 /tmp,与 hook 写入的目录分家。DARWIN_USER_TEMP_DIR 按用户固定、
|
|
28
|
-
// 不依赖环境变量,也正是桌宠原生端 NSTemporaryDirectory() 返回的目录。
|
|
29
|
-
let cachedUserTempDirectory;
|
|
30
|
-
const userTempDirectory = () => {
|
|
31
|
-
if (cachedUserTempDirectory === undefined) {
|
|
32
|
-
cachedUserTempDirectory = null;
|
|
33
|
-
if (process.platform === "darwin") {
|
|
34
|
-
try {
|
|
35
|
-
const value = execFileSync("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"],
|
|
36
|
-
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
37
|
-
if (value) cachedUserTempDirectory = value;
|
|
38
|
-
} catch {
|
|
39
|
-
// 退回 os.tmpdir()。
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return cachedUserTempDirectory || os.tmpdir();
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
export const bridgeDirectory = () => path.join(
|
|
47
|
-
process.env.CC_PETS_STATE_DIR || userTempDirectory(), `cc-bridge-${uid()}`);
|
|
48
|
-
|
|
49
|
-
export const bridgeHomeDirectory = () =>
|
|
50
|
-
process.env.CC_PETS_HOME || path.join(os.homedir(), ".cc-pets");
|
|
51
|
-
|
|
52
|
-
const enabledFlagPath = () => path.join(bridgeHomeDirectory(), "bridge-enabled");
|
|
53
|
-
|
|
54
|
-
export const isBridgeEnabled = () => fs.existsSync(enabledFlagPath());
|
|
55
|
-
|
|
56
|
-
// 桌宠(~/Applications 下的 App)不知道 cc-pets 包装在哪,菜单开关要靠这个文件找到 node 与 CLI。
|
|
57
|
-
// 每次安装(bridge refresh)、enable、configure 都会重写,包路径随升级变化也能跟上。
|
|
58
|
-
export const writeCliLocator = (cliPath) => {
|
|
59
|
-
fs.mkdirSync(bridgeHomeDirectory(), { recursive: true, mode: 0o700 });
|
|
60
|
-
const file = path.join(bridgeHomeDirectory(), "bridge-cli.json");
|
|
61
|
-
const temporary = `${file}.${process.pid}.tmp`;
|
|
62
|
-
fs.writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, node: process.execPath, cli: cliPath }, null, 2)}\n`,
|
|
63
|
-
{ mode: 0o600 });
|
|
64
|
-
fs.renameSync(temporary, file);
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
// 正式发布前叫过 "Agent Bus",开关文件是 bus-enabled。迁移成新名字并保留当时的选项,
|
|
68
|
-
// 这样 refresh / 卸载能认出"用户开启过",把旧集成清掉后按原选项重写。
|
|
69
|
-
export const migrateLegacyFlag = () => {
|
|
70
|
-
const legacy = path.join(bridgeHomeDirectory(), "bus-enabled");
|
|
71
|
-
if (!fs.existsSync(legacy)) return false;
|
|
72
|
-
if (fs.existsSync(enabledFlagPath())) {
|
|
73
|
-
fs.rmSync(legacy, { force: true });
|
|
74
|
-
} else {
|
|
75
|
-
fs.renameSync(legacy, enabledFlagPath());
|
|
76
|
-
}
|
|
77
|
-
return true;
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
// 开关文件同时保存 enable 时的选项:重装 / 升级后包路径会变,安装流程要用同样的选项
|
|
81
|
-
// 重写一遍 hooks 与 MCP 注册(见 cli.mjs 的 refresh)。
|
|
82
|
-
export const readBridgeOptions = () => {
|
|
83
|
-
try {
|
|
84
|
-
const parsed = JSON.parse(fs.readFileSync(enabledFlagPath(), "utf8"));
|
|
85
|
-
return parsed && typeof parsed === "object" ? parsed : {};
|
|
86
|
-
} catch {
|
|
87
|
-
return {};
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
export const setBridgeEnabled = (enabled, options = {}) => {
|
|
92
|
-
if (enabled) {
|
|
93
|
-
fs.mkdirSync(bridgeHomeDirectory(), { recursive: true, mode: 0o700 });
|
|
94
|
-
fs.writeFileSync(enabledFlagPath(),
|
|
95
|
-
`${JSON.stringify({ ...options, enabledAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
|
|
96
|
-
} else {
|
|
97
|
-
fs.rmSync(enabledFlagPath(), { force: true });
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
// 目录一律 0700:信箱里是消息正文,同机其他用户不能读,也不能往里塞"任务"。
|
|
102
|
-
// 已存在的目录也要校正权限并确认归属,防止有人提前在共享 /tmp 里抢建同名目录。
|
|
103
|
-
const ensureDirectory = (directory) => {
|
|
104
|
-
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
105
|
-
const status = fs.lstatSync(directory);
|
|
106
|
-
if (!status.isDirectory() || status.isSymbolicLink()) {
|
|
107
|
-
throw new Error(t("{directory} isn't a regular directory", { directory }));
|
|
108
|
-
}
|
|
109
|
-
if (status.uid !== uid()) throw new Error(t("{directory} isn't owned by the current user", { directory }));
|
|
110
|
-
if ((status.mode & 0o077) !== 0) fs.chmodSync(directory, 0o700);
|
|
111
|
-
return directory;
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
export const bridgePath = (...parts) => {
|
|
115
|
-
const root = ensureDirectory(bridgeDirectory());
|
|
116
|
-
if (parts.length === 0) return root;
|
|
117
|
-
const directory = path.join(root, ...parts.slice(0, -1));
|
|
118
|
-
if (parts.length > 1) ensureDirectory(directory);
|
|
119
|
-
return path.join(directory, parts[parts.length - 1]);
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
export const bridgeSubdirectory = (...parts) => ensureDirectory(path.join(bridgePath(), ...parts));
|
|
123
|
-
|
|
124
|
-
// session id 会拼进文件路径,只放行 UUID 一类的安全字符,杜绝 ../ 之类的路径穿越。
|
|
125
|
-
export const safeSessionId = (value) =>
|
|
126
|
-
typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value) && !/^\.+$/.test(value)
|
|
127
|
-
? value : null;
|
|
128
|
-
|
|
129
|
-
// 先写同目录临时文件再 rename:读取端永远看不到写了一半的 JSON。
|
|
130
|
-
export const writeJsonAtomic = (file, value) => {
|
|
131
|
-
const temporary = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
132
|
-
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
133
|
-
fs.renameSync(temporary, file);
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
export const readJson = (file) => {
|
|
137
|
-
try {
|
|
138
|
-
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
139
|
-
} catch {
|
|
140
|
-
return null;
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
const listJson = (directory) => {
|
|
145
|
-
let entries;
|
|
146
|
-
try {
|
|
147
|
-
entries = fs.readdirSync(directory);
|
|
148
|
-
} catch {
|
|
149
|
-
return [];
|
|
150
|
-
}
|
|
151
|
-
return entries.filter((name) => name.endsWith(".json")).sort();
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
// ---------------------------------------------------------------------------
|
|
155
|
-
// 会话注册表
|
|
156
|
-
|
|
157
|
-
export const sessionRef = (sessionId) =>
|
|
158
|
-
crypto.createHash("sha1").update(sessionId).digest("hex").slice(0, 6);
|
|
159
|
-
|
|
160
|
-
const sessionFile = (sessionId) => path.join(bridgeSubdirectory("sessions"), `${sessionId}.json`);
|
|
161
|
-
|
|
162
|
-
export const readSession = (sessionId) => {
|
|
163
|
-
const safe = safeSessionId(sessionId);
|
|
164
|
-
return safe ? readJson(sessionFile(safe)) : null;
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
export const listSessions = () => {
|
|
168
|
-
const directory = bridgeSubdirectory("sessions");
|
|
169
|
-
return listJson(directory).map((name) => readJson(path.join(directory, name))).filter(Boolean);
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
export const removeSession = (sessionId) => {
|
|
173
|
-
const safe = safeSessionId(sessionId);
|
|
174
|
-
if (safe) fs.rmSync(sessionFile(safe), { force: true });
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
const projectSlug = (cwd) => {
|
|
178
|
-
const base = path.basename(cwd || "") || "session";
|
|
179
|
-
const slug = base.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
180
|
-
return (slug || "session").slice(0, 32);
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
// 名字是给 Agent 和人看的地址:<provider>-<项目目录名>-<n>。n 取同前缀下在线会话
|
|
184
|
-
// 未占用的最小正整数,会话结束后编号可以被复用;ref 由 session id 派生,永不变化,
|
|
185
|
-
// 用于重名时消歧。
|
|
186
|
-
const allocateName = (provider, cwd, sessionId, liveSessions) => {
|
|
187
|
-
const prefix = `${provider.toLowerCase()}-${projectSlug(cwd)}`;
|
|
188
|
-
const taken = new Set(liveSessions
|
|
189
|
-
.filter((entry) => entry.session !== sessionId)
|
|
190
|
-
.map((entry) => entry.name));
|
|
191
|
-
for (let index = 1; ; index += 1) {
|
|
192
|
-
const candidate = `${prefix}-${index}`;
|
|
193
|
-
if (!taken.has(candidate)) return candidate;
|
|
194
|
-
}
|
|
195
|
-
};
|
|
196
|
-
|
|
197
|
-
// 自定义名字:启动时用 CC_BRIDGE_NAME 指定,或会话里调用 set_name 修改。
|
|
198
|
-
// 只允许小写字母、数字和 . _ -,首字符必须是字母或数字,最长 40 个字符——名字会出现在消息头
|
|
199
|
-
// 和 Agent 的工具参数里,不能带空格、方括号(与 "名字 [ref]" 语法冲突)或控制字符。
|
|
200
|
-
export const normalizeSessionName = (value) => {
|
|
201
|
-
const name = String(value ?? "").trim().toLowerCase();
|
|
202
|
-
return /^[a-z0-9][a-z0-9._-]{0,39}$/.test(name) ? name : null;
|
|
203
|
-
};
|
|
204
|
-
|
|
205
|
-
const nameTakenBy = (name, sessionId, liveSessions) =>
|
|
206
|
-
liveSessions.find((entry) => entry.session !== sessionId && entry.name === name) || null;
|
|
207
|
-
|
|
208
|
-
// 启动时指定的名字被占用就追加序号(frontend → frontend-2),不让会话因此注册失败。
|
|
209
|
-
const allocateCustomName = (name, sessionId, liveSessions) => {
|
|
210
|
-
if (!nameTakenBy(name, sessionId, liveSessions)) return name;
|
|
211
|
-
for (let index = 2; ; index += 1) {
|
|
212
|
-
const candidate = `${name}-${index}`.slice(0, 40);
|
|
213
|
-
if (!nameTakenBy(candidate, sessionId, liveSessions)) return candidate;
|
|
214
|
-
}
|
|
215
|
-
};
|
|
216
|
-
|
|
217
|
-
// liveSessions 由调用方传入(需要进程探测,放在 process.mjs 里做),避免存储层依赖 ps。
|
|
218
|
-
export const upsertSession = ({
|
|
219
|
-
sessionId, provider, pid, cwd, tty, status, preferredName, liveSessions = []
|
|
220
|
-
}) => {
|
|
221
|
-
const safe = safeSessionId(sessionId);
|
|
222
|
-
if (!safe) return null;
|
|
223
|
-
const now = Date.now();
|
|
224
|
-
const existing = readSession(safe);
|
|
225
|
-
const record = existing || {
|
|
226
|
-
session: safe,
|
|
227
|
-
provider,
|
|
228
|
-
ref: sessionRef(safe),
|
|
229
|
-
startedAt: now
|
|
230
|
-
};
|
|
231
|
-
record.provider = provider || record.provider;
|
|
232
|
-
if (Number.isInteger(pid) && pid > 1) record.pid = pid;
|
|
233
|
-
if (cwd) record.cwd = cwd;
|
|
234
|
-
if (tty) record.tty = tty;
|
|
235
|
-
if (!record.name) {
|
|
236
|
-
const custom = normalizeSessionName(preferredName);
|
|
237
|
-
record.name = custom
|
|
238
|
-
? allocateCustomName(custom, safe, liveSessions)
|
|
239
|
-
: allocateName(record.provider, record.cwd, safe, liveSessions);
|
|
240
|
-
}
|
|
241
|
-
if (status) record.status = status;
|
|
242
|
-
record.updatedAt = now;
|
|
243
|
-
writeJsonAtomic(sessionFile(safe), record);
|
|
244
|
-
return record;
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
// 会话内改名:名字被其他在线会话占用时直接报错,由调用方换一个,不自动追加序号。
|
|
248
|
-
export const renameSession = (sessionId, requestedName, liveSessions) => {
|
|
249
|
-
const record = readSession(sessionId);
|
|
250
|
-
if (!record) return { error: t("This session isn't registered yet.") };
|
|
251
|
-
const name = normalizeSessionName(requestedName);
|
|
252
|
-
if (!name) {
|
|
253
|
-
return { error: t("Names may only contain lowercase letters, digits and . _ -, must start with a letter or digit, and be at most 40 characters.") };
|
|
254
|
-
}
|
|
255
|
-
const holder = nameTakenBy(name, record.session, liveSessions);
|
|
256
|
-
if (holder) return { error: t("The name {name} is taken by {holder} [{ref}]; pick another.", { name, holder: holder.name, ref: holder.ref }) };
|
|
257
|
-
const previous = record.name;
|
|
258
|
-
record.name = name;
|
|
259
|
-
record.updatedAt = Date.now();
|
|
260
|
-
writeJsonAtomic(sessionFile(record.session), record);
|
|
261
|
-
return { session: record, previous };
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
// ---------------------------------------------------------------------------
|
|
265
|
-
// 消息
|
|
266
|
-
|
|
267
|
-
export const newMessageId = () =>
|
|
268
|
-
`m${Date.now().toString(36)}${crypto.randomBytes(5).toString("hex")}`;
|
|
269
|
-
|
|
270
|
-
const inboxDirectory = (sessionId) => bridgeSubdirectory("inbox", sessionId);
|
|
271
|
-
const claimedDirectory = (sessionId) => bridgeSubdirectory("claimed", sessionId);
|
|
272
|
-
const receiptFile = (messageId) => path.join(bridgeSubdirectory("sent"), `${messageId}.json`);
|
|
273
|
-
|
|
274
|
-
export const readReceipt = (messageId) =>
|
|
275
|
-
/^[a-z0-9]+$/.test(messageId || "") ? readJson(receiptFile(messageId)) : null;
|
|
276
|
-
|
|
277
|
-
export const writeReceipt = (message) => writeJsonAtomic(receiptFile(message.id), message);
|
|
278
|
-
|
|
279
|
-
export const updateReceipt = (messageId, patch) => {
|
|
280
|
-
const current = readReceipt(messageId);
|
|
281
|
-
if (!current) return null;
|
|
282
|
-
const next = { ...current, ...patch, updatedAt: Date.now() };
|
|
283
|
-
writeReceipt(next);
|
|
284
|
-
return next;
|
|
285
|
-
};
|
|
286
|
-
|
|
287
|
-
export const listReceipts = () => {
|
|
288
|
-
const directory = bridgeSubdirectory("sent");
|
|
289
|
-
return listJson(directory).map((name) => readJson(path.join(directory, name))).filter(Boolean);
|
|
290
|
-
};
|
|
291
|
-
|
|
292
|
-
// 发送前的配额检查。返回 null 表示放行,否则返回拒绝原因。
|
|
293
|
-
export const checkSendLimits = (fromSession, toSession, now = Date.now()) => {
|
|
294
|
-
const recent = listReceipts().filter((entry) => now - (entry.createdAt || 0) < PAIR_LIMIT_WINDOW_MS);
|
|
295
|
-
const pair = recent.filter((entry) =>
|
|
296
|
-
(entry.from?.session === fromSession && entry.to?.session === toSession) ||
|
|
297
|
-
(entry.from?.session === toSession && entry.to?.session === fromSession));
|
|
298
|
-
if (pair.length >= PAIR_LIMIT_COUNT) {
|
|
299
|
-
return t("These two sessions exchanged {length} messages in 10 minutes, which looks like an auto-reply loop, so sending is paused. Ask the user before continuing.", { length: pair.length });
|
|
300
|
-
}
|
|
301
|
-
const sent = recent.filter((entry) => entry.from?.session === fromSession);
|
|
302
|
-
if (sent.length >= SENDER_LIMIT_COUNT) {
|
|
303
|
-
return t("This session sent {length} messages in 10 minutes, over the limit, so sending is paused.", { length: sent.length });
|
|
304
|
-
}
|
|
305
|
-
return null;
|
|
306
|
-
};
|
|
307
|
-
|
|
308
|
-
export const enqueueInbox = (message) => {
|
|
309
|
-
const target = safeSessionId(message.to?.session);
|
|
310
|
-
if (!target) throw new Error(t("invalid target session id"));
|
|
311
|
-
writeJsonAtomic(path.join(inboxDirectory(target), `${message.id}.json`), message);
|
|
312
|
-
};
|
|
313
|
-
|
|
314
|
-
// 认领:inbox → claimed。rename 失败(被别的进程抢先认领)就跳过。
|
|
315
|
-
// 过期消息顺手标记 expired 并丢弃,不再投递。
|
|
316
|
-
export const claimInbox = (sessionId, now = Date.now()) => {
|
|
317
|
-
const safe = safeSessionId(sessionId);
|
|
318
|
-
if (!safe) return [];
|
|
319
|
-
const inbox = inboxDirectory(safe);
|
|
320
|
-
const claimed = claimedDirectory(safe);
|
|
321
|
-
const messages = [];
|
|
322
|
-
for (const name of listJson(inbox)) {
|
|
323
|
-
const source = path.join(inbox, name);
|
|
324
|
-
const destination = path.join(claimed, name);
|
|
325
|
-
try {
|
|
326
|
-
fs.renameSync(source, destination);
|
|
327
|
-
} catch {
|
|
328
|
-
continue;
|
|
329
|
-
}
|
|
330
|
-
const message = readJson(destination);
|
|
331
|
-
fs.rmSync(destination, { force: true });
|
|
332
|
-
if (!message) continue;
|
|
333
|
-
if (now - (message.createdAt || 0) > MESSAGE_TTL_MS) {
|
|
334
|
-
updateReceipt(message.id, { status: "expired" });
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
messages.push(message);
|
|
338
|
-
}
|
|
339
|
-
return messages;
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
export const pendingCount = (sessionId) => {
|
|
343
|
-
const safe = safeSessionId(sessionId);
|
|
344
|
-
return safe ? listJson(inboxDirectory(safe)).length : 0;
|
|
345
|
-
};
|
|
346
|
-
|
|
347
|
-
// 会话结束:信箱里还没投出去的消息标记为 undeliverable,回执里能看到。
|
|
348
|
-
export const abandonInbox = (sessionId) => {
|
|
349
|
-
const safe = safeSessionId(sessionId);
|
|
350
|
-
if (!safe) return;
|
|
351
|
-
const inbox = inboxDirectory(safe);
|
|
352
|
-
for (const name of listJson(inbox)) {
|
|
353
|
-
const file = path.join(inbox, name);
|
|
354
|
-
const message = readJson(file);
|
|
355
|
-
fs.rmSync(file, { force: true });
|
|
356
|
-
if (message) updateReceipt(message.id, { status: "undeliverable", reason: t("the target session has ended") });
|
|
357
|
-
}
|
|
358
|
-
};
|
|
359
|
-
|
|
360
|
-
// 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。
|
|
361
|
-
export const pruneReceipts = (now = Date.now()) => {
|
|
362
|
-
const directory = bridgeSubdirectory("sent");
|
|
363
|
-
for (const name of listJson(directory)) {
|
|
364
|
-
const file = path.join(directory, name);
|
|
365
|
-
const receipt = readJson(file);
|
|
366
|
-
if (!receipt || now - (receipt.createdAt || 0) > MESSAGE_TTL_MS * 2) fs.rmSync(file, { force: true });
|
|
367
|
-
}
|
|
368
|
-
};
|
|
369
|
-
|
|
370
|
-
// ---------------------------------------------------------------------------
|
|
371
|
-
// 空闲订阅:subscriptions/<target>/<subscriber>.json,一次性。
|
|
372
|
-
|
|
373
|
-
export const addIdleSubscription = (targetSession, subscriberSession) => {
|
|
374
|
-
const target = safeSessionId(targetSession);
|
|
375
|
-
const subscriber = safeSessionId(subscriberSession);
|
|
376
|
-
if (!target || !subscriber) return;
|
|
377
|
-
writeJsonAtomic(path.join(bridgeSubdirectory("subscriptions", target), `${subscriber}.json`),
|
|
378
|
-
{ subscriber, createdAt: Date.now() });
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
export const hasIdleSubscriptions = (targetSession) => {
|
|
382
|
-
const target = safeSessionId(targetSession);
|
|
383
|
-
return target ? listJson(path.join(bridgeDirectory(), "subscriptions", target)).length > 0 : false;
|
|
384
|
-
};
|
|
385
|
-
|
|
386
|
-
export const takeIdleSubscriptions = (targetSession) => {
|
|
387
|
-
const target = safeSessionId(targetSession);
|
|
388
|
-
if (!target) return [];
|
|
389
|
-
const directory = bridgeSubdirectory("subscriptions", target);
|
|
390
|
-
const subscribers = [];
|
|
391
|
-
for (const name of listJson(directory)) {
|
|
392
|
-
const file = path.join(directory, name);
|
|
393
|
-
const claimed = `${file}.taken`;
|
|
394
|
-
try {
|
|
395
|
-
fs.renameSync(file, claimed);
|
|
396
|
-
} catch {
|
|
397
|
-
continue;
|
|
398
|
-
}
|
|
399
|
-
const entry = readJson(claimed);
|
|
400
|
-
fs.rmSync(claimed, { force: true });
|
|
401
|
-
if (entry?.subscriber) subscribers.push(entry.subscriber);
|
|
402
|
-
}
|
|
403
|
-
return subscribers;
|
|
404
|
-
};
|
|
405
|
-
|
|
406
|
-
// ---------------------------------------------------------------------------
|
|
407
|
-
// 锁:O_EXCL 创建,内容是持有者 pid。持有者已死的锁视为陈旧,可以抢占。
|
|
408
|
-
|
|
409
|
-
export const acquireLock = (name, isHolderAlive) => {
|
|
410
|
-
const file = path.join(bridgeSubdirectory("locks"), `${name}.pid`);
|
|
411
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
412
|
-
try {
|
|
413
|
-
const descriptor = fs.openSync(file, "wx", 0o600);
|
|
414
|
-
fs.writeSync(descriptor, String(process.pid));
|
|
415
|
-
fs.closeSync(descriptor);
|
|
416
|
-
return () => {
|
|
417
|
-
const holder = Number.parseInt(fs.readFileSync(file, "utf8"), 10);
|
|
418
|
-
if (holder === process.pid) fs.rmSync(file, { force: true });
|
|
419
|
-
};
|
|
420
|
-
} catch (error) {
|
|
421
|
-
if (error.code !== "EEXIST") throw error;
|
|
422
|
-
let holder = 0;
|
|
423
|
-
try {
|
|
424
|
-
holder = Number.parseInt(fs.readFileSync(file, "utf8"), 10);
|
|
425
|
-
} catch {
|
|
426
|
-
// 锁文件刚被释放,下一轮重试。
|
|
427
|
-
}
|
|
428
|
-
if (holder > 0 && isHolderAlive(holder)) return null;
|
|
429
|
-
fs.rmSync(file, { force: true });
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
return null;
|
|
433
|
-
};
|
package/scripts/bridge/watch.mjs
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// Claude 端的投递者:以 asyncRewake hook 运行,等信箱来消息后 exit 2 唤醒会话。
|
|
2
|
-
//
|
|
3
|
-
// 实测(Claude Code 2.1.281):
|
|
4
|
-
// - asyncRewake hook 以 exit 2 退出时,stderr 作为系统提醒进入会话;会话空闲会被唤醒,
|
|
5
|
-
// 忙碌则注入当前回合;
|
|
6
|
-
// - hook 的 timeout 会被强制执行,所以 watcher 在超时前主动退出,下一次 SessionStart /
|
|
7
|
-
// UserPromptSubmit / Stop 事件再重新挂上;
|
|
8
|
-
// - 会话退出时 hook 子进程会被清理。
|
|
9
|
-
//
|
|
10
|
-
// 每个会话只保留一个 watcher(锁文件),否则多个 watcher 会抢同一个信箱、重复唤醒。
|
|
11
|
-
|
|
12
|
-
import fs from "node:fs";
|
|
13
|
-
import { formatEnvelope } from "./core.mjs";
|
|
14
|
-
import { currentOptions } from "./options.mjs";
|
|
15
|
-
import { isProcessAlive } from "./process.mjs";
|
|
16
|
-
import { acquireLock, claimInbox, isBridgeEnabled, safeSessionId, updateReceipt } from "./store.mjs";
|
|
17
|
-
|
|
18
|
-
// 安装时 hook 的 timeout 是 3600 秒,这里留 5 分钟余量主动退出,保证锁由自己释放。
|
|
19
|
-
const DEFAULT_WATCH_SECONDS = 3300;
|
|
20
|
-
const DEFAULT_POLL_MS = 1000;
|
|
21
|
-
|
|
22
|
-
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
23
|
-
|
|
24
|
-
export const runWatch = async (rawInput, environment = process.env) => {
|
|
25
|
-
// 关闭"自动唤醒"后 watcher 本不会被安装;配置还没刷新到对方 CLI 时在这里兜底。
|
|
26
|
-
if (!isBridgeEnabled() || !currentOptions().wake) return 0;
|
|
27
|
-
let payload;
|
|
28
|
-
try {
|
|
29
|
-
payload = JSON.parse(rawInput);
|
|
30
|
-
} catch {
|
|
31
|
-
return 0;
|
|
32
|
-
}
|
|
33
|
-
const sessionId = safeSessionId(payload?.session_id);
|
|
34
|
-
if (!sessionId) return 0;
|
|
35
|
-
|
|
36
|
-
const release = acquireLock(`watch-${sessionId}`, isProcessAlive);
|
|
37
|
-
if (!release) return 0;
|
|
38
|
-
|
|
39
|
-
const seconds = Number(environment.CC_BRIDGE_WATCH_SECONDS) || DEFAULT_WATCH_SECONDS;
|
|
40
|
-
const pollMs = Number(environment.CC_BRIDGE_POLL_MS) || DEFAULT_POLL_MS;
|
|
41
|
-
const deadline = Date.now() + seconds * 1000;
|
|
42
|
-
const parent = process.ppid;
|
|
43
|
-
try {
|
|
44
|
-
while (Date.now() < deadline) {
|
|
45
|
-
// 宿主会话已经没了(被 kill -9 等,没来得及清理子进程)就别再占着锁。
|
|
46
|
-
if (!isProcessAlive(parent)) return 0;
|
|
47
|
-
const messages = claimInbox(sessionId);
|
|
48
|
-
if (messages.length > 0) {
|
|
49
|
-
for (const message of messages) {
|
|
50
|
-
updateReceipt(message.id, { status: "delivered", transport: { kind: "claude-rewake" } });
|
|
51
|
-
}
|
|
52
|
-
process.stderr.write(`${messages.map(formatEnvelope).join("\n\n")}\n`);
|
|
53
|
-
return 2;
|
|
54
|
-
}
|
|
55
|
-
await sleep(pollMs);
|
|
56
|
-
}
|
|
57
|
-
return 0;
|
|
58
|
-
} finally {
|
|
59
|
-
release();
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
export const main = async () => {
|
|
64
|
-
try {
|
|
65
|
-
return await runWatch(fs.readFileSync(0, "utf8"));
|
|
66
|
-
} catch {
|
|
67
|
-
return 0;
|
|
68
|
-
}
|
|
69
|
-
};
|
package/scripts/check-l10n.mjs
DELETED
|
@@ -1,168 +0,0 @@
|
|
|
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("、")})。`);
|