cc-pets 1.1.0 → 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 +18 -0
- package/README.md +112 -7
- package/Sources/CCPets/CCPetsAppDelegate.h +4 -1
- package/Sources/CCPets/CCPetsAppDelegate.m +65 -50
- package/Sources/CCPets/CCPetsPaths.h +8 -0
- package/Sources/CCPets/CCPetsPaths.m +68 -0
- package/Sources/CCPets/CCPetsUsage.m +8 -2
- package/Sources/CCPets/PetView.h +0 -1
- package/Sources/CCPets/PetView.m +5 -2
- package/Sources/CCPets/QuotaDashboardView.m +79 -46
- package/bin/cc-pets +5 -0
- package/package.json +1 -1
- package/scripts/pet-store.mjs +394 -0
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
|
-
|
|
61
|
+
右键菜单中的“切换桌宠”只扫描 `~/.cc-pets/pets/`(见 [素材管理](#素材管理))和包内素材,
|
|
62
|
+
**不会**去读 `~/.petdex/pets/` 和 `~/.codex/pets/`——那两个目录由 PetDex CLI 和 Codex 写入,
|
|
63
|
+
混在一起就找不到自己装的宠物了。要用 Codex 那边的素材,打开右键菜单里的“导入 Codex
|
|
64
|
+
素材”开关,它们会被复制进你自己的目录(见 [导入 Codex 素材](#导入-codex-素材))。
|
|
65
|
+
|
|
62
66
|
外部桌宠使用目录名作为菜单名称,内置桌宠使用素材文件名(不显示扩展名)。选择后立即
|
|
63
67
|
切换并持久保存;下次启动会继续使用上次选择的桌宠。该菜单只负责切换已有素材,不提供
|
|
64
|
-
|
|
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`。
|
|
@@ -129,6 +137,31 @@ Hooks、shell alias 和 `~/Applications/CC Pets.app` 的安装;`--prefer-onlin
|
|
|
129
137
|
cc-pets install
|
|
130
138
|
```
|
|
131
139
|
|
|
140
|
+
#### 关于安装脚本白名单
|
|
141
|
+
|
|
142
|
+
新版 npm(12 起默认)引入了安装脚本白名单:不在白名单里的包,`postinstall` 一律不执行。
|
|
143
|
+
它只打印一行 `warn install-scripts`,进程仍然以成功退出,所以**安装看起来是成功的**,
|
|
144
|
+
但原生应用、Hooks 和 shell alias 都不会被安装 —— 表现为敲 `codex` / `claude` 时桌宠不出现。
|
|
145
|
+
|
|
146
|
+
不想每次都带 `--allow-scripts` 参数的话,可以配置一次持久白名单:
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
npm config set allow-scripts=cc-pets --location=user
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
这个机制作用于所有带 `postinstall` 的包,不限于 CC Pets。常见的一个例子是 Claude Code 自身:
|
|
153
|
+
它的原生二进制正是由 `postinstall` 铺开的,被拦下时执行 `claude` 会提示
|
|
154
|
+
`claude native binary not installed`,而重装并不能修好 —— 因为每次重装都会被同样拦下。
|
|
155
|
+
这类情况可以按需把多个包一起加进白名单:
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
npm config set allow-scripts=cc-pets,@anthropic-ai/claude-code --location=user
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
怀疑某个 CLI 装完后行为异常时,可以在 `~/.npm/_logs/` 最近的日志里搜 `install-scripts`,
|
|
162
|
+
确认是不是同一个原因。注意白名单只对之后的安装生效,不会回头补跑已经被拦下的脚本,
|
|
163
|
+
所以配置完还需要重装一次对应的包。
|
|
164
|
+
|
|
132
165
|
### 本地源码安装
|
|
133
166
|
|
|
134
167
|
```bash
|
|
@@ -162,6 +195,7 @@ Codex/Claude Hooks 和 shell 集成,并自动重启正在运行的桌宠。自
|
|
|
162
195
|
|
|
163
196
|
```bash
|
|
164
197
|
npm install -g cc-pets@latest \
|
|
198
|
+
--allow-scripts=cc-pets \
|
|
165
199
|
--prefer-online
|
|
166
200
|
```
|
|
167
201
|
|
|
@@ -208,6 +242,11 @@ cc-pets --history
|
|
|
208
242
|
# 清理可重建的临时状态、更新日志和构建缓存,保留历史、配置与偏好
|
|
209
243
|
cc-pets clean
|
|
210
244
|
|
|
245
|
+
# 管理 ~/.cc-pets/pets 里的桌宠素材,详见「素材与版权」
|
|
246
|
+
cc-pets pet search otter
|
|
247
|
+
cc-pets pet add boba
|
|
248
|
+
cc-pets pet list
|
|
249
|
+
|
|
211
250
|
# 从标准输入发送第三方 Provider 状态事件
|
|
212
251
|
printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
|
|
213
252
|
| cc-pets provider-event
|
|
@@ -316,16 +355,82 @@ v2(`1536×2288`、`8×11`),单元格均为 `192×208`,前九行遵循相
|
|
|
316
355
|
角色可能属于受版权保护的作品;公开
|
|
317
356
|
发布本项目或 npm 包前,请确认已经获得素材的使用和分发授权,或替换为原创、可公开分发的素材。
|
|
318
357
|
|
|
319
|
-
|
|
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
|
+
受保护:
|
|
320
393
|
|
|
321
394
|
```bash
|
|
322
|
-
|
|
395
|
+
cc-pets pet add petdex:boba --as boba-petdex
|
|
396
|
+
cc-pets pet add boba --as 波霸
|
|
323
397
|
```
|
|
324
398
|
|
|
325
|
-
|
|
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/` 为空时桌宠才会去读那里。
|
|
326
431
|
|
|
327
|
-
|
|
328
|
-
提示窗口,可打开 `~/.
|
|
432
|
+
项目允许在没有内置素材时构建。若启动时内置目录和所有外部目录都没有可用素材,应用会显示
|
|
433
|
+
提示窗口,可打开 `~/.cc-pets/pets/`、安装素材后重新扫描,或安全退出。
|
|
329
434
|
|
|
330
435
|
## 隐私
|
|
331
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;
|
|
@@ -48,7 +52,6 @@
|
|
|
48
52
|
- (void)positionAgentStatus;
|
|
49
53
|
- (void)showAgentStatusForRecord:(NSDictionary *)record;
|
|
50
54
|
- (void)prunePendingApprovalRecords;
|
|
51
|
-
- (void)toggleAgentStatusBubble:(id)sender;
|
|
52
55
|
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender;
|
|
53
56
|
- (void)refreshUsage:(id)sender;
|
|
54
57
|
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage;
|
|
@@ -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;
|
|
@@ -405,20 +424,8 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
405
424
|
[self.statusPanel orderOut:nil];
|
|
406
425
|
self.hasAgentStatus = NO;
|
|
407
426
|
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
self.statusBubbleExpanded = !self.statusBubbleExpanded;
|
|
411
|
-
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
412
|
-
forKey:StatusBubbleExpandedKey];
|
|
413
|
-
if (self.statusBubbleExpanded) {
|
|
414
|
-
[self positionAgentStatus];
|
|
415
|
-
[self.statusPanel orderFrontRegardless];
|
|
416
|
-
} else {
|
|
417
|
-
[self.statusPanel orderOut:nil];
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
// 菜单开关的语义和点击宠物相反:勾选 = 显示气泡。没有 agent 状态时也允许改,
|
|
421
|
-
// 这样用户可以提前设好偏好,而不必等下一次会话开始。
|
|
427
|
+
// 勾选 = 显示气泡。没有 agent 状态时也允许改,这样用户可以提前设好偏好,
|
|
428
|
+
// 而不必等下一次会话开始。
|
|
422
429
|
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender {
|
|
423
430
|
self.statusBubbleExpanded = !self.statusBubbleExpanded;
|
|
424
431
|
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
@@ -598,35 +605,18 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
598
605
|
}
|
|
599
606
|
return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
|
|
600
607
|
}
|
|
608
|
+
// 桌宠只扫 OwnPetsDirectory() 加包内素材,无条件、不看那里有没有东西。~/.petdex/pets 和
|
|
609
|
+
// ~/.codex/pets 由别的工具写入,直接扫就永远分不清哪只是自己装的;要用 Codex 的素材就打开
|
|
610
|
+
// "导入 Codex 素材"开关,由 ImportCodexPets 复制进来,之后它们和自己装的没有区别。
|
|
601
611
|
- (NSArray<NSDictionary *> *)discoverPetOptions {
|
|
602
|
-
NSString *
|
|
603
|
-
NSString *petdexRoot = [home stringByAppendingPathComponent:@".petdex/pets"];
|
|
604
|
-
NSString *codexRoot = [home stringByAppendingPathComponent:@".codex/pets"];
|
|
612
|
+
NSString *ownRoot = OwnPetsDirectory();
|
|
605
613
|
NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
|
|
606
|
-
NSMutableSet<NSString *> *externalNames = [NSMutableSet set];
|
|
607
614
|
|
|
608
|
-
for (NSString *name in [self petDirectoryNamesAtPath:
|
|
609
|
-
NSString *
|
|
610
|
-
NSString *
|
|
611
|
-
NSString *path = [self spritePathInDirectory:petdexDirectory];
|
|
612
|
-
if (!path) path = [self spritePathInDirectory:codexDirectory];
|
|
613
|
-
if (!path) continue;
|
|
614
|
-
NSInteger version = [self spriteVersionInDirectory:petdexDirectory fallbackDirectory:codexDirectory];
|
|
615
|
-
[result addObject:@{
|
|
616
|
-
@"id": [@"external:" stringByAppendingString:name],
|
|
617
|
-
@"name": name,
|
|
618
|
-
@"path": path,
|
|
619
|
-
@"spriteVersionNumber": @(version),
|
|
620
|
-
@"spriteRowCount": @([self spriteRowCountForVersion:version])
|
|
621
|
-
}];
|
|
622
|
-
[externalNames addObject:name];
|
|
623
|
-
}
|
|
624
|
-
for (NSString *name in [self petDirectoryNamesAtPath:codexRoot]) {
|
|
625
|
-
if ([externalNames containsObject:name]) continue;
|
|
626
|
-
NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
|
|
627
|
-
NSString *path = [self spritePathInDirectory:codexDirectory];
|
|
615
|
+
for (NSString *name in [self petDirectoryNamesAtPath:ownRoot]) {
|
|
616
|
+
NSString *directory = [ownRoot stringByAppendingPathComponent:name];
|
|
617
|
+
NSString *path = [self spritePathInDirectory:directory];
|
|
628
618
|
if (!path) continue;
|
|
629
|
-
NSInteger version = [self spriteVersionInDirectory:
|
|
619
|
+
NSInteger version = [self spriteVersionInDirectory:directory fallbackDirectory:nil];
|
|
630
620
|
[result addObject:@{
|
|
631
621
|
@"id": [@"external:" stringByAppendingString:name],
|
|
632
622
|
@"name": name,
|
|
@@ -634,10 +624,10 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
634
624
|
@"spriteVersionNumber": @(version),
|
|
635
625
|
@"spriteRowCount": @([self spriteRowCountForVersion:version])
|
|
636
626
|
}];
|
|
637
|
-
[externalNames addObject:name];
|
|
638
627
|
}
|
|
639
628
|
|
|
640
|
-
NSArray<NSString *> *bundled = [NSFileManager.defaultManager
|
|
629
|
+
NSArray<NSString *> *bundled = [NSFileManager.defaultManager
|
|
630
|
+
contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
|
|
641
631
|
for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
|
|
642
632
|
NSString *extension = fileName.pathExtension.lowercaseString;
|
|
643
633
|
if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
|
|
@@ -651,26 +641,51 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
651
641
|
}
|
|
652
642
|
return result;
|
|
653
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
|
+
}
|
|
654
666
|
- (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
|
|
655
667
|
for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
|
|
656
668
|
return nil;
|
|
657
669
|
}
|
|
658
670
|
- (NSArray<NSDictionary *> *)waitForPetOptions {
|
|
659
671
|
while (YES) {
|
|
660
|
-
|
|
672
|
+
// 这个循环就是"重新扫描"按钮的实现,必须绕开缓存。
|
|
673
|
+
[self invalidatePetOptionsCache];
|
|
674
|
+
NSArray<NSDictionary *> *options = [self petOptions];
|
|
661
675
|
if (options.count > 0) return options;
|
|
662
676
|
|
|
663
677
|
[NSApp activateIgnoringOtherApps:YES];
|
|
664
678
|
NSAlert *alert = [NSAlert new];
|
|
665
679
|
alert.messageText = @"没有找到桌宠素材";
|
|
666
|
-
alert.informativeText = @"
|
|
667
|
-
@"~/.
|
|
680
|
+
alert.informativeText = @"用 `cc-pets pet add <名称>` 下载素材,或把 PNG / WebP 精灵图放入 "
|
|
681
|
+
@"~/.cc-pets/pets/<名称>/。桌宠不会去读 ~/.petdex/pets/ 和 ~/.codex/pets/;"
|
|
682
|
+
@"要用 Codex 的素材,请在右键菜单打开“导入 Codex 素材”。完成后点击“重新扫描”。";
|
|
668
683
|
[alert addButtonWithTitle:@"重新扫描"];
|
|
669
684
|
[alert addButtonWithTitle:@"打开素材目录"];
|
|
670
685
|
[alert addButtonWithTitle:@"退出"];
|
|
671
686
|
NSModalResponse response = [alert runModal];
|
|
672
687
|
if (response == NSAlertSecondButtonReturn) {
|
|
673
|
-
NSString *directory =
|
|
688
|
+
NSString *directory = OwnPetsDirectory();
|
|
674
689
|
[NSFileManager.defaultManager createDirectoryAtPath:directory
|
|
675
690
|
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
676
691
|
[NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
|
|
@@ -687,6 +702,9 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
687
702
|
self.binaryDirectory = runsFromAppBundle && mainBundle.resourcePath.length > 0
|
|
688
703
|
? mainBundle.resourcePath
|
|
689
704
|
: binaryDir;
|
|
705
|
+
// 必须在 waitForPetOptions 之前:否则自己的目录还空着、素材全在 Codex 那边时,
|
|
706
|
+
// 会先弹一次"没有找到桌宠素材",等用户点完重新扫描才导入。
|
|
707
|
+
if ([NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]) ImportCodexPets();
|
|
690
708
|
NSArray<NSDictionary *> *petOptions = [self waitForPetOptions];
|
|
691
709
|
if (petOptions.count == 0) {
|
|
692
710
|
[NSApp terminate:nil];
|
|
@@ -748,7 +766,7 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
748
766
|
else [weakSelf scheduleQuotaDashboardHide];
|
|
749
767
|
};
|
|
750
768
|
self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
|
|
751
|
-
return [weakSelf
|
|
769
|
+
return [weakSelf petOptions] ?: @[];
|
|
752
770
|
};
|
|
753
771
|
self.petView.switchPetRequested = ^(NSString *petID) {
|
|
754
772
|
[weakSelf switchPetToID:petID];
|
|
@@ -757,9 +775,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
757
775
|
weakSelf.petDragging = dragging;
|
|
758
776
|
if (!dragging) [weakSelf scheduleQuotaDashboardHide];
|
|
759
777
|
};
|
|
760
|
-
self.petView.statusToggleRequested = ^{
|
|
761
|
-
[weakSelf toggleAgentStatusBubble:nil];
|
|
762
|
-
};
|
|
763
778
|
// 附属面板的跟随必须挂在窗口自身的移动通知上,不能只挂 PetView 的拖动回调:
|
|
764
779
|
// panel 开了 movableByWindowBackground,按在 PetView 之外的透明边上时由 AppKit
|
|
765
780
|
// 直接搬窗口,PetView 的 mouseDragged 根本不触发,气泡就会留在原地。
|
|
@@ -1014,7 +1029,7 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
1014
1029
|
}
|
|
1015
1030
|
}
|
|
1016
1031
|
- (void)switchPetToID:(NSString *)petID {
|
|
1017
|
-
NSArray<NSDictionary *> *options = [self
|
|
1032
|
+
NSArray<NSDictionary *> *options = [self petOptions];
|
|
1018
1033
|
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
1019
1034
|
if (!option) return;
|
|
1020
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
|
-
|
|
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) {
|
package/Sources/CCPets/PetView.h
CHANGED
|
@@ -17,7 +17,6 @@
|
|
|
17
17
|
@property id localMouseMonitor;
|
|
18
18
|
@property(copy) void (^pocketHoverChanged)(BOOL hovering);
|
|
19
19
|
@property(copy) void (^dragStateChanged)(BOOL dragging);
|
|
20
|
-
@property(copy) void (^statusToggleRequested)(void);
|
|
21
20
|
@property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
|
|
22
21
|
@property(copy) void (^switchPetRequested)(NSString *petID);
|
|
23
22
|
@property NSCache<NSString *, NSImage *> *petMenuPreviewCache;
|
package/Sources/CCPets/PetView.m
CHANGED
|
@@ -305,7 +305,6 @@ static const CGFloat PetDragThreshold = 3.0;
|
|
|
305
305
|
// 就说明本次按下没有拖动过,不需要额外的标志来区分。
|
|
306
306
|
- (void)mouseUp:(NSEvent *)event {
|
|
307
307
|
[self playRow:7 throughFrame:5 oneShot:YES];
|
|
308
|
-
if (self.statusToggleRequested) self.statusToggleRequested();
|
|
309
308
|
}
|
|
310
309
|
- (void)drawRect:(NSRect)dirtyRect {
|
|
311
310
|
CGFloat cellWidth = self.sheet.size.width / 8.0;
|
|
@@ -494,7 +493,6 @@ static const CGFloat PetDragThreshold = 3.0;
|
|
|
494
493
|
[menu addItem:NSMenuItem.separatorItem];
|
|
495
494
|
NSMenuItem *refreshItem = [menu addItemWithTitle:@"刷新用量" action:@selector(refreshUsage:) keyEquivalent:@"r"];
|
|
496
495
|
refreshItem.target = NSApp.delegate;
|
|
497
|
-
// 点击宠物本体也能折叠气泡,但那个交互没有任何视觉提示。这里留一个可发现的入口。
|
|
498
496
|
[self addPersistentSwitchToMenu:menu
|
|
499
497
|
title:@"显示消息气泡"
|
|
500
498
|
checked:[NSUserDefaults.standardUserDefaults boolForKey:StatusBubbleExpandedKey]
|
|
@@ -505,6 +503,11 @@ static const CGFloat PetDragThreshold = 3.0;
|
|
|
505
503
|
checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
|
|
506
504
|
action:@selector(toggleQuotaHistory:)
|
|
507
505
|
tag:0];
|
|
506
|
+
[self addPersistentSwitchToMenu:menu
|
|
507
|
+
title:@"导入 Codex 素材"
|
|
508
|
+
checked:[NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]
|
|
509
|
+
action:@selector(toggleImportCodexPets:)
|
|
510
|
+
tag:0];
|
|
508
511
|
NSMenuItem *notificationItem = [menu addItemWithTitle:@"系统通知" action:nil keyEquivalent:@""];
|
|
509
512
|
NSMenu *notificationMenu = [NSMenu new];
|
|
510
513
|
NSArray<NSDictionary *> *notificationOptions = @[
|
|
@@ -57,14 +57,13 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
57
57
|
- (NSRect)logicalSummaryRect {
|
|
58
58
|
return NSMakeRect(20, 372, QuotaLogicalWidth - 40, 86);
|
|
59
59
|
}
|
|
60
|
+
// 刷新时间挪去了右上角,这一版块整宽留给两个统计格,各占一半。
|
|
60
61
|
- (NSRect)logicalSummaryCellRectAtIndex:(NSUInteger)index {
|
|
61
62
|
NSRect summary = [self logicalSummaryRect];
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
return index < 3 ? NSMakeRect(x, NSMinY(summary), widths[index], NSHeight(summary)) : NSZeroRect;
|
|
63
|
+
CGFloat width = NSWidth(summary) / 2;
|
|
64
|
+
return index < 2
|
|
65
|
+
? NSMakeRect(NSMinX(summary) + index * width, NSMinY(summary), width, NSHeight(summary))
|
|
66
|
+
: NSZeroRect;
|
|
68
67
|
}
|
|
69
68
|
- (void)mouseMoved:(NSEvent *)event {
|
|
70
69
|
NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
|
|
@@ -109,16 +108,31 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
109
108
|
? usage[@"tokenUsage"] : nil;
|
|
110
109
|
return [tokenUsage[key] isKindOfClass:NSDictionary.class] ? tokenUsage[key] : nil;
|
|
111
110
|
}
|
|
112
|
-
- (NSString *)
|
|
113
|
-
NSNumber *number = [totals[@"total_tokens"] isKindOfClass:NSNumber.class]
|
|
114
|
-
? totals[@"total_tokens"] : nil;
|
|
115
|
-
if (!number) return @"--";
|
|
116
|
-
double value = number.doubleValue;
|
|
111
|
+
- (NSString *)formattedTokenValue:(double)value {
|
|
117
112
|
if (value >= 1000000000) return [NSString stringWithFormat:@"%.2fB", value / 1000000000.0];
|
|
118
113
|
if (value >= 1000000) return [NSString stringWithFormat:@"%.2fM", value / 1000000.0];
|
|
119
114
|
if (value >= 1000) return [NSString stringWithFormat:@"%.1fK", value / 1000.0];
|
|
120
115
|
return [NSString stringWithFormat:@"%.0f", value];
|
|
121
116
|
}
|
|
117
|
+
- (NSString *)formattedTokenCount:(NSDictionary *)totals {
|
|
118
|
+
NSNumber *number = [totals[@"total_tokens"] isKindOfClass:NSNumber.class]
|
|
119
|
+
? totals[@"total_tokens"] : nil;
|
|
120
|
+
return number ? [self formattedTokenValue:number.doubleValue] : @"--";
|
|
121
|
+
}
|
|
122
|
+
// 输入取 total - output,而不是把几个 input_* 字段加起来:两家的包含关系是相反的。
|
|
123
|
+
// Codex 的 cached_input_tokens 是 input_tokens 的子集(实测 input+output == total),
|
|
124
|
+
// 相加会把缓存部分算两遍;Claude 的 input_tokens 不含缓存读写,两者是并列项,不加又会漏。
|
|
125
|
+
// total - output 对两家都成立,也保证"输入 + 输出"正好等于卡片上那个已用 Token。
|
|
126
|
+
- (NSString *)formattedTokenSplit:(NSDictionary *)totals wantsOutput:(BOOL)wantsOutput {
|
|
127
|
+
NSNumber *total = [totals[@"total_tokens"] isKindOfClass:NSNumber.class]
|
|
128
|
+
? totals[@"total_tokens"] : nil;
|
|
129
|
+
if (!total) return @"--";
|
|
130
|
+
NSNumber *output = [totals[@"output_tokens"] isKindOfClass:NSNumber.class]
|
|
131
|
+
? totals[@"output_tokens"] : nil;
|
|
132
|
+
double outputValue = output ? output.doubleValue : 0;
|
|
133
|
+
return [self formattedTokenValue:
|
|
134
|
+
wantsOutput ? outputValue : fmax(0, total.doubleValue - outputValue)];
|
|
135
|
+
}
|
|
122
136
|
// 两个窗口共用。resets_at 是整分对齐的,带秒只会多占宽度。
|
|
123
137
|
- (NSString *)clockText:(NSTimeInterval)value {
|
|
124
138
|
NSDateFormatter *formatter = [NSDateFormatter new];
|
|
@@ -146,6 +160,11 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
146
160
|
- (NSString *)formattedTokenCountForUsage:(NSDictionary *)usage key:(NSString *)key {
|
|
147
161
|
return [self formattedTokenCount:[self tokenTotals:usage key:key] ?: @{}];
|
|
148
162
|
}
|
|
163
|
+
- (NSString *)formattedTokenSplitForUsage:(NSDictionary *)usage key:(NSString *)key
|
|
164
|
+
wantsOutput:(BOOL)wantsOutput {
|
|
165
|
+
return [self formattedTokenSplit:[self tokenTotals:usage key:key] ?: @{}
|
|
166
|
+
wantsOutput:wantsOutput];
|
|
167
|
+
}
|
|
149
168
|
- (NSNumber *)usedForQuota:(NSDictionary *)quota usedKey:(NSString *)usedKey {
|
|
150
169
|
NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
|
|
151
170
|
return used ? @(fmax(0, fmin(100, used.doubleValue))) : nil;
|
|
@@ -162,6 +181,14 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
162
181
|
return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
|
|
163
182
|
NSForegroundColorAttributeName: color};
|
|
164
183
|
}
|
|
184
|
+
- (NSDictionary *)rightAlignedTextAttributesWithSize:(CGFloat)size color:(NSColor *)color
|
|
185
|
+
weight:(NSFontWeight)weight {
|
|
186
|
+
NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
|
|
187
|
+
style.alignment = NSTextAlignmentRight;
|
|
188
|
+
return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
|
|
189
|
+
NSForegroundColorAttributeName: color,
|
|
190
|
+
NSParagraphStyleAttributeName: style};
|
|
191
|
+
}
|
|
165
192
|
- (NSDictionary *)centeredTextAttributesWithSize:(CGFloat)size color:(NSColor *)color weight:(NSFontWeight)weight {
|
|
166
193
|
NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
|
|
167
194
|
style.alignment = NSTextAlignmentCenter;
|
|
@@ -363,6 +390,12 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
363
390
|
[self fillRoundedRect:refreshRect radius:10 color:[NSColor colorWithWhite:1 alpha:buttonAlpha]];
|
|
364
391
|
[recentlyRefreshed ? @"✓" : @"↻" drawInRect:NSInsetRect(refreshRect, 8, 4)
|
|
365
392
|
withAttributes:[self textAttributesWithSize:19 color:[NSColor colorWithWhite:0.9 alpha:1] weight:NSFontWeightRegular]];
|
|
393
|
+
// 贴着刷新按钮左侧右对齐:它说明的正是这个按钮上次生效的时间,挨着放才不用再标一遍
|
|
394
|
+
// "数据刷新"是什么意思。放回汇总条里会挤掉一整格 Provider 数据。
|
|
395
|
+
[[NSString stringWithFormat:@"数据刷新 %@", [self refreshAgeText]]
|
|
396
|
+
drawInRect:NSMakeRect(NSMinX(logicalRefreshRect) - 206, NSMinY(logicalRefreshRect) + 7, 200, 18)
|
|
397
|
+
withAttributes:[self rightAlignedTextAttributesWithSize:11 color:secondary
|
|
398
|
+
weight:NSFontWeightRegular]];
|
|
366
399
|
|
|
367
400
|
NSRect summary = [self logicalSummaryRect];
|
|
368
401
|
NSBezierPath *summaryPath = [NSBezierPath bezierPathWithRoundedRect:summary xRadius:18 yRadius:18];
|
|
@@ -373,12 +406,16 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
373
406
|
|
|
374
407
|
// 今日与最近 7 天都按 Provider 分开展示。底层本来就是两套独立的自然日统计,
|
|
375
408
|
// 不在展示层相加,避免用户无法判断 Token 来自 Codex 还是 Claude。
|
|
376
|
-
//
|
|
409
|
+
// 每格内是一张 2×2 表:行是 Provider,列是输入/输出,列头与格标题共用一行 —— 86pt
|
|
410
|
+
// 高度只够三行,再单开一行列头就得把格子拔高,挤掉下面两张 Provider 卡片。
|
|
377
411
|
NSArray<NSDictionary *> *cells = @[
|
|
378
412
|
@{@"icon": @"◔", @"key": @"today", @"label": @"今日已用 Token"},
|
|
379
|
-
@{@"icon": @"◉", @"key": @"recentWeek", @"label": @"近 7 天已用 Token"}
|
|
380
|
-
|
|
381
|
-
|
|
413
|
+
@{@"icon": @"◉", @"key": @"recentWeek", @"label": @"近 7 天已用 Token"}
|
|
414
|
+
];
|
|
415
|
+
NSColor *claudeColor = [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1];
|
|
416
|
+
NSArray<NSDictionary *> *rows = @[
|
|
417
|
+
@{@"name": @"Codex", @"usage": self.codexUsage ?: @{}, @"color": cyan, @"y": @35},
|
|
418
|
+
@{@"name": @"Claude", @"usage": self.claudeUsage ?: @{}, @"color": claudeColor, @"y": @12}
|
|
382
419
|
];
|
|
383
420
|
[[NSColor colorWithWhite:1 alpha:0.10] setStroke];
|
|
384
421
|
for (NSUInteger index = 1; index < cells.count; index++) {
|
|
@@ -388,36 +425,32 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
388
425
|
}
|
|
389
426
|
for (NSUInteger index = 0; index < cells.count; index++) {
|
|
390
427
|
NSDictionary *cell = cells[index];
|
|
391
|
-
|
|
392
|
-
CGFloat x = NSMinX(
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
withAttributes:[self textAttributesWithSize:
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
withAttributes:[self textAttributesWithSize:20 color:primary weight:NSFontWeightBold]];
|
|
418
|
-
[cell[@"label"] drawInRect:NSMakeRect(x + 56, NSMinY(summary) + 17, 96, 20)
|
|
419
|
-
withAttributes:[self textAttributesWithSize:11 color:secondary
|
|
420
|
-
weight:NSFontWeightRegular]];
|
|
428
|
+
NSString *key = cell[@"key"];
|
|
429
|
+
CGFloat x = NSMinX([self logicalSummaryCellRectAtIndex:index]);
|
|
430
|
+
const CGFloat inputX = x + 176;
|
|
431
|
+
const CGFloat outputX = x + 266;
|
|
432
|
+
[cell[@"icon"] drawInRect:NSMakeRect(x + 24, NSMinY(summary) + 23, 42, 42)
|
|
433
|
+
withAttributes:[self textAttributesWithSize:30 color:cyan weight:NSFontWeightRegular]];
|
|
434
|
+
NSDictionary *headerAttributes = [self textAttributesWithSize:11 color:secondary
|
|
435
|
+
weight:NSFontWeightRegular];
|
|
436
|
+
[cell[@"label"] drawInRect:NSMakeRect(x + 72, NSMinY(summary) + 59, 100, 18)
|
|
437
|
+
withAttributes:headerAttributes];
|
|
438
|
+
[@"输入" drawInRect:NSMakeRect(inputX, NSMinY(summary) + 59, 86, 18)
|
|
439
|
+
withAttributes:headerAttributes];
|
|
440
|
+
[@"输出" drawInRect:NSMakeRect(outputX, NSMinY(summary) + 59, 86, 18)
|
|
441
|
+
withAttributes:headerAttributes];
|
|
442
|
+
for (NSDictionary *row in rows) {
|
|
443
|
+
CGFloat y = NSMinY(summary) + [row[@"y"] doubleValue];
|
|
444
|
+
NSDictionary *usage = row[@"usage"];
|
|
445
|
+
[row[@"name"] drawInRect:NSMakeRect(x + 72, y, 60, 20)
|
|
446
|
+
withAttributes:[self textAttributesWithSize:12 color:row[@"color"]
|
|
447
|
+
weight:NSFontWeightMedium]];
|
|
448
|
+
NSDictionary *valueAttributes = [self textAttributesWithSize:16 color:primary
|
|
449
|
+
weight:NSFontWeightBold];
|
|
450
|
+
[[self formattedTokenSplitForUsage:usage key:key wantsOutput:NO]
|
|
451
|
+
drawInRect:NSMakeRect(inputX, y - 2, 86, 23) withAttributes:valueAttributes];
|
|
452
|
+
[[self formattedTokenSplitForUsage:usage key:key wantsOutput:YES]
|
|
453
|
+
drawInRect:NSMakeRect(outputX, y - 2, 86, 23) withAttributes:valueAttributes];
|
|
421
454
|
}
|
|
422
455
|
}
|
|
423
456
|
|
|
@@ -426,7 +459,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
426
459
|
[self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
|
|
427
460
|
color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
|
|
428
461
|
cardRect:NSMakeRect(20, 44, QuotaLogicalWidth - 40, 152)];
|
|
429
|
-
NSString *footer = @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token =
|
|
462
|
+
NSString *footer = @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量(输入含缓存读写),两者口径不同";
|
|
430
463
|
// 卡片底边在 y=44,原来 footer 顶到 44 完全没有间隙。下移到与卡片留约 8pt,
|
|
431
464
|
// 同时底部留白 16pt,和顶部标题的留白大致对称。
|
|
432
465
|
[footer drawInRect:NSMakeRect(28, 16, 650, 20)
|
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
|
@@ -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) => `[2m${text}[0m`;
|
|
47
|
+
const cyan = (text) => `[36m${text}[0m`;
|
|
48
|
+
const green = (text) => `[32m${text}[0m`;
|
|
49
|
+
const red = (text) => `[31m${text}[0m`;
|
|
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
|
+
}
|