chatccc 0.2.231 → 0.2.232

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 (127) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -86
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +449 -393
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +319 -202
  28. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  29. package/src/__tests__/builtin-permissions.test.ts +211 -211
  30. package/src/__tests__/builtin-session-search.test.ts +228 -0
  31. package/src/__tests__/builtin-session-select.test.ts +116 -116
  32. package/src/__tests__/builtin-sigint.test.ts +56 -56
  33. package/src/__tests__/builtin-skills.test.ts +284 -284
  34. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  35. package/src/__tests__/card-action-routing.test.ts +18 -18
  36. package/src/__tests__/cardkit.test.ts +60 -60
  37. package/src/__tests__/ccc-adapter.test.ts +170 -170
  38. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  39. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  40. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  41. package/src/__tests__/claude-adapter.test.ts +614 -614
  42. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  43. package/src/__tests__/codex-adapter.test.ts +58 -58
  44. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  45. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  46. package/src/__tests__/cursor-adapter.test.ts +268 -268
  47. package/src/__tests__/feishu-api.test.ts +60 -60
  48. package/src/__tests__/feishu-avatar.test.ts +164 -164
  49. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  50. package/src/__tests__/feishu-platform.test.ts +22 -22
  51. package/src/__tests__/format-message.test.ts +47 -47
  52. package/src/__tests__/jsonl-stream.test.ts +79 -79
  53. package/src/__tests__/package-files.test.ts +24 -24
  54. package/src/__tests__/privacy.test.ts +198 -198
  55. package/src/__tests__/progress-reducer.test.ts +121 -121
  56. package/src/__tests__/raw-stream-log.test.ts +106 -106
  57. package/src/__tests__/response-stall.test.ts +49 -49
  58. package/src/__tests__/restart.test.ts +132 -132
  59. package/src/__tests__/session.test.ts +199 -199
  60. package/src/__tests__/shared-prefix.test.ts +36 -36
  61. package/src/__tests__/sim-platform.test.ts +16 -16
  62. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  63. package/src/__tests__/stop-session.test.ts +34 -34
  64. package/src/__tests__/stream-state.test.ts +42 -42
  65. package/src/__tests__/terminal-error.test.ts +54 -54
  66. package/src/__tests__/terminal-renderer.test.ts +247 -247
  67. package/src/__tests__/update-command-guard.test.ts +144 -144
  68. package/src/__tests__/web-ui.test.ts +326 -326
  69. package/src/adapters/adapter-interface.ts +33 -33
  70. package/src/adapters/ccc-adapter.ts +141 -141
  71. package/src/adapters/claude-adapter.ts +620 -620
  72. package/src/adapters/claude-session-meta-store.ts +120 -120
  73. package/src/adapters/codex-adapter.ts +426 -426
  74. package/src/adapters/cursor-adapter.ts +681 -681
  75. package/src/adapters/jsonl-stream.ts +157 -157
  76. package/src/adapters/raw-stream-log.ts +124 -124
  77. package/src/adapters/resource-monitor.ts +140 -140
  78. package/src/agent-activity.ts +175 -175
  79. package/src/agent-delegate-task-rpc.ts +153 -153
  80. package/src/agent-delegate-task.ts +91 -91
  81. package/src/agent-reload-config-rpc.ts +34 -34
  82. package/src/agent-stop-stuck.ts +129 -129
  83. package/src/builtin/cli.ts +6 -0
  84. package/src/builtin/config.ts +84 -84
  85. package/src/builtin/context.ts +465 -391
  86. package/src/builtin/file-log.ts +38 -38
  87. package/src/builtin/file-tools.ts +34 -0
  88. package/src/builtin/index.ts +24 -23
  89. package/src/builtin/proc-tree-kill.ts +61 -61
  90. package/src/builtin/progress/cards-helpers.ts +76 -76
  91. package/src/builtin/progress/reducer.ts +113 -113
  92. package/src/builtin/progress/terminal-renderer.ts +294 -294
  93. package/src/builtin/progress/view.ts +77 -77
  94. package/src/builtin/raw-stream-log.ts +124 -124
  95. package/src/builtin/session-search.ts +363 -0
  96. package/src/builtin/session-select.ts +48 -48
  97. package/src/builtin/sigint.ts +50 -50
  98. package/src/builtin/skills.ts +205 -205
  99. package/src/builtin/web-tools.ts +313 -313
  100. package/src/card-action-routing.ts +14 -14
  101. package/src/chatgpt-subscription-rpc.ts +27 -27
  102. package/src/chatgpt-subscription.ts +299 -299
  103. package/src/chrome-devtools-guard.ts +318 -318
  104. package/src/codex-reset-actions.ts +184 -184
  105. package/src/feishu-api.ts +193 -193
  106. package/src/feishu-message-ingress.ts +195 -195
  107. package/src/feishu-platform.ts +20 -20
  108. package/src/format-message.ts +293 -293
  109. package/src/litellm-proxy.ts +374 -374
  110. package/src/orchestrator.ts +2494 -2494
  111. package/src/platform-adapter.ts +6 -6
  112. package/src/privacy.ts +118 -118
  113. package/src/progress/reducer.ts +113 -113
  114. package/src/progress/terminal-renderer.ts +294 -294
  115. package/src/progress/view.ts +77 -77
  116. package/src/response-stall.ts +28 -28
  117. package/src/runtime-reload.ts +34 -34
  118. package/src/session-chat-binding.ts +82 -82
  119. package/src/session-name.ts +8 -8
  120. package/src/session.ts +201 -201
  121. package/src/shared-prefix.ts +29 -29
  122. package/src/sim-platform.ts +20 -20
  123. package/src/startup-lifecycle.ts +250 -250
  124. package/src/stream-state.ts +21 -21
  125. package/src/terminal-error.ts +129 -129
  126. package/src/turn-cards.ts +117 -117
  127. package/src/update-command-guard.ts +165 -165
