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
@@ -5,3 +5,7 @@ void PruneStaleRuntimeState(void);
5
5
 
6
6
  // clean 删除可重建缓存;purge 额外删除历史、更新配置和用户偏好。
7
7
  int CleanCCPetsData(BOOL purge);
8
+
9
+ // cc-pets paths / doctor 用:各类数据的实际路径(已套用环境变量覆盖)与桌宠是否在运行。
10
+ // 台词路径在 CCPetsPhrases 里,由 main.m 补上,免得只链接清理模块的测试也得带上整个词库。
11
+ NSDictionary<NSString *, id> *CCPetsDataPaths(void);
@@ -1,3 +1,4 @@
1
+ #import "CCPetsL10n.h"
1
2
  #import "CCPetsCleanup.h"
2
3
  #import "CCPetsPaths.h"
3
4
  #import <sys/file.h>
@@ -19,6 +20,14 @@ static NSString *ClientStateDirectory(void) {
19
20
  return [PetStateDirectory() stringByAppendingPathComponent:name];
20
21
  }
21
22
 
23
+ // pet-store 的素材源清单缓存(~/.cc-pets/cache,可用 CC_PETS_HOME 覆盖)。过期会自动重拉,
24
+ // 属于纯缓存;~/.cc-pets 下其余内容(素材、台词)是用户数据,clean 和 purge 都不碰。
25
+ static NSString *PetStoreCacheDirectory(void) {
26
+ NSString *home = NSProcessInfo.processInfo.environment[@"CC_PETS_HOME"];
27
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets"];
28
+ return [home.stringByStandardizingPath stringByAppendingPathComponent:@"cache"];
29
+ }
30
+
22
31
  static BOOL RemoveIfPresent(NSString *path) {
23
32
  if (path.length == 0 || ![NSFileManager.defaultManager fileExistsAtPath:path]) return NO;
24
33
  return [NSFileManager.defaultManager removeItemAtPath:path error:nil];
@@ -139,19 +148,19 @@ int CleanCCPetsData(BOOL purge) {
139
148
  NSString *supportDirectory = ApplicationSupportDirectory();
140
149
  NSString *buildCache = BuildCacheDirectory();
141
150
  if (!IsSafeSupportDirectory(supportDirectory)) {
142
- fprintf(stderr, "清理失败:应用数据目录不属于 CC Pets:%s\n",
143
- supportDirectory.UTF8String);
151
+ fprintf(stderr, "%s\n", [NSString stringWithFormat:
152
+ L(@"Clean failed: the app data directory doesn't belong to CC Pets: %@"), supportDirectory].UTF8String);
144
153
  return 3;
145
154
  }
146
155
  if (buildCache.length > 0 && !IsSafeBuildCacheDirectory(buildCache)) {
147
- fprintf(stderr, "清理失败:构建缓存目录不属于 CC Pets:%s\n",
148
- buildCache.UTF8String);
156
+ fprintf(stderr, "%s\n", [NSString stringWithFormat:
157
+ L(@"Clean failed: the build cache directory doesn't belong to CC Pets: %@"), buildCache].UTF8String);
149
158
  return 3;
150
159
  }
151
160
  NSUInteger removed = 0;
152
161
  if (RemoveClaudeUsageIfUnlocked()) removed += 1;
153
162
  for (NSString *path in @[AgentEventPath(), CodexLiveUsagePath(), CodexLaunchRegistryPath(), RuntimeLockPath(),
154
- ClientStateDirectory(), buildCache ?: @""]) {
163
+ ClientStateDirectory(), PetStoreCacheDirectory(), buildCache ?: @""]) {
155
164
  if (RemoveIfPresent(path)) removed += 1;
156
165
  }
157
166
  // Token 摘要缓存也是纯缓存(丢了只是重新解析一遍会话文件),原先漏在清理之外,
@@ -166,7 +175,32 @@ int CleanCCPetsData(BOOL purge) {
166
175
  [NSUserDefaults.standardUserDefaults removePersistentDomainForName:domain];
167
176
  [NSUserDefaults.standardUserDefaults synchronize];
168
177
  }
169
- printf("%s完成,共移除 %lu 项。\n", purge ? "完整数据清理" : "缓存清理",
170
- (unsigned long)removed);
178
+ NSString *format = purge
179
+ ? (removed != 1 ? L(@"Full cleanup done. Removed %lu items.") : L(@"Full cleanup done. Removed %lu item."))
180
+ : (removed != 1 ? L(@"Cache cleanup done. Removed %lu items.") : L(@"Cache cleanup done. Removed %lu item."));
181
+ printf("%s\n", [NSString stringWithFormat:format, (unsigned long)removed].UTF8String);
171
182
  return EXIT_SUCCESS;
172
183
  }
