cc-pets 2.4.0 → 2.6.0-beta.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.
Files changed (111) hide show
  1. package/CC_BRIDGE.md +93 -14
  2. package/CC_BRIDGE.zh-CN.md +71 -11
  3. package/CHANGELOG.md +55 -0
  4. package/CHANGELOG.zh-CN.md +56 -1
  5. package/CONTRIBUTING.md +1 -1
  6. package/CONTRIBUTING.zh-CN.md +1 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +116 -34
  10. package/README.zh-CN.md +99 -35
  11. package/Resources/AgentIcons/antigravity.icns +0 -0
  12. package/Resources/zh-Hans.lproj/Localizable.strings +99 -26
  13. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +51 -4
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +120 -17
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +24 -11
  16. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +24 -1
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +21 -11
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +33 -17
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +43 -7
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +7 -4
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +7 -4
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +24 -22
  24. package/Sources/CCPets/App/CCPetsAppDelegate.h +10 -0
  25. package/Sources/CCPets/App/CCPetsAppDelegate.m +18 -8
  26. package/Sources/CCPets/App/CCPetsVersion.h +4 -0
  27. package/Sources/CCPets/App/CCPetsVersion.m +34 -0
  28. package/Sources/CCPets/App/main.m +11 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +41 -17
  30. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.h +4 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.m +119 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +3 -1
  33. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +272 -50
  34. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +12 -3
  35. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +341 -95
  36. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  37. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +227 -95
  38. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +35 -5
  39. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +310 -42
  40. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.h +12 -0
  41. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.m +105 -0
  42. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.h +17 -0
  43. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.m +462 -0
  44. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.h +5 -0
  45. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.m +180 -0
  46. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.h +3 -0
  47. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.m +463 -0
  48. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  49. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  50. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +1 -1
  51. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +38 -8
  52. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +15 -5
  53. package/Sources/CCPets/Integrations/CCPetsProfiles.h +2 -1
  54. package/Sources/CCPets/Integrations/CCPetsProfiles.m +112 -81
  55. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +11 -1
  56. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +217 -45
  57. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  58. package/Sources/CCPets/Pet/CCPetsPreviews.m +16 -8
  59. package/Sources/CCPets/Pet/PetView+Menu.m +64 -5
  60. package/Sources/CCPets/Pet/PetView.h +7 -0
  61. package/Sources/CCPets/Pet/PetView.m +12 -1
  62. package/Sources/CCPets/Support/CCPetsDoctor.m +126 -37
  63. package/Sources/CCPets/Support/CCPetsPaths.h +5 -0
  64. package/Sources/CCPets/Support/CCPetsPaths.m +15 -0
  65. package/Sources/CCPets/Support/CCPetsPreferences.h +14 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.m +36 -0
  67. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  68. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  69. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  70. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +533 -0
  71. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  72. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +98 -0
  73. package/Sources/CCPets/UI/CCPetsSettingsPage.h +7 -1
  74. package/Sources/CCPets/UI/CCPetsSettingsPage.m +205 -8
  75. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  76. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  77. package/Sources/CCPets/UI/CCPetsUIStyle.m +3 -1
  78. package/Sources/CCPets/UI/CCPetsUsagePage.h +4 -3
  79. package/Sources/CCPets/UI/CCPetsUsagePage.m +69 -43
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +11 -1
  81. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +6 -4
  82. package/Sources/CCPets/Usage/CCPetsAntigravityQuota.m +115 -0
  83. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.h +5 -0
  84. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.m +43 -0
  85. package/Sources/CCPets/Usage/CCPetsProviderRegistry+Testing.h +13 -0
  86. package/Sources/CCPets/Usage/CCPetsProviderRegistry.h +25 -0
  87. package/Sources/CCPets/Usage/CCPetsProviderRegistry.m +94 -0
  88. package/Sources/CCPets/Usage/CCPetsQuotaHistory.h +1 -1
  89. package/Sources/CCPets/Usage/CCPetsQuotaHistory.m +11 -8
  90. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +2 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +206 -14
  92. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +4 -4
  93. package/Sources/CCPets/Usage/CCPetsUsage.h +7 -2
  94. package/Sources/CCPets/Usage/CCPetsUsageMode.h +2 -0
  95. package/Sources/CCPets/Usage/CCPetsUsageMode.m +29 -4
  96. package/Sources/CCPets/Usage/CCPetsUsageMonitor.h +4 -4
  97. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +90 -7
  98. package/Sources/CCPets/Usage/QuotaDashboardView+CompactRow.m +81 -0
  99. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +5 -8
  100. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +26 -4
  101. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +99 -99
  102. package/Sources/CCPets/Usage/QuotaDashboardView.h +9 -10
  103. package/Sources/CCPets/Usage/QuotaDashboardView.m +232 -79
  104. package/THIRD_PARTY_NOTICES.md +5 -4
  105. package/THIRD_PARTY_NOTICES.zh-CN.md +6 -5
  106. package/bin/agy-with-pet +82 -0
  107. package/bin/cc-pets +1 -1
  108. package/bin/claude-with-pet +15 -0
  109. package/bin/codex-with-pet +17 -2
  110. package/package.json +5 -3
  111. package/scripts/install-shell-integration.sh +5 -0
