cc-pets 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ #import "CCPetsBridge.h"
2
+ #import "CCPetsPaths.h"
3
+ #import <errno.h>
4
+ #import <signal.h>
5
+ #import <unistd.h>
6
+
7
+ NSString *const BridgeBadgeEnabledKey = @"CCPetsBridgeBadgeEnabled";
8
+ NSString *const BridgeNotificationKey = @"CCPetsBridgeNotification";
9
+
10
+ // 目录里文件数的上限。回执保留 48 小时,正常使用远到不了这个量;
11
+ // 真到了说明有东西在刷消息,宁可少显示几条也不让桌宠主线程卡在读盘上。
12
+ static const NSUInteger BridgeFileScanLimit = 500;
13
+
14
+ NSString *CCBridgeStateDirectory(void) {
15
+ NSString *name = [NSString stringWithFormat:@"cc-bridge-%u", getuid()];
16
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
17
+ }
18
+
19
+ static NSString *BridgeHomeDirectory(void) {
20
+ NSString *home = NSProcessInfo.processInfo.environment[@"CC_PETS_HOME"];
21
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets"];
22
+ return home.stringByStandardizingPath;
23
+ }
24
+
25
+ BOOL CCBridgeEnabled(void) {
26
+ return [NSFileManager.defaultManager fileExistsAtPath:
27
+ [BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-enabled"]];
28
+ }
29
+
30
+ NSArray<NSString *> *CCBridgeToolGroupNames(void) {
31
+ return @[@"view", @"send", @"reserve", @"name"];
32
+ }
33
+
34
+ NSArray<NSString *> *CCBridgeToolGroup(NSString *group) {
35
+ static NSDictionary<NSString *, NSArray<NSString *> *> *groups;
36
+ static dispatch_once_t once;
37
+ dispatch_once(&once, ^{
38
+ groups = @{
39
+ @"view": @[@"list_agents", @"list_reservations", @"check_inbox"],
40
+ @"send": @[@"send_message"],
41
+ @"reserve": @[@"reserve_files", @"release_files"],
42
+ @"name": @[@"set_name"]
43
+ };
44
+ });
45
+ return groups[group] ?: @[];
46
+ }
47
+
48
+ static NSArray<NSString *> *KnownTools(id value) {
49
+ if (![value isKindOfClass:NSArray.class]) return @[];
50
+ NSMutableArray<NSString *> *tools = [NSMutableArray array];
51
+ for (NSString *group in CCBridgeToolGroupNames()) {
52
+ for (NSString *tool in CCBridgeToolGroup(group)) {
53
+ if ([value containsObject:tool]) [tools addObject:tool];
54
+ }
55
+ }
56
+ return tools;
57
+ }
58
+
59
+ // 名字、ref、tty 都会进菜单标题。bridge 端已经约束过格式,这里再按同一字符集收一遍,
60
+ // 防止被手改的状态文件往菜单里塞奇怪的东西。
61
+ static NSString *BridgeSafeString(id value, NSUInteger maximumLength) {
62
+ if (![value isKindOfClass:NSString.class]) return @"";
63
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
64
+ @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"];
65
+ NSMutableString *safe = [NSMutableString string];
66
+ NSString *text = value;
67
+ for (NSUInteger index = 0; index < text.length && safe.length < maximumLength; index++) {
68
+ unichar character = [text characterAtIndex:index];
69
+ if ([allowed characterIsMember:character]) [safe appendFormat:@"%C", character];
70
+ }
71
+ return safe;
72
+ }
73
+
74
+ static NSArray<NSString *> *JSONFilesInDirectory(NSString *directory) {
75
+ NSArray<NSString *> *names = [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil];
76
+ NSMutableArray<NSString *> *files = [NSMutableArray array];
77
+ for (NSString *name in names) {
78
+ if (![name hasSuffix:@".json"]) continue;
79
+ [files addObject:[directory stringByAppendingPathComponent:name]];
80
+ if (files.count >= BridgeFileScanLimit) break;
81
+ }
82
+ return files;
83
+ }
84
+
85
+ static NSDictionary *ReadJSONObject(NSString *path) {
86
+ NSData *data = [NSData dataWithContentsOfFile:path];
87
+ if (data.length == 0) return nil;
88
+ id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
89
+ return [object isKindOfClass:NSDictionary.class] ? object : nil;
90
+ }
91
+
92
+ NSDictionary *CCBridgeOptions(void) {
93
+ NSDictionary *raw = nil;
94
+ if (CCBridgeEnabled()) {
95
+ raw = ReadJSONObject([BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-enabled"]);
96
+ }
97
+ return @{
98
+ @"codexApprove": KnownTools(raw[@"codexApprove"]),
99
+ @"claudeAllow": KnownTools(raw[@"claudeAllow"]),
100
+ @"wake": @(![raw[@"wake"] isEqual:@NO]),
101
+ @"editGuard": @(![raw[@"editGuard"] isEqual:@NO])
102
+ };
103
+ }
104
+
105
+ NSDictionary<NSString *, NSString *> *CCBridgeCLILocator(void) {
106
+ NSDictionary *raw = ReadJSONObject([BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-cli.json"]);
107
+ NSString *node = [raw[@"node"] isKindOfClass:NSString.class] ? [raw[@"node"] stringByStandardizingPath] : nil;
108
+ NSString *cli = [raw[@"cli"] isKindOfClass:NSString.class] ? [raw[@"cli"] stringByStandardizingPath] : nil;
109
+ NSFileManager *files = NSFileManager.defaultManager;
110
+ if (!node.isAbsolutePath || !cli.isAbsolutePath) return nil;
111
+ if (![files isExecutableFileAtPath:node] || ![files isReadableFileAtPath:cli]) return nil;
112
+ return @{@"node": node, @"cli": cli};
113
+ }
114
+
115
+ NSUInteger CCBridgeActiveReservationCount(NSSet<NSString *> *sessionIds) {
116
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"reservations"];
117
+ double now = NSDate.date.timeIntervalSince1970 * 1000.0;
118
+ NSUInteger count = 0;
119
+ for (NSString *path in JSONFilesInDirectory(directory)) {
120
+ NSDictionary *reservation = ReadJSONObject(path);
121
+ if ([reservation[@"expiresAt"] doubleValue] <= now) continue;
122
+ NSString *session = [reservation[@"session"] isKindOfClass:NSString.class] ? reservation[@"session"] : nil;
123
+ if (session && [sessionIds containsObject:session]) count++;
124
+ }
125
+ return count;
126
+ }
127
+
128
+ static BOOL ProcessAlive(id pidValue) {
129
+ if (![pidValue isKindOfClass:NSNumber.class]) return YES; // 没记 pid 的会话交给 bridge 端判定
130
+ pid_t pid = [pidValue intValue];
131
+ if (pid <= 1) return YES;
132
+ return kill(pid, 0) == 0 || errno == EPERM;
133
+ }
134
+
135
+ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
136
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sessions"];
137
+ NSMutableDictionary<NSString *, NSDictionary *> *sessions = [NSMutableDictionary dictionary];
138
+ for (NSString *path in JSONFilesInDirectory(directory)) {
139
+ NSDictionary *record = ReadJSONObject(path);
140
+ NSString *session = BridgeSafeString(record[@"session"], 128);
141
+ NSString *name = BridgeSafeString(record[@"name"], 40);
142
+ if (session.length == 0 || name.length == 0 || !ProcessAlive(record[@"pid"])) continue;
143
+ NSMutableDictionary *entry = [@{
144
+ @"name": name,
145
+ @"ref": BridgeSafeString(record[@"ref"], 6),
146
+ @"provider": BridgeSafeString(record[@"provider"], 16)
147
+ } mutableCopy];
148
+ NSString *tty = BridgeSafeString(record[@"tty"], 32);
149
+ if (tty.length > 0) entry[@"tty"] = tty;
150
+ sessions[session] = entry;
151
+ }
152
+ return sessions;
153
+ }
154
+
155
+ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteger limit) {
156
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sent"];
157
+ NSMutableArray<NSDictionary *> *deliveries = [NSMutableArray array];
158
+ for (NSString *path in JSONFilesInDirectory(directory)) {
159
+ NSDictionary *receipt = ReadJSONObject(path);
160
+ if (![receipt[@"status"] isEqual:@"delivered"]) continue;
161
+ NSDictionary *from = [receipt[@"from"] isKindOfClass:NSDictionary.class] ? receipt[@"from"] : nil;
162
+ NSDictionary *to = [receipt[@"to"] isKindOfClass:NSDictionary.class] ? receipt[@"to"] : nil;
163
+ if (!from || !to || [from[@"system"] boolValue]) continue;
164
+ id stamp = receipt[@"updatedAt"] ?: receipt[@"createdAt"];
165
+ if (![stamp isKindOfClass:NSNumber.class]) continue;
166
+ NSTimeInterval at = [stamp doubleValue] / 1000.0;
167
+ if (at < since) continue;
168
+ NSString *fromName = BridgeSafeString(from[@"name"], 40);
169
+ NSString *toName = BridgeSafeString(to[@"name"], 40);
170
+ NSString *toSession = BridgeSafeString(to[@"session"], 128);
171
+ if (fromName.length == 0 || toName.length == 0 || toSession.length == 0) continue;
172
+ // 只取元数据:receipt[@"body"] 不进入返回值。
173
+ [deliveries addObject:@{
174
+ @"id": BridgeSafeString(receipt[@"id"], 64),
175
+ @"from": fromName,
176
+ @"to": toName,
177
+ @"toSession": toSession,
178
+ @"at": @(at)
179
+ }];
180
+ }
181
+ [deliveries sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
182
+ return [right[@"at"] compare:left[@"at"]];
183
+ }];
184
+ if (deliveries.count > limit) return [deliveries subarrayWithRange:NSMakeRange(0, limit)];
185
+ return deliveries;
186
+ }
187
+
188
+ NSDictionary<NSString *, NSNumber *> *CCBridgePendingCounts(void) {
189
+ NSString *inbox = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"inbox"];
190
+ NSMutableDictionary<NSString *, NSNumber *> *counts = [NSMutableDictionary dictionary];
191
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:inbox error:nil]) {
192
+ NSString *session = BridgeSafeString(name, 128);
193
+ if (session.length == 0 || ![session isEqualToString:name]) continue;
194
+ NSUInteger count = JSONFilesInDirectory([inbox stringByAppendingPathComponent:name]).count;
195
+ if (count > 0) counts[session] = @(count);
196
+ }
197
+ return counts;
198
+ }
@@ -3,6 +3,7 @@
3
3
  #import "MenuToggleSwitch.h"