184
+
185
+ // 路径全部取自运行时真正使用的函数,Node 侧的 doctor 只负责展示,不再自己拼一套。
186
+ NSDictionary<NSString *, id> *CCPetsDataPaths(void) {
187
+ NSString *domain = NSProcessInfo.processInfo.environment[@"CC_PETS_PREFERENCES_DOMAIN"];
188
+ if (domain.length == 0) domain = PreferencesDomain;
189
+ NSString *preferences = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Preferences"]
190
+ stringByAppendingPathComponent:domain] stringByAppendingPathExtension:@"plist"];
191
+ return @{
192
+ @"running": @(RuntimeIsActive()),
193
+ @"preferences": preferences,
194
+ @"applicationSupport": ApplicationSupportDirectory(),
195
+ @"quotaHistory": QuotaHistoryPath(),
196
+ @"stateDirectory": PetStateDirectory(),
197
+ @"agentEvents": AgentEventPath(),
198
+ @"claudeUsage": ClaudeUsagePath(),
199
+ @"codexLiveUsage": CodexLiveUsagePath(),
200
+ @"codexLaunches": CodexLaunchRegistryPath(),
201
+ @"runtimeLock": RuntimeLockPath(),
202
+ @"clients": ClientStateDirectory(),
203
+ @"pets": OwnPetsDirectory(),
204
+ @"petStoreCache": PetStoreCacheDirectory(),
205
+ };
206
+ }
@@ -1,3 +1,4 @@
1
+ #import "CCPetsL10n.h"
1
2
  #import "CCPetsEvents.h"
2
3
  #import "CCPetsPaths.h"
3
4
  #import "CCPetsTerminalFocus.h"
@@ -210,7 +211,7 @@ int RecordProviderEvent(void) {
210
211
  if (![payload isKindOfClass:NSDictionary.class] ||
211
212
  ![payload[@"schemaVersion"] isKindOfClass:NSNumber.class] ||
212
213
  [payload[@"schemaVersion"] integerValue] != 1) {
213
- fprintf(stderr, "provider-event 需要 schemaVersion 为 1 的 JSON 对象。\n");
214
+ fprintf(stderr, "%s\n", L(@"provider-event needs a JSON object with schemaVersion 1.").UTF8String);
214
215
  return 2;
215
216
  }
216
217
  NSString *provider = SanitizedShortString(payload[@"provider"], 32);
@@ -221,7 +222,7 @@ int RecordProviderEvent(void) {
221
222
  @"tool_completed", @"tool_failed", @"completed", @"failed", @"notification"
222
223
  ]];
223
224
  if (provider.length == 0 || ![states containsObject:state]) {
224
- fprintf(stderr, "provider-event 的 provider 或 state 无效。\n");
225
+ fprintf(stderr, "%s\n", L(@"provider-event has an invalid provider or state.").UTF8String);
225
226
  return 2;
226
227
  }