@@ -1,318 +1,318 @@
1
- import { spawn, type ChildProcess } from "node:child_process";
2
- import { existsSync, mkdirSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- import { appendStartupTrace } from "./shared.ts";
6
- import { config, ts, USER_DATA_DIR, type ChromeDevtoolsConfig } from "./config.ts";
7
-
8
- const CDP_HOST = "127.0.0.1";
9
- const DEFAULT_CDP_PORT = 15166;
10
- const HEALTH_TIMEOUT_MS = 3000;
11
- const START_VERIFY_ATTEMPTS = 10;
12
- const START_VERIFY_DELAY_MS = 500;
13
- const GUARD_INTERVAL_MS = 60_000;
14
-
15
- type FetchLike = typeof fetch;
16
-
17
- export interface ChromeDevtoolsGuardDeps {
18
- fetchImpl?: FetchLike;
19
- spawnImpl?: typeof spawn;
20
- existsSyncImpl?: typeof existsSync;
21
- mkdirSyncImpl?: typeof mkdirSync;
22
- platform?: NodeJS.Platform;
23
- env?: NodeJS.ProcessEnv;
24
- log?: (message: string) => void;
25
- }
26
-
27
- export interface ChromeCdpEnsureResult {
28
- ok: boolean;
29
- started: boolean;
30
- port: number;
31
- error?: string;
32
- }
33
-
34
- export type ChromeCdpProbeStatus = "healthy" | "occupied" | "unreachable";
35
-
36
- interface ChromeCdpPage {
37
- id?: string;
38
- type?: string;
39
- url?: string;
40
- }
41
-
42
- export interface EnsureChatcccPageResult {
43
- ok: boolean;
44
- opened: boolean;
45
- error?: string;
46
- }
47
-
48
- let guardTimer: ReturnType<typeof setInterval> | null = null;
49
- let ensureInFlight: Promise<ChromeCdpEnsureResult> | null = null;
50
-
51
- function normalizePort(value: unknown): number {
52
- const port = Number(value);
53
- return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
54
- }
55
-
56
- function chromeCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
57
- if (platform === "win32") {
58
- return [
59
- env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
60
- env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"]!, "Google", "Chrome", "Application", "chrome.exe") : "",
61
- env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
62
- ].filter(Boolean);
63
- }
64
-
65
- if (platform === "darwin") {
66
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
67
- }
68
-
69
- return [
70
- "/usr/bin/google-chrome",
71
- "/usr/bin/google-chrome-stable",
72
- "/usr/bin/chromium",
73
- "/usr/bin/chromium-browser",
74
- ];
75
- }
76
-
77
- export function resolveChromeExecutable(
78
- chromePath: string | undefined,
79
- deps: Pick<ChromeDevtoolsGuardDeps, "existsSyncImpl" | "platform" | "env"> = {},
80
- ): string | null {
81
- const exists = deps.existsSyncImpl ?? existsSync;
82
- const explicit = chromePath?.trim();
83
- if (explicit) return exists(explicit) ? explicit : null;
84
-
85
- for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
86
- if (exists(candidate)) return candidate;
87
- }
88
- return null;
89
- }
90
-
91
- export function resolveChromeUserDataDir(port: number, env: NodeJS.ProcessEnv = process.env): string {
92
- const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
93
- return join(root, `chrome-cdp-${port}`);
94
- }
95
-
96
- async function fetchWithTimeout(url: string, fetchImpl: FetchLike, timeoutMs: number, init: RequestInit = {}): Promise<Response> {
97
- const controller = new AbortController();
98
- const timer = setTimeout(() => controller.abort(), timeoutMs);
99
- try {
100
- return await fetchImpl(url, { ...init, signal: controller.signal });
101
- } finally {
102
- clearTimeout(timer);
103
- }
104
- }
105
-
106
- export async function probeChromeCdp(
107
- port: number,
108
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
109
- ): Promise<ChromeCdpProbeStatus> {
110
- const normalizedPort = normalizePort(port);
111
- try {
112
- const response = await fetchWithTimeout(
113
- `http://${CDP_HOST}:${normalizedPort}/json/version`,
114
- deps.fetchImpl ?? fetch,
115
- HEALTH_TIMEOUT_MS,
116
- );
117
- if (!response.ok) return "occupied";
118
- const data = await response.json() as Record<string, unknown>;
119
- return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
120
- ? "healthy"
121
- : "occupied";
122
- } catch {
123
- return "unreachable";
124
- }
125
- }
126
-
127
- export async function isChromeCdpHealthy(
128
- port: number,
129
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
130
- ): Promise<boolean> {
131
- return (await probeChromeCdp(port, deps)) === "healthy";
132
- }
133
-
134
- function startChromeForCdp(
135
- cfg: ChromeDevtoolsConfig,
136
- deps: ChromeDevtoolsGuardDeps = {},
137
- ): { ok: true; child: ChildProcess } | { ok: false; error: string } {
138
- const port = normalizePort(cfg.port);
139
- const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
140
- if (!chromeExe) {
141
- return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
142
- }
143
-
144
- const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
145
- try {
146
- (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
147
- } catch (err) {
148
- return { ok: false, error: `Cannot create Chrome user data dir: ${(err as Error).message}` };
149
- }
150
-
151
- const args = [
152
- `--remote-debugging-address=${CDP_HOST}`,
153
- `--remote-debugging-port=${port}`,
154
- `--user-data-dir=${userDataDir}`,
155
- "--no-first-run",
156
- "--no-default-browser-check",
157
- "--new-window",
158
- "about:blank",
159
- ];
160
-
161
- try {
162
- const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
163
- detached: true,
164
- stdio: "ignore",
165
- windowsHide: true,
166
- });
167
- child.unref();
168
- return { ok: true, child };
169
- } catch (err) {
170
- return { ok: false, error: `Failed to start Chrome: ${(err as Error).message}` };
171
- }
172
- }
173
-
174
- function sleep(ms: number): Promise<void> {
175
- return new Promise((resolve) => setTimeout(resolve, ms));
176
- }
177
-
178
- function cdpBaseUrl(port: number): string {
179
- return `http://${CDP_HOST}:${port}`;
180
- }
181
-
182
- function isChatcccPageUrl(value: string | undefined, chatcccPort: number): boolean {
183
- if (!value) return false;
184
- try {
185
- const url = new URL(value);
186
- return url.protocol === "http:" &&
187
- (url.hostname === "localhost" || url.hostname === CDP_HOST) &&
188
- url.port === String(chatcccPort);
189
- } catch {
190
- return false;
191
- }
192
- }
193
-
194
- export async function ensureChatcccPageOpen(
195
- cdpPort: number,
196
- chatcccPort: number,
197
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
198
- ): Promise<EnsureChatcccPageResult> {
199
- const normalizedCdpPort = normalizePort(cdpPort);
200
- const normalizedChatcccPort = normalizePort(chatcccPort);
201
- const fetchImpl = deps.fetchImpl ?? fetch;
202
-
203
- try {
204
- const listResponse = await fetchWithTimeout(
205
- `${cdpBaseUrl(normalizedCdpPort)}/json/list`,
206
- fetchImpl,
207
- HEALTH_TIMEOUT_MS,
208
- );
209
- if (!listResponse.ok) {
210
- return { ok: false, opened: false, error: `Cannot list Chrome CDP pages: HTTP ${listResponse.status}` };
211
- }
212
- const pages = await listResponse.json() as unknown;
213
- if (Array.isArray(pages) && pages.some((page: ChromeCdpPage) => isChatcccPageUrl(page?.url, normalizedChatcccPort))) {
214
- return { ok: true, opened: false };
215
- }
216
-
217
- const targetUrl = `http://localhost:${normalizedChatcccPort}/`;
218
- const openResponse = await fetchWithTimeout(
219
- `${cdpBaseUrl(normalizedCdpPort)}/json/new?${encodeURIComponent(targetUrl)}`,
220
- fetchImpl,
221
- HEALTH_TIMEOUT_MS,
222
- { method: "PUT" },
223
- );
224
- if (!openResponse.ok) {
225
- return { ok: false, opened: false, error: `Cannot open ${targetUrl}: HTTP ${openResponse.status}` };
226
- }
227
- return { ok: true, opened: true };
228
- } catch (err) {
229
- return { ok: false, opened: false, error: (err as Error).message };
230
- }
231
- }
232
-
233
- export async function ensureChromeCdpRunning(
234
- cfg: ChromeDevtoolsConfig = config.chromeDevtools,
235
- deps: ChromeDevtoolsGuardDeps = {},
236
- ): Promise<ChromeCdpEnsureResult> {
237
- const port = normalizePort(cfg.port);
238
- if (!cfg.enabled) return { ok: true, started: false, port };
239
-
240
- const probe = await probeChromeCdp(port, deps);
241
- if (probe === "healthy") {
242
- return { ok: true, started: false, port };
243
- }
244
- if (probe === "occupied") {
245
- return {
246
- ok: false,
247
- started: false,
248
- port,
249
- error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
250
- };
251
- }
252
-
253
- const started = startChromeForCdp({ ...cfg, port }, deps);
254
- if (!started.ok) return { ok: false, started: false, port, error: started.error };
255
-
256
- for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
257
- await sleep(START_VERIFY_DELAY_MS);
258
- if (await isChromeCdpHealthy(port, deps)) {
259
- return { ok: true, started: true, port };
260
- }
261
- }
262
-
263
- return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
264
- }
265
-
266
- async function runGuardOnce(reason: string, deps: ChromeDevtoolsGuardDeps = {}): Promise<void> {
267
- if (ensureInFlight) return;
268
- const log = deps.log ?? ((message: string) => console.log(message));
269
- ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
270
- try {
271
- const result = await ensureInFlight;
272
- const chatcccPage = config.chromeDevtools.enabled && result.ok
273
- ? await ensureChatcccPageOpen(result.port, config.port, deps)
274
- : null;
275
- appendStartupTrace("chrome-devtools-guard: ensure result", {
276
- reason,
277
- enabled: config.chromeDevtools.enabled,
278
- port: result.port,
279
- ok: result.ok,
280
- started: result.started,
281
- error: result.error,
282
- chatcccPage,
283
- });
284
- if (!config.chromeDevtools.enabled) return;
285
- if (result.ok && result.started) {
286
- log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
287
- } else if (!result.ok) {
288
- log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
289
- }
290
- if (chatcccPage?.opened) {
291
- log(`[${ts()}] [Chrome CDP] Opened ChatCCC page http://localhost:${config.port}/`);
292
- } else if (chatcccPage && !chatcccPage.ok) {
293
- log(`[${ts()}] [Chrome CDP] Failed to ensure ChatCCC page: ${chatcccPage.error}`);
294
- }
295
- } finally {
296
- ensureInFlight = null;
297
- }
298
- }
299
-
300
- export function startChromeDevtoolsGuard(deps: ChromeDevtoolsGuardDeps = {}): void {
301
- stopChromeDevtoolsGuard();
302
- if (!config.chromeDevtools.enabled) {
303
- appendStartupTrace("chrome-devtools-guard: disabled");
304
- return;
305
- }
306
-
307
- void runGuardOnce("startup", deps);
308
- guardTimer = setInterval(() => {
309
- void runGuardOnce("interval", deps);
310
- }, GUARD_INTERVAL_MS);
311
- }
312
-
313
- export function stopChromeDevtoolsGuard(): void {
314
- if (guardTimer) {
315
- clearInterval(guardTimer);
316
- guardTimer = null;
317
- }
318
- }
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ import { appendStartupTrace } from "./shared.ts";
6
+ import { config, ts, USER_DATA_DIR, type ChromeDevtoolsConfig } from "./config.ts";
7
+
8
+ const CDP_HOST = "127.0.0.1";
9
+ const DEFAULT_CDP_PORT = 15166;
10
+ const HEALTH_TIMEOUT_MS = 3000;
11
+ const START_VERIFY_ATTEMPTS = 10;
12
+ const START_VERIFY_DELAY_MS = 500;
13
+ const GUARD_INTERVAL_MS = 60_000;
14
+
15
+ type FetchLike = typeof fetch;
16
+
17
+ export interface ChromeDevtoolsGuardDeps {
18
+ fetchImpl?: FetchLike;
19
+ spawnImpl?: typeof spawn;
20
+ existsSyncImpl?: typeof existsSync;
21
+ mkdirSyncImpl?: typeof mkdirSync;
22
+ platform?: NodeJS.Platform;
23
+ env?: NodeJS.ProcessEnv;
24
+ log?: (message: string) => void;
25
+ }
26
+
27
+ export interface ChromeCdpEnsureResult {
28
+ ok: boolean;
29
+ started: boolean;
30
+ port: number;
31
+ error?: string;
32
+ }
33
+
34
+ export type ChromeCdpProbeStatus = "healthy" | "occupied" | "unreachable";
35
+
36
+ interface ChromeCdpPage {
37
+ id?: string;
38
+ type?: string;
39
+ url?: string;
40
+ }
41
+
42
+ export interface EnsureChatcccPageResult {
43
+ ok: boolean;
44
+ opened: boolean;
45
+ error?: string;
46
+ }
47
+
48
+ let guardTimer: ReturnType<typeof setInterval> | null = null;
49
+ let ensureInFlight: Promise<ChromeCdpEnsureResult> | null = null;
50
+
51
+ function normalizePort(value: unknown): number {
52
+ const port = Number(value);
53
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
54
+ }
55
+
56
+ function chromeCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
57
+ if (platform === "win32") {
58
+ return [
59
+ env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
60
+ env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"]!, "Google", "Chrome", "Application", "chrome.exe") : "",
61
+ env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
62
+ ].filter(Boolean);
63
+ }
64
+
65
+ if (platform === "darwin") {
66
+ return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
67
+ }
68
+
69
+ return [
70
+ "/usr/bin/google-chrome",
71
+ "/usr/bin/google-chrome-stable",
72
+ "/usr/bin/chromium",
73
+ "/usr/bin/chromium-browser",
74
+ ];
75
+ }
76
+
77
+ export function resolveChromeExecutable(
78
+ chromePath: string | undefined,
79
+ deps: Pick<ChromeDevtoolsGuardDeps, "existsSyncImpl" | "platform" | "env"> = {},
80
+ ): string | null {
81
+ const exists = deps.existsSyncImpl ?? existsSync;
82
+ const explicit = chromePath?.trim();
83
+ if (explicit) return exists(explicit) ? explicit : null;
84
+
85
+ for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
86
+ if (exists(candidate)) return candidate;
87
+ }
88
+ return null;
89
+ }
90
+
91
+ export function resolveChromeUserDataDir(port: number, env: NodeJS.ProcessEnv = process.env): string {
92
+ const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
93
+ return join(root, `chrome-cdp-${port}`);
94
+ }
95
+
96
+ async function fetchWithTimeout(url: string, fetchImpl: FetchLike, timeoutMs: number, init: RequestInit = {}): Promise<Response> {
97
+ const controller = new AbortController();
98
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
99
+ try {
100
+ return await fetchImpl(url, { ...init, signal: controller.signal });
101
+ } finally {
102
+ clearTimeout(timer);
103
+ }
104
+ }
105
+
106
+ export async function probeChromeCdp(
107
+ port: number,
108
+ deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
109
+ ): Promise<ChromeCdpProbeStatus> {
110
+ const normalizedPort = normalizePort(port);
111
+ try {
112
+ const response = await fetchWithTimeout(
113
+ `http://${CDP_HOST}:${normalizedPort}/json/version`,
114
+ deps.fetchImpl ?? fetch,
115
+ HEALTH_TIMEOUT_MS,
116
+ );
117
+ if (!response.ok) return "occupied";
118
+ const data = await response.json() as Record<string, unknown>;
119
+ return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
120
+ ? "healthy"
121
+ : "occupied";
122
+ } catch {
123
+ return "unreachable";
124
+ }
125
+ }
126
+
127
+ export async function isChromeCdpHealthy(
128
+ port: number,
129
+ deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
130
+ ): Promise<boolean> {
131
+ return (await probeChromeCdp(port, deps)) === "healthy";
132
+ }
133
+
134
+ function startChromeForCdp(
135
+ cfg: ChromeDevtoolsConfig,
136
+ deps: ChromeDevtoolsGuardDeps = {},
137
+ ): { ok: true; child: ChildProcess } | { ok: false; error: string } {
138
+ const port = normalizePort(cfg.port);
139
+ const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
140
+ if (!chromeExe) {
141
+ return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
142
+ }
143
+
144
+ const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
145
+ try {
146
+ (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
147
+ } catch (err) {
148
+ return { ok: false, error: `Cannot create Chrome user data dir: ${(err as Error).message}` };
149
+ }
150
+
151
+ const args = [
152
+ `--remote-debugging-address=${CDP_HOST}`,
153
+ `--remote-debugging-port=${port}`,
154
+ `--user-data-dir=${userDataDir}`,
155
+ "--no-first-run",
156
+ "--no-default-browser-check",
157
+ "--new-window",
158
+ "about:blank",
159
+ ];
160
+
161
+ try {
162
+ const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
163
+ detached: true,
164
+ stdio: "ignore",
165
+ windowsHide: true,
166
+ });
167
+ child.unref();
168
+ return { ok: true, child };
169
+ } catch (err) {
170
+ return { ok: false, error: `Failed to start Chrome: ${(err as Error).message}` };
171
+ }
172
+ }
173
+
174
+ function sleep(ms: number): Promise<void> {
175
+ return new Promise((resolve) => setTimeout(resolve, ms));
176
+ }
177
+
178
+ function cdpBaseUrl(port: number): string {
179
+ return `http://${CDP_HOST}:${port}`;
180
+ }
181
+
182
+ function isChatcccPageUrl(value: string | undefined, chatcccPort: number): boolean {
183
+ if (!value) return false;
184
+ try {
185
+ const url = new URL(value);
186
+ return url.protocol === "http:" &&
187
+ (url.hostname === "localhost" || url.hostname === CDP_HOST) &&
188
+ url.port === String(chatcccPort);
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+
194
+ export async function ensureChatcccPageOpen(
195
+ cdpPort: number,
196
+ chatcccPort: number,
197
+ deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
198
+ ): Promise<EnsureChatcccPageResult> {
199
+ const normalizedCdpPort = normalizePort(cdpPort);
200
+ const normalizedChatcccPort = normalizePort(chatcccPort);
201
+ const fetchImpl = deps.fetchImpl ?? fetch;
202
+
203
+ try {
204
+ const listResponse = await fetchWithTimeout(
205
+ `${cdpBaseUrl(normalizedCdpPort)}/json/list`,
206
+ fetchImpl,
207
+ HEALTH_TIMEOUT_MS,
208
+ );
209
+ if (!listResponse.ok) {
210
+ return { ok: false, opened: false, error: `Cannot list Chrome CDP pages: HTTP ${listResponse.status}` };
211
+ }
212
+ const pages = await listResponse.json() as unknown;
213
+ if (Array.isArray(pages) && pages.some((page: ChromeCdpPage) => isChatcccPageUrl(page?.url, normalizedChatcccPort))) {
214
+ return { ok: true, opened: false };
215
+ }
216
+
217
+ const targetUrl = `http://localhost:${normalizedChatcccPort}/`;
218
+ const openResponse = await fetchWithTimeout(
219
+ `${cdpBaseUrl(normalizedCdpPort)}/json/new?${encodeURIComponent(targetUrl)}`,
220
+ fetchImpl,
221
+ HEALTH_TIMEOUT_MS,
222
+ { method: "PUT" },
223
+ );
224
+ if (!openResponse.ok) {
225
+ return { ok: false, opened: false, error: `Cannot open ${targetUrl}: HTTP ${openResponse.status}` };
226
+ }
227
+ return { ok: true, opened: true };
228
+ } catch (err) {
229
+ return { ok: false, opened: false, error: (err as Error).message };
230
+ }
231
+ }
232
+
233
+ export async function ensureChromeCdpRunning(
234
+ cfg: ChromeDevtoolsConfig = config.chromeDevtools,
235
+ deps: ChromeDevtoolsGuardDeps = {},
236
+ ): Promise<ChromeCdpEnsureResult> {
237
+ const port = normalizePort(cfg.port);
238
+ if (!cfg.enabled) return { ok: true, started: false, port };
239
+
240
+ const probe = await probeChromeCdp(port, deps);
241
+ if (probe === "healthy") {
242
+ return { ok: true, started: false, port };
243
+ }
244
+ if (probe === "occupied") {
245
+ return {
246
+ ok: false,
247
+ started: false,
248
+ port,
249
+ error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
250
+ };
251
+ }
252
+
253
+ const started = startChromeForCdp({ ...cfg, port }, deps);
254
+ if (!started.ok) return { ok: false, started: false, port, error: started.error };
255
+
256
+ for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
257
+ await sleep(START_VERIFY_DELAY_MS);
258
+ if (await isChromeCdpHealthy(port, deps)) {
259
+ return { ok: true, started: true, port };
260
+ }
261
+ }
262
+
263
+ return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
264
+ }
265
+
266
+ async function runGuardOnce(reason: string, deps: ChromeDevtoolsGuardDeps = {}): Promise<void> {
267
+ if (ensureInFlight) return;
268
+ const log = deps.log ?? ((message: string) => console.log(message));
269
+ ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
270
+ try {
271
+ const result = await ensureInFlight;
272
+ const chatcccPage = config.chromeDevtools.enabled && result.ok
273
+ ? await ensureChatcccPageOpen(result.port, config.port, deps)
274
+ : null;
275
+ appendStartupTrace("chrome-devtools-guard: ensure result", {
276
+ reason,
277
+ enabled: config.chromeDevtools.enabled,
278
+ port: result.port,
279
+ ok: result.ok,
280
+ started: result.started,
281
+ error: result.error,
282
+ chatcccPage,
283
+ });
284
+ if (!config.chromeDevtools.enabled) return;
285
+ if (result.ok && result.started) {
286
+ log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
287
+ } else if (!result.ok) {
288
+ log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
289
+ }
290
+ if (chatcccPage?.opened) {
291
+ log(`[${ts()}] [Chrome CDP] Opened ChatCCC page http://localhost:${config.port}/`);
292
+ } else if (chatcccPage && !chatcccPage.ok) {
293
+ log(`[${ts()}] [Chrome CDP] Failed to ensure ChatCCC page: ${chatcccPage.error}`);
294
+ }
295
+ } finally {
296
+ ensureInFlight = null;
297
+ }
298
+ }
299
+
300
+ export function startChromeDevtoolsGuard(deps: ChromeDevtoolsGuardDeps = {}): void {
301
+ stopChromeDevtoolsGuard();
302
+ if (!config.chromeDevtools.enabled) {
303
+ appendStartupTrace("chrome-devtools-guard: disabled");
304
+ return;
305
+ }
306
+
307
+ void runGuardOnce("startup", deps);
308
+ guardTimer = setInterval(() => {
309
+ void runGuardOnce("interval", deps);
310
+ }, GUARD_INTERVAL_MS);
311
+ }
312
+
313
+ export function stopChromeDevtoolsGuard(): void {
314
+ if (guardTimer) {
315
+ clearInterval(guardTimer);
316
+ guardTimer = null;
317
+ }
318
+ }