cc-pets 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ - 新增 `cc-pets pet` 素材管理命令(`search` / `add` / `list` / `remove` / `source` / `dir`),
8
+ 把素材下载到 cc-pets 自己的目录 `~/.cc-pets/pets/`,不再写 `~/.petdex/pets/` 和
9
+ `~/.codex/pets/`。两端都认 `CC_PETS_PETS_DIR` 覆盖。
10
+ - 桌宠端只扫 `~/.cc-pets/pets/` 和包内素材,无条件不再读 `~/.petdex/pets/` 和
11
+ `~/.codex/pets/`——那两个目录由别的工具写入,混在一起就挑不出自己装的宠物。
12
+ - 新增“导入 Codex 素材”开关(右键菜单,默认关):打开时立即把 `~/.codex/pets/` 里
13
+ 有精灵图的素材**复制**进自己的目录,之后每次启动再导入一次。复制而非关联,Codex
14
+ 那边的后续改动不影响桌宠;同名目录一律跳过不覆盖,自己装的素材优先;导入的素材写
15
+ `.source.json`(`source: "codex"`),`cc-pets pet list` 里单独分组。重复导入是幂等的。
16
+ - 素材列表改为启动时加载一次,之后按素材目录的 mtime 判断是否重扫。`add` / `remove`
17
+ 会改动目录因而立即生效,没有增删时打开右键菜单只做一次 `stat`,不再每次遍历目录。
18
+ - 素材来源抽象成「源」:`SOURCES` 表里一行就是一个源(清单地址、资源 host 白名单、
19
+ Referer),当前内置 PetDex,名称支持 `petdex:boba` 这样的源前缀,默认源用
20
+ `CC_PETS_SOURCE` 切换。这样以后接自建 registry 不用动命令面和目录结构。
21
+ 清单按源分别缓存 6 小时,下载只接受源白名单内的 host。
22
+ - 素材来源记在宠物目录内的 `.source.json`,目录名保持素材本名,桌宠菜单不受影响;
23
+ `list` 按来源分组。跨源同名或覆盖手放素材时 `add` 会拒绝并提示用 `--as` 改名安装,
24
+ 同源重装则直接更新。
7
25
  - 新增 Codex 与 Claude Code 本地 Token 用量统计,按官方重置时间对齐 5 小时与 7 天窗口;
8
26
  Claude 侧按 `message.id + requestId` 去重,避免 `--resume`/fork 复制的记录重复计数。
9
27
  官方订阅额度仍以服务端百分比为准。
package/README.md CHANGED
@@ -58,10 +58,18 @@ Claude Code Hook 会合并到 `~/.claude/settings.json`,现有的 `env`、`mod
58
58
  | 鼠标移开或拖动结束 | 恢复默认待机动画 |
59
59
  | 右键桌宠 | 切换桌宠、刷新用量、设置历史/通知、检查更新或退出 |
60
60
 
61
- 右键菜单中的“切换桌宠”会动态扫描 `~/.petdex/pets/`、`~/.codex/pets/` 以及包内素材。
61
+ 右键菜单中的“切换桌宠”只扫描 `~/.cc-pets/pets/`(见 [素材管理](#素材管理))和包内素材,
62
+ **不会**去读 `~/.petdex/pets/` 和 `~/.codex/pets/`——那两个目录由 PetDex CLI 和 Codex 写入,
63
+ 混在一起就找不到自己装的宠物了。要用 Codex 那边的素材,打开右键菜单里的“导入 Codex
64
+ 素材”开关,它们会被复制进你自己的目录(见 [导入 Codex 素材](#导入-codex-素材))。
65
+
62
66
  外部桌宠使用目录名作为菜单名称,内置桌宠使用素材文件名(不显示扩展名)。选择后立即
63
67
  切换并持久保存;下次启动会继续使用上次选择的桌宠。该菜单只负责切换已有素材,不提供
64
- 添加或删除功能。每次打开菜单都会重新扫描,因此通过 PetDex 安装新素材后无需重新编译。
68
+ 添加或删除功能。
69
+
70
+ 素材列表在启动时加载一次,之后按 `~/.cc-pets/pets/` 的修改时间判断是否需要重扫:
71
+ `cc-pets pet add` / `remove` 会改动这个目录,因此增删素材后打开菜单就能看到,
72
+ 不需要重启桌宠,也不需要重新编译;没有增删时打开菜单只做一次 `stat`,不会遍历目录。
65
73
 
66
74
  当 `~/.petdex/pets/<name>/` 只有 `pet.json` 时,程序会自动到
67
75
  `~/.codex/pets/<name>/` 查找同名桌宠的 `spritesheet.webp` 或 `spritesheet.png`。
@@ -234,6 +242,11 @@ cc-pets --history
234
242
  # 清理可重建的临时状态、更新日志和构建缓存,保留历史、配置与偏好
235
243
  cc-pets clean
236
244
 
245
+ # 管理 ~/.cc-pets/pets 里的桌宠素材,详见「素材与版权」
246
+ cc-pets pet search otter
247
+ cc-pets pet add boba
248
+ cc-pets pet list
249
+
237
250
  # 从标准输入发送第三方 Provider 状态事件
238
251
  printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
239
252
  | cc-pets provider-event
@@ -342,16 +355,82 @@ v2(`1536×2288`、`8×11`),单元格均为 `192×208`,前九行遵循相
342
355
  角色可能属于受版权保护的作品;公开
343
356
  发布本项目或 npm 包前,请确认已经获得素材的使用和分发授权,或替换为原创、可公开分发的素材。
344
357
 
345
- 也可以直接使用 PetDex 安装素材,无需放入项目目录:
358
+ ### 素材管理
359
+
360
+ `cc-pets pet` 把素材下载到 cc-pets 自己的目录 `~/.cc-pets/pets/<名称>/`,不写
361
+ `~/.petdex/pets/` 和 `~/.codex/pets/`:
362
+
363
+ ```bash
364
+ cc-pets pet search otter # 搜索可用素材(不带关键词就列全部)
365
+ cc-pets pet add boba # 下载到 ~/.cc-pets/pets/boba/
366
+ cc-pets pet add boba doraemon # 一次装多个
367
+ cc-pets pet list # 列出已安装的素材,按来源分组
368
+ cc-pets pet remove boba # 删除
369
+ cc-pets pet source # 列出可用的素材源
370
+ cc-pets pet dir # 打印素材目录路径
371
+ ```
372
+
373
+ #### 素材源
374
+
375
+ 素材来自「源」(source),当前内置 [PetDex](https://petdex.dev)(默认)。名称可以带源前缀,
376
+ 不带就用默认源:
377
+
378
+ ```bash
379
+ cc-pets pet add petdex:boba
380
+ cc-pets pet search petdex:otter
381
+ ```
382
+
383
+ 一个源的完整定义就是清单地址、资源 host 白名单和 Referer 三项,集中在
384
+ `scripts/pet-store.mjs` 顶部的 `SOURCES` 表里。以后接自建 registry 时在表里加一行即可,
385
+ 命令、目录结构和桌宠端都不用改。默认源用 `CC_PETS_SOURCE` 切换。
386
+
387
+ 来源记录在宠物目录内的 `.source.json`(`{ "source", "slug", "installedAt" }`),下载来的
388
+ `pet.json` 保持上游原样、不掺自己的字段。目录名就是素材本名,所以桌宠右键菜单里看到的
389
+ 仍然是干净的 `boba` 而不是 `boba@petdex`。
390
+
391
+ 不同源出现同名素材时,`add` 会拒绝覆盖并提示改名安装;手工放进去、没有来源记录的目录同样
392
+ 受保护:
346
393
 
347
394
  ```bash
