cc-pets 1.4.8 → 2.0.1

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.
@@ -89,85 +89,84 @@
89
89
  # agent工作时的状态播报,需要至少保留一行
90
90
 
91
91
  [state_starting] # 正在启动
92
- 正在把它叫醒…
93
- 它还在穿鞋,稍等。
94
- 马上就好。
95
- 它爬起来了。
92
+ 我醒啦,马上就好。
93
+ 我还在穿鞋,稍等。
94
+ 马上开工。
95
+ 我爬起来了。
96
96
 
97
97
  [state_idle] # 待机中
98
- 它准备好了,你说吧。
99
- 安静着呢,随时开工。
100
- 就位了,等你发话。
101
- 我们都听着。
98
+ 我准备好了,你说吧。
99
+ 我在这儿,随时开工。
100
+ 我已就位,等你发话。
101
+ 我听着呢。
102
102
 
103
103
  [state_thinking] # 正在思考
104
- 它在想,我在旁边看着。
105
- 让它想想,别催。
106
- 脑子转起来了。
107
- 这题它得琢磨会儿。
108
- 安静,它在思考。
104
+ 我在想,让我琢磨会儿。
105
+ 别催,我脑子转着呢。
106
+ 这题我得想想。
107
+ 安静,我在思考。
109
108
 
110
109
  [state_tool] # 正在用工具(说不清是哪类时)
111
- 它动手了。
112
- 在翻工具箱。
113
- 忙起来了。
110
+ 我动手了。
111
+ 我在翻工具箱。
112
+ 我忙起来了。
114
113
 
115
114
  [state_tool_bash] # 正在执行命令
116
- 在敲命令了。
117
- 终端里忙着呢。
118
- 这条命令我看着。
115
+ 我在敲命令。
116
+ 我在终端里忙着呢。
117
+ 这条命令交给我。
119
118
 
120
119
  [state_tool_edit] # 正在编辑文件
121
- 在改文件,别手抖。
122
- 动笔了。
123
- 文件正在被折腾。
120
+ 我在改文件,别手抖。
121
+ 我动笔了。
122
+ 我来收拾这个文件。
124
123
 
125
124
  [state_tool_read] # 正在查找资料
126
- 到处翻资料呢。
127
- 在找线索。
128
- 翻书中…
125
+ 我在翻资料。
126
+ 我在找线索。
127
+ 我翻翻看…
129
128
 
130
129
  [state_tool_done] # 单步操作完成
131
- 这一步成了。
132
- 搞定一个。
130
+ 这一步我搞定了。
131
+ 我搞定一个。
133
132
  稳住了。
134
133
 
135
134
  [state_tool_failed] # 工具执行失败
136
- 这步崴了。
137
- 工具闹脾气了。
138
- 它好像有点坏了。。。
135
+ 这步我崴了。
136
+ 工具跟我闹脾气了。
137
+ 我得换个办法。。。
139
138
 
140
139
  [state_subagent] # 子 Agent 工作中
141
- 它喊帮手了。
142
- 派了个小弟出去。
143
- 这活儿分出去了。
140
+ 我喊了个帮手。
141
+ 我派了个小伙伴出去。
142
+ 这活儿我分出去啦。
144
143
 
145
144
  [state_approval] # 等待审批
146
- 它等你点头。
147
- 卡住了,回终端看一眼。
148
- 要你拿主意。
149
- 不敢乱动,等你发话。
145
+ 我等你点头。
146
+ 我卡住了,回终端看一眼。
147
+ 这步得你拿主意。
148
+ 我不敢乱动,等你发话。
150
149
 
151
150
  [state_auto_review] # 自动审批中
152
- 有人替你把关了。
153
- 自动审着呢,不用管。
154
- 这轮它自己会查。
151
+ 我在自动检查。
152
+ 我自己把关,你先忙。
153
+ 这轮我会查好。
155
154
 
156
155
  [state_completed] # 任务已完成
157
- 干完了,歇会儿。
158
- 收工!
159
- 这轮结束了。
156
+ 我干完了,歇会儿。
157
+ 我收工啦!
158
+ 这轮我完成了。
160
159
  齐活。
161
160
 
162
161
  [state_failed] # 任务失败
163
- 翻车了,回终端看看。
164
- 没成,去瞧瞧。
165
- 这次栽了。
162
+ 我翻车了,回终端看看。
163
+ 我没成,去瞧瞧。
164
+ 这次我栽了。
166
165
 
