cc-pets 1.2.3 → 1.2.5

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.
@@ -449,80 +449,129 @@ static NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skip
449
449
  return newest;
450
450
  }
451
451
 
452
- static NSDictionary *FirstTimestampRecordInData(NSData *data) {
453
- const uint8_t *bytes = data.bytes;
454
- NSUInteger start = 0;
455
- for (NSUInteger index = 0; index <= data.length; index++) {
456
- if (index < data.length && bytes[index] != '\n') continue;
457
- if (index > start) {
458
- NSData *line = [data subdataWithRange:NSMakeRange(start, index - start)];
459
- id root = [NSJSONSerialization JSONObjectWithData:line options:0 error:nil];
460
- NSDate *date = [root isKindOfClass:NSDictionary.class]
461
- ? ISO8601Timestamp(((NSDictionary *)root)[@"timestamp"]) : nil;
462
- if (date) return @{@"timestamp": @([date timeIntervalSince1970])};
452
+ static NSTimeInterval LineTimestamp(NSData *line) {
453
+ if (line.length == 0) return 0;
454
+ id root = [NSJSONSerialization JSONObjectWithData:line options:0 error:nil];
455
+ if (![root isKindOfClass:NSDictionary.class]) return 0;
456
+ NSDate *date = ISO8601Timestamp(((NSDictionary *)root)[@"timestamp"]);
457
+ return date ? date.timeIntervalSince1970 : 0;
458
+ }
459
+
460
+ // 按块切行喂给 consume,返回消费掉的字节数(截止最后一个换行)。返回值就是下一次可以
461
+ // 安全续读的偏移:结尾那半行还没写完,不能算进去。includeTail=YES 时残行照样交给
462
+ // consume(一次性整篇扫描的调用方要它,最后一行未必有换行结尾)。
463
+ static unsigned long long EnumerateLines(NSFileHandle *handle, BOOL includeTail,
464
+ void (^consume)(NSData *)) {
465
+ NSMutableData *pending = [NSMutableData data];
466
+ unsigned long long consumed = 0;
467
+ while (YES) {
468
+ NSData *chunk = [handle readDataOfLength:256 * 1024];
469
+ if (chunk.length == 0) break;
470
+ [pending appendData:chunk];
471
+ const uint8_t *bytes = pending.bytes;
472
+ NSUInteger lineStart = 0;
473
+ for (NSUInteger index = 0; index < pending.length; index++) {
474
+ if (bytes[index] != '\n') continue;
475
+ if (index > lineStart) {
476
+ consume([pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
477
+ }
478
+ lineStart = index + 1;
479
+ }
480
+ if (lineStart > 0) {
481
+ consumed += lineStart;
482
+ pending = [[pending subdataWithRange:NSMakeRange(
483
+ lineStart, pending.length - lineStart)] mutableCopy];
463
484
  }
464
- start = index + 1;
465
485
  }
466
- return nil;
486
+ if (includeTail && pending.length > 0) consume(pending);
487
+ return consumed;
467
488
  }
468
489
 
469
- static NSDictionary *LatestTokenRecordInData(NSData *data) {
470
- const uint8_t *bytes = data.bytes;
471
- NSUInteger end = data.length;
472
- while (end > 0) {
473
- NSUInteger start = end;
474
- while (start > 0 && bytes[start - 1] != '\n') start -= 1;
475
- if (end > start) {
476
- NSDictionary *record = TokenRecordFromLine(
477
- [data subdataWithRange:NSMakeRange(start, end - start)]);
478
- if (record[@"total"]) return record;
479
- }
480
- end = start > 0 ? start - 1 : 0;
490
+ static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
491
+ for (NSString *key in TokenKeys()) {
492
+ unsigned long long current = [target[key] unsignedLongLongValue];
493
+ unsigned long long addition = [counts[key] unsignedLongLongValue];
494
+ if (counts[key]) target[key] = @(current + addition);
481
495
  }
482
- return nil;
483
496
  }
484
497
 
498
+ // total_token_usage 是会话内累计值,但同一个 rollout 文件里它会中途归零重来:resume 或
499
+ // 上下文压缩之后进程从头开始计数。本机近 14 天 106 个会话里 3 个如此,最狠的一个从
500
+ // 1098 万掉回 11 万——只认末行 total 的话,归零之前那一整段全被吞掉(该会话真实用量
501
+ // 约 1146 万,末行只有 47 万,漏掉 96%)。因此把会话按归零点切成若干段:段内仍然用
502
+ // 累计值(对重复写入的 token_count 幂等),段与段之间相加。
503
+ static BOOL TokenTotalsDidReset(NSDictionary *totals, NSDictionary *previous) {
504
+ for (NSString *key in TokenKeys()) {
505
+ if (!totals[key] || !previous[key]) continue;
506
+ if ([totals[key] unsignedLongLongValue] < [previous[key] unsignedLongLongValue]) return YES;
507
+ }
508
+ return NO;
509
+ }
510
+
511
+ static NSDictionary *SummedSegmentTotals(NSArray<NSDictionary *> *segments) {
512
+ NSMutableDictionary *total = [NSMutableDictionary dictionary];
513
+ for (NSDictionary *segment in segments) AddTokenCounts(total, segment);
514
+ return total;
515
+ }
516
+
517
+ // 分段必须整篇扫描(末行 total 不再够用),因此改成按偏移增量追读:活跃会话每轮只解析
518
+ // 新增的那几行,段状态(各段末尾的累计值)留在缓存里续接。
485
519
  static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache) {
486
520
  NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path error:nil];
487
521
  unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
488
522
  NSDictionary *cached = cache[url.path];
523
+ // 没有 token_count 的会话(旧格式、被截断、刚创建)也会留下缓存条目,否则每一轮都要
524
+ // 把整篇重读一遍。文件长大后 size 变化自然会让缓存失效。
489
525
  if (cached && [cached[@"size"] unsignedLongLongValue] == size) {
490
- return [cached[@"invalid"] boolValue] ? nil : cached;
526
+ return (cached[@"start"] && cached[@"total"]) ? cached : nil;
527
+ }
528
+
529
+ unsigned long long offset = 0;
530
+ NSMutableArray<NSDictionary *> *segments = [NSMutableArray array];
531
+ __block NSNumber *start = nil;
532
+ __block NSTimeInterval last = 0;
533
+ if (cached) {
534
+ unsigned long long cachedOffset = [cached[@"offset"] unsignedLongLongValue];
535
+ // offset > size 只可能是文件被改写(截断/重建),旧的段全部作废,整篇重来。
536
+ if (cachedOffset <= size) {
537
+ offset = cachedOffset;
538
+ start = [cached[@"start"] isKindOfClass:NSNumber.class] ? cached[@"start"] : nil;
539
+ last = [cached[@"end"] doubleValue];
540
+ if ([cached[@"segments"] isKindOfClass:NSArray.class]) {
541
+ [segments addObjectsFromArray:cached[@"segments"]];
542
+ }
543
+ }
491
544
  }
492
545
 
493
546
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
494
547
  if (!handle) return nil;
495
- const unsigned long long headLength = MIN(size, 64 * 1024);
496
- NSData *head = [handle readDataOfLength:(NSUInteger)headLength];
497
- const unsigned long long tailStart = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
498
- [handle seekToFileOffset:tailStart];
499
- NSData *tail = [handle readDataToEndOfFile];
548
+ if (offset > 0) [handle seekToFileOffset:offset];
549
+ unsigned long long consumed = EnumerateLines(handle, NO, ^(NSData *line) {
550
+ // 会话起点取文件第一条带 timestamp 的行,不限于 token_count:它决定这个会话算不算
551
+ // 整段落在窗口内。找到之后就不再对普通行做 JSON 解析。
552
+ if (!start) {
553
+ NSTimeInterval timestamp = LineTimestamp(line);
554
+ if (timestamp > 0) start = @(timestamp);
555
+ }
556
+ NSDictionary *record = TokenRecordFromLine(line);
557
+ NSDictionary *total = record[@"total"];
558
+ if (!total) return;
559
+ last = [record[@"timestamp"] doubleValue];
560
+ NSDictionary *previous = segments.lastObject;
561
+ if (!previous || TokenTotalsDidReset(total, previous)) [segments addObject:total];
562
+ else segments[segments.count - 1] = total;
563
+ });
500
564
  [handle closeFile];
501
565
 
502
- NSDictionary *first = FirstTimestampRecordInData(head);
503
- NSDictionary *latest = LatestTokenRecordInData(tail);
504
- // 没有 token_count 的会话(旧格式、被截断、刚创建)也必须记住,否则每一轮都会
505
- // 把 64KB head + 2MB tail 重读一遍。文件长大后 size 变化自然会让缓存失效。
506
- if (!first || !latest[@"total"]) {
507
- cache[url.path] = @{@"size": @(size), @"invalid": @YES};
508
- return nil;
566
+ NSMutableDictionary *summary = [@{@"size": @(size), @"offset": @(offset + consumed)} mutableCopy];
567
+ if (start) summary[@"start"] = start;
568
+ if (segments.count > 0) {
569
+ summary[@"segments"] = [segments copy];
570
+ summary[@"end"] = @(last);
571
+ summary[@"total"] = SummedSegmentTotals(segments);
509
572
  }
510
- NSMutableDictionary *summary = [@{
511
- @"size": @(size),
512
- @"start": first[@"timestamp"],
513
- @"end": latest[@"timestamp"],
514
- @"total": latest[@"total"]
515
- } mutableCopy];
516
573
  cache[url.path] = summary;
517
- return summary;
518
- }
519
-
520
- static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
521
- for (NSString *key in TokenKeys()) {
522
- unsigned long long current = [target[key] unsignedLongLongValue];
523
- unsigned long long addition = [counts[key] unsignedLongLongValue];
524
- if (counts[key]) target[key] = @(current + addition);
525
- }
574
+ return (start && summary[@"total"]) ? summary : nil;
526
575
  }
527
576
 
528
577
  // 累计值相减,而不是累加窗口内的 last_token_usage:Codex 会把同一份 token_count
@@ -540,40 +589,34 @@ static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary
540
589
  return result;
541
590
  }
542
591
 
592
+ // 跨窗口起点的会话只算窗口内的增量。分段规则与 TokenSessionSummary 一致:累计值一旦
593
+ // 归零,窗口起点之前取到的基线就作废了,后面那一段要从 0 起算,段与段的增量再相加。
543
594
  static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTimeInterval end) {
544
595
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
545
596
  if (!handle) return nil;
597
+ NSMutableDictionary *result = [NSMutableDictionary dictionary];
598
+ __block NSDictionary *previous = nil;
546
599
  __block NSDictionary *baseline = nil;
547
600
  __block NSDictionary *inside = nil;
548
- void (^consume)(NSData *) = ^(NSData *line) {
601
+ // 窗口内一条 token_count 都没有的段不贡献任何用量。
602
+ void (^flush)(void) = ^{
603
+ if (inside) AddTokenCounts(result, TokenCountsBySubtracting(inside, baseline));
604
+ baseline = nil;
605
+ inside = nil;
606
+ };
607
+ EnumerateLines(handle, YES, ^(NSData *line) {
549
608
  NSDictionary *record = TokenRecordFromLine(line);
550
609
  NSDictionary *total = record[@"total"];
551
610
  if (!total) return;
611
+ if (previous && TokenTotalsDidReset(total, previous)) flush();
612
+ previous = total;
552
613
  NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
553
614
  if (timestamp < start) baseline = total;
554
615
  else if (timestamp < end) inside = total;
555
- };
556
- NSMutableData *pending = [NSMutableData data];
557
- while (YES) {
558
- NSData *chunk = [handle readDataOfLength:256 * 1024];
559
- if (chunk.length == 0) break;
560
- [pending appendData:chunk];
561
- const uint8_t *bytes = pending.bytes;
562
- NSUInteger lineStart = 0;
563
- for (NSUInteger index = 0; index < pending.length; index++) {
564
- if (bytes[index] != '\n') continue;
565
- consume([pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
566
- lineStart = index + 1;
567
- }
568
- if (lineStart > 0) {
569
- pending = [[pending subdataWithRange:NSMakeRange(
570
- lineStart, pending.length - lineStart)] mutableCopy];
571
- }
572
- }
573
- if (pending.length > 0) consume(pending);
616
+ });
617
+ flush();
574
618
  [handle closeFile];
575
- // 窗口内一条 token_count 都没有:这段时间没有产生用量。
576
- return inside ? TokenCountsBySubtracting(inside, baseline) : @{};
619
+ return result;
577
620
  }
578
621
 
579
622
  // 聚合区间对齐官方重置时间:[resets_at - 窗长, resets_at)。
@@ -1268,8 +1311,12 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1268
1311
  };
1269
1312
  }
1270
1313
  - (NSDictionary *)refresh {
1271
- NSDictionary *limits = ClaudeRateLimits();
1272
- if (!limits) return nil;
1314
+ // 额度快照是 statusline hook 写出来的(见 RecordClaudeUsage):第三方 statusline 注入不
1315
+ // 进去、或者账号本身(API key / Bedrock / Vertex)就不带 rate_limits 时,这份文件永远
1316
+ // 不存在。而 Token 是本机从转录里数出来的,跟官方额度没有半点关系,不能被它一票否决
1317
+ // ——原先这里直接 return nil,面板上 Claude 整行(百分比、已用 Token、今日输入输出)
1318
+ // 全是 `--`,看起来像统计坏了。缺额度时百分比照样 `--`,用量正常显示。
1319
+ NSDictionary *limits = ClaudeRateLimits() ?: @{@"fiveHour": NSNull.null, @"week": NSNull.null};
1273
1320
  NSString *identity = TokenWindowIdentity(limits);
1274
1321
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
1275
1322
  BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
@@ -168,7 +168,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
168
168
  formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
169
169
  formatter.timeZone = NSTimeZone.localTimeZone;
170
170
  formatter.dateFormat = @"yyyy-MM-dd";
171
- return [NSString stringWithFormat:@"近 7 天(%@ 至今)",
171
+ return [NSString stringWithFormat:@"近 7 天累计用量(%@ 至今·滚动记录)",
172
172
  [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:start.doubleValue]]];
173
173
  }
174
174
  // 在线 = 这一家还有活着的客户端,和有没有额度数据无关:额度会一直缓存着,
@@ -306,10 +306,10 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
306
306
  // 层级:官方剩余额度是订阅限额的权威值,占主位;本机 Token 是参考量,降一级并用
307
307
  // 强调色区分;重置时间最小。反过来会让最抢眼的数字恰好是最不该照着做决定的那个。
308
308
  NSArray<NSDictionary *> *windows = @[
309
- @{@"x": @(NSMinX(card) + 214), @"title": @"5 小时窗口", @"quota": five ?: @{},
309
+ @{@"x": @(NSMinX(card) + 214), @"title": @"官方 5 小时窗口", @"quota": five ?: @{},
310
310
  @"tokens": fiveTokens ?: @{}, @"used": fiveUsed ?: NSNull.null,
311
311
  @"rolling": @"无官方窗口 · 近 5 小时"},
312
- @{@"x": @(NSMinX(card) + 394), @"title": @"7 天窗口", @"quota": week ?: @{},
312
+ @{@"x": @(NSMinX(card) + 394), @"title": @"官方 7 天窗口", @"quota": week ?: @{},
313
313
  @"tokens": weekTokens ?: @{}, @"used": weekUsed ?: NSNull.null,
314
314
  @"rolling": @"无官方窗口 · 近 7 天"}
315
315
  ];
@@ -339,7 +339,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
339
339
  // 说清楚这一行的口径,比留一个 `--` 让人以为是渲染坏了要好。
340
340
  NSString *resetValue = [self resetText:window[@"quota"]];
341
341
  NSString *reset = [resetValue isEqualToString:@"--"]
342
- ? window[@"rolling"] : [NSString stringWithFormat:@"额度重置 %@", resetValue];
342
+ ? window[@"rolling"] : [NSString stringWithFormat:@"官方重置 %@", resetValue];
343
343
  [reset drawInRect:NSMakeRect(x, NSMinY(card) + 22, 150, 18)
344
344
  withAttributes:[self textAttributesWithSize:11 color:secondary weight:NSFontWeightRegular]];
345
345
  }
@@ -399,7 +399,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
399
399
  NSColor *agentColor = self.agentStatusColor;
400
400
  [@"Agent Usage" drawInRect:NSMakeRect(28, QuotaLogicalHeight - 65, 260, 42)
401
401
  withAttributes:[self textAttributesWithSize:30 color:primary weight:NSFontWeightBold]];
402
- [@"实时使用统计" drawInRect:NSMakeRect(30, QuotaLogicalHeight - 94, 130, 22)
402
+ [@"实时状态与滚动用量" drawInRect:NSMakeRect(30, QuotaLogicalHeight - 94, 130, 22)
403
403
  withAttributes:[self textAttributesWithSize:14 color:secondary weight:NSFontWeightRegular]];
404
404
  [agentColor setFill];
405
405
  [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(174, QuotaLogicalHeight - 88, 9, 9)] fill];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
@@ -3,6 +3,7 @@
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
 
7
8
  const binary = process.argv[2];
8
9
  if (!binary) {
@@ -165,9 +166,37 @@ const statusLineScript = resolveStatusLineScript(originalStatusLineCommand);
165
166
  const statusLineInstalled = Boolean(
166
167
  statusLineScript && installStatusLinePrelude(statusLineScript, createdStatusLine)
167
168
  );
168
- if (!statusLineInstalled) {
169
- console.warn(`未修改 Claude status line:command 不是可直接编辑的脚本路径:${originalStatusLineCommand}`);
170
- console.warn("Claude Hooks 仍会正常工作,但 CC Pets 暂时无法采集 Claude 额度。");
169
+
170
+ // 就地往用户脚本里插 prelude 只对"绝对路径的可编辑脚本"成立。第三方状态栏基本都不是这个
171
+ // 形态(`bun x ccstatusline`、`npx …`、任何带参数或管道的命令行),resolveStatusLineScript
172
+ // 一律拒绝。以前这里只打印一行警告就算了,而 statusline 是 Claude 额度的唯一来源
173
+ // (转录 jsonl 和 stats-cache.json 里都没有 rate_limits),于是这类用户的额度永远是 `--`。
174
+ // 回退到包装器:command 换成 claude-statusline-with-pet + base64 编码的原命令,它先把 stdin
175
+ // 喂给 cc-pets --claude-usage,再原样转发给原命令执行。卸载侧本来就认这个形态(marker +
176
+ // 末尾的 base64),能原样还原回去。
177
+ const statusLineWrapper = path.resolve(
178
+ path.dirname(fileURLToPath(import.meta.url)), "..", "bin", "claude-statusline-with-pet");
179
+ let statusLineWrapped = false;
180
+ if (!statusLineInstalled && originalStatusLineCommand && fs.existsSync(statusLineWrapper)) {
181
+ try {
182
+ fs.chmodSync(statusLineWrapper, fs.statSync(statusLineWrapper).mode | 0o100);
183
+ } catch {
184
+ // 包内文件不可写(只读安装)时权限位通常本来就是对的,交给下面的可执行判断兜底。
185
+ }
186
+ if (fs.existsSync(statusLineWrapper)) {
187
+ const encoded = Buffer.from(originalStatusLineCommand, "utf8").toString("base64");
188
+ config.statusLine = {
189
+ ...config.statusLine,
190
+ type: "command",
191
+ command: `${statusLineMarker} ${shellQuote(statusLineWrapper)} '${encoded}'`
192
+ };
193
+ statusLineWrapped = true;
194
+ }
195
+ }
196
+
197
+ if (!statusLineInstalled && !statusLineWrapped) {
198
+ console.warn(`未接入 Claude status line:${originalStatusLineCommand || "(未配置)"}`);
199
+ console.warn("Claude Hooks 仍会正常工作,但桌宠拿不到 Claude 额度百分比(Token 用量不受影响)。");
171
200
  }
172
201
 
173
202
  const temporaryPath = `${settingsPath}.cc-pets.tmp`;
@@ -177,4 +206,6 @@ fs.chmodSync(settingsPath, 0o600);
177
206
  console.log(`Claude Code Hooks 已安装到 ${settingsPath}`);
178
207
  if (statusLineInstalled) {
179
208
  console.log("Claude 额度采集已接入现有 status line。首次 API 响应后桌宠会显示额度。");
209
+ } else if (statusLineWrapped) {
210
+ console.log("Claude 额度采集已通过包装器接入 status line,原命令仍照常执行。首次 API 响应后桌宠会显示额度。");
180
211
  }