348
- npx petdex install <slug>
395
+ cc-pets pet add petdex:boba --as boba-petdex
396
+ cc-pets pet add boba --as 波霸
349
397
  ```
350
398
 
351
- 安装完成后,打开桌宠右键菜单即可看到对应目录名。
399
+ `--as` 的本地名支持中文;为避免路径穿越,不允许路径分隔符、空白或连续的 `..`。
400
+
401
+ 同一个源重装同名素材则直接更新,不需要 `--as`。
402
+
403
+ #### 导入 Codex 素材
404
+
405
+ 桌宠不读 `~/.codex/pets/`。如果你在 Codex 桌面端已经装了一批素材,打开右键菜单里的
406
+ **“导入 Codex 素材”** 开关,桌宠会把那里的素材**复制**进 `~/.cc-pets/pets/`:开关打开的
407
+ 当下导入一次,之后每次启动再导入一次。
408
+
409
+ - 复制而不是关联:导入之后 Codex 那边再改再删都不影响桌宠,桌宠也仍然只需要扫一个目录。
410
+ - 只导入真正有精灵图的目录,没有 `spritesheet.webp` / `spritesheet.png` 的会跳过。
411
+ - **同名目录一律跳过、绝不覆盖**——你自己 `cc-pets pet add` 装的素材优先。
412
+ - 导入的素材会写上 `.source.json`(`source: "codex"`),`cc-pets pet list` 里单独分一组。
413
+
414
+ 反复启动是幂等的:已经导入过的素材因为同名而跳过,不会重复复制。关掉开关不会删除已经
415
+ 导入的素材,想删用 `cc-pets pet remove`。
416
+
417
+ #### 其他
418
+
419
+ 素材清单按源分别缓存 6 小时,加 `--refresh` 强制刷新。下载只接受源白名单内的 host(PetDex
420
+ 是 `https://assets.petdex.dev`)。`CC_PETS_PETS_DIR` 可以换一个素材目录,CLI 和桌宠端读同一
421
+ 个变量;注意桌宠是用 `open` 启动的,不继承 shell 环境,要让它也认这个变量需要
422
+ `cc-pets --foreground` 或 `launchctl setenv`——和 `CC_PETS_CLAUDE_CONFIG_DIR` 等其他覆盖变量
423
+ 的限制一致。
424
+
425
+ 安装完成后,打开桌宠右键菜单即可看到对应目录名。也可以自己把 `spritesheet.webp` /
426
+ `spritesheet.png` 和 `pet.json` 放进 `~/.cc-pets/pets/<名称>/`,效果相同,`list` 会把它们
427
+ 归到「本地素材(无来源记录)」下。
428
+
429
+ 也可以继续用 PetDex 官方 CLI(`npx petdex install <slug>`),素材会落在 `~/.petdex/pets/`;
430
+ 只有在 `~/.cc-pets/pets/` 为空时桌宠才会去读那里。
352
431
 
353
- 项目允许在没有内置素材时构建。若启动时内置目录和两个外部目录都没有可用素材,应用会显示
354
- 提示窗口,可打开 `~/.petdex/pets/`、安装素材后重新扫描,或安全退出。
432
+ 项目允许在没有内置素材时构建。若启动时内置目录和所有外部目录都没有可用素材,应用会显示
433
+ 提示窗口,可打开 `~/.cc-pets/pets/`、安装素材后重新扫描,或安全退出。
355
434
 
356
435
  ## 隐私
357
436
 
@@ -30,6 +30,10 @@
30
30
  @property BOOL dashboardHovering;
31
31
  @property BOOL petDragging;
32
32
  @property NSString *binaryDirectory;
33
+ // 素材列表只在启动时扫一次,之后靠素材目录的 mtime 判断要不要重扫——add/remove 必然改动
34
+ // 目录本身,所以打开菜单只需要一次 stat,既不用常驻监听也不用和 CLI 做进程间通信。
35
+ @property NSArray<NSDictionary *> *cachedPetOptions;
36
+ @property NSDate *cachedPetOptionsStamp;
33
37
  @property PetView *petView;
34
38
  @property CCPetsUsageMonitor *usageMonitor;
35
39
  @property unsigned long long agentEventOffset;
@@ -260,6 +260,25 @@ static void TrimUpdateLog(NSString *path) {
260
260
  self.quotaView.historyEnabled = enabled;
261
261
  [self refreshUsage:nil];
262
262
  }