167
166
  [state_notification] # 需要关注
168
- 有点事找你聊聊。
169
- 抬头看一眼。
170
- 这儿有情况。
167
+ 我有点事找你聊聊。
168
+ 抬头看看我。
169
+ 我这儿有情况。
171
170
 
172
171
 
173
172
  # ============ 连击互动配置 ============
package/SECURITY.md CHANGED
@@ -1,17 +1,20 @@
1
- # 安全策略
1
+ # Security Policy
2
2
 
3
- ## 支持范围
3
+ English | [简体中文](./SECURITY.zh-CN.md)
4
4
 
5
- 安全修复优先应用于最新发布版本和 `main` 分支。
5
+ ## Supported versions
6
6
 
7
- ## 报告安全问题
7
+ Security fixes are prioritized for the latest release and the `main` branch.
8
8
 
9
- 请不要在公开 Issue 中披露尚未修复的漏洞、凭据或私人会话数据。请通过
10
- [Gitee 维护者主页](https://gitee.com/wangxinyusqn) 私下联系,并提供:
9
+ ## Reporting a vulnerability
11
10
 
12
- - 受影响版本与 macOS 版本
13
- - 可复现步骤和影响范围
14
- - 必要的最小日志;提交前请移除 Token、Cookie、用户名和本机路径
11
+ Do not disclose an unpatched vulnerability, credentials, or private session data in
12
+ a public Issue. Use GitHub's **Security → Report a vulnerability** private reporting
13
+ form and include:
15
14
 
16
- 维护者确认问题并准备修复后,再协调公开披露时间。
15
+ - the affected CC Pets version and macOS version;
16
+ - reproduction steps and the impact;
17
+ - only the minimum necessary logs, with tokens, cookies, usernames, and local paths removed.
17
18
 
19
+ After the maintainer confirms the issue and prepares a fix, coordinate the timing
20
+ of public disclosure.
@@ -0,0 +1,18 @@
1
+ # 安全策略
2
+
3
+ [English](./SECURITY.md) | 简体中文
4
+
5
+ ## 支持范围
6
+
7
+ 安全修复优先应用于最新发布版本和 `main` 分支。
8
+
9
+ ## 报告安全问题
10
+
11
+ 请不要在公开 Issue 中披露尚未修复的漏洞、凭据或私人会话数据。请使用 GitHub 的
12
+ **Security → Report a vulnerability**(私密漏洞报告)提交,并提供:
13
+
14
+ - 受影响版本与 macOS 版本
15
+ - 可复现步骤和影响范围
16
+ - 必要的最小日志;提交前请移除 Token、Cookie、用户名和本机路径
17
+
18
+ 维护者确认问题并准备修复后,再协调公开披露时间。
@@ -132,7 +132,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
132
132
  if (!nodeExecutable || !npmCliExists) {
133
133
  [self showUpdateAlertWithTitle:@"无法自动更新"
134
134
  message:@"没有找到安装 CC Pets 时使用的 Node.js/npm。请先手动执行一次:\n\n"
135
- "npm install -g cc-pets@latest --allow-scripts=cc-pets --prefer-online"];
135
+ "npm install -g cc-pets@latest --allow-scripts=cc-pets"];
136
136
  return;
137
137
  }
138
138
 
