chatccc 0.2.200 → 0.2.202

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 (92) hide show
  1. package/README.md +17 -15
  2. package/agent-prompts/claude_specific.md +45 -45
  3. package/agent-prompts/codex_specific.md +2 -2
  4. package/agent-prompts/cursor_specific.md +13 -13
  5. package/bin/cccagent.mjs +17 -17
  6. package/config.sample.json +27 -27
  7. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  8. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  9. package/im-skills/feishu-skill/skill.md +3 -3
  10. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  11. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  12. package/im-skills/wechat-file-skill/skill.md +10 -10
  13. package/im-skills/wechat-image-skill/skill.md +10 -10
  14. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  15. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  16. package/im-skills/wechat-video-skill/skill.md +10 -10
  17. package/package.json +1 -1
  18. package/scripts/postinstall-sharp-check.mjs +58 -58
  19. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  20. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  21. package/src/__tests__/builtin-chat-session.test.ts +277 -277
  22. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  23. package/src/__tests__/builtin-config.test.ts +33 -33
  24. package/src/__tests__/builtin-context.test.ts +163 -163
  25. package/src/__tests__/builtin-file-tools.test.ts +224 -224
  26. package/src/__tests__/builtin-session-select.test.ts +116 -116
  27. package/src/__tests__/builtin-sigint.test.ts +56 -56
  28. package/src/__tests__/card-plain-text.test.ts +5 -5
  29. package/src/__tests__/cardkit.test.ts +60 -60
  30. package/src/__tests__/cards.test.ts +133 -122
  31. package/src/__tests__/ccc-adapter.test.ts +114 -114
  32. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  33. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  34. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  35. package/src/__tests__/claude-adapter.test.ts +592 -592
  36. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  37. package/src/__tests__/codex-raw-stream-log.test.ts +163 -163
  38. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  39. package/src/__tests__/config-reload.test.ts +10 -10
  40. package/src/__tests__/config-sample.test.ts +18 -18
  41. package/src/__tests__/cursor-adapter.test.ts +226 -226
  42. package/src/__tests__/feishu-api.test.ts +60 -60
  43. package/src/__tests__/feishu-avatar.test.ts +90 -90
  44. package/src/__tests__/feishu-platform.test.ts +22 -22
  45. package/src/__tests__/format-message.test.ts +47 -47
  46. package/src/__tests__/jsonl-stream.test.ts +79 -79
  47. package/src/__tests__/orchestrator.test.ts +464 -301
  48. package/src/__tests__/privacy.test.ts +198 -198
  49. package/src/__tests__/raw-stream-log.test.ts +106 -106
  50. package/src/__tests__/session.test.ts +46 -44
  51. package/src/__tests__/shared-prefix.test.ts +36 -36
  52. package/src/__tests__/sim-platform.test.ts +12 -12
  53. package/src/__tests__/stream-state.test.ts +42 -42
  54. package/src/__tests__/web-ui.test.ts +209 -209
  55. package/src/adapters/ccc-adapter.ts +121 -121
  56. package/src/adapters/claude-adapter.ts +603 -603
  57. package/src/adapters/claude-session-meta-store.ts +120 -120
  58. package/src/adapters/codex-adapter.ts +380 -380
  59. package/src/adapters/cursor-adapter.ts +673 -673
  60. package/src/adapters/jsonl-stream.ts +157 -157
  61. package/src/adapters/raw-stream-log.ts +124 -124
  62. package/src/adapters/resource-monitor.ts +140 -140
  63. package/src/agent-delegate-task-rpc.ts +153 -153
  64. package/src/agent-delegate-task.ts +81 -81
  65. package/src/agent-reload-config-rpc.ts +34 -34
  66. package/src/agent-stop-stuck.ts +129 -129
  67. package/src/builtin/cli.ts +473 -473
  68. package/src/builtin/context.ts +323 -323
  69. package/src/builtin/file-tools.ts +1072 -1072
  70. package/src/builtin/index.ts +404 -404
  71. package/src/builtin/session-select.ts +48 -48
  72. package/src/builtin/sigint.ts +50 -50
  73. package/src/cards.ts +222 -210
  74. package/src/chatgpt-subscription-rpc.ts +27 -27
  75. package/src/chatgpt-subscription.ts +299 -299
  76. package/src/chrome-devtools-guard.ts +318 -318
  77. package/src/codex-reset-actions.ts +184 -184
  78. package/src/config.ts +125 -125
  79. package/src/feishu-api.ts +118 -118
  80. package/src/feishu-platform.ts +20 -20
  81. package/src/format-message.ts +293 -293
  82. package/src/litellm-proxy.ts +374 -374
  83. package/src/orchestrator.ts +348 -329
  84. package/src/privacy.ts +118 -118
  85. package/src/runtime-reload.ts +34 -34
  86. package/src/session-chat-binding.ts +6 -6
  87. package/src/session-name.ts +8 -8
  88. package/src/session.ts +177 -169
  89. package/src/shared-prefix.ts +29 -29
  90. package/src/sim-platform.ts +20 -20
  91. package/src/turn-cards.ts +117 -117
  92. package/src/web-ui.ts +205 -205
@@ -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
+ }