4
4
  #import "CCPetsPaths.h"
5
5
  #import "CCPetsImageLoader.h"
6
+ #import "CCPetsBridge.h"
6
7
 
7
8
  // 碎碎念频率档位的 defaults 键。定义在 CCPetsAppDelegate.m,这里只读不写;
8
9
  // 单独 extern 而不 import 那个头文件,是因为它反过来 import 了 PetView.h。
@@ -1466,6 +1467,88 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
1466
1467
  [menu addItem:item];
1467
1468
  return item;
1468
1469
  }
1470
+ // CC Bridge 开关组。状态每次打开菜单时现读(开关文件 / 选项),不在视图里缓存。
1471
+ // 除"消息角标 / 新消息通知"这两项只影响桌宠外,其余开关都通过 cc-pets bridge enable / configure
1472
+ // 落到 Claude Code / Codex 的配置里;bridge 未开启时它们置灰。
1473
+ - (void)addBridgeSwitchToMenu:(NSMenu *)menu title:(NSString *)title checked:(BOOL)checked
1474
+ action:(SEL)action tag:(NSInteger)tag enabled:(BOOL)enabled toolTip:(NSString *)toolTip {
1475
+ // 与其他子菜单同宽。菜单宽度取最宽的一行:标题都控制在 5 个字以内,说明性文字放进悬停提示,
1476
+ // 否则长文字行会把菜单撑宽,而自绘开关行是固定宽度,开关就不再贴右边。
1477
+ NSMenuItem *item = [self addPersistentSwitchToMenu:menu title:title checked:checked
1478
+ action:action width:PetSubmenuRowWidth tag:tag];
1479
+ item.view.toolTip = toolTip;
1480
+ for (NSView *subview in item.view.subviews) {
1481
+ if ([subview isKindOfClass:MenuToggleSwitch.class]) ((MenuToggleSwitch *)subview).enabled = enabled;
1482
+ if ([subview isKindOfClass:NSTextField.class] && !enabled) {
1483
+ ((NSTextField *)subview).textColor = NSColor.disabledControlTextColor;
1484
+ }
1485
+ }
1486
+ }
1487
+ - (void)addBridgeMenuToMenu:(NSMenu *)menu {
1488
+ NSMenuItem *bridgeItem = [menu addItemWithTitle:@"CC Bridge" action:nil keyEquivalent:@""];
1489
+ NSMenu *bridgeMenu = [NSMenu new];
1490
+ BOOL enabled = CCBridgeEnabled();
1491
+ NSDictionary *options = CCBridgeOptions();
1492
+ [self addBridgeSwitchToMenu:bridgeMenu title:@"启用" checked:enabled
1493
+ action:@selector(toggleBridgeEnabled:) tag:0 enabled:YES
1494
+ toolTip:@"让本机 Claude Code / Codex 会话互相发消息、唤醒对方、预留文件"];
1495
+
1496
+ [bridgeMenu addItem:NSMenuItem.separatorItem];
1497
+ NSMenuItem *approvalHeader = [bridgeMenu addItemWithTitle:@"免审批" action:nil keyEquivalent:@""];
1498
+ approvalHeader.enabled = NO;
1499
+ approvalHeader.toolTip = @"每组同时作用于 Codex 免审批与 Claude 免确认;Codex 需重启会话生效";
1500
+ NSArray<NSDictionary *> *groups = @[
1501
+ @{@"title": @"查看类", @"group": @"view", @"tag": @1,
1502
+ @"tip": @"列出会话、查看预留、读取信箱免审批;只读,放开没有风险"},
1503
+ @{@"title": @"发消息", @"group": @"send", @"tag": @2,
1504
+ @"tip": @"开启后,Agent 可以不经确认给其他会话发消息"},
1505
+ @{@"title": @"文件预留", @"group": @"reserve", @"tag": @3,
1506
+ @"tip": @"预留 / 释放文件免审批"},
1507
+ @{@"title": @"改会话名", @"group": @"name", @"tag": @4,
1508
+ @"tip": @"修改当前会话在 CC Bridge 中的名字免审批"}
1509
+ ];
1510
+ for (NSDictionary *group in groups) {
1511
+ NSArray<NSString *> *tools = CCBridgeToolGroup(group[@"group"]);
1512
+ NSSet *codex = [NSSet setWithArray:options[@"codexApprove"]];
1513
+ NSSet *claude = [NSSet setWithArray:options[@"claudeAllow"]];
1514
+ BOOL checked = tools.count > 0 && [[NSSet setWithArray:tools] isSubsetOfSet:codex] &&
1515
+ [[NSSet setWithArray:tools] isSubsetOfSet:claude];
1516
+ [self addBridgeSwitchToMenu:bridgeMenu title:group[@"title"] checked:checked
1517
+ action:@selector(toggleBridgeApproval:) tag:[group[@"tag"] integerValue] enabled:enabled
1518
+ toolTip:group[@"tip"]];
1519
+ }
1520
+
1521
+ [bridgeMenu addItem:NSMenuItem.separatorItem];
1522
+ NSMenuItem *behaviorHeader = [bridgeMenu addItemWithTitle:@"行为" action:nil keyEquivalent:@""];
1523
+ behaviorHeader.enabled = NO;
1524
+ [self addBridgeSwitchToMenu:bridgeMenu title:@"自动唤醒" checked:[options[@"wake"] boolValue]
1525
+ action:@selector(toggleBridgeWake:) tag:0 enabled:enabled
1526
+ toolTip:@"自动唤醒空闲会话。关闭后消息只进信箱,等对方下次收到你的输入时带入,可省 token;Codex 需重启会话生效"];
1527
+ [self addBridgeSwitchToMenu:bridgeMenu title:@"编辑拦截" checked:[options[@"editGuard"] boolValue]
1528
+ action:@selector(toggleBridgeEditGuard:) tag:0 enabled:enabled
1529
+ toolTip:@"编辑他人预留的文件时先暂停一次并说明原因,重试即放行;Codex 需重启会话生效"];
1530
+ [self addBridgeSwitchToMenu:bridgeMenu title:@"消息角标"
1531
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey]
1532
+ action:@selector(toggleBridgeBadge:) tag:0 enabled:YES
1533
+ toolTip:@"状态图标右下角:蓝色为新送达,橙色为信箱积压"];
1534
+ [self addBridgeSwitchToMenu:bridgeMenu title:@"新消息通知"
1535
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:BridgeNotificationKey]
1536
+ action:@selector(toggleBridgeNotification:) tag:0 enabled:YES
1537
+ toolTip:@"会话之间有消息送达时发一条系统通知(只含谁发给谁,不含正文)"];
1538
+
1539
+ [bridgeMenu addItem:NSMenuItem.separatorItem];
1540
+ NSString *status = @"未开启";
1541
+ if (enabled) {
1542
+ NSDictionary *sessions = CCBridgeSessions();
1543
+ NSUInteger reservations = CCBridgeActiveReservationCount([NSSet setWithArray:sessions.allKeys]);
1544
+ status = [NSString stringWithFormat:@"%lu 会话 · %lu 预留",
1545
+ (unsigned long)sessions.count, (unsigned long)reservations];
1546
+ }
1547
+ NSMenuItem *statusItem = [bridgeMenu addItemWithTitle:status action:nil keyEquivalent:@""];
1548
+ statusItem.enabled = NO;
1549
+ statusItem.toolTip = @"在线会话数 · 有效的文件预留数";
1550
+ bridgeItem.submenu = bridgeMenu;
1551
+ }
1469
1552
  - (void)rightMouseDown:(NSEvent *)event {
1470
1553
  NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
1471
1554
  NSMenu *menu = [NSMenu new];
@@ -1517,6 +1600,7 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
1517
1600
  tag:[option[@"tag"] integerValue]];