263
+ // 开关打开时立刻导入一次,不用等下次启动——用户点开关就是想现在看到那些素材。
264
+ - (void)toggleImportCodexPets:(NSButton *)sender {
265
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
266
+ BOOL enabled = ![defaults boolForKey:ImportCodexPetsKey];
267
+ [defaults setBool:enabled forKey:ImportCodexPetsKey];
268
+ sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
269
+ if (!enabled) return;
270
+ NSUInteger imported = ImportCodexPets();
271
+ if (imported == 0) return;
272
+ [self invalidatePetOptionsCache];
273
+ [self showImportedCodexPetsAlert:imported];
274
+ }
275
+ - (void)showImportedCodexPetsAlert:(NSUInteger)imported {
276
+ [NSApp activateIgnoringOtherApps:YES];
277
+ NSAlert *alert = [NSAlert new];
278
+ alert.messageText = @"已导入 Codex 素材";
279
+ [alert addButtonWithTitle:@"好"];
280
+ [alert runModal];
281
+ }
263
282
  - (NSString *)notificationKeyForTag:(NSInteger)tag {
264
283
  if (tag == 1) return NotificationCompletionKey;
265
284
  if (tag == 2) return NotificationFailureKey;
@@ -586,20 +605,18 @@ static void TrimUpdateLog(NSString *path) {
586
605
  }
587
606
  return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
588
607
  }