@@ -905,7 +905,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
905
905
  - (void)applicationDidFinishLaunching:(NSNotification *)notification {
906
906
  // 没有主菜单的话,台词编辑器里 ⌘C/⌘V/⌘A/⌘Z 全部没反应。
907
907
  [self installEditMenu];
908
- // 台词全在这个文件里,代码里没有第二份。首次启动先从出厂词库拷一份出来,
908
+ // 台词全在这个文件里,代码里没有第二份。首次启动先从默认词库拷一份出来,
909
909
  // 否则新装的桌宠一句话都不会说。
910
910
  PetPhrasesEnsureFileExists();
911
911
  if (![NSUserDefaults.standardUserDefaults boolForKey:PetInteractionPhrasesV1MigratedKey] &&
@@ -947,15 +947,6 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
947
947
  }
948
948
  self.statusBubbleExpanded = [defaults boolForKey:StatusBubbleExpandedKey];
949
949
  NSString *selected = [defaults stringForKey:@"CCPetsSelectedSprite"];
950
- if (selected.length == 0) {
951
- NSDictionary *legacyDefaults = [defaults persistentDomainForName:@"com.universewang.codex-pet"];
952
- NSString *legacySelected = [legacyDefaults[@"CodexPetSelectedSprite"] isKindOfClass:NSString.class]
953
- ? legacyDefaults[@"CodexPetSelectedSprite"] : nil;
954
- if (legacySelected.length > 0) {
955
- selected = legacySelected;
956
- [defaults setObject:selected forKey:@"CCPetsSelectedSprite"];
957
- }
958
- }
959
950
  if (selected.length > 0 && ![selected containsString:@":"]) selected = [@"builtin:" stringByAppendingString:selected];
960
951
  NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
961
952
  selected = selectedOption[@"id"];
@@ -0,0 +1,13 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // 通过 `codex app-server` 的 account/rateLimits/read 读取服务端当前额度。会话转录里的
4
+ // rate_limits 只是一份历史快照,不能作为当前窗口的唯一事实来源。
5
+ @interface CCPetsCodexRateLimitsReader : NSObject
6
+ @property(copy) void (^liveUsageHandler)(NSDictionary *liveUsage);
7
+ - (void)refresh;
8
+ - (void)stop;
9
+ @end
10
+
11
+ // 把实时额度覆盖到会话读取器产出的用量上;本机 Token 聚合等非官方字段会被保留。
12
+ NSDictionary *CodexUsageByApplyingLiveUsage(NSDictionary *sessionUsage,
13
+ NSDictionary *liveUsage);
@@ -0,0 +1,383 @@
1
+ #import "CCPetsCodexRateLimits.h"
2
+ #import "CCPetsPaths.h"
3
+ #import "CCPetsVersion.h"
4
+
5
+ static const NSTimeInterval CodexRateLimitRequestTimeout = 20.0;
6
+ static char CodexRateLimitsQueueKey;
7
+
8
+ static NSNumber *NumberForKeys(NSDictionary *dictionary, NSArray<NSString *> *keys) {
9
+ for (NSString *key in keys) {
10
+ id value = dictionary[key];
11
+ if ([value isKindOfClass:NSNumber.class]) return value;
12
+ }
13
+ return nil;
14
+ }
15
+
16
+ static NSDictionary *QuotaFromAppServerWindow(NSDictionary *window) {
17
+ if (![window isKindOfClass:NSDictionary.class]) return nil;
18
+ NSNumber *used = NumberForKeys(window, @[@"usedPercent", @"used_percent"]);
19
+ NSNumber *minutes = NumberForKeys(window, @[@"windowDurationMins", @"window_minutes"]);
20
+ NSNumber *reset = NumberForKeys(window, @[@"resetsAt", @"resets_at"]);
21
+ if (!used && !minutes && !reset) return nil;
22
+ NSMutableDictionary *quota = [NSMutableDictionary dictionary];
23
+ if (used) quota[@"used_percent"] = @(fmax(0, fmin(100, used.doubleValue)));
24
+ if (minutes) quota[@"window_minutes"] = minutes;
25
+ if (reset) quota[@"resets_at"] = reset;
26
+ return quota;
27
+ }
28
+
29
+ static BOOL RateLimitReached(id value) {
30
+ if (!value || value == NSNull.null) return NO;
31
+ if ([value isKindOfClass:NSNumber.class]) return [value boolValue];
32
+ if ([value isKindOfClass:NSString.class]) return ((NSString *)value).length > 0;
33
+ return YES;
34
+ }
35
+
36
+ // App Server 以 camelCase 返回额度。按 windowDurationMins 分窗而不是假设 primary/
37
+ // secondary 的位置,这样服务端将来调整字段顺序时,5 小时和 7 天也不会被画反。
38
+ //
39
+ // 分窗结果决定了要不要写 NSNull:账号确实没有某个窗口时,用 NSNull 盖掉会话里的陈旧
40
+ // 快照是对的;但一个窗口都没认出来(服务端改了窗长、或响应里缺 windowDurationMins)
41
+ // 时再盖,就等于用一次解析失败清空本来可用的数据——那比不读实时额度还糟。所以两个窗口
42
+ // 全没命中时只回传受限状态,让会话快照继续兜底。
43
+ static NSDictionary *LiveUsageFromRateLimitBucket(NSDictionary *bucket) {
44
+ if (![bucket isKindOfClass:NSDictionary.class]) return nil;
45
+ NSString *limitID = [bucket[@"limitId"] isKindOfClass:NSString.class]
46
+ ? bucket[@"limitId"] : nil;
47
+ if (limitID.length > 0 && ![limitID hasPrefix:@"codex"]) return nil;
48
+
49
+ NSDictionary *fiveHour = nil;
50
+ NSDictionary *week = nil;
51
+ for (id value in @[bucket[@"primary"] ?: NSNull.null,
52
+ bucket[@"secondary"] ?: NSNull.null]) {
53
+ NSDictionary *quota = QuotaFromAppServerWindow(value);
54
+ NSInteger minutes = [quota[@"window_minutes"] integerValue];
55
+ if (minutes == 300) fiveHour = quota;
56
+ else if (minutes == 10080) week = quota;
57
+ }
58
+
59
+ BOOL exhausted = RateLimitReached(bucket[@"rateLimitReachedType"]);
60
+ if (!fiveHour && !week && !exhausted) return nil;
61
+
62
+ NSNumber *sampledAt = @(NSDate.date.timeIntervalSince1970);
63
+ NSMutableDictionary *usage = [@{@"sampledAt": sampledAt} mutableCopy];
64
+ if (fiveHour || week) {
65
+ usage[@"fiveHour"] = fiveHour ?: NSNull.null;
66
+ usage[@"week"] = week ?: NSNull.null;
67
+ }
68
+ if (exhausted) {
69
+ // 服务端已分类为额度受限时,不能让一次成功请求留下的百分比继续显示为可用。
70
+ usage[@"exhaustedAt"] = sampledAt;
71
+ }
72
+ return usage;
73
+ }
74
+
75
+ static NSDictionary *LiveUsageFromRateLimitResponse(NSDictionary *result) {
76
+ if (![result isKindOfClass:NSDictionary.class]) return nil;
77
+ NSDictionary *byLimitID = [result[@"rateLimitsByLimitId"] isKindOfClass:NSDictionary.class]
78
+ ? result[@"rateLimitsByLimitId"] : nil;
79
+ NSDictionary *fallback = [result[@"rateLimits"] isKindOfClass:NSDictionary.class]
80
+ ? result[@"rateLimits"] : nil;
81
+ NSDictionary *codex = [byLimitID[@"codex"] isKindOfClass:NSDictionary.class]
82
+ ? byLimitID[@"codex"] : nil;
83
+ // 单桶视图由当前 Codex 客户端选择,是最接近终端 /status 的口径;多桶对象只在
84
+ // 服务端未给单桶视图时才作为兼容兜底。
85
+ return LiveUsageFromRateLimitBucket(fallback ?: codex);
86
+ }
87
+
88
+ static BOOL IsCCPetsCodexWrapper(NSString *path) {
89
+ NSString *resolved = path.stringByResolvingSymlinksInPath.stringByStandardizingPath;
90
+ if ([resolved.lastPathComponent isEqualToString:@"codex-with-pet"]) return YES;
91
+ NSString *shims = [[NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets/shims"]
92
+ stringByStandardizingPath];
93
+ return [resolved hasPrefix:[shims stringByAppendingString:@"/"]];
94
+ }
95
+
96
+ static BOOL IsUsableCodexExecutable(NSString *path) {
97
+ return path.length > 0 && [NSFileManager.defaultManager isExecutableFileAtPath:path] &&
98
+ !IsCCPetsCodexWrapper(path);
99
+ }
100
+
101
+ static NSString *CodexAppServerExecutablePath(void) {
102
+ NSDictionary *environment = NSProcessInfo.processInfo.environment;
103
+ for (NSString *key in @[@"CC_PETS_CODEX_BIN", @"CODEX_REAL_BIN"]) {
104
+ id value = environment[key];
105
+ NSString *path = [value isKindOfClass:NSString.class]
106
+ ? [value stringByStandardizingPath] : nil;
107
+ if (IsUsableCodexExecutable(path)) return path;
108
+ }
109
+
110
+ NSMutableOrderedSet<NSString *> *directories = [NSMutableOrderedSet orderedSet];
111
+ for (NSString *path in [environment[@"PATH"] componentsSeparatedByString:@":"]) {
112
+ if (path.length > 0) [directories addObject:path.stringByStandardizingPath];
113
+ }
114
+ for (NSString *path in @[
115
+ [NSHomeDirectory() stringByAppendingPathComponent:@".local/bin"],
116
+ [NSHomeDirectory() stringByAppendingPathComponent:@".npm-global/bin"],
117
+ [NSHomeDirectory() stringByAppendingPathComponent:@".npm/bin"],
118
+ @"/opt/homebrew/bin", @"/usr/local/bin", @"/usr/bin", @"/bin"
119
+ ]) [directories addObject:path.stringByStandardizingPath];
120
+
121
+ // Finder 拉起的 App 通常没有终端里的 nvm PATH。补上已安装 Node 版本的 bin 目录,
122
+ // 同时仍跳过 CC Pets 自己的 codex shim,避免 app-server 反过来再启动桌宠。
123
+ NSString *nvmVersions = [NSHomeDirectory() stringByAppendingPathComponent:@".nvm/versions/node"];
124
+ NSArray<NSString *> *versions = [[NSFileManager.defaultManager
125
+ contentsOfDirectoryAtPath:nvmVersions error:nil]
126
+ sortedArrayUsingComparator:^NSComparisonResult(NSString *left, NSString *right) {
127
+ return [right compare:left options:NSNumericSearch];
128
+ }];
129
+ for (NSString *version in versions) {
130
+ [directories addObject:[[nvmVersions stringByAppendingPathComponent:version]
131
+ stringByAppendingPathComponent:@"bin"]];
132
+ }
133
+
134
+ for (NSString *directory in directories) {
135
+ NSString *candidate = [directory stringByAppendingPathComponent:@"codex"];
136
+ if (IsUsableCodexExecutable(candidate)) return candidate;
137
+ }
138
+ return nil;
139
+ }
140
+
141
+ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString *executablePath) {
142
+ NSMutableDictionary<NSString *, NSString *> *environment =
143
+ [NSProcessInfo.processInfo.environment mutableCopy];
144
+ NSMutableOrderedSet<NSString *> *paths = [NSMutableOrderedSet orderedSet];
145
+ if (executablePath.stringByDeletingLastPathComponent.length > 0) {
146
+ [paths addObject:executablePath.stringByDeletingLastPathComponent];
147
+ }
148
+ for (NSString *path in [environment[@"PATH"] componentsSeparatedByString:@":"]) {
149
+ if (path.length == 0 || IsCCPetsCodexWrapper([path stringByAppendingPathComponent:@"codex"])) continue;
150
+ [paths addObject:path];
151
+ }
152
+ environment[@"PATH"] = [paths.array componentsJoinedByString:@":"];
153
+ // 与会话扫描使用同一份配置目录,避免备用 CODEX_HOME 下的账号被错读成默认账号。
154
+ environment[@"CODEX_HOME"] = DefaultCodexHomeDirectory();
155
+ return environment;
156
+ }
157
+
158
+ @interface CCPetsCodexRateLimitsReader ()
159
+ @property dispatch_queue_t queue;
160
+ @property NSTask *task;
161
+ @property NSFileHandle *input;
162
+ @property NSFileHandle *output;
163
+ @property NSMutableData *partialOutput;
164
+ @property NSInteger nextRequestID;
165
+ @property NSInteger pendingRequestID;
166
+ @property BOOL stopped;
167
+ @end
168
+
169
+ @implementation CCPetsCodexRateLimitsReader
170
+
171
+ - (instancetype)init {
172
+ if ((self = [super init])) {
173
+ _queue = dispatch_queue_create("com.universewang.cc-pets.codex-rate-limits",
174
+ DISPATCH_QUEUE_SERIAL);
175
+ dispatch_queue_set_specific(_queue, &CodexRateLimitsQueueKey, (__bridge void *)self, NULL);
176
+ _partialOutput = [NSMutableData data];
177
+ _nextRequestID = 2; // 1 留给 initialize。
178
+ }
179
+ return self;
180
+ }
181
+
182
+ - (void)refresh {
183
+ __weak typeof(self) weakSelf = self;
184
+ dispatch_async(self.queue, ^{ [weakSelf refreshOnQueue]; });
185
+ }
186
+
187
+ - (void)stop {
188
+ void (^stopOnQueue)(void) = ^{
189
+ self.stopped = YES;
190
+ [self stopTaskOnQueue];
191
+ };
192
+ if (dispatch_get_specific(&CodexRateLimitsQueueKey) == (__bridge void *)self) {
193
+ stopOnQueue();
194
+ } else {
195
+ dispatch_sync(self.queue, stopOnQueue);
196
+ }
197
+ }
198
+
199
+ - (BOOL)sendMessageOnQueue:(NSDictionary *)message {
200
+ if (!self.input || !message) return NO;
201
+ NSData *data = [NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
202
+ if (!data) return NO;
203
+ NSMutableData *line = [data mutableCopy];
204
+ [line appendData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];
205
+ @try {
206
+ [self.input writeData:line];
207
+ return YES;
208
+ } @catch (NSException *exception) {
209
+ return NO;
210
+ }
211
+ }
212
+
213
+ - (BOOL)ensureTaskOnQueue {
214
+ if (self.task.running) return YES;
215
+ NSString *path = CodexAppServerExecutablePath();
216
+ if (path.length == 0) return NO;
217
+
218
+ NSTask *task = [NSTask new];
219
+ NSPipe *inputPipe = [NSPipe pipe];
220
+ NSPipe *outputPipe = [NSPipe pipe];
221
+ task.executableURL = [NSURL fileURLWithPath:path];
222
+ task.arguments = @[@"app-server", @"--stdio"];
223
+ task.environment = CodexAppServerEnvironment(path);
224
+ task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
225
+ task.standardInput = inputPipe;
226
+ task.standardOutput = outputPipe;
227
+ task.standardError = [NSFileHandle fileHandleForWritingAtPath:@"/dev/null"];
228
+
229
+ __weak typeof(self) weakSelf = self;
230
+ // 两个回调都跑在后台线程,与 dealloc -> stop 清理回调之间存在竞态窗口。reader 已经
231
+ // 释放时 weakSelf.queue 是 nil,而 dispatch_async 到 NULL 队列会直接崩,所以必须先
232
+ // strongify 再判空,不能图省事写成 dispatch_async(weakSelf.queue, ...)。
233
+ outputPipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *handle) {
234
+ NSData *data = handle.availableData;
235
+ typeof(self) strongSelf = weakSelf;
236
+ if (!strongSelf) {
237
+ handle.readabilityHandler = nil;
238
+ return;
239
+ }
240
+ dispatch_async(strongSelf.queue, ^{
241
+ [weakSelf consumeOutputDataOnQueue:data fromHandle:handle];
242
+ });
243
+ };
244
+ task.terminationHandler = ^(NSTask *finishedTask) {
245
+ typeof(self) strongSelf = weakSelf;
246
+ if (!strongSelf) return;
247
+ dispatch_async(strongSelf.queue, ^{ [weakSelf taskDidTerminateOnQueue:finishedTask]; });
248
+ };
249
+
250
+ NSError *error = nil;
251
+ if (![task launchAndReturnError:&error]) {
252
+ outputPipe.fileHandleForReading.readabilityHandler = nil;
253
+ return NO;
254
+ }
255
+ self.task = task;
256
+ self.input = inputPipe.fileHandleForWriting;
257
+ self.output = outputPipe.fileHandleForReading;
258
+ [self.partialOutput setLength:0];
259
+ NSDictionary *initialize = @{
260
+ @"method": @"initialize", @"id": @1,
261
+ @"params": @{ @"clientInfo": @{
262
+ @"name": @"cc_pets", @"title": @"CC Pets", @"version": @CC_PETS_VERSION
263
+ }}
264
+ };
265
+ if (![self sendMessageOnQueue:initialize] ||
266
+ ![self sendMessageOnQueue:@{ @"method": @"initialized", @"params": @{} }]) {
267
+ [self stopTaskOnQueue];
268
+ return NO;
269
+ }
270
+ return YES;
271
+ }
272
+
273
+ - (void)refreshOnQueue {
274
+ if (self.stopped || self.pendingRequestID != 0 || ![self ensureTaskOnQueue]) return;
275
+ NSInteger requestID = self.nextRequestID++;
276
+ self.pendingRequestID = requestID;
277
+ if (![self sendMessageOnQueue:@{ @"method": @"account/rateLimits/read", @"id": @(requestID) }]) {
278
+ self.pendingRequestID = 0;
279
+ [self stopTaskOnQueue];
280
+ return;
281
+ }
282
+ __weak typeof(self) weakSelf = self;
283
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
284
+ (int64_t)(CodexRateLimitRequestTimeout * NSEC_PER_SEC)), self.queue, ^{
285
+ typeof(self) strongSelf = weakSelf;
286
+ if (!strongSelf || strongSelf.pendingRequestID != requestID) return;
287
+ strongSelf.pendingRequestID = 0;
288
+ [strongSelf stopTaskOnQueue];
289
+ });
290
+ }
291
+
292
+ - (void)deliverLiveUsageOnQueue:(NSDictionary *)usage {
293
+ if (!usage) return;
294
+ void (^handler)(NSDictionary *) = self.liveUsageHandler;
295
+ if (handler) handler(usage);
296
+ }
297
+
298
+ - (void)consumeMessageOnQueue:(NSDictionary *)message {
299
+ if (![message isKindOfClass:NSDictionary.class]) return;
300
+ NSNumber *requestID = [message[@"id"] isKindOfClass:NSNumber.class] ? message[@"id"] : nil;
301
+ if (requestID && requestID.integerValue == self.pendingRequestID) {
302
+ self.pendingRequestID = 0;
303
+ NSDictionary *usage = LiveUsageFromRateLimitResponse(message[@"result"]);
304
+ [self deliverLiveUsageOnQueue:usage];
305
+ return;
306
+ }
307
+ NSString *method = [message[@"method"] isKindOfClass:NSString.class] ? message[@"method"] : nil;
308
+ if (![method isEqualToString:@"account/rateLimits/updated"]) return;
309
+ NSDictionary *params = [message[@"params"] isKindOfClass:NSDictionary.class]
310
+ ? message[@"params"] : nil;
311
+ [self deliverLiveUsageOnQueue:LiveUsageFromRateLimitBucket(params[@"rateLimits"])];
312
+ }
313
+
314
+ - (void)consumeOutputDataOnQueue:(NSData *)data fromHandle:(NSFileHandle *)handle {
315
+ // 旧进程退出时可能还留下一次 readability 回调;不能让它把刚重连的新 stdout
316
+ // 处理器清掉,或把上一代进程的响应套到新请求上。
317
+ if (handle != self.output) return;
318
+ if (data.length == 0) {
319
+ handle.readabilityHandler = nil;
320
+ return;
321
+ }
322
+ [self.partialOutput appendData:data];
323
+ const uint8_t *bytes = self.partialOutput.bytes;
324
+ NSUInteger lineStart = 0;
325
+ for (NSUInteger index = 0; index < self.partialOutput.length; index++) {
326
+ if (bytes[index] != '\n') continue;
327
+ NSData *line = [self.partialOutput subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
328
+ NSDictionary *message = line.length > 0
329
+ ? [NSJSONSerialization JSONObjectWithData:line options:0 error:nil] : nil;
330
+ [self consumeMessageOnQueue:message];
331
+ lineStart = index + 1;
332
+ }
333
+ if (lineStart > 0) {
334
+ self.partialOutput = [[self.partialOutput subdataWithRange:
335
+ NSMakeRange(lineStart, self.partialOutput.length - lineStart)] mutableCopy];
336
+ }
337
+ if (self.partialOutput.length > 1024 * 1024) [self.partialOutput setLength:0];
338
+ }
339
+
340
+ - (void)taskDidTerminateOnQueue:(NSTask *)task {
341
+ if (task != self.task) return;
342
+ self.output.readabilityHandler = nil;
343
+ self.task = nil;
344
+ self.input = nil;
345
+ self.output = nil;
346
+ self.pendingRequestID = 0;
347
+ [self.partialOutput setLength:0];
348
+ }
349
+
350
+ - (void)stopTaskOnQueue {
351
+ NSTask *task = self.task;
352
+ self.output.readabilityHandler = nil;
353
+ self.task = nil;
354
+ self.input = nil;
355
+ self.output = nil;
356
+ self.pendingRequestID = 0;
357
+ [self.partialOutput setLength:0];
358
+ if (task.running) [task terminate];
359
+ }
360
+
361
+ - (void)dealloc {
362
+ [self stop];
363
+ }
364
+
365
+ @end
366
+
367
+ NSDictionary *CodexUsageByApplyingLiveUsage(NSDictionary *sessionUsage,
368
+ NSDictionary *liveUsage) {
369
+ if (![liveUsage isKindOfClass:NSDictionary.class]) return sessionUsage;
370
+ NSMutableDictionary *merged = [sessionUsage isKindOfClass:NSDictionary.class]
371
+ ? [sessionUsage mutableCopy] : [NSMutableDictionary dictionary];
372
+ for (NSString *key in @[@"fiveHour", @"week"]) {
373
+ id quota = liveUsage[key];
374
+ if (quota) merged[key] = quota;
375
+ }
376
+ merged[@"sampledAt"] = liveUsage[@"sampledAt"] ?: @(NSDate.date.timeIntervalSince1970);
377
+ if ([liveUsage[@"exhaustedAt"] isKindOfClass:NSNumber.class]) {
378
+ merged[@"exhaustedAt"] = liveUsage[@"exhaustedAt"];
379
+ } else {
380
+ [merged removeObjectForKey:@"exhaustedAt"];
381
+ }
382
+ return merged;
383
+ }
@@ -80,35 +80,12 @@ void PetPhrasesSetCurrentPetID(NSString *petID);
80
80
  NSString *PetPhrasesCurrentPetID(void);
81
81
  // 当前宠物的专属词库路径。还没设过宠物时返回 nil。
82
82
  NSString *PetPhrasesCurrentPetFilePath(void);
83
- // 出厂词库路径:app bundle 里的 phrases.default.txt。
83
+ // 默认词库路径:app bundle 里的 phrases.default.txt。
84
84
  // 可用 CC_PETS_PHRASES_DEFAULT_FILE 覆盖(测试用)。
85
85
  NSString *PetPhrasesDefaultFilePath(void);
86
- // 老版词库路径:~/.cc-pets/phrases.txt。可用 CC_PETS_PHRASES_LEGACY_FILE 覆盖(测试用)。
86
+ // 用户词库不存在就从默认词库拷一份出来。返回是否可用。
87
87
  //
88
- // 换个文件名是为了让"迁移过没有"这件事变成一个平凡的判断:新文件在就是迁移过了。
89
- // 靠猜内容特征(有没有 replace 行、缺不缺某个小节)都不可靠,用户改过之后更没法判断。
90
- NSString *PetPhrasesLegacyFilePath(void);
91
-
92
- // 老版词库还在不在。在的话说明还没提示用户删掉它。
93
- BOOL PetPhrasesLegacyFileExists(void);
94
- // 把老版词库改名成 phrases.txt.bak。用户在提示里确认之后调用。
95
- //
96
- // 改名而不是删除:内容还在原地,万一合并合错了还能翻出来对。同时 PetPhrasesLegacyFilePath
97
- // 只认 phrases.txt,改完名它既不会再被当成迁移源,也不会再弹询问——留着原名不动的话,
98
- // 哪天 speech.txt 丢了,启动时会再从它合并一遍,把用户迁移之后写的台词全冲掉。
99
- BOOL PetPhrasesArchiveLegacyFile(void);
100
-
101
- // 把老版词库合并进出厂词库。纯函数,不碰磁盘,方便测。
102
- //
103
- // 合并而不是覆盖:老语义是"内置 + 用户的混着说",用户当时听到的就是两者的并集,
104
- // 直接拿用户那几句顶掉整节的话,桌宠会突然变哑。老文件里写了 replace 的除外——
105
- // 那是"只说我的",照办。
106
- // 注释一律不搬,按新模板的来。
107
- NSString *PetPhraseTextMergedFromLegacy(NSString *legacyText, NSString *defaultText);
108
-
109
- // 用户词库不存在就准备一份:有老版词库就合并过来,否则从出厂词库拷。返回是否可用。
110
- //
111
- // 出厂词库是一个随 app 打包的文本文件,不是代码里的字典:默认台词只在"生成文件"
88
+ // 默认词库是一个随 app 打包的文本文件,不是代码里的字典:默认台词只在"生成文件"
112
89
  // 这一刻出现一次,之后运行时只认用户文件。两份词库同时存在于运行期就必然要回答
113
90
  // "以谁为准",那正是 merge/replace 那套让人看不懂的根源。
114
91
  BOOL PetPhrasesEnsureFileExists(void);