1518
1601
  }
1519
1602
  notificationItem.submenu = notificationMenu;
1603
+ [self addBridgeMenuToMenu:menu];
1520
1604
  NSMenuItem *interactionItem = [menu addItemWithTitle:@"连击互动" action:nil keyEquivalent:@""];
1521
1605
  NSMenu *interactionMenu = [NSMenu new];
1522
1606
  [self addPersistentSwitchToMenu:interactionMenu
package/bin/cc-pets CHANGED
@@ -16,6 +16,11 @@ if [[ "${1:-}" == "pet" ]]; then
16
16
  exec node "${PROJECT_DIR}/scripts/pet-store.mjs" "$@"
17
17
  fi
18
18
 
19
+ if [[ "${1:-}" == "bridge" ]]; then
20
+ shift
21
+ exec node "${PROJECT_DIR}/scripts/bridge/cli.mjs" "$@"
22
+ fi
23
+
19
24
  if [[ "${1:-}" == "uninstall" ]]; then
20
25
  exec "${PROJECT_DIR}/scripts/uninstall-shell-integration.sh"
21
26
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": {
6
6
  "name": "Sunnyshiny",
@@ -40,6 +40,8 @@
40
40
  "README.zh-CN.md",
41
41
  "PROVIDER_PROTOCOL.md",
42
42
  "PROVIDER_PROTOCOL.zh-CN.md",
43
+ "CC_BRIDGE.md",
44
+ "CC_BRIDGE.zh-CN.md",
43
45
  "CHANGELOG.md",
44
46
  "CHANGELOG.zh-CN.md",
45
47
  "CONTRIBUTING.md",
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ // `cc-pets bridge <子命令>` 的入口。
3
+ //
4
+ // 面向用户:enable / disable / status / list / send / inbox
5
+ // 面向 CLI 集成(由 hooks / MCP 配置调用):hook / watch / mcp / notify-idle
6
+
7
+ import {
8
+ describeSession, identifySelf, liveSessions, receiptSummary, resolveTarget, sendIdleNotices,
9
+ sendMessage, formatEnvelope
10
+ } from "./core.mjs";
11
+ import { install, uninstall } from "./install.mjs";
12
+ import { DEFAULT_OPTIONS, currentOptions, describeOptions, mergeOptionFlags, normalizeOptions } from "./options.mjs";
13
+ import { fileURLToPath } from "node:url";
14
+ import { activeReservations, describeReservation } from "./reservations.mjs";
15
+ import {
16
+ bridgeDirectory, claimInbox, isBridgeEnabled, listReceipts, pendingCount, migrateLegacyFlag, readBridgeOptions, readSession, renameSession,
17
+ setBridgeEnabled, takeIdleSubscriptions, updateReceipt, writeCliLocator
18
+ } from "./store.mjs";
19
+
20
+ const recordCliLocation = () => writeCliLocator(fileURLToPath(import.meta.url));
21
+
22
+ const USAGE = `用法: cc-pets bridge <命令>
23
+
24
+ enable [选项] 开启 CC Bridge:写入 Claude Code / Codex hooks 并注册 MCP
25
+ configure [选项] 已开启时只修改选项(不重新注册 MCP)
26
+ disable 关闭并移除所有 CC Bridge 集成
27
+ status 查看开关状态与在线会话
28
+ list 列出在线会话
29
+ send <to> <消息…> 以当前会话身份发送(需在 Agent 会话内执行,或用 --from 指定)
30
+ name <新名字> 修改当前会话的名字(需在 Agent 会话内执行,或用 --from 指定)
31
+ inbox 读取当前会话信箱(调试用)
32
+
33
+ 选项(没给的保持原值):
34
+ --approve=<列表> Codex 与 Claude 同时免审批
35
+ --codex-approve=<列表> 只设 Codex 免审批
36
+ --claude-allow=<列表> 只设 Claude 免确认
37
+ 列表可写分组 view, send, reserve, name,或具体工具名;传空值表示清空
38
+ --wake=on|off 自动唤醒空闲会话(关闭可省 token,消息等对方下次收到用户输入时带入)
39
+ --edit-guard=on|off 编辑他人预留的文件时暂停一次
40
+
41
+ 启动时指定会话名:CC_BRIDGE_NAME=frontend claude(或 codex)
42
+
43
+ CC Bridge 让本机的 Claude Code 与 Codex 终端会话互相发现、发消息、唤醒对方。
44
+ 消息正文会保存在本机临时目录(仅当前用户可读),默认关闭。`;
45
+
46
+ const parseFlag = (args, name) => {
47
+ const prefix = `--${name}=`;
48
+ const index = args.findIndex((arg) => arg === `--${name}` || arg.startsWith(prefix));
49
+ if (index < 0) return undefined;
50
+ const [flag] = args.splice(index, 1);
51
+ if (flag.startsWith(prefix)) return flag.slice(prefix.length);
52
+ return args.splice(index, 1)[0];
53
+ };
54
+
55
+ const readOptionFlags = (args) => ({
56
+ approve: parseFlag(args, "approve"),
57
+ codexApprove: parseFlag(args, "codex-approve"),
58
+ claudeAllow: parseFlag(args, "claude-allow"),
59
+ wake: parseFlag(args, "wake"),
60
+ editGuard: parseFlag(args, "edit-guard")
61
+ });
62
+
63
+ const printSessions = () => {
64
+ const sessions = liveSessions();
65
+ if (sessions.length === 0) {
66
+ console.log("没有在线会话。");
67
+ return;
68
+ }
69
+ for (const session of sessions) {
70
+ console.log(`${describeSession(session)} ${session.provider} ${session.status || "-"} pid=${session.pid ?? "-"} ${session.tty || "-"} ${session.cwd || "-"} 待投递=${pendingCount(session.session)}`);
71
+ }
72
+ };
73
+
74
+ const selfOrFrom = (args) => {
75
+ const from = parseFlag(args, "from");
76
+ if (from) {
77
+ const resolved = resolveTarget(from, liveSessions());
78
+ if (resolved.error) throw new Error(resolved.error);
79
+ return resolved.session;
80
+ }
81
+ const self = identifySelf();
82
+ if (!self) throw new Error("无法识别当前会话;在普通终端里调试请用 --from <会话名>。");
83
+ return self;
84
+ };
85
+
86
+ const commands = {
87
+ async enable(args) {
88
+ const options = mergeOptionFlags(isBridgeEnabled() ? currentOptions() : DEFAULT_OPTIONS, readOptionFlags(args));
89
+ for (const line of install({ options })) console.log(line);
90
+ setBridgeEnabled(true, options);
91
+ recordCliLocation();
92
+ console.log("CC Bridge 已开启。");
93
+ console.log("- 已在运行的 Claude Code 会话会热加载 hooks、立即开始收消息,但要重启后才有 cc-bridge 工具(期间可用 cc-pets bridge send 回复)。");
94
+ console.log("- 已在运行的 Codex 会话需要重启,并在 /hooks 中信任 cc-pets bridge 的 hooks。");
95
+ return 0;
96
+ },
97
+
98
+ // 只改选项:重写 hooks、Codex 审批块、Claude 放行规则,不重跑 claude / codex mcp add,
99
+ // 所以很快。桌宠菜单的开关走这条路。
100
+ async configure(args) {
101
+ if (!isBridgeEnabled()) throw new Error("CC Bridge 未开启,请先执行 cc-pets bridge enable。");
102
+ const options = mergeOptionFlags(currentOptions(), readOptionFlags(args));
103
+ install({ options, registerMcp: false });
104
+ setBridgeEnabled(true, options);
105
+ recordCliLocation();
106
+ for (const line of describeOptions(options)) console.log(line);
107
+ return 0;
108
+ },
109
+
110
+ // 安装 / 升级流程调用:已开启时按原选项重写集成(包路径可能变了),未开启时什么都不做。
111
+ async refresh() {
112
+ // 未开启也要写:桌宠菜单的"启用"开关就靠它找到 CLI。
113
+ recordCliLocation();
114
+ if (!isBridgeEnabled()) return 0;
115
+ const options = normalizeOptions(readBridgeOptions());
116
+ for (const line of install({ options })) console.log(line);
117
+ setBridgeEnabled(true, options);
118
+ return 0;
119
+ },
120
+
121
+ async disable() {
122
+ for (const line of uninstall()) console.log(line);
123
+ setBridgeEnabled(false);
124
+ console.log("CC Bridge 已关闭。");
125
+ return 0;
126
+ },
127
+
128
+ async status() {
129
+ console.log(`CC Bridge:${isBridgeEnabled() ? "已开启" : "未开启"}`);
130
+ if (isBridgeEnabled()) for (const line of describeOptions(currentOptions())) console.log(` ${line}`);
131
+ console.log(`状态目录:${bridgeDirectory()}`);
132
+ printSessions();
133
+ const reservations = activeReservations();
134
+ if (reservations.length > 0) {
135
+ console.log("\n文件预留:");
136
+ for (const reservation of reservations) console.log(` ${reservation.root} ${describeReservation(reservation)}`);
137
+ }
138
+ const receipts = listReceipts().sort((left, right) => right.createdAt - left.createdAt).slice(0, 5);
139
+ if (receipts.length > 0) {
140
+ console.log("\n最近消息:");
141
+ for (const receipt of receipts) {
142
+ const from = receipt.from.system ? "cc-pets" : receipt.from.name;
143
+ console.log(` ${receipt.id} ${from} → ${receipt.to.name} ${receipt.status}${receipt.reason ? `(${receipt.reason})` : ""}`);
144
+ }
145
+ }
146
+ return 0;
147
+ },
148
+
149
+ async list() {
150
+ printSessions();
151
+ return 0;
152
+ },
153
+
154
+ async send(args) {
155
+ const from = selfOrFrom(args);
156
+ const [to, ...words] = args;
157
+ if (!to || words.length === 0) throw new Error("用法: cc-pets bridge send <to> <消息…>");
158
+ const target = resolveTarget(to, liveSessions());
159
+ if (target.error) throw new Error(target.error);
160
+ const result = await sendMessage({ from, to: target.session, body: words.join(" ") });
161
+ if (result.error) throw new Error(result.error);
162
+ console.log(receiptSummary(result.receipt, target.session));
163
+ return result.receipt.status === "undeliverable" ? 1 : 0;
164
+ },
165
+
166
+ async name(args) {
167
+ const self = selfOrFrom(args);
168
+ if (!args[0]) throw new Error("用法: cc-pets bridge name <新名字>");
169
+ const result = renameSession(self.session, args[0], liveSessions());
170
+ if (result.error) throw new Error(result.error);
171
+ console.log(`已从 ${result.previous} 改名为 ${describeSession(result.session)}。`);
172
+ return 0;
173
+ },
174
+
175
+ async inbox(args) {
176
+ const self = selfOrFrom(args);
177
+ const messages = claimInbox(self.session);
178
+ for (const message of messages) {
179
+ updateReceipt(message.id, { status: "delivered", transport: { kind: "check-inbox" } });
180
+ }
181
+ console.log(messages.length > 0 ? messages.map(formatEnvelope).join("\n\n") : "信箱里没有新消息。");
182
+ return 0;
183
+ },
184
+
185
+ async hook() {
186
+ return (await import("./hook.mjs")).main();
187
+ },
188
+
189
+ async watch() {
190
+ return (await import("./watch.mjs")).main();
191
+ },
192
+
193
+ async mcp() {
194
+ return (await import("./mcp-server.mjs")).main();
195
+ },
196
+
197
+ // Stop hook 脱离出来的子进程:给订阅了该会话空闲的会话发通知。
198
+ async "notify-idle"(args) {
199
+ if (!isBridgeEnabled()) return 0;
200
+ const target = readSession(args[0]);
201
+ if (!target) return 0;
202
+ const subscribers = takeIdleSubscriptions(target.session);
203
+ if (subscribers.length > 0) await sendIdleNotices(target, subscribers);
204
+ return 0;
205
+ }
206
+ };
207
+
208
+ const run = async () => {
209
+ const [command, ...args] = process.argv.slice(2);
210
+ if (!command || command === "help" || command === "--help" || command === "-h") {
211
+ console.log(USAGE);
212
+ return command ? 0 : 2;
213
+ }
214
+ const handler = commands[command];
215
+ // 集成子命令(hook / watch / mcp)跑在对方 CLI 的关键路径上,不做迁移这类文件操作。
216
+ if (!["hook", "watch", "mcp", "notify-idle"].includes(command)) migrateLegacyFlag();
217
+ if (!handler) {
218
+ console.error(`未知命令:${command}\n\n${USAGE}`);
219
+ return 2;
220
+ }
221
+ try {
222
+ return await handler(args);
223
+ } catch (error) {
224
+ console.error(error.message);
225
+ return 1;
226
+ }
227
+ };
228
+
229
+ process.exitCode = await run();