@@ -0,0 +1,180 @@
1
+ #import "CCPetsAntigravityEvents.h"
2
+ #import "CCPetsBridgeCLI.h"
3
+ #import "CCPetsBridgeStore.h"
4
+ #import "CCPetsCLISupport.h"
5
+ #import "CCPetsEvents.h"
6
+ #import "CCPetsPaths.h"
7
+ #import "CCPetsProfiles.h"
8
+ #import "CCPetsTerminalFocus.h"
9
+ #import <sys/stat.h>
10
+ #import <unistd.h>
11
+
12
+ static NSString *StringValue(id value) {
13
+ return [value isKindOfClass:NSString.class] ? value : nil;
14
+ }
15
+
16
+ static NSString *ToolCategory(id value) {
17
+ NSString *tool = SanitizedShortString(value, 64);
18
+ if ([tool hasPrefix:@"browser_"] || [tool isEqual:@"search_web"] || [tool isEqual:@"read_url_content"]) return @"web";
19
+ if ([tool hasPrefix:@"mcp_"] || [tool isEqual:@"call_mcp_tool"]) return @"mcp";
20
+ return @{
21
+ @"run_command": @"shell", @"send_command_input": @"shell",
22
+ @"write_to_file": @"write", @"replace_file_content": @"edit", @"multi_replace_file_content": @"edit", @"sed_file": @"edit",
23
+ @"view_file": @"read", @"list_dir": @"read", @"view_file_outline": @"read",
24
+ @"find_by_name": @"search", @"grep_search": @"search",
25
+ @"invoke_subagent": @"agent", @"manage_subagents": @"agent"
26
+ }[tool] ?: tool;
27
+ }
28
+
29
+ NSString *CCPetsRegisterAntigravityTerminalClient(pid_t pid) {
30
+ NSString *tty = StringValue(TerminalFocusTargetFromEnvironment()[@"tty"]);
31
+ if (tty.length == 0) return nil;
32
+ NSString *directory = [PetStateDirectory() stringByAppendingPathComponent:
33
+ [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()]];
34
+ [NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES
35
+ attributes:@{NSFilePosixPermissions: @0700} error:nil];
36
+ struct stat info;
37
+ if (lstat(directory.fileSystemRepresentation, &info) != 0 || !S_ISDIR(info.st_mode) || info.st_uid != getuid()) return nil;
38
+ NSString *path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", pid]];
39
+ NSDictionary *profile = CCPetsProfileForHome(CCPetsProfileProviderAntigravity, DefaultAntigravityConfigDirectory());
40
+ NSString *contents = [NSString stringWithFormat:@"%@\n%@\n%@\n", CCBridgeAntigravityProvider, tty,
41
+ NormalizedAgentProfileID(profile[@"id"])];
42
+ return CCPetsWriteFileAtomically(path, contents, 0600, NULL) ? path : nil;
43
+ }
44
+
45
+ // App 与 CLI 共用 Gemini 根目录里的 Hooks,靠祖先进程区分来源。App 会话没有终端,
46
+ // 回跳目标是 App 本身;标题用 Provider 名,避免和同一账号的 CLI 会话混在一起。
47
+ static BOOL AppendAntigravityEvent(NSString *session, NSString *cwd, NSString *event, NSString *tool, BOOL failed,
48
+ NSString *state, BOOL app) {
49
+ NSString *identifier = CCBridgeSafeSessionId(session);
50
+ if (!identifier) return NO;
51
+ NSMutableDictionary *record = [@{
52
+ @"event": event,
53
+ @"tool": ToolCategory(tool),
54
+ @"failed": @(failed),
55
+ @"provider": app ? CCBridgeAntigravityAppProvider : CCBridgeAntigravityProvider,
56
+ @"state": state ?: NormalizedStateForEvent(event, failed),
57
+ @"timestamp": @(NSDate.date.timeIntervalSince1970),
58
+ @"session": identifier
59
+ } mutableCopy];
60
+ NSString *directory = SanitizedWorkingDirectory(cwd);
61
+ if (directory.length > 0) record[@"cwd"] = directory;
62
+ if (app) {
63
+ NSDictionary *profile = CCPetsProfileForHome(CCPetsProfileProviderAntigravity, DefaultAntigravityAppConfigDirectory());
64
+ NSString *profileID = NormalizedAgentProfileID(profile[@"id"]);
65
+ if (profileID.length > 0) record[@"profileId"] = profileID;
66
+ record[@"terminal"] = @{@"bundleID": CCPetsAntigravityAppBundleIdentifier};
67
+ return AppendAgentEventRecord(record);
68
+ }
69
+ NSString *profileID = NormalizedAgentProfileID(CCPetsEnvironmentValue(@"CC_PETS_PROFILE_ID"));
70
+ NSString *profileName = SanitizedShortString(CCPetsEnvironmentValue(@"CC_PETS_PROFILE_NAME"), 64);
71
+ if (![profileID hasPrefix:@"antigravity:"]) {
72
+ NSDictionary *profile = CCPetsProfileForHome(CCPetsProfileProviderAntigravity, DefaultAntigravityConfigDirectory());
73
+ profileID = NormalizedAgentProfileID(profile[@"id"]);
74
+ profileName = SanitizedShortString(profile[@"displayName"], 64);
75
+ }
76
+ if (profileID.length > 0) record[@"profileId"] = profileID;
77
+ if (profileName.length > 0) record[@"profileName"] = profileName;
78
+ NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
79
+ if (terminal.count > 0) record[@"terminal"] = terminal;
80
+ return AppendAgentEventRecord(record);
81
+ }
82
+
83
+ static void AppendHookEvent(NSString *hookEvent, NSDictionary *payload, BOOL app) {
84
+ NSString *event = @{
85
+ @"SessionStart": @"SessionStart", @"PreInvocation": @"UserPromptSubmit", @"PreToolUse": @"PreToolUse",
86
+ @"PostToolUse": @"PostToolUse", @"Stop": @"Stop"
87
+ }[hookEvent];
88
+ if (!event) return;
89
+ BOOL failed = StringValue(payload[@"error"]).length > 0;
90
+ if ([hookEvent isEqual:@"Stop"]) {
91
+ if ([payload[@"fullyIdle"] isEqual:@NO]) return;
92
+ NSString *reason = StringValue(payload[@"terminationReason"]);
93
+ failed = failed || [reason isEqual:@"error"] || [reason isEqual:@"max_steps_exceeded"];
94
+ if (failed) event = @"StopFailure";
95
+ }
96
+ if ([hookEvent isEqual:@"PostToolUse"] && failed) event = @"PostToolUseFailure";
97
+ NSArray *workspaces = [payload[@"workspacePaths"] isKindOfClass:NSArray.class] ? payload[@"workspacePaths"] : nil;
98
+ NSString *cwd = StringValue(payload[@"cwd"]) ?: StringValue(workspaces.firstObject);
99
+ NSDictionary *tool = [payload[@"toolCall"] isKindOfClass:NSDictionary.class] ? payload[@"toolCall"] : nil;
100
+ AppendAntigravityEvent(StringValue(payload[@"conversationId"]), cwd, event, StringValue(tool[@"name"]), failed, nil, app);
101
+ }
102
+
103
+ static NSDictionary *ReadPayload(void) {
104
+ NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
105
+ id payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
106
+ return [payload isKindOfClass:NSDictionary.class] ? payload : nil;
107
+ }
108
+
109
+ int CCPetsRecordAntigravityHook(NSString *hookEvent) {
110
+ NSDictionary *payload = ReadPayload();
111
+ NSDictionary *response = [hookEvent isEqual:@"PreToolUse"] ? @{@"decision": @"allow"}
112
+ : ([hookEvent isEqual:@"Stop"] ? @{@"decision": @"stop"} : @{});
113
+ BOOL written = NO;
114
+ // CLI 与 App 共用这一个 Hook:两边都上报会话状态,Provider 按祖先进程区分。
115
+ @try {
116
+ @try {
117
+ NSDictionary *ancestor = CCBridgeFindAgentAncestor(getppid());
118
+ BOOL cli = [ancestor[@"provider"] isEqual:CCBridgeAntigravityProvider];
119
+ BOOL app = [ancestor[@"provider"] isEqual:CCBridgeAntigravityAppProvider];
120
+ if (payload && (cli || app)) {
121
+ AppendHookEvent(hookEvent, payload, app);
122
+ response = CCBridgeHandleAntigravityHook(hookEvent, payload) ?: response;
123
+ }
124
+ } @catch (NSException *exception) {
125
+ // A monitoring failure must not block the user's Antigravity turn.
126
+ }
127
+ NSData *json = [NSJSONSerialization dataWithJSONObject:response options:0 error:nil];
128
+ if (json) {
129
+ written = fwrite(json.bytes, 1, json.length, stdout) == json.length && fputc('\n', stdout) != EOF;
130
+ written = fflush(stdout) == 0 && written && !ferror(stdout);
131
+ }
132
+ } @finally {
133
+ CCBridgeFinishAntigravityHook(written);
134
+ }
135
+ return 0;
136
+ }
137
+
138
+ int CCPetsRecordAntigravityStatusLine(void) {
139
+ @try {
140
+ NSDictionary *payload = ReadPayload();
141
+ NSString *session = CCBridgeSafeSessionId(payload[@"conversation_id"]) ?: CCBridgeSafeSessionId(payload[@"session_id"]);
142
+ NSString *state = StringValue(payload[@"agent_state"]);
143
+ id confirmation = payload[@"tool_confirmation_pending"];
144
+ if (!session || (!state.length && ![confirmation isKindOfClass:NSNumber.class])) return 0;
145
+ BOOL pending = [confirmation isEqual:@YES] || [state isEqual:@"reviewing"];
146
+ NSString *file = [CCBridgeSubdirectory(@[]) stringByAppendingPathComponent:@"agy-approvals.json"];
147
+ if (!pending && ![NSFileManager.defaultManager fileExistsAtPath:file]) return 0;
148
+
149
+ NSDictionary *ancestor = CCBridgeFindAgentAncestor(getppid());
150
+ if (![ancestor[@"provider"] isEqual:CCBridgeAntigravityProvider]) return 0;
151
+ NSNumber *owner = ancestor[@"pid"];
152
+ NSString *lock = CCBridgeAcquireLock(@"agy-approvals");
153
+ if (!lock) return 0;
154
+ @try {
155
+ id snapshot = CCBridgeReadJSON(file);
156
+ NSMutableDictionary *approvals = [snapshot isKindOfClass:NSDictionary.class] ? [snapshot mutableCopy]
157
+ : [NSMutableDictionary dictionary];
158
+ for (NSString *identifier in approvals.allKeys) {
159
+ id pid = approvals[identifier];
160
+ if (![pid isKindOfClass:NSNumber.class] || !CCBridgeProcessAlive([pid intValue])) {
161
+ [approvals removeObjectForKey:identifier];
162
+ }
163
+ }
164
+ BOOL wasPending = [approvals[session] isEqual:owner];
165
+ if (pending != wasPending) {
166
+ NSString *event = pending ? @"PermissionRequest" : @"ApprovalResolved";
167
+ NSString *eventState = pending ? @"approval" : ([state isEqual:@"idle"] ? @"idle" : @"thinking");
168
+ if (AppendAntigravityEvent(session, StringValue(payload[@"cwd"]), event, nil, NO, eventState, NO)) {
169
+ if (pending) approvals[session] = owner;
170
+ else [approvals removeObjectForKey:session];
171
+ }
172
+ }
173
+ if (approvals.count == 0) unlink(file.fileSystemRepresentation);
174
+ else if (![approvals isEqual:snapshot]) CCBridgeWriteJSON(file, approvals);
175
+ } @finally {
176
+ CCBridgeReleaseLock(lock);
177
+ }
178
+ } @catch (NSException *exception) {}
179
+ return 0;
180
+ }
@@ -0,0 +1,3 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ int CCPetsRunBridgeTitleRelay(NSArray<NSString *> *arguments);
@@ -0,0 +1,463 @@
1
+ #import "CCPetsBridgeTitleRelay.h"
2
+ #import "CCPetsBridgeTerminalTitle.h"
3
+ #import "CCPetsCLISupport.h"
4
+ #import "CCPetsTerminalFocus.h"
5
+ #import <errno.h>
6
+ #import <fcntl.h>
7
+ #import <poll.h>
8
+ #import <signal.h>
9
+ #import <sys/ioctl.h>
10
+ #import <sys/stat.h>
11
+ #import <sys/wait.h>
12
+ #import <termios.h>
13
+ #import <unistd.h>
14
+ #import <util.h>
15
+
16
+ static const NSUInteger RelayBufferLimit = 64 * 1024;
17
+ static const NSUInteger RelayTitleLimit = 4096;
18
+
19
+ typedef NS_ENUM(NSUInteger, RelayOutputState) {
20
+ RelayPlain, RelayEscape, RelayCSI, RelayEscapeIntermediate, RelayOSCCode, RelayOSCSeparator, RelayTitle,
21
+ RelayTitleEscape, RelayControlString, RelayControlEscape
22
+ };
23
+
24
+ @interface CCPetsTerminalTitleOutput : NSObject
25
+ @property RelayOutputState state;
26
+ @property BOOL oscString;
27
+ @property NSUInteger utf8Remaining;
28
+ @property NSMutableData *frame;
29
+ @property NSData *lastTitle;
30
+ @property(copy) NSString *nickname;
31
+ - (void)appendBytes:(const uint8_t *)bytes length:(NSUInteger)length to:(NSMutableData *)output;
32
+ - (void)refreshNickname:(NSString *)nickname output:(NSMutableData *)output;
33
+ - (void)flushTo:(NSMutableData *)output;
34
+ @end
35
+
36
+ static NSUInteger RemainingUTF8Bytes(const uint8_t *bytes, NSUInteger length, NSUInteger previous) {
37
+ NSUInteger continuation = 0;
38
+ while (continuation < length && (bytes[length - continuation - 1] & 0xc0) == 0x80) continuation++;
39
+ if (continuation == length) return previous > length ? previous - length : 0;
40
+ uint8_t lead = bytes[length - continuation - 1];
41
+ NSUInteger expected = 0;
42
+ if (lead >= 0xc2 && lead <= 0xdf) expected = 1;
43
+ else if (lead >= 0xe0 && lead <= 0xef) expected = 2;
44
+ else if (lead >= 0xf0 && lead <= 0xf4) expected = 3;
45
+ return expected > continuation ? expected - continuation : 0;
46
+ }
47
+
48
+ @implementation CCPetsTerminalTitleOutput
49
+
50
+ - (instancetype)init {
51
+ if ((self = [super init])) _frame = [NSMutableData data];
52
+ return self;
53
+ }
54
+
55
+ - (void)appendTitleTo:(NSMutableData *)output {
56
+ NSData *title = self.lastTitle;
57
+ if (!title) return;
58
+ const uint8_t *bytes = title.bytes;
59
+ NSUInteger terminatorLength = bytes[title.length - 1] == '\a' ? 1 : 2;
60
+ NSUInteger baseLength = title.length - terminatorLength;
61
+ if (!self.nickname.length || baseLength <= 4) {
62
+ [output appendData:title];
63
+ return;
64
+ }
65
+ static const char separator[] = " · ";
66
+ [output appendBytes:bytes length:baseLength];
67
+ [output appendBytes:separator length:sizeof(separator) - 1];
68
+ [output appendData:[self.nickname dataUsingEncoding:NSUTF8StringEncoding]];
69
+ [output appendBytes:bytes + baseLength length:terminatorLength];
70
+ }
71
+
72
+ - (void)refreshNickname:(NSString *)nickname output:(NSMutableData *)output {
73
+ if (nickname == self.nickname || [nickname isEqualToString:self.nickname]) return;
74
+ self.nickname = nickname;
75
+ // Keep the title as emitted by the child. Never append a suffix to its empty reset sequence.
76
+ if (self.lastTitle.length > 0) {
77
+ const uint8_t *bytes = self.lastTitle.bytes;
78
+ NSUInteger terminatorLength = bytes[self.lastTitle.length - 1] == '\a' ? 1 : 2;
79
+ if (self.lastTitle.length > 4 + terminatorLength) [self appendTitleTo:output];
80
+ }
81
+ }
82
+
83
+ - (void)flushTo:(NSMutableData *)output {
84
+ [output appendData:self.frame];
85
+ [self.frame setLength:0];
86
+ }
87
+
88
+ - (void)finishTitleWithByte:(uint8_t)byte output:(NSMutableData *)output {
89
+ [self.frame appendBytes:&byte length:1];
90
+ self.lastTitle = [self.frame copy];
91
+ [self appendTitleTo:output];
92
+ [self.frame setLength:0];
93
+ self.state = RelayPlain;
94
+ }
95
+
96
+ - (void)appendBytes:(const uint8_t *)bytes length:(NSUInteger)length to:(NSMutableData *)output {
97
+ for (NSUInteger index = 0; index < length;) {
98
+ uint8_t byte = bytes[index++];
99
+ switch (self.state) {
100
+ case RelayPlain: {
101
+ const uint8_t *start = bytes + index - 1;
102
+ const uint8_t *escape = memchr(start, '\033', length - index + 1);
103
+ NSUInteger run = escape ? (NSUInteger)(escape - start) : length - index + 1;
104
+ [output appendBytes:start length:run];
105
+ self.utf8Remaining = escape ? 0 : RemainingUTF8Bytes(start, run, self.utf8Remaining);
106
+ if (!escape) return;
107
+ index += run;
108
+ [self.frame appendBytes:escape length:1];
109
+ self.state = RelayEscape;
110
+ break;
111
+ }
112
+ case RelayEscape:
113
+ if (byte == ']') {
114
+ [self.frame appendBytes:&byte length:1];
115
+ self.state = RelayOSCCode;
116
+ } else {
117
+ [self flushTo:output];
118
+ if (byte == '\033') {
119
+ [self.frame appendBytes:&byte length:1];
120
+ } else {
121
+ [output appendBytes:&byte length:1];
122
+ self.oscString = NO;
123
+ if (byte == 'P' || byte == 'X' || byte == '^' || byte == '_') self.state = RelayControlString;
124
+ else if (byte == '[') self.state = RelayCSI;
125
+ else if (byte >= 0x20 && byte <= 0x2f) self.state = RelayEscapeIntermediate;
126
+ else self.state = RelayPlain;
127
+ }
128
+ }
129
+ break;
130
+ case RelayCSI:
131
+ case RelayEscapeIntermediate: {
132
+ uint8_t firstFinal = self.state == RelayCSI ? 0x40 : 0x30;
133
+ if (byte == '\033') {
134
+ [self.frame appendBytes:&byte length:1];
135
+ self.state = RelayEscape;
136
+ } else {
137
+ [output appendBytes:&byte length:1];
138
+ if ((byte >= firstFinal && byte <= 0x7e) || byte == 0x18 || byte == 0x1a) self.state = RelayPlain;
139
+ }
140
+ break;
141
+ }
142
+ case RelayOSCCode:
143
+ case RelayOSCSeparator: {
144
+ BOOL code = self.state == RelayOSCCode;
145
+ if (code ? (byte == '0' || byte == '2') : byte == ';') {
146
+ [self.frame appendBytes:&byte length:1];
147
+ self.state = code ? RelayOSCSeparator : RelayTitle;
148
+ } else {
149
+ [self flushTo:output];
150
+ [output appendBytes:&byte length:1];
151
+ self.oscString = YES;
152
+ self.state = byte == '\a' || byte == 0x18 || byte == 0x1a
153
+ ? RelayPlain : (byte == '\033' ? RelayControlEscape : RelayControlString);
154
+ }
155
+ break;
156
+ }
157
+ case RelayTitle:
158
+ if (byte == '\a') {
159
+ [self finishTitleWithByte:byte output:output];
160
+ } else if (byte == 0x18 || byte == 0x1a) {
161
+ [self flushTo:output];
162
+ [output appendBytes:&byte length:1];
163
+ self.state = RelayPlain;
164
+ } else {
165
+ [self.frame appendBytes:&byte length:1];
166
+ self.state = byte == '\033' ? RelayTitleEscape : RelayTitle;
167
+ if (self.frame.length >= RelayTitleLimit) {
168
+ [self flushTo:output];
169
+ self.lastTitle = nil;
170
+ self.oscString = YES;
171
+ self.state = byte == '\033' ? RelayControlEscape : RelayControlString;
172
+ }
173
+ }
174
+ break;
175
+ case RelayTitleEscape:
176
+ if (byte == '\\') {
177
+ [self finishTitleWithByte:byte output:output];
178
+ } else {
179
+ // An unexpected escape inside OSC cancels its rewrite. Reprocess it as a new escape.
180
+ NSUInteger prefix = self.frame.length - 1;
181
+ [output appendBytes:self.frame.bytes length:prefix];
182
+ [self.frame replaceBytesInRange:NSMakeRange(0, prefix) withBytes:NULL length:0];
183
+ self.lastTitle = nil;
184
+ self.state = RelayEscape;
185
+ index--;
186
+ }
187
+ break;
188
+ case RelayControlString:
189
+ case RelayControlEscape: {
190
+ BOOL escaped = self.state == RelayControlEscape;
191
+ [output appendBytes:&byte length:1];
192
+ if ((escaped && byte == '\\') || (self.oscString && byte == '\a') || byte == 0x18 || byte == 0x1a) {
193
+ self.state = RelayPlain;
194
+ }
195
+ else if (byte == '\033' && (!escaped || self.oscString)) self.state = RelayControlEscape;
196
+ else self.state = RelayControlString;
197
+ break;
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ @end
204
+
205
+ static const int RelaySignals[] = {SIGWINCH, SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGTSTP};
206
+ static volatile sig_atomic_t RelayResize, RelayInterrupt, RelaySuspend;
207
+
208
+ static void HandleRelaySignal(int signalNumber) {
209
+ if (signalNumber == SIGWINCH) RelayResize = 1;
210
+ else if (signalNumber == SIGTSTP) RelaySuspend = 1;
211
+ else RelayInterrupt = signalNumber;
212
+ }
213
+
214
+ static void RestoreRelaySignalActions(const struct sigaction *actions, NSUInteger count) {
215
+ for (NSUInteger index = 0; index < count; index++) sigaction(RelaySignals[index], &actions[index], NULL);
216
+ }
217
+
218
+ static int ExecRelayChild(char **arguments) {
219
+ execvp(arguments[0], arguments);
220
+ int failure = errno;
221
+ perror(arguments[0]);
222
+ return failure == ENOENT ? 127 : 126;
223
+ }
224
+
225
+ static void RegisterRelayCodexLaunch(NSString *provider, pid_t pid, NSTimeInterval launchedAt) {
226
+ if (![provider isEqual:@"Codex"]) return;
227
+ @try {
228
+ RegisterCodexLaunchForProcess(pid, NSFileManager.defaultManager.currentDirectoryPath,
229
+ TerminalFocusTargetFromEnvironment(), launchedAt);
230
+ } @catch (NSException *exception) {}
231
+ }
232
+
233
+ static int ExecWithoutRelay(char **arguments, NSString *provider) {
234
+ unsetenv("CC_PETS_BRIDGE_TITLE_TOKEN");
235
+ RegisterRelayCodexLaunch(provider, getpid(), NSDate.date.timeIntervalSince1970);
236
+ return ExecRelayChild(arguments);
237
+ }
238
+
239
+ static void SignalRelayChild(pid_t child, int signalNumber) {
240
+ if (kill(-child, signalNumber) != 0 && errno == ESRCH) kill(child, signalNumber);
241
+ }
242
+
243
+ static BOOL IsForegroundTerminal(void) {
244
+ pid_t foreground = tcgetpgrp(STDIN_FILENO);
245
+ return foreground > 0 && foreground == getpgrp();
246
+ }
247
+
248
+ static void RestoreOuterTerminal(const struct termios *settings) {
249
+ if (IsForegroundTerminal()) tcsetattr(STDIN_FILENO, TCSANOW, settings);
250
+ }
251
+
252
+ static BOOL WriteRelayData(int descriptor, NSMutableData *data) {
253
+ ssize_t written = write(descriptor, data.bytes, data.length);
254
+ if (written < 0) return errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK;
255
+ if (written > 0) [data replaceBytesInRange:NSMakeRange(0, (NSUInteger)written) withBytes:NULL length:0];
256
+ return YES;
257
+ }
258
+
259
+ static int RunRelay(char **arguments, NSString *provider, NSString *launchToken) {
260
+ struct termios original;
261
+ if (!launchToken.length || !isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO) ||
262
+ !IsForegroundTerminal() || tcgetattr(STDIN_FILENO, &original) != 0) return ExecWithoutRelay(arguments, provider);
263
+
264
+ struct stat inputStat, outputStat;
265
+ if (fstat(STDIN_FILENO, &inputStat) != 0 || fstat(STDOUT_FILENO, &outputStat) != 0 ||
266
+ inputStat.st_rdev != outputStat.st_rdev) return ExecWithoutRelay(arguments, provider);
267
+ // A separately opened descriptor doesn't change O_NONBLOCK for the invoking shell or its jobs.
268
+ const char *terminalPath = ttyname(STDOUT_FILENO);
269
+ int outerOutput = terminalPath ? open(terminalPath, O_WRONLY | O_NOCTTY | O_CLOEXEC | O_NONBLOCK) : -1;
270
+ if (outerOutput < 0) return ExecWithoutRelay(arguments, provider);
271
+ // forkpty joins all three descriptors to the PTY. Keep a separate stderr redirection intact.
272
+ BOOL relayStderr = isatty(STDERR_FILENO) && fstat(STDERR_FILENO, &outputStat) == 0 &&
273
+ inputStat.st_rdev == outputStat.st_rdev;
274
+ int savedStderr = relayStderr ? -1 : fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 3);
275
+ int launchGate[2];
276
+ if ((!relayStderr && savedStderr < 0) || pipe(launchGate) != 0) {
277
+ if (savedStderr >= 0) close(savedStderr);
278
+ close(outerOutput);
279
+ return ExecWithoutRelay(arguments, provider);
280
+ }
281
+ struct termios raw = original;
282
+ cfmakeraw(&raw);
283
+ struct winsize size = {0};
284
+ ioctl(STDIN_FILENO, TIOCGWINSZ, &size);
285
+
286
+ RelayResize = RelayInterrupt = RelaySuspend = 0;
287
+ struct sigaction action = {0};
288
+ struct sigaction previous[sizeof(RelaySignals) / sizeof(*RelaySignals)];
289
+ action.sa_handler = HandleRelaySignal;
290
+ sigemptyset(&action.sa_mask);
291
+ NSUInteger actionCount = 0;
292
+ while (actionCount < sizeof(RelaySignals) / sizeof(*RelaySignals) &&
293
+ sigaction(RelaySignals[actionCount], &action, &previous[actionCount]) == 0) actionCount++;
294
+ if (actionCount != sizeof(RelaySignals) / sizeof(*RelaySignals) || tcsetattr(STDIN_FILENO, TCSANOW, &raw) != 0) {
295
+ close(launchGate[0]);
296
+ close(launchGate[1]);
297
+ if (savedStderr >= 0) close(savedStderr);
298
+ close(outerOutput);
299
+ RestoreRelaySignalActions(previous, actionCount);
300
+ return ExecWithoutRelay(arguments, provider);
301
+ }
302
+
303
+ int master = -1;
304
+ NSTimeInterval launchedAt = NSDate.date.timeIntervalSince1970;
305
+ pid_t child = forkpty(&master, NULL, &original, &size);
306
+ if (child == 0) {
307
+ close(launchGate[1]);
308
+ RestoreRelaySignalActions(previous, actionCount);
309
+ char unused;
310
+ while (read(launchGate[0], &unused, 1) < 0 && errno == EINTR) {}
311
+ close(launchGate[0]);
312
+ if (savedStderr >= 0) {
313
+ if (dup2(savedStderr, STDERR_FILENO) < 0) _exit(126);
314
+ close(savedStderr);
315
+ }
316
+ _exit(ExecRelayChild(arguments));
317
+ }
318
+ close(launchGate[0]);
319
+ if (savedStderr >= 0) close(savedStderr);
320
+ // Register the actual child PID before a shared Codex host can emit SessionStart.
321
+ if (child > 0) RegisterRelayCodexLaunch(provider, child, launchedAt);
322
+ close(launchGate[1]);
323
+ if (child < 0) {
324
+ close(outerOutput);
325
+ RestoreOuterTerminal(&original);
326
+ RestoreRelaySignalActions(previous, actionCount);
327
+ return ExecWithoutRelay(arguments, provider);
328
+ }
329
+
330
+ BOOL exited = NO;
331
+ int completion = 0;
332
+ @try {
333
+ fcntl(master, F_SETFD, FD_CLOEXEC);
334
+ int masterFlags = fcntl(master, F_GETFL);
335
+ if (masterFlags < 0 || fcntl(master, F_SETFL, masterFlags | O_NONBLOCK) != 0) return 1;
336
+ CCPetsTerminalTitleOutput *parser = [CCPetsTerminalTitleOutput new];
337
+ NSMutableData *pendingInput = [NSMutableData data];
338
+ NSMutableData *pendingOutput = [NSMutableData data];
339
+ BOOL masterOpen = YES;
340
+ NSTimeInterval nicknameRefresh = 0, stopDeadline = 0, drainDeadline = 0;
341
+ while (!exited || masterOpen || pendingOutput.length > 0) {
342
+ @autoreleasepool {
343
+ NSTimeInterval now = NSProcessInfo.processInfo.systemUptime;
344
+ BOOL childStopped = NO;
345
+ if (!exited) {
346
+ int status = 0;
347
+ if (waitpid(child, &status, WNOHANG | WUNTRACED) == child) {
348
+ if (WIFSTOPPED(status)) childStopped = YES;
349
+ else {
350
+ completion = status;
351
+ exited = YES;
352
+ drainDeadline = now + 0.5;
353
+ }
354
+ }
355
+ }
356
+ if ((RelaySuspend || childStopped) && !exited && !RelayInterrupt && !stopDeadline) {
357
+ RelaySuspend = 0;
358
+ if (!childStopped) SignalRelayChild(child, SIGSTOP);
359
+ RestoreOuterTerminal(&original);
360
+ do { raise(SIGSTOP); } while (!IsForegroundTerminal() && !RelayInterrupt);
361
+ if (!RelayInterrupt) {
362
+ tcsetattr(STDIN_FILENO, TCSANOW, &raw);
363
+ SignalRelayChild(child, SIGCONT);
364
+ RelayResize = 1;
365
+ }
366
+ }
367
+ if (RelayResize) {
368
+ RelayResize = 0;
369
+ if (masterOpen && ioctl(STDIN_FILENO, TIOCGWINSZ, &size) == 0) ioctl(master, TIOCSWINSZ, &size);
370
+ }
371
+ if (RelayInterrupt) {
372
+ int signalNumber = RelayInterrupt;
373
+ RelayInterrupt = 0;
374
+ if (!exited) {
375
+ SignalRelayChild(child, signalNumber);
376
+ if (signalNumber != SIGINT || !IsForegroundTerminal()) stopDeadline = now + 2;
377
+ }
378
+ }
379
+ if (stopDeadline && now >= stopDeadline && !exited) SignalRelayChild(child, SIGKILL);
380
+ if (masterOpen && !exited && now >= nicknameRefresh && pendingOutput.length < RelayBufferLimit &&
381
+ parser.state == RelayPlain && parser.utf8Remaining == 0) {
382
+ @try {
383
+ NSString *name = CCBridgeTerminalTitleName(provider, launchToken, child);
384
+ NSString *nickname = name.length > 0 ? CCBridgeComposeTerminalTitle(nil, name) : nil;
385
+ [parser refreshNickname:nickname output:pendingOutput];
386
+ } @catch (NSException *exception) {}
387
+ nicknameRefresh = now + 0.25;
388
+ }
389
+
390
+ BOOL readInput = !exited && masterOpen && !stopDeadline && pendingInput.length < RelayBufferLimit;
391
+ BOOL readOutput = masterOpen && pendingOutput.length < RelayBufferLimit;
392
+ struct pollfd descriptors[] = {
393
+ {.fd = readInput ? STDIN_FILENO : -1, .events = POLLIN},
394
+ {.fd = masterOpen ? master : -1, .events = (readOutput ? POLLIN : 0) | (pendingInput.length > 0 ? POLLOUT : 0)},
395
+ {.fd = pendingOutput.length > 0 ? outerOutput : -1, .events = POLLOUT}
396
+ };
397
+ int ready = poll(descriptors, 3, 100);
398
+ if (ready < 0) {
399
+ if (errno == EINTR) continue;
400
+ return 1;
401
+ }
402
+ if (!ready && masterOpen && exited && pendingOutput.length == 0 && now >= drainDeadline) {
403
+ masterOpen = NO;
404
+ [parser flushTo:pendingOutput];
405
+ }
406
+ uint8_t bytes[8192];
407
+ if (descriptors[0].revents) {
408
+ ssize_t length = read(STDIN_FILENO, bytes, sizeof(bytes));
409
+ if (length > 0) [pendingInput appendBytes:bytes length:(NSUInteger)length];
410
+ else if (length == 0 || (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
411
+ SignalRelayChild(child, SIGHUP);
412
+ stopDeadline = now + 2;
413
+ }
414
+ }
415
+ if (descriptors[1].revents & POLLOUT && pendingInput.length > 0 && !WriteRelayData(master, pendingInput)) {
416
+ [pendingInput setLength:0];
417
+ }
418
+ if (readOutput && (descriptors[1].revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL))) {
419
+ ssize_t length = read(master, bytes, sizeof(bytes));
420
+ if (length > 0) {
421
+ [parser appendBytes:bytes length:(NSUInteger)length to:pendingOutput];
422
+ if (exited) drainDeadline = now + 0.5;
423
+ }
424
+ else if (length == 0 || (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
425
+ masterOpen = NO;
426
+ [parser flushTo:pendingOutput];
427
+ if (!exited && !stopDeadline) stopDeadline = now + 2;
428
+ }
429
+ }
430
+ if (descriptors[2].revents && pendingOutput.length > 0 && !WriteRelayData(outerOutput, pendingOutput)) return 1;
431
+ }
432
+ }
433
+ return WIFSIGNALED(completion) ? 128 + WTERMSIG(completion) : WEXITSTATUS(completion);
434
+ } @finally {
435
+ RestoreOuterTerminal(&original);
436
+ close(outerOutput);
437
+ close(master);
438
+ if (!exited) {
439
+ SignalRelayChild(child, SIGKILL);
440
+ while (waitpid(child, NULL, 0) < 0 && errno == EINTR) {}
441
+ }
442
+ RestoreRelaySignalActions(previous, actionCount);
443
+ @try { CCBridgeClearTerminalTitleBinding(launchToken); } @catch (NSException *exception) {}
444
+ }
445
+ }
446
+
447
+ int CCPetsRunBridgeTitleRelay(NSArray<NSString *> *arguments) {
448
+ if (arguments.count < 2 || ![@[@"Codex", @"Claude"] containsObject:arguments.firstObject]) return 2;
449
+ // Build argv before forkpty; its child must not call Foundation between fork and exec.
450
+ char **childArguments = calloc(arguments.count, sizeof(*childArguments));
451
+ if (!childArguments) return 1;
452
+ @try {
453
+ for (NSUInteger index = 1; index < arguments.count; index++) {
454
+ const char *argument = arguments[index].UTF8String;
455
+ childArguments[index - 1] = argument ? strdup(argument) : NULL;
456
+ if (!childArguments[index - 1]) return 1;
457
+ }
458
+ return RunRelay(childArguments, arguments.firstObject, CCPetsEnvironmentValue(@"CC_PETS_BRIDGE_TITLE_TOKEN"));
459
+ } @finally {
460
+ for (NSUInteger index = 0; index + 1 < arguments.count; index++) free(childArguments[index]);
461
+ free(childArguments);
462
+ }
463
+ }
@@ -2,6 +2,11 @@
2
2
 
3
3
  // Agent 事件的记录与状态归一化,同时是 --hook / --provider-event 两个子命令的实现。
4
4
  NSString *SanitizedShortString(id value, NSUInteger maximumLength);
5
+ // 账号 ID 是标识符而非展示文字:保留冒号,并修复旧事件中 provider:hash 丢失冒号的格式。
6
+ NSString *NormalizedAgentProfileID(id value);
7
+ NSString *SanitizedWorkingDirectory(id value);
8
+ // 状态卡标题里的会话标签:优先 CC Bridge 短名,其次目录名;过长时保留末尾的动物后缀。
9
+ NSString *StatusSessionLabel(NSString *bridgeName, NSString *cwd);
5
10
  NSString *ProviderFromEnvironment(void);
6
11
  NSString *NormalizedStateForEvent(NSString *event, BOOL failed);
7
12
  // 在线会话的 key:provider + 账号 + tty。同一个终端先后跑过两个账号时,只看 provider + tty