227
228
  NSDictionary<NSString *, NSString *> *events = @{
@@ -247,7 +248,7 @@ int RecordProviderEvent(void) {
247
248
  NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
248
249
  if (terminal.count > 0) record[@"terminal"] = terminal;
249
250
  if (!AppendAgentEventRecord(record)) {
250
- fprintf(stderr, "无法写入 Provider 事件。\n");
251
+ fprintf(stderr, "%s\n", L(@"Couldn't write the provider event.").UTF8String);
251
252
  return EXIT_FAILURE;
252
253
  }
253
254
  return EXIT_SUCCESS;
@@ -0,0 +1,55 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // 界面多语言。
4
+ //
5
+ // 源码里直接写英文原文,它同时就是查表的 key(gettext 的做法):
6
+ // - 英文界面不查表,原样返回;
7
+ // - 其他语言查 <语言>.lproj/Localizable.strings,查不到就退回英文原文。
8
+ // 英文是源语言:漏翻的条目显示英文,比让别的语言用户看到某种第三语言好接受;
9
+ // 新语言也从英文译。代价是改了英文原文要同步改各语言表的 key,
10
+ // scripts/check-l10n.mjs 会把漏掉的报出来。
11
+ //
12
+ // 带参数的文案照常写 %@ / %ld;参数顺序和译文语序不同时,两边都用 %1$@ / %2$@ 标位置。
13
+ //
14
+ // 支持哪些语言不写在代码里:英文之外,有 <语言>.lproj/Localizable.strings 的就算支持。
15
+ // 新增一种语言只需加文件,见 CONTRIBUTING.md 的「多语言」一节。每张表除了界面文案,
16
+ // 还要带两条约定的元信息(键见下方常量):语言自己的名字、Release 说明里对应段落的标题。
17
+
18
+ // 语言偏好(NSUserDefaults):system 或某个支持的语言标识(en、zh-Hans…)。
19
+ extern NSString *const CCPetsLanguageKey;
20
+ extern NSString *const CCPetsLanguageSystem;
21
+ // 源语言,也是什么都匹配不上时的兜底。
22
+ extern NSString *const CCPetsSourceLanguage;
23
+ // 表里的元信息键。"Language Name" 的值是菜单里显示的语言名(用该语言自己的写法);
24
+ // "Release Notes Section" 是 GitHub Release 里该语言段落的标题,有多种写法时用 | 隔开。
25
+ extern NSString *const CCPetsLanguageNameKey;
26
+ extern NSString *const CCPetsReleaseNotesSectionKey;
27
+ // 切换语言后发出;常驻的界面(状态卡、额度面板、编辑器)收到后重绘。菜单每次现建,不用管。
28
+ extern NSNotificationName const CCPetsLanguageDidChangeNotification;
29
+
30
+ // 支持的语言:源语言在最前,其余按标识排序。
31
+ NSArray<NSString *> *CCPetsSupportedLanguages(void);
32
+ // 菜单里显示的语言名。
33
+ NSString *CCPetsLanguageDisplayName(NSString *language);
34
+ // Release 说明里该语言段落可能的标题。
35
+ NSArray<NSString *> *CCPetsReleaseNotesSectionTitles(NSString *language);
36
+
37
+ NSString *CCPetsLanguagePreference(void);
38
+ void CCPetsSetLanguagePreference(NSString *preference);
39
+ // 实际生效的语言,一定在 CCPetsSupportedLanguages() 里。
40
+ // 环境变量 CC_PETS_LANGUAGE 优先(测试用,也方便临时切换),其次是偏好,最后跟随系统:
41
+ // 系统首选语言里第一个能匹配上的说了算,都匹配不上就用源语言。
42
+ NSString *CCPetsCurrentLanguage(void);
43
+ BOOL CCPetsLanguageIsSource(void);
44
+ // 按给定的支持列表解析,不读任何全局状态,测试用。匹配规则:先找完全一致或前缀一致的
45
+ // (zh-Hans-CN → zh-Hans),再退到只比主语言(zh-Hant → zh-Hans、ja_JP → ja)。
46
+ NSString *CCPetsResolveLanguageAmong(NSString *preference, NSArray<NSString *> *systemLanguages,
47
+ NSArray<NSString *> *supported);
48
+
49
+ NSString *CCPetsLocalized(NSString *text) NS_FORMAT_ARGUMENT(1);
50
+ #define L(text) CCPetsLocalized(text)
51
+
52
+ // ~/.cc-pets/language(可用 CC_PETS_HOME 覆盖)。桌宠把实际生效的语言写在这里,
53
+ // Node 端的 cc-pets / hook / CC Bridge 据此输出同一种语言。
54
+ NSString *CCPetsLanguageFilePath(void);
55
+ void CCPetsWriteLanguageFile(void);
@@ -0,0 +1,219 @@
1
+ #import "CCPetsL10n.h"
2
+
3
+ NSString *const CCPetsLanguageKey = @"CCPetsLanguage";
4
+ NSString *const CCPetsLanguageSystem = @"system";
5
+ NSString *const CCPetsSourceLanguage = @"en";
6
+ NSString *const CCPetsLanguageNameKey = @"Language Name";
7
+ NSString *const CCPetsReleaseNotesSectionKey = @"Release Notes Section";
8
+ NSNotificationName const CCPetsLanguageDidChangeNotification = @"CCPetsLanguageDidChange";
9
+
10
+ // 源语言没有表,名字和 Release 段落标题只能写在这里。
11
+ static NSString *const CCPetsSourceLanguageName = @"English";
12
+
13
+ // 放 .lproj 的目录,依次是:CC_PETS_LOCALIZATION_DIR(测试用)、app bundle、
14
+ // 可执行文件旁边(直接跑 .build/release/cc-pets 时没有 bundle)。
15
+ static NSArray<NSString *> *CCPetsLocalizationDirectories(void) {
16
+ NSMutableArray<NSString *> *directories = [NSMutableArray array];
17
+ NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_LOCALIZATION_DIR"];
18
+ if (override.length > 0) [directories addObject:override.stringByStandardizingPath];
19
+ NSString *resources = NSBundle.mainBundle.resourcePath;
20
+ if (resources.length > 0) [directories addObject:resources];
21
+ NSString *executableDirectory =
22
+ NSBundle.mainBundle.executablePath.stringByDeletingLastPathComponent;
23
+ if (executableDirectory.length > 0) [directories addObject:executableDirectory];
24
+ return directories;
25
+ }
26
+
27
+ static NSString *CCPetsTablePath(NSString *directory, NSString *language) {
28
+ return [[directory stringByAppendingPathComponent:
29
+ [language stringByAppendingPathExtension:@"lproj"]]
30
+ stringByAppendingPathComponent:@"Localizable.strings"];
31
+ }
32
+
33
+ // 每种语言的表只读一次。表随 app 打包,运行期不会变。
34
+ static NSMutableDictionary<NSString *, NSDictionary<NSString *, NSString *> *> *CCPetsTables;
35
+
36
+ static NSDictionary<NSString *, NSString *> *CCPetsTable(NSString *language) {
37
+ if (language.length == 0 || [language isEqualToString:CCPetsSourceLanguage]) return nil;
38
+ @synchronized(CCPetsLanguageKey) {
39
+ if (!CCPetsTables) CCPetsTables = [NSMutableDictionary dictionary];
40
+ id cached = CCPetsTables[language];
41
+ if (cached) return cached == NSNull.null ? nil : cached;
42
+ NSDictionary *table = nil;
43
+ for (NSString *directory in CCPetsLocalizationDirectories()) {
44
+ NSDictionary *candidate = [NSDictionary dictionaryWithContentsOfFile:
45
+ CCPetsTablePath(directory, language)];
46
+ if ([candidate isKindOfClass:NSDictionary.class]) {
47
+ table = candidate;
48
+ break;
49
+ }
50
+ }
51
+ CCPetsTables[language] = table ?: (id)NSNull.null;
52
+ return table;
53
+ }
54
+ }
55
+
56
+ NSArray<NSString *> *CCPetsSupportedLanguages(void) {
57
+ static NSArray<NSString *> *languages;
58
+ static dispatch_once_t once;
59
+ dispatch_once(&once, ^{
60
+ NSMutableSet<NSString *> *found = [NSMutableSet set];
61
+ NSFileManager *manager = NSFileManager.defaultManager;
62
+ for (NSString *directory in CCPetsLocalizationDirectories()) {
63
+ for (NSString *entry in [manager contentsOfDirectoryAtPath:directory error:nil]) {
64
+ if (![entry.pathExtension isEqualToString:@"lproj"]) continue;
65
+ NSString *language = entry.stringByDeletingPathExtension;
66
+ if ([language isEqualToString:CCPetsSourceLanguage]) continue;
67
+ // 只有 InfoPlist.strings 的目录(如 en.lproj)不算一种界面语言。
68
+ if ([manager fileExistsAtPath:CCPetsTablePath(directory, language)]) {
69
+ [found addObject:language];
70
+ }
71
+ }
72
+ }
73
+ NSArray *sorted = [found.allObjects sortedArrayUsingSelector:@selector(compare:)];
74
+ languages = [@[CCPetsSourceLanguage] arrayByAddingObjectsFromArray:sorted];
75
+ });
76
+ return languages;
77
+ }
78
+
79
+ NSString *CCPetsLanguageDisplayName(NSString *language) {
80
+ if ([language isEqualToString:CCPetsSourceLanguage]) return CCPetsSourceLanguageName;
81
+ NSString *name = CCPetsTable(language)[CCPetsLanguageNameKey];
82
+ return name.length > 0 ? name : language;
83
+ }
84
+
85
+ NSArray<NSString *> *CCPetsReleaseNotesSectionTitles(NSString *language) {
86
+ if ([language isEqualToString:CCPetsSourceLanguage]) return @[CCPetsSourceLanguageName];
87
+ NSString *titles = CCPetsTable(language)[CCPetsReleaseNotesSectionKey];
88
+ NSMutableArray<NSString *> *result = [NSMutableArray array];
89
+ for (NSString *title in [titles componentsSeparatedByString:@"|"]) {
90
+ NSString *trimmed = [title stringByTrimmingCharactersInSet:
91
+ NSCharacterSet.whitespaceCharacterSet];
92
+ if (trimmed.length > 0) [result addObject:trimmed];
93
+ }
94
+ return result;
95
+ }
96
+
97
+ // zh_CN.UTF-8 → zh-cn。系统给的是 BCP 47(zh-Hans-CN),环境变量里常是 POSIX 写法。
98
+ static NSString *CCPetsNormalizedTag(NSString *tag) {
99
+ NSString *lower = [tag.lowercaseString stringByReplacingOccurrencesOfString:@"_" withString:@"-"];
100
+ NSRange dot = [lower rangeOfString:@"."];
101
+ return dot.location == NSNotFound ? lower : [lower substringToIndex:dot.location];
102
+ }
103
+
104
+ static NSString *CCPetsBaseLanguage(NSString *normalizedTag) {
105
+ return [normalizedTag componentsSeparatedByString:@"-"].firstObject;
106
+ }
107
+
108
+ static NSString *CCPetsMatchLanguage(NSString *candidate, NSArray<NSString *> *supported) {
109
+ NSString *tag = CCPetsNormalizedTag(candidate);
110
+ if (tag.length == 0) return nil;
111
+ for (NSString *language in supported) {
112
+ NSString *lower = language.lowercaseString;
113
+ if ([tag isEqualToString:lower] || [tag hasPrefix:[lower stringByAppendingString:@"-"]]) {
114
+ return language;
115
+ }
116
+ }
117
+ NSString *base = CCPetsBaseLanguage(tag);
118
+ for (NSString *language in supported) {
119
+ if ([CCPetsBaseLanguage(language.lowercaseString) isEqualToString:base]) return language;
120
+ }
121
+ return nil;
122
+ }
123
+
124
+ NSString *CCPetsResolveLanguageAmong(NSString *preference, NSArray<NSString *> *systemLanguages,
125
+ NSArray<NSString *> *supported) {
126
+ NSString *explicit = [preference isEqualToString:CCPetsLanguageSystem] ? nil
127
+ : CCPetsMatchLanguage(preference, supported);
128
+ if (explicit) return explicit;
129
+ for (NSString *language in systemLanguages) {
130
+ NSString *match = CCPetsMatchLanguage(language, supported);
131
+ if (match) return match;
132
+ }
133
+ return CCPetsSourceLanguage;
134
+ }
135
+
136
+ static NSString *CCPetsNormalizedPreference(NSString *preference) {
137
+ return [CCPetsSupportedLanguages() containsObject:preference] ? preference : CCPetsLanguageSystem;
138
+ }
139
+
140
+ NSString *CCPetsLanguagePreference(void) {
141
+ return CCPetsNormalizedPreference(
142
+ [NSUserDefaults.standardUserDefaults stringForKey:CCPetsLanguageKey]);
143
+ }
144
+
145
+ // 当前语言在偏好和环境变量都不变时不会变,但查表在绘制路径上每帧都可能调用,
146
+ // 缓存一份,切换偏好时清掉。
147
+ static NSString *CCPetsCachedLanguage;
148
+
149
+ // 系统首选语言。偏好里选了具体语言时,桌宠会把 AppleLanguages 写进自己的 defaults 域,
150
+ // 好让系统自带的按钮、面板在下次启动后也换成同一种语言;所以这里要读全局域,
151
+ // 不能用 NSLocale.preferredLanguages(它会读到我们自己写进去的那份)。
152
+ static NSArray<NSString *> *CCPetsSystemLanguages(void) {
153
+ NSArray *global = [[NSUserDefaults.standardUserDefaults
154
+ persistentDomainForName:NSGlobalDomain] objectForKey:@"AppleLanguages"];
155
+ if ([global isKindOfClass:NSArray.class] && global.count > 0) return global;
156
+ return NSLocale.preferredLanguages;
157
+ }
158
+
159
+ NSString *CCPetsCurrentLanguage(void) {
160
+ @synchronized(CCPetsLanguageKey) {
161
+ if (CCPetsCachedLanguage) return CCPetsCachedLanguage;
162
+ NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_LANGUAGE"];
163
+ NSString *preference = override.length > 0 ? override : CCPetsLanguagePreference();
164
+ CCPetsCachedLanguage = CCPetsResolveLanguageAmong(preference, CCPetsSystemLanguages(),
165
+ CCPetsSupportedLanguages());
166
+ return CCPetsCachedLanguage;
167
+ }
168
+ }
169
+
170
+ BOOL CCPetsLanguageIsSource(void) {
171
+ return [CCPetsCurrentLanguage() isEqualToString:CCPetsSourceLanguage];
172
+ }
173
+
174
+ NSString *CCPetsLocalized(NSString *text) {
175
+ if (text.length == 0) return text;
176
+ NSString *language = CCPetsCurrentLanguage();
177
+ if ([language isEqualToString:CCPetsSourceLanguage]) return text;
178
+ NSString *translated = CCPetsTable(language)[text];
179
+ return translated.length > 0 ? translated : text;
180
+ }
181
+
182
+ NSString *CCPetsLanguageFilePath(void) {
183
+ NSString *home = NSProcessInfo.processInfo.environment[@"CC_PETS_HOME"];
184
+ if (home.length == 0) {
185
+ home = [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets"];
186
+ }
187
+ return [home.stringByStandardizingPath stringByAppendingPathComponent:@"language"];
188
+ }
189
+
190
+ void CCPetsWriteLanguageFile(void) {
191
+ NSString *path = CCPetsLanguageFilePath();
192
+ NSString *language = CCPetsCurrentLanguage();
193
+ NSString *existing = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding
194
+ error:nil];
195
+ NSString *content = [language stringByAppendingString:@"\n"];
196
+ if ([existing isEqualToString:content]) return;
197
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
198
+ withIntermediateDirectories:YES attributes:nil error:nil];
199
+ [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
200
+ }
201
+
202
+ void CCPetsSetLanguagePreference(NSString *preference) {
203
+ NSString *normalized = CCPetsNormalizedPreference(preference);
204
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
205
+ [defaults setObject:normalized forKey:CCPetsLanguageKey];
206
+ // 系统自带的部分(NSAlert 默认按钮、打开面板、编辑菜单的系统项)跟 AppleLanguages 走,
207
+ // 只在下次启动时生效。跟随系统时删掉,回到全局设置。
208
+ if ([normalized isEqualToString:CCPetsLanguageSystem]) {
209
+ [defaults removeObjectForKey:@"AppleLanguages"];
210
+ } else {
211
+ [defaults setObject:@[normalized] forKey:@"AppleLanguages"];
212
+ }
213
+ @synchronized(CCPetsLanguageKey) {
214
+ CCPetsCachedLanguage = nil;
215
+ }
216
+ CCPetsWriteLanguageFile();
217
+ [NSNotificationCenter.defaultCenter
218
+ postNotificationName:CCPetsLanguageDidChangeNotification object:nil];
219
+ }
@@ -42,7 +42,6 @@ BOOL ClaudeCLIDetected(void);
42
42
  // 已存在的同名目录一律跳过,不覆盖。
43
43
  NSUInteger ImportCodexPets(void);
44
44
 
45
- extern NSString *const HistoryEnabledKey;
46
45
  extern NSString *const NotificationCompletionKey;
47
46
  extern NSString *const NotificationFailureKey;
48
47
  extern NSString *const NotificationApprovalKey;
@@ -223,7 +223,6 @@ NSUInteger ImportCodexPets(void) {
223
223
  return imported;
224
224
  }
225
225
 
226
- NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
227
226
  NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
228
227
  NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
229
228
  NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
@@ -80,7 +80,7 @@ void PetPhrasesSetCurrentPetID(NSString *petID);
80
80
  NSString *PetPhrasesCurrentPetID(void);
81
81
  // 当前宠物的专属词库路径。还没设过宠物时返回 nil。
82
82
  NSString *PetPhrasesCurrentPetFilePath(void);
83
- // 默认词库路径:app bundle 里的 phrases.default.txt。
83
+ // 默认词库路径:app bundle 里当前语言的 phrases.default.<语言>.txt,没有就用英文那份。
84
84
  // 可用 CC_PETS_PHRASES_DEFAULT_FILE 覆盖(测试用)。
85
85
  NSString *PetPhrasesDefaultFilePath(void);
86
86
  // 用户词库不存在就从默认词库拷一份出来。返回是否可用。
@@ -89,6 +89,9 @@ NSString *PetPhrasesDefaultFilePath(void);
89
89
  // 这一刻出现一次,之后运行时只认用户文件。两份词库同时存在于运行期就必然要回答
90
90
  // "以谁为准",那正是 merge/replace 那套让人看不懂的根源。
91
91
  BOOL PetPhrasesEnsureFileExists(void);
92
+ // 用户词库和"另一种语言"的默认词库一字不差(也就是从没改过)时,换成当前语言的默认词库。
93
+ // 改过一个字都不动:那是用户自己的台词,语言切换不该替他做主。返回是否替换了。
94
+ BOOL PetPhrasesAdoptLanguageDefaults(void);
92
95
  // 给升级用户补一次新加入的连击互动小节;已有小节(包括用户主动留空)绝不覆盖。
93
96
  BOOL PetPhrasesEnsureInteractionSections(void);
94
97
 
@@ -104,7 +107,10 @@ NSArray<NSString *> *PetPhraseSlotNames(void);
104
107
 
105
108
  // 单条模板的长度上限(字符)。超了直接丢弃——气泡布局撑不下,
106
109
  // 与其截断出半句话不如不说。
110
+ // 含中日韩字符的句子按 PetPhraseMaxLength,纯拉丁文字的按 PetPhraseMaxLatinLength。
107
111
  extern const NSUInteger PetPhraseMaxLength;
112
+ extern const NSUInteger PetPhraseMaxLatinLength;
113
+ NSUInteger PetPhraseMaxLengthForText(NSString *text);
108
114
 
109
115
  // 校验结果的一条。
110
116
  typedef NS_ENUM(NSInteger, PetPhraseIssueLevel) {
@@ -1,4 +1,5 @@
1
1
  #import "CCPetsPhrases.h"
2
+ #import "CCPetsL10n.h"
2
3
 
3
4
  NSString *const PetPhraseTagDone = @"done";
4
5
  NSString *const PetPhraseTagFail = @"fail";
@@ -27,6 +28,26 @@ NSString *const PetPhraseTagStateFailed = @"state_failed";
27
28
  NSString *const PetPhraseTagStateNotification = @"state_notification";
28
29
 
29
30
  const NSUInteger PetPhraseMaxLength = 30;
31
+ const NSUInteger PetPhraseMaxLatinLength = 40;
32
+
33
+ // 气泡最宽 300pt、13pt 字号:汉字一个顶一个字宽,30 个刚好;英文字母大约半个字宽,
34
+ // 同样宽度能放 40 个上下。按"有没有中日韩字符"二选一,不做逐字加权——加权之后用户
35
+ // 没法对着报错数出自己超了多少。
36
+ NSUInteger PetPhraseMaxLengthForText(NSString *text) {
37
+ static NSCharacterSet *wide;
38
+ static dispatch_once_t once;
39
+ dispatch_once(&once, ^{
40
+ NSMutableCharacterSet *set = [NSMutableCharacterSet new];
41
+ [set addCharactersInRange:NSMakeRange(0x1100, 0x0100)]; // 谚文字母
42
+ [set addCharactersInRange:NSMakeRange(0x2E80, 0xA4D0 - 0x2E80)]; // 中日韩部首到彝文
43
+ [set addCharactersInRange:NSMakeRange(0xAC00, 0xD7A4 - 0xAC00)]; // 谚文音节
44
+ [set addCharactersInRange:NSMakeRange(0xF900, 0x0200)]; // 兼容汉字
45
+ [set addCharactersInRange:NSMakeRange(0xFF00, 0x0061)]; // 全角 ASCII
46
+ wide = set;
47
+ });
48
+ return [text rangeOfCharacterFromSet:wide].location == NSNotFound
49
+ ? PetPhraseMaxLatinLength : PetPhraseMaxLength;
50
+ }
30
51
  // 最近说过的这么多条不再重复。模板库不大,靠这个把主观重复感压下去。
31
52
  static const NSUInteger PetPhraseRecentMemory = 12;
32
53
 
@@ -118,16 +139,49 @@ NSString *PetPhrasesCurrentPetFilePath(void) {
118
139
  return PetPhrasesFilePathForPetID(PetPhrasesCurrentPet);
119
140
  }
120
141
 
121
- NSString *PetPhrasesDefaultFilePath(void) {
122
- NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_PHRASES_DEFAULT_FILE"];
123
- if (override.length > 0) return override.stringByStandardizingPath;
124
- NSString *bundled = [NSBundle.mainBundle pathForResource:@"phrases.default"
125
- ofType:@"txt"];
142
+ // 每种界面语言一份默认词库:phrases.default.<语言>.txt(zh-Hans、en…)。找不到返回 nil。
143
+ static NSString *PetPhrasesBundledDefaultPath(NSString *language) {
144
+ NSString *name = [@"phrases.default." stringByAppendingString:language];
145
+ NSString *bundled = [NSBundle.mainBundle pathForResource:name ofType:@"txt"];
126
146
  if (bundled.length > 0) return bundled;
127
147
  // 直接跑 .build/release/cc-pets(没有 app bundle)时退到可执行文件旁边,
128
148
  // 否则开发期跑起来一句台词都没有,会被误当成解析出了问题。
129
149
  NSString *executable = NSBundle.mainBundle.executablePath.stringByDeletingLastPathComponent;
130
- return [executable stringByAppendingPathComponent:@"phrases.default.txt"];
150
+ NSString *path = [executable stringByAppendingPathComponent:
151
+ [name stringByAppendingPathExtension:@"txt"]];
152
+ return [NSFileManager.defaultManager fileExistsAtPath:path] ? path : nil;
153
+ }
154
+
155
+ // 当前语言没有默认台词(翻译只做了界面)时退回源语言那份。
156
+ NSString *PetPhrasesDefaultFilePath(void) {
157
+ NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_PHRASES_DEFAULT_FILE"];
158
+ if (override.length > 0) return override.stringByStandardizingPath;
159
+ NSString *path = PetPhrasesBundledDefaultPath(CCPetsCurrentLanguage()) ?:
160
+ PetPhrasesBundledDefaultPath(CCPetsSourceLanguage);
161
+ if (path.length > 0) return path;
162
+ NSString *executable = NSBundle.mainBundle.executablePath.stringByDeletingLastPathComponent;
163
+ return [executable stringByAppendingPathComponent:
164
+ [NSString stringWithFormat:@"phrases.default.%@.txt", CCPetsSourceLanguage]];
165
+ }
166
+
167
+ BOOL PetPhrasesAdoptLanguageDefaults(void) {
168
+ // 测试指定了默认词库时只有那一份,没有"另一种语言"可比。
169
+ if (NSProcessInfo.processInfo.environment[@"CC_PETS_PHRASES_DEFAULT_FILE"].length > 0) return NO;
170
+ NSString *path = PetPhrasesFilePath();
171
+ NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
172
+ NSString *currentPath = PetPhrasesDefaultFilePath();
173
+ NSString *currentText = [NSString stringWithContentsOfFile:currentPath
174
+ encoding:NSUTF8StringEncoding error:nil];
175
+ if (text.length == 0 || currentText.length == 0 || [text isEqualToString:currentText]) return NO;
176
+ for (NSString *language in CCPetsSupportedLanguages()) {
177
+ NSString *otherPath = PetPhrasesBundledDefaultPath(language);
178
+ if (otherPath.length == 0 || [otherPath isEqualToString:currentPath]) continue;
179
+ NSString *otherText = [NSString stringWithContentsOfFile:otherPath
180
+ encoding:NSUTF8StringEncoding error:nil];
181
+ if (![text isEqualToString:otherText]) continue;
182
+ return [currentText writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
183
+ }
184
+ return NO;
131
185
  }
132
186
 
133
187
  BOOL PetPhrasesEnsureFileExists(void) {
@@ -178,20 +232,20 @@ NSString *PetPhraseTagDescription(NSString *tag) {
178
232
  static dispatch_once_t once;
179
233
  dispatch_once(&once, ^{
180
234
  map = @{
181
- PetPhraseTagIdle: @"闲着没事", PetPhraseTagDone: @"任务完成",
182
- PetPhraseTagFail: @"连续失败", PetPhraseTagWake: @"隔了很久又开工",
183
- PetPhraseTagLateNight: @"深夜还在干", PetPhraseTagLongSession: @"连续工作很久",
184
- PetPhraseTagQuotaLow: @"额度告急",
185
- PetPhraseTagClickHeart: @"连续点击后开心",
186
- PetPhraseTagClickAnnoyed: @"连续点击过多后烦躁",
187
- PetPhraseTagStateStarting: @"正在启动", PetPhraseTagStateIdle: @"待机中",
188
- PetPhraseTagStateThinking: @"正在思考", PetPhraseTagStateTool: @"正在用工具",
189
- PetPhraseTagStateToolBash: @"正在执行命令", PetPhraseTagStateToolEdit: @"正在编辑文件",
190
- PetPhraseTagStateToolRead: @"正在查找资料", PetPhraseTagStateToolDone: @"单步操作完成",
191
- PetPhraseTagStateToolFailed: @"工具执行失败", PetPhraseTagStateSubagent: @"子 Agent 工作中",
192
- PetPhraseTagStateApproval: @"等待审批", PetPhraseTagStateAutoReview: @"自动审批中",
193
- PetPhraseTagStateCompleted: @"任务已完成", PetPhraseTagStateFailed: @"任务失败",
194
- PetPhraseTagStateNotification: @"需要关注",
235
+ PetPhraseTagIdle: L(@"idle"), PetPhraseTagDone: L(@"Task done"),
236
+ PetPhraseTagFail: L(@"repeated failures"), PetPhraseTagWake: L(@"back after a long break"),
237
+ PetPhraseTagLateNight: L(@"working late at night"), PetPhraseTagLongSession: L(@"long session"),
238
+ PetPhraseTagQuotaLow: L(@"quota running low"),
239
+ PetPhraseTagClickHeart: L(@"happy after a few clicks"),
240
+ PetPhraseTagClickAnnoyed: L(@"annoyed after too many clicks"),
241
+ PetPhraseTagStateStarting: L(@"Starting"), PetPhraseTagStateIdle: L(@"Idle"),
242
+ PetPhraseTagStateThinking: L(@"Thinking"), PetPhraseTagStateTool: L(@"using a tool"),
243
+ PetPhraseTagStateToolBash: L(@"Running a command"), PetPhraseTagStateToolEdit: L(@"Editing files"),
244
+ PetPhraseTagStateToolRead: L(@"Looking things up"), PetPhraseTagStateToolDone: L(@"step done"),
245
+ PetPhraseTagStateToolFailed: L(@"Tool failed"), PetPhraseTagStateSubagent: L(@"Subagent working"),
246
+ PetPhraseTagStateApproval: L(@"Awaiting approval"), PetPhraseTagStateAutoReview: L(@"Auto-reviewing"),
247
+ PetPhraseTagStateCompleted: L(@"Task completed"), PetPhraseTagStateFailed: L(@"Task failed"),
248
+ PetPhraseTagStateNotification: L(@"Needs attention"),
195
249
  };
196
250
  });
197
251
  return map[tag] ?: tag;
@@ -241,8 +295,8 @@ static void FlushOrphans(void (^onDrop)(NSInteger line, NSString *reason),
241
295
  NSInteger *start, NSInteger *count) {
242
296
  if (*count == 0) return;
243
297
  if (onDrop) {
244
- onDrop(*start, *count == 1 ? @"这一句不在任何 [情境] 下面,不会生效" :
245
- [NSString stringWithFormat:@"这里有 %ld 句不在任何 [情境] 下面,都不会生效",
298
+ onDrop(*start, *count == 1 ? L(@"This line isn't under any [tag] and won't be used") :
299
+ [NSString stringWithFormat:L(@"%ld lines here aren't under any [tag] and won't be used"),
246
300
  (long)*count]);
247
301
  }
248
302
  *count = 0;
@@ -277,7 +331,7 @@ static NSDictionary<NSString *, NSArray<NSString *> *> *ParsePhrasesText(NSStrin
277
331
  current = nil;
278
332
  insideUnknownSection = YES;
279
333
  if (onDrop) onDrop(lineNumber,
280
- [NSString stringWithFormat:@"没有 [%@] 这个情境,下面的台词都不会生效", tag]);
334
+ [NSString stringWithFormat:L(@"There's no [%@] tag; the lines below won't be used"), tag]);
281
335
  continue;
282
336
  }
283
337
  insideUnknownSection = NO;
@@ -293,10 +347,11 @@ static NSDictionary<NSString *, NSArray<NSString *> *> *ParsePhrasesText(NSStrin
293
347
  }
294
348
  continue;
295
349
  }
296
- if (line.length > PetPhraseMaxLength) {
350
+ NSUInteger maxLength = PetPhraseMaxLengthForText(line);
351
+ if (line.length > maxLength) {
297
352
  if (onDrop) onDrop(lineNumber, [NSString stringWithFormat:
298
- @"这句 %lu 个字,超过 %lu 字上限", (unsigned long)line.length,
299
- (unsigned long)PetPhraseMaxLength]);
353
+ L(@"This line has %lu characters, over the %lu limit"), (unsigned long)line.length,
354
+ (unsigned long)maxLength]);
300
355
  continue;
301
356
  }
302
357
  [groups[current] addObject:line];
@@ -413,7 +468,7 @@ static NSArray<NSString *> *CandidatesForTag(NSString *tag) {
413
468
  // 解析时已逐行校验过,这里再挡一道,防止将来换了来源出岔子。
414
469
  if (![entry isKindOfClass:NSString.class]) continue;
415
470
  NSString *text = entry;
416
- if (text.length == 0 || text.length > PetPhraseMaxLength) continue;
471
+ if (text.length == 0 || text.length > PetPhraseMaxLengthForText(text)) continue;
417
472
  [result addObject:text];
418
473
  }
419
474
  return result;
@@ -634,7 +689,7 @@ static NSArray<PetPhraseIssue *> *ValidateText(NSString *text, BOOL forPet) {
634
689
  NSString *name = [line substringWithRange:[match rangeAtIndex:1]];
635
690
  if ([slots containsObject:name]) continue;
636
691
  [issues addObject:MakeIssue((NSInteger)index + 1, PetPhraseIssueLevelWarning,
637
- [NSString stringWithFormat:@"{%@} 不是可用的数据名,这句永远不会出现", name])];
692
+ [NSString stringWithFormat:L(@"{%@} isn't a known placeholder; this line will never be said"), name])];
638
693
  }
639
694
  }
640
695
 
@@ -652,17 +707,17 @@ static NSArray<PetPhraseIssue *> *ValidateText(NSString *text, BOOL forPet) {
652
707
  NSArray *entries = groups[tag];
653
708
  if (entries == nil) {
654
709
  [issues addObject:MakeIssue(0, PetPhraseIssueLevelError, [NSString stringWithFormat:
655
- @"少了 [%@](%@)这一行,标签不能删——加回来即可,下面不写台词也行",
710
+ L(@"The [%1$@] (%2$@) line is missing. Tags can't be deleted; add it back (it can stay empty)"),
656
711
  tag, PetPhraseTagDescription(tag)])];
657
712
  continue;
658
713
  }
659
714
  if (entries.count > 0) continue;
660
715
  if ([stateTags containsObject:tag]) {
661
716
  [issues addObject:MakeIssue(0, PetPhraseIssueLevelError, [NSString stringWithFormat:
662
- @"[%@](%@)至少要留一句", tag, PetPhraseTagDescription(tag)])];
717
+ L(@"[%1$@] (%2$@) needs at least one line"), tag, PetPhraseTagDescription(tag)])];
663
718
  } else {
664
719
  [issues addObject:MakeIssue(0, PetPhraseIssueLevelWarning, [NSString stringWithFormat:
665
- @"[%@](%@)是空的,这个情境桌宠不会主动开口", tag, PetPhraseTagDescription(tag)])];
720
+ L(@"[%1$@] (%2$@) is empty; the pet will stay quiet here"), tag, PetPhraseTagDescription(tag)])];
666
721
  }
667
722
  }
668
723