608
+ // 桌宠只扫 OwnPetsDirectory() 加包内素材,无条件、不看那里有没有东西。~/.petdex/pets 和
609
+ // ~/.codex/pets 由别的工具写入,直接扫就永远分不清哪只是自己装的;要用 Codex 的素材就打开
610
+ // "导入 Codex 素材"开关,由 ImportCodexPets 复制进来,之后它们和自己装的没有区别。
589
611
  - (NSArray<NSDictionary *> *)discoverPetOptions {
590
- NSString *home = NSHomeDirectory();
591
- NSString *petdexRoot = [home stringByAppendingPathComponent:@".petdex/pets"];
592
- NSString *codexRoot = [home stringByAppendingPathComponent:@".codex/pets"];
612
+ NSString *ownRoot = OwnPetsDirectory();
593
613
  NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
594
- NSMutableSet<NSString *> *externalNames = [NSMutableSet set];
595
614
 
596
- for (NSString *name in [self petDirectoryNamesAtPath:petdexRoot]) {
597
- NSString *petdexDirectory = [petdexRoot stringByAppendingPathComponent:name];
598
- NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
599
- NSString *path = [self spritePathInDirectory:petdexDirectory];
600
- if (!path) path = [self spritePathInDirectory:codexDirectory];
615
+ for (NSString *name in [self petDirectoryNamesAtPath:ownRoot]) {
616
+ NSString *directory = [ownRoot stringByAppendingPathComponent:name];
617
+ NSString *path = [self spritePathInDirectory:directory];
601
618
  if (!path) continue;
602
- NSInteger version = [self spriteVersionInDirectory:petdexDirectory fallbackDirectory:codexDirectory];
619
+ NSInteger version = [self spriteVersionInDirectory:directory fallbackDirectory:nil];
603
620
  [result addObject:@{
604
621
  @"id": [@"external:" stringByAppendingString:name],
605
622
  @"name": name,
@@ -607,25 +624,10 @@ static void TrimUpdateLog(NSString *path) {
607
624
  @"spriteVersionNumber": @(version),
608
625
  @"spriteRowCount": @([self spriteRowCountForVersion:version])
609
626
  }];
610
- [externalNames addObject:name];
611
- }
612
- for (NSString *name in [self petDirectoryNamesAtPath:codexRoot]) {
613
- if ([externalNames containsObject:name]) continue;
614
- NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
615
- NSString *path = [self spritePathInDirectory:codexDirectory];
616
- if (!path) continue;
617
- NSInteger version = [self spriteVersionInDirectory:codexDirectory fallbackDirectory:nil];
618
- [result addObject:@{
619
- @"id": [@"external:" stringByAppendingString:name],
620
- @"name": name,
621
- @"path": path,
622
- @"spriteVersionNumber": @(version),
623
- @"spriteRowCount": @([self spriteRowCountForVersion:version])
624
- }];
625
- [externalNames addObject:name];
626
627
  }
627
628
 
628
- NSArray<NSString *> *bundled = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
629
+ NSArray<NSString *> *bundled = [NSFileManager.defaultManager
630
+ contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
629
631
  for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
630
632
  NSString *extension = fileName.pathExtension.lowercaseString;
631
633
  if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
@@ -639,26 +641,51 @@ static void TrimUpdateLog(NSString *path) {
639
641
  }
640
642
  return result;
641
643
  }
644
+ // 素材目录的 mtime。目录里增删条目会改动它,而 `cc-pets pet add` / `remove` 正是在增删
645
+ // 条目——所以这一个时间戳就足以判断列表是否需要重扫,不必每次打开菜单都遍历目录。
646
+ - (NSDate *)petOptionsStamp {
647
+ NSDictionary *attributes = [NSFileManager.defaultManager
648
+ attributesOfItemAtPath:OwnPetsDirectory() error:nil];
649
+ return attributes[NSFileModificationDate];
650
+ }
651
+ - (void)invalidatePetOptionsCache {
652
+ self.cachedPetOptions = nil;
653
+ self.cachedPetOptionsStamp = nil;
654
+ }
655
+ - (NSArray<NSDictionary *> *)petOptions {
656
+ NSDate *stamp = [self petOptionsStamp];
657
+ BOOL stale = !self.cachedPetOptions ||
658
+ (stamp == nil) != (self.cachedPetOptionsStamp == nil) ||
659
+ (stamp && ![stamp isEqualToDate:self.cachedPetOptionsStamp]);
660
+ if (stale) {
661
+ self.cachedPetOptions = [self discoverPetOptions];
662
+ self.cachedPetOptionsStamp = stamp;
663
+ }
664
+ return self.cachedPetOptions;
665
+ }
642
666
  - (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
643
667
  for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
644
668
  return nil;
645
669
  }
646
670
  - (NSArray<NSDictionary *> *)waitForPetOptions {
647
671
  while (YES) {
648
- NSArray<NSDictionary *> *options = [self discoverPetOptions];
672
+ // 这个循环就是"重新扫描"按钮的实现,必须绕开缓存。
673
+ [self invalidatePetOptionsCache];
674
+ NSArray<NSDictionary *> *options = [self petOptions];
649
675
  if (options.count > 0) return options;
650
676
 
651
677
  [NSApp activateIgnoringOtherApps:YES];
652
678
  NSAlert *alert = [NSAlert new];
653
679
  alert.messageText = @"没有找到桌宠素材";
654
- alert.informativeText = @"请将 PNG 或 WebP 精灵图放入 ~/.petdex/pets/<名称>/ 或 "
655
- @"~/.codex/pets/<名称>/,也可以通过 PetDex 安装。完成后点击“重新扫描”。";
680
+ alert.informativeText = @"用 `cc-pets pet add <名称>` 下载素材,或把 PNG / WebP 精灵图放入 "
681
+ @"~/.cc-pets/pets/<名称>/。桌宠不会去读 ~/.petdex/pets/ 和 ~/.codex/pets/;"
682
+ @"要用 Codex 的素材,请在右键菜单打开“导入 Codex 素材”。完成后点击“重新扫描”。";
656
683
  [alert addButtonWithTitle:@"重新扫描"];
657
684
  [alert addButtonWithTitle:@"打开素材目录"];
658
685
  [alert addButtonWithTitle:@"退出"];
659
686
  NSModalResponse response = [alert runModal];
660
687
  if (response == NSAlertSecondButtonReturn) {
661
- NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@".petdex/pets"];
688
+ NSString *directory = OwnPetsDirectory();
662
689
  [NSFileManager.defaultManager createDirectoryAtPath:directory
663
690
  withIntermediateDirectories:YES attributes:nil error:nil];
664
691
  [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
@@ -675,6 +702,9 @@ static void TrimUpdateLog(NSString *path) {
675
702
  self.binaryDirectory = runsFromAppBundle && mainBundle.resourcePath.length > 0
676
703
  ? mainBundle.resourcePath
677
704
  : binaryDir;
705
+ // 必须在 waitForPetOptions 之前:否则自己的目录还空着、素材全在 Codex 那边时,
706
+ // 会先弹一次"没有找到桌宠素材",等用户点完重新扫描才导入。
707
+ if ([NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]) ImportCodexPets();
678
708
  NSArray<NSDictionary *> *petOptions = [self waitForPetOptions];
679
709
  if (petOptions.count == 0) {
680
710
  [NSApp terminate:nil];
@@ -736,7 +766,7 @@ static void TrimUpdateLog(NSString *path) {
736
766
  else [weakSelf scheduleQuotaDashboardHide];
737
767
  };
738
768
  self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
739
- return [weakSelf discoverPetOptions] ?: @[];
769
+ return [weakSelf petOptions] ?: @[];
740
770
  };
741
771
  self.petView.switchPetRequested = ^(NSString *petID) {
742
772
  [weakSelf switchPetToID:petID];
@@ -999,7 +1029,7 @@ static void TrimUpdateLog(NSString *path) {
999
1029
  }
1000
1030
  }
1001
1031
  - (void)switchPetToID:(NSString *)petID {
1002
- NSArray<NSDictionary *> *options = [self discoverPetOptions];
1032
+ NSArray<NSDictionary *> *options = [self petOptions];
1003
1033
  NSDictionary *option = [self petOptionWithID:petID inOptions:options];
1004
1034
  if (!option) return;
1005
1035
  NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
@@ -13,6 +13,13 @@ NSString *DefaultCodexHomeDirectory(void);
13
13
  NSString *ClaudeUsagePathForConfigDirectory(NSString *configDirectory);
14
14
  NSString *ApplicationSupportDirectory(void);
15
15
  NSString *QuotaHistoryPath(void);
16
+ // 桌宠只认这一个素材目录。~/.petdex/pets 和 ~/.codex/pets 由别的工具写入,
17
+ // 永远不直接扫描,只在开关打开时由 ImportCodexPets 复制进来。
18
+ NSString *OwnPetsDirectory(void);
19
+ NSString *CodexPetsDirectory(void);
20
+ // 把 ~/.codex/pets 里的素材复制进 OwnPetsDirectory(),返回新导入的数量。
21
+ // 已存在的同名目录一律跳过,不覆盖。
22
+ NSUInteger ImportCodexPets(void);
16
23
 
17
24
  extern NSString *const HistoryEnabledKey;
18
25
  extern NSString *const NotificationCompletionKey;
@@ -20,6 +27,7 @@ extern NSString *const NotificationFailureKey;
20
27
  extern NSString *const NotificationApprovalKey;
21
28
  extern NSString *const StatusBubbleExpandedKey;
22
29
  extern NSString *const StatusBubblePreferenceV2Key;
30
+ extern NSString *const ImportCodexPetsKey;
23
31
 
24
32
  extern const NSTimeInterval AgentStatusInactivityInterval;
25
33
  extern const NSTimeInterval AgentStatusOrphanInterval;
@@ -77,12 +77,80 @@ NSString *QuotaHistoryPath(void) {
77
77
  return [ApplicationSupportDirectory() stringByAppendingPathComponent:@"quota-history.json"];
78
78
  }
79
79
 
80
+ // cc-pets 自己的素材目录,由 `cc-pets pet add` 写入。桌宠只扫这一个目录加包内素材。
81
+ NSString *OwnPetsDirectory(void) {
82
+ NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_PETS_DIR"];
83
+ if (override.length > 0) return override.stringByStandardizingPath;
84
+ return [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets/pets"];
85
+ }
86
+
87
+ NSString *CodexPetsDirectory(void) {
88
+ return [DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"pets"];
89
+ }
90
+
91
+ // 素材目录里认哪些文件算"有图"。和 CCPetsAppDelegate 的 spritePathInDirectory 保持一致,
92
+ // 但这里只做存在性判断,不需要读 pet.json 里的 spritesheetPath。
93
+ static BOOL DirectoryHasSprite(NSString *directory) {
94
+ for (NSString *name in @[@"spritesheet.webp", @"spritesheet.png"]) {
95
+ BOOL isDirectory = NO;
96
+ NSString *path = [directory stringByAppendingPathComponent:name];
97
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] &&
98
+ !isDirectory) {
99
+ return YES;
100
+ }
101
+ }
102
+ return NO;
103
+ }
104
+
105
+ // 导入是"复制"而不是"关联":复制过来之后 Codex 那边再删也不影响桌宠,桌宠也仍然只需要
106
+ // 扫一个目录。同名目录一律跳过——用户自己装的素材优先,导入不能踩掉它。
107
+ NSUInteger ImportCodexPets(void) {
108
+ NSFileManager *manager = NSFileManager.defaultManager;
109
+ NSString *source = CodexPetsDirectory();
110
+ NSString *destination = OwnPetsDirectory();
111
+ NSArray<NSString *> *entries = [manager contentsOfDirectoryAtPath:source error:nil];
112
+ if (entries.count == 0) return 0;
113
+
114
+ NSUInteger imported = 0;
115
+ for (NSString *name in entries) {
116
+ if ([name hasPrefix:@"."]) continue;
117
+ BOOL isDirectory = NO;
118
+ NSString *petDirectory = [source stringByAppendingPathComponent:name];
119
+ if (![manager fileExistsAtPath:petDirectory isDirectory:&isDirectory] || !isDirectory) continue;
120
+ if (!DirectoryHasSprite(petDirectory)) continue;
121
+ NSString *target = [destination stringByAppendingPathComponent:name];
122
+ if ([manager fileExistsAtPath:target]) continue;
123
+ if (![manager createDirectoryAtPath:destination withIntermediateDirectories:YES
124
+ attributes:nil error:nil]) {
125
+ continue;
126
+ }
127
+ if (![manager copyItemAtPath:petDirectory toPath:target error:nil]) continue;
128
+ // 和 `cc-pets pet add` 写的 sidecar 同一份格式,这样 `cc-pets pet list` 能把
129
+ // 导入进来的素材单独归到 codex 一组。
130
+ NSDictionary *sidecar = @{
131
+ @"source": @"codex",
132
+ @"slug": name,
133
+ @"installedAt": [NSISO8601DateFormatter stringFromDate:NSDate.date
134
+ timeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]
135
+ formatOptions:NSISO8601DateFormatWithInternetDateTime]
136
+ };
137
+ NSData *data = [NSJSONSerialization dataWithJSONObject:sidecar
138
+ options:NSJSONWritingPrettyPrinted error:nil];
139
+ if (data) {
140
+ [data writeToFile:[target stringByAppendingPathComponent:@".source.json"] atomically:YES];
141
+ }
142
+ imported += 1;
143
+ }
144
+ return imported;
145
+ }
146
+
80
147
  NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
81
148
  NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
82
149
  NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
83
150
  NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
84
151
  NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
85
152
  NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
153
+ NSString *const ImportCodexPetsKey = @"CCPetsImportCodexPets";
86
154
  const NSTimeInterval AgentStatusInactivityInterval = 60.0;
87
155
  // 客户端进程已经消失、但状态气泡还停在它最后一条事件上时,多等这么久再清场。
88
156
  // 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
@@ -541,8 +541,14 @@ static void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *week
541
541
  options:0];
542
542
  *weekStart = (start ?: midnight).timeIntervalSince1970;
543
543
  }
544
- // 时钟轻微前后跳动时,不要把刚落盘的记录挡在窗口外。
545
- if (end) *end = now.timeIntervalSince1970 + 60;
544
+ // 时钟轻微前后跳动时,不要把刚落盘的记录挡在窗口外,因此终点先留出 60 秒余量。
545
+ // 之后再向上对齐到 10 分钟:分片缓存的键里同时含起点和终点,终点每秒都在动的话,
546
+ // 键每一轮都是新的,起点对齐到零点省下的那次命中会被它整个抵消——跨界会话照样
547
+ // 每轮重扫,而且上一轮写下的分片还会被 PruneTokenCache 当成过期窗口清掉。
548
+ if (end) {
549
+ *end = ceil((now.timeIntervalSince1970 + 60) / TokenFallbackGranularity) *
550
+ TokenFallbackGranularity;
551
+ }
546
552
  }
547
553
 
548
554
  static NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end) {
@@ -503,6 +503,11 @@ static const CGFloat PetDragThreshold = 3.0;
503
503
  checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
504
504
  action:@selector(toggleQuotaHistory:)
505
505
  tag:0];
506
+ [self addPersistentSwitchToMenu:menu
507
+ title:@"导入 Codex 素材"
508
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]
509
+ action:@selector(toggleImportCodexPets:)
510
+ tag:0];
506
511
  NSMenuItem *notificationItem = [menu addItemWithTitle:@"系统通知" action:nil keyEquivalent:@""];
507
512
  NSMenu *notificationMenu = [NSMenu new];
508
513
  NSArray<NSDictionary *> *notificationOptions = @[
package/bin/cc-pets CHANGED
@@ -11,6 +11,11 @@ if [[ "${1:-}" == "install" ]]; then
11
11
  exec "${PROJECT_DIR}/scripts/install-shell-integration.sh"
12
12
  fi
13
13
 
14
+ if [[ "${1:-}" == "pet" ]]; then
15
+ shift
16
+ exec node "${PROJECT_DIR}/scripts/pet-store.mjs" "$@"
17
+ fi
18
+
14
19
  if [[ "${1:-}" == "uninstall" ]]; then
15
20
  exec "${PROJECT_DIR}/scripts/uninstall-shell-integration.sh"
16
21
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
@@ -0,0 +1,394 @@
1
+ #!/usr/bin/env node
2
+
3
+ // cc-pets 自己的素材仓库。素材可以来自多个"源"(source),但一律落到 ~/.cc-pets/pets,
4
+ // 不碰 ~/.petdex/pets 和 ~/.codex/pets——那两个目录是别的工具在写,混在一起就没法
5
+ // "只看自己装的宠物"。桌宠端(discoverPetOptions)只要发现这个目录有内容,就只认它。
6
+ //
7
+ // 目录名保持素材本名(boba 就是 boba),来源记在宠物目录内的 .source.json 里。这样
8
+ // 桌宠端不需要知道"源"这回事,右键菜单里也不会出现 boba@petdex 这种名字;同名素材
9
+ // 的冲突交给 --as 显式改名解决,那是低频事件,不值得为它把所有目录名都变丑。
10
+
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ // 一个源的完整定义就是这几项。以后接自建 registry 时在这里加一行即可,
16
+ // 命令、目录结构和桌宠端都不用动。
17
+ const SOURCES = {
18
+ petdex: {
19
+ label: "PetDex",
20
+ manifestUrl: "https://petdex.dev/api/manifest",
21
+ // 清单是远端数据,理论上可以指向任意地址。下载前把 host 卡死,
22
+ // 免得一次清单投毒就变成"从任意地址往本地写文件"。
23
+ assetHosts: ["assets.petdex.dev"],
24
+ referer: "https://petdex.dev/",
25
+ homepage: "https://petdex.dev"
26
+ }
27
+ };
28
+ // 不能 add、只会出现在已装素材里的来源。桌宠的"导入 Codex 素材"开关会写 source: "codex"。
29
+ const LOCAL_SOURCE_LABELS = { codex: "Codex(导入)" };
30
+ const DEFAULT_SOURCE = process.env.CC_PETS_SOURCE || "petdex";
31
+ const SIDECAR_NAME = ".source.json";
32
+ const MANIFEST_TTL_MS = 6 * 60 * 60 * 1000;
33
+
34
+ const untilde = (value) => (value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : value);
35
+ const petsRoot = () => {
36
+ const override = process.env.CC_PETS_PETS_DIR;
37
+ if (override && override.length > 0) return path.resolve(untilde(override));
38
+ return path.join(os.homedir(), ".cc-pets", "pets");
39
+ };
40
+ const cachePath = (sourceName) =>
41
+ path.join(os.homedir(), ".cc-pets", "cache", `manifest-${sourceName}.json`);
42
+ // 每个源都可以单独用环境变量改清单地址,主要给测试和自建源的本地联调用。
43
+ const manifestUrlFor = (sourceName) =>
44
+ process.env[`CC_PETS_MANIFEST_URL_${sourceName.toUpperCase()}`] || SOURCES[sourceName].manifestUrl;
45
+
46
+ const dim = (text) => `${text}`;
47
+ const cyan = (text) => `${text}`;
48
+ const green = (text) => `${text}`;
49
+ const red = (text) => `${text}`;
50
+
51
+ const fail = (message) => {
52
+ console.error(red(message));
53
+ process.exit(1);
54
+ };
55
+
56
+ // slug 直接用作目录名,而它来自远端清单,必须自己校验,不能指望上游。
57
+ const isSafeSlug = (slug) =>
58
+ typeof slug === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) && !slug.includes("..");
59
+
60
+ // 本地名由用户通过 --as 指定,可以用中文等 Unicode 字母。路径分隔符、空白和
61
+ // 控制字符不在允许集内;首字符必须是字母或数字,避免生成隐藏目录。
62
+ const isSafeLocalName = (name) =>
63
+ typeof name === "string" &&
64
+ /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]*$/u.test(name) &&
65
+ !name.includes("..");
66
+
67
+ // "petdex:boba" -> { source: "petdex", slug: "boba" };不带前缀就用默认源。
68
+ function parseSpec(spec) {
69
+ const separator = spec.indexOf(":");
70
+ if (separator === -1) return { source: DEFAULT_SOURCE, slug: spec };
71
+ const source = spec.slice(0, separator);
72
+ const slug = spec.slice(separator + 1);
73
+ if (!SOURCES[source]) {
74
+ fail(`未知的素材源 "${source}"。可用的源: ${Object.keys(SOURCES).join(", ")}`);
75
+ }
76
+ return { source, slug };
77
+ }
78
+
79
+ async function fetchManifest(sourceName, { refresh }) {
80
+ const cache = cachePath(sourceName);
81
+ if (!refresh) {
82
+ try {
83
+ const stat = fs.statSync(cache);
84
+ if (Date.now() - stat.mtimeMs < MANIFEST_TTL_MS) {
85
+ const cached = JSON.parse(fs.readFileSync(cache, "utf8"));
86
+ if (Array.isArray(cached?.pets)) return cached.pets;
87
+ }
88
+ } catch {
89
+ // 缓存缺失或损坏都当作没有缓存,直接回源。
90
+ }
91
+ }
92
+ const response = await fetch(manifestUrlFor(sourceName), { redirect: "follow" });
93
+ if (!response.ok) fail(`拉取 ${SOURCES[sourceName].label} 素材清单失败: HTTP ${response.status}`);
94
+ const body = await response.json();
95
+ if (!Array.isArray(body?.pets)) fail(`${SOURCES[sourceName].label} 素材清单格式不符合预期`);
96
+ fs.mkdirSync(path.dirname(cache), { recursive: true });
97
+ fs.writeFileSync(cache, JSON.stringify(body));
98
+ return body.pets;
99
+ }
100
+
101
+ async function download(url, source) {
102
+ let parsed;
103
+ try {
104
+ parsed = new URL(url);
105
+ } catch {
106
+ throw new Error(`非法的素材地址: ${url}`);
107
+ }
108
+ if (parsed.protocol !== "https:" || !source.assetHosts.includes(parsed.hostname)) {
109
+ throw new Error(`不受信任的素材来源: ${parsed.hostname || url}`);
110
+ }
111
+ const response = await fetch(parsed, { headers: { Referer: source.referer } });
112
+ if (!response.ok) throw new Error(`下载失败 ${parsed.pathname} -> HTTP ${response.status}`);
113
+ return Buffer.from(await response.arrayBuffer());
114
+ }
115
+
116
+ function readSidecar(directory) {
117
+ try {
118
+ const raw = JSON.parse(fs.readFileSync(path.join(directory, SIDECAR_NAME), "utf8"));
119
+ return typeof raw?.source === "string" ? raw : null;
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ // 已经存在的目录不能闷声覆盖:可能是另一个源的同名素材,也可能是用户自己手放的图。
126
+ function assertInstallable(directory, sourceName, localName) {
127
+ if (!fs.existsSync(directory)) return;
128
+ const sidecar = readSidecar(directory);
129
+ if (sidecar?.source === sourceName) return;
130
+ const owner = sidecar ? `来自 ${sidecar.source}` : "不是 cc-pets pet 装的(没有来源记录)";
131
+ throw new Error(
132
+ `${localName} 已存在且${owner}。换个名字装: ` +
133
+ `cc-pets pet add ${sourceName}:${localName} --as ${localName}-${sourceName}`
134
+ );
135
+ }
136
+
137
+ async function installPet(pet, sourceName, localName) {
138
+ const source = SOURCES[sourceName];
139
+ if (!isSafeSlug(pet.slug)) throw new Error(`素材名不合法: ${pet.slug}`);
140
+ const directory = path.join(petsRoot(), localName);
141
+ assertInstallable(directory, sourceName, localName);
142
+
143
+ const [meta, sprite] = await Promise.all([
144
+ download(pet.petJsonUrl, source),
145
+ download(pet.spritesheetUrl, source)
146
+ ]);
147
+ const extension = new URL(pet.spritesheetUrl).pathname.endsWith(".png") ? "png" : "webp";
148
+ fs.mkdirSync(directory, { recursive: true });
149
+ // 同一只宠物换过格式时,旧的 spritesheet 会留下来抢加载顺序,先清掉。
150
+ for (const stale of ["spritesheet.webp", "spritesheet.png"]) {
151
+ if (stale !== `spritesheet.${extension}`) fs.rmSync(path.join(directory, stale), { force: true });
152
+ }
153
+ // pet.json 原样落盘,不掺自己的字段——保持上游原始内容,以后比对和更新才干净。
154
+ fs.writeFileSync(path.join(directory, "pet.json"), meta);
155
+ fs.writeFileSync(path.join(directory, `spritesheet.${extension}`), sprite);
156
+ fs.writeFileSync(
157
+ path.join(directory, SIDECAR_NAME),
158
+ `${JSON.stringify({ source: sourceName, slug: pet.slug, installedAt: new Date().toISOString() }, null, 2)}\n`
159
+ );
160
+ return directory;
161
+ }
162
+
163
+ function installedPets() {
164
+ const root = petsRoot();
165
+ let entries;
166
+ try {
167
+ entries = fs.readdirSync(root, { withFileTypes: true });
168
+ } catch {
169
+ return [];
170
+ }
171
+ return entries
172
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
173
+ .map((entry) => {
174
+ const sidecar = readSidecar(path.join(root, entry.name));
175
+ return { name: entry.name, source: sidecar?.source ?? null, slug: sidecar?.slug ?? null };
176
+ })
177
+ .sort((a, b) => a.name.localeCompare(b.name));
178
+ }
179
+
180
+ async function commandAdd(args) {
181
+ const refresh = args.includes("--refresh");
182
+ const asIndex = args.indexOf("--as");
183
+ const alias = asIndex === -1 ? null : args[asIndex + 1];
184
+ if (asIndex !== -1 && (!alias || alias.startsWith("--"))) fail("--as 后面要跟一个名字。");
185
+ if (alias && !isSafeLocalName(alias)) fail(`--as 的名字不合法: ${alias}`);
186
+
187
+ // asIndex 为 -1 时 asIndex + 1 是 0,会把第一个位置参数当成 --as 的取值吃掉。
188
+ const aliasValueIndex = asIndex === -1 ? -1 : asIndex + 1;
189
+ const positional = args.filter(
190
+ (value, index) => !value.startsWith("--") && index !== aliasValueIndex);
191
+ const specs = [...new Set(positional)];
192
+ if (specs.length === 0) fail(`用法: ${cyan("cc-pets pet add [源:]<名称> [名称...] [--as <本地名>]")}`);
193
+ if (alias && specs.length > 1) fail("--as 一次只能给一个素材改名。");
194
+
195
+ // 按源分组,同一个源只拉一次清单。
196
+ const wanted = specs.map(parseSpec);
197
+ const bySource = new Map();
198
+ for (const item of wanted) {
199
+ if (!bySource.has(item.source)) bySource.set(item.source, []);
200
+ bySource.get(item.source).push(item.slug);
201
+ }
202
+
203
+ let failed = 0;
204
+ let installed = 0;
205
+ for (const [sourceName, slugs] of bySource) {
206
+ const pets = await fetchManifest(sourceName, { refresh });
207
+ const index = new Map(pets.map((pet) => [pet.slug, pet]));
208
+ for (const slug of slugs) {
209
+ const pet = index.get(slug);
210
+ if (!pet) {
211
+ failed += 1;
212
+ console.error(`${red("×")} ${sourceName}:${slug}: 清单里没有这个素材`);
213
+ continue;
214
+ }
215
+ const localName = alias ?? slug;
216
+ try {
217
+ const directory = await installPet(pet, sourceName, localName);
218
+ installed += 1;
219
+ const renamed = localName === slug ? "" : dim(` (${sourceName}:${slug})`);
220
+ console.log(`${green("✓")} ${localName}${renamed} ${dim(`→ ${directory}`)}`);
221
+ } catch (error) {
222
+ failed += 1;
223
+ console.error(`${red("×")} ${sourceName}:${slug}: ${error.message}`);
224
+ }
225
+ }
226
+ }
227
+
228
+ if (installed > 0) {
229
+ console.log(dim(`素材目录: ${petsRoot()}`));
230
+ console.log(dim("桌宠菜单里点“重新扫描”或重启桌宠即可看到新素材。"));
231
+ }
232
+ if (failed > 0) process.exit(1);
233
+ }
234
+
235
+ async function commandSearch(args) {
236
+ const refresh = args.includes("--refresh");
237
+ const positional = args.filter((value) => !value.startsWith("--"));
238
+ // 关键词本身也可以带源前缀:`cc-pets pet search petdex:otter`。
239
+ const scoped = positional.length > 0 && positional[0].includes(":")
240
+ ? parseSpec(positional[0])
241
+ : { source: DEFAULT_SOURCE, slug: positional.join(" ") };
242
+ const sourceName = scoped.source;
243
+ const keyword = [scoped.slug, ...positional.slice(1)].join(" ").trim().toLowerCase();
244
+
245
+ const pets = await fetchManifest(sourceName, { refresh });
246
+ const matched = keyword.length === 0
247
+ ? pets
248
+ : pets.filter((pet) =>
249
+ `${pet.slug} ${pet.displayName ?? ""} ${pet.submittedBy ?? ""}`.toLowerCase().includes(keyword));
250
+ if (matched.length === 0) fail(`${SOURCES[sourceName].label} 上没有匹配 "${keyword}" 的素材。`);
251
+ const shown = matched.slice(0, 60);
252
+ for (const pet of shown) {
253
+ const author = pet.submittedBy ? dim(` by ${pet.submittedBy}`) : "";
254
+ console.log(` ${cyan(pet.slug)} ${pet.displayName ?? ""}${author}`);
255
+ }
256
+ if (matched.length > shown.length) {
257
+ console.log(dim(` … 共 ${matched.length} 个结果,只显示前 ${shown.length} 个。`));
258
+ }
259
+ console.log(dim(`装上其中一个: cc-pets pet add ${sourceName}:${shown[0].slug}`));
260
+ }
261
+
262
+ function commandList() {
263
+ const pets = installedPets();
264
+ if (pets.length === 0) {
265
+ console.log(dim(`${petsRoot()} 里还没有素材。`));
266
+ console.log(dim("试试: cc-pets pet add boba"));
267
+ return;
268
+ }
269
+ const groups = new Map();
270
+ for (const pet of pets) {
271
+ const key = pet.source ?? "__unknown__";
272
+ if (!groups.has(key)) groups.set(key, []);
273
+ groups.get(key).push(pet);
274
+ }
275
+ // 有来源记录的源按名字排在前面,手放的素材垫底。
276
+ const keys = [...groups.keys()].sort((a, b) => {
277
+ if (a === "__unknown__") return 1;
278
+ if (b === "__unknown__") return -1;
279
+ return a.localeCompare(b);
280
+ });
281
+ for (const key of keys) {
282
+ const label = key === "__unknown__"
283
+ ? "本地素材(无来源记录)"
284
+ : SOURCES[key]?.label ?? LOCAL_SOURCE_LABELS[key] ?? key;
285
+ console.log(` ${label}`);
286
+ for (const pet of groups.get(key)) {
287
+ // 目录名和上游 slug 不一致时(--as 改过名)把原名标出来。
288
+ const origin = pet.slug && pet.slug !== pet.name ? dim(` (${key}:${pet.slug})`) : "";
289
+ console.log(` ${cyan(pet.name)}${origin}`);
290
+ }
291
+ }
292
+ console.log(dim(`共 ${pets.length} 个,位于 ${petsRoot()}`));
293
+ }
294
+
295
+ function commandRemove(args) {
296
+ const names = args.filter((value) => !value.startsWith("--"));
297
+ if (names.length === 0) fail(`用法: ${cyan("cc-pets pet remove <名称> [名称...]")}`);
298
+ const root = petsRoot();
299
+ let removed = 0;
300
+ for (const name of names) {
301
+ if (!isSafeLocalName(name)) {
302
+ console.error(`${red("×")} ${name}: 名称不合法`);
303
+ continue;
304
+ }
305
+ const directory = path.join(root, name);
306
+ if (!fs.existsSync(directory)) {
307
+ console.error(`${red("×")} ${name}: 没有安装`);
308
+ continue;
309
+ }
310
+ const sidecar = readSidecar(directory);
311
+ fs.rmSync(directory, { recursive: true, force: true });
312
+ removed += 1;
313
+ console.log(`${green("✓")} 已删除 ${name}${sidecar ? dim(` (来自 ${sidecar.source})`) : ""}`);
314
+ }
315
+ if (removed < names.length) process.exit(1);
316
+ }
317
+
318
+ function commandSource() {
319
+ for (const [name, source] of Object.entries(SOURCES)) {
320
+ const marker = name === DEFAULT_SOURCE ? green(" (默认)") : "";
321
+ console.log(` ${cyan(name)}${marker} ${source.label} ${dim(source.homepage)}`);
322
+ }
323
+ console.log(dim("用 CC_PETS_SOURCE 换默认源,或在名称前加 `源:` 前缀。"));
324
+ }
325
+
326
+ function commandDir() {
327
+ const root = petsRoot();
328
+ fs.mkdirSync(root, { recursive: true });
329
+ console.log(root);
330
+ }
331
+
332
+ function usage() {
333
+ console.log([
334
+ "",
335
+ ` ${cyan("cc-pets pet")} — 把素材装进 cc-pets 自己的目录`,
336
+ "",
337
+ ` ${cyan("add")} [源:]<名称>... 下载素材到 ${dim(petsRoot())}`,
338
+ ` ${cyan("search")} [源:][关键词] 搜索可用素材(不带关键词就列全部)`,
339
+ ` ${cyan("list")} 列出已安装的素材,按来源分组`,
340
+ ` ${cyan("remove")} <名称>... 删除已安装的素材`,
341
+ ` ${cyan("source")} 列出可用的素材源`,
342
+ ` ${cyan("dir")} 打印素材目录路径`,
343
+ "",
344
+ ` ${dim("名称可以带源前缀(petdex:boba);不带就用默认源 " + DEFAULT_SOURCE + "。")}`,
345
+ ` ${dim("--as <本地名> 换个目录名安装,支持中文,用来避开同名素材的冲突。")}`,
346
+ ` ${dim("--refresh 强制刷新素材清单缓存(默认缓存 6 小时)。")}`,
347
+ ` ${dim("CC_PETS_PETS_DIR 换素材目录,CC_PETS_SOURCE 换默认源。")}`,
348
+ "",
349
+ ` ${dim("$")} cc-pets pet search otter`,
350
+ ` ${dim("$")} cc-pets pet add boba`,
351
+ ` ${dim("$")} cc-pets pet add petdex:boba --as boba-petdex`,
352
+ ` ${dim("$")} cc-pets pet add boba --as 波霸`,
353
+ ""
354
+ ].join("\n"));
355
+ }
356
+
357
+ const [command, ...args] = process.argv.slice(2);
358
+ if (!SOURCES[DEFAULT_SOURCE]) {
359
+ fail(`CC_PETS_SOURCE 指向未知的源 "${DEFAULT_SOURCE}"。可用的源: ${Object.keys(SOURCES).join(", ")}`);
360
+ }
361
+ switch (command) {
362
+ case "add":
363
+ case "install":
364
+ await commandAdd(args);
365
+ break;
366
+ case "search":
367
+ await commandSearch(args);
368
+ break;
369
+ case "list":
370
+ case "ls":
371
+ commandList();
372
+ break;
373
+ case "remove":
374
+ case "rm":
375
+ commandRemove(args);
376
+ break;
377
+ case "source":
378
+ case "sources":
379
+ commandSource();
380
+ break;
381
+ case "dir":
382
+ commandDir();
383
+ break;
384
+ case undefined:
385
+ case "help":
386
+ case "--help":
387
+ case "-h":
388
+ usage();
389
+ break;
390
+ default:
391
+ console.error(red(`未知子命令: ${command}`));
392
+ usage();
393
+ process.exit(2);
394
+ }