chatccc 0.2.187 → 0.2.189

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 (71) hide show
  1. package/agent-prompts/claude_specific.md +45 -45
  2. package/agent-prompts/codex_specific.md +2 -2
  3. package/agent-prompts/cursor_specific.md +13 -13
  4. package/config.sample.json +5 -0
  5. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  6. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  7. package/im-skills/feishu-skill/skill.md +3 -3
  8. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  9. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  10. package/im-skills/wechat-file-skill/skill.md +10 -10
  11. package/im-skills/wechat-image-skill/skill.md +10 -10
  12. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  13. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  14. package/im-skills/wechat-video-skill/skill.md +10 -10
  15. package/package.json +1 -1
  16. package/scripts/postinstall-sharp-check.mjs +58 -58
  17. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  18. package/src/__tests__/builtin-config.test.ts +33 -0
  19. package/src/__tests__/card-plain-text.test.ts +5 -5
  20. package/src/__tests__/cardkit.test.ts +60 -60
  21. package/src/__tests__/cards.test.ts +77 -77
  22. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  23. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  24. package/src/__tests__/chrome-devtools-guard.test.ts +165 -125
  25. package/src/__tests__/claude-adapter.test.ts +592 -592
  26. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  27. package/src/__tests__/config-reload.test.ts +1 -0
  28. package/src/__tests__/config-sample.test.ts +11 -0
  29. package/src/__tests__/feishu-api.test.ts +60 -60
  30. package/src/__tests__/feishu-avatar.test.ts +180 -115
  31. package/src/__tests__/feishu-platform.test.ts +22 -22
  32. package/src/__tests__/format-message.test.ts +47 -47
  33. package/src/__tests__/orchestrator.test.ts +150 -2
  34. package/src/__tests__/privacy.test.ts +198 -198
  35. package/src/__tests__/raw-stream-log.test.ts +106 -106
  36. package/src/__tests__/session.test.ts +10 -0
  37. package/src/__tests__/shared-prefix.test.ts +36 -36
  38. package/src/__tests__/stream-state.test.ts +42 -42
  39. package/src/__tests__/web-ui.test.ts +209 -130
  40. package/src/adapters/claude-adapter.ts +566 -566
  41. package/src/adapters/claude-session-meta-store.ts +120 -120
  42. package/src/adapters/codex-adapter.ts +10 -6
  43. package/src/adapters/cursor-adapter.ts +46 -46
  44. package/src/adapters/raw-stream-log.ts +124 -124
  45. package/src/adapters/resource-monitor.ts +140 -140
  46. package/src/agent-delegate-task-rpc.ts +153 -153
  47. package/src/agent-delegate-task.ts +81 -81
  48. package/src/agent-stop-stuck.ts +129 -129
  49. package/src/builtin/cli.ts +189 -197
  50. package/src/builtin/index.ts +168 -167
  51. package/src/cards.ts +130 -89
  52. package/src/chatgpt-subscription-rpc.ts +27 -27
  53. package/src/chatgpt-subscription.ts +299 -299
  54. package/src/chrome-devtools-guard.ts +318 -242
  55. package/src/codex-reset-actions.ts +184 -184
  56. package/src/config.ts +38 -0
  57. package/src/feishu-api.ts +219 -190
  58. package/src/feishu-platform.ts +20 -20
  59. package/src/format-message.ts +293 -293
  60. package/src/index.ts +2 -2
  61. package/src/litellm-proxy.ts +374 -374
  62. package/src/orchestrator.ts +201 -9
  63. package/src/platform-adapter.ts +9 -1
  64. package/src/privacy.ts +118 -118
  65. package/src/session-chat-binding.ts +6 -6
  66. package/src/session-name.ts +8 -8
  67. package/src/session.ts +44 -16
  68. package/src/shared-prefix.ts +29 -29
  69. package/src/sim-platform.ts +20 -20
  70. package/src/turn-cards.ts +117 -117
  71. package/src/web-ui.ts +142 -24
@@ -1,242 +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
- let guardTimer: ReturnType<typeof setInterval> | null = null;
37
- let ensureInFlight: Promise<ChromeCdpEnsureResult> | null = null;
38
-
39
- function normalizePort(value: unknown): number {
40
- const port = Number(value);
41
- return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
42
- }
43
-
44
- function chromeCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
45
- if (platform === "win32") {
46
- return [
47
- env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
48
- env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"]!, "Google", "Chrome", "Application", "chrome.exe") : "",
49
- env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
50
- ].filter(Boolean);
51
- }
52
-
53
- if (platform === "darwin") {
54
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
55
- }
56
-
57
- return [
58
- "/usr/bin/google-chrome",
59
- "/usr/bin/google-chrome-stable",
60
- "/usr/bin/chromium",
61
- "/usr/bin/chromium-browser",
62
- ];
63
- }
64
-
65
- export function resolveChromeExecutable(
66
- chromePath: string | undefined,
67
- deps: Pick<ChromeDevtoolsGuardDeps, "existsSyncImpl" | "platform" | "env"> = {},
68
- ): string | null {
69
- const exists = deps.existsSyncImpl ?? existsSync;
70
- const explicit = chromePath?.trim();
71
- if (explicit) return exists(explicit) ? explicit : null;
72
-
73
- for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
74
- if (exists(candidate)) return candidate;
75
- }
76
- return null;
77
- }
78
-
79
- export function resolveChromeUserDataDir(port: number, env: NodeJS.ProcessEnv = process.env): string {
80
- const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
81
- return join(root, `chrome-cdp-${port}`);
82
- }
83
-
84
- async function fetchWithTimeout(url: string, fetchImpl: FetchLike, timeoutMs: number): Promise<Response> {
85
- const controller = new AbortController();
86
- const timer = setTimeout(() => controller.abort(), timeoutMs);
87
- try {
88
- return await fetchImpl(url, { signal: controller.signal });
89
- } finally {
90
- clearTimeout(timer);
91
- }
92
- }
93
-
94
- export async function probeChromeCdp(
95
- port: number,
96
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
97
- ): Promise<ChromeCdpProbeStatus> {
98
- const normalizedPort = normalizePort(port);
99
- try {
100
- const response = await fetchWithTimeout(
101
- `http://${CDP_HOST}:${normalizedPort}/json/version`,
102
- deps.fetchImpl ?? fetch,
103
- HEALTH_TIMEOUT_MS,
104
- );
105
- if (!response.ok) return "occupied";
106
- const data = await response.json() as Record<string, unknown>;
107
- return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
108
- ? "healthy"
109
- : "occupied";
110
- } catch {
111
- return "unreachable";
112
- }
113
- }
114
-
115
- export async function isChromeCdpHealthy(
116
- port: number,
117
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
118
- ): Promise<boolean> {
119
- return (await probeChromeCdp(port, deps)) === "healthy";
120
- }
121
-
122
- function startChromeForCdp(
123
- cfg: ChromeDevtoolsConfig,
124
- deps: ChromeDevtoolsGuardDeps = {},
125
- ): { ok: true; child: ChildProcess } | { ok: false; error: string } {
126
- const port = normalizePort(cfg.port);
127
- const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
128
- if (!chromeExe) {
129
- return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
130
- }
131
-
132
- const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
133
- try {
134
- (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
135
- } catch (err) {
136
- return { ok: false, error: `Cannot create Chrome user data dir: ${(err as Error).message}` };
137
- }
138
-
139
- const args = [
140
- `--remote-debugging-address=${CDP_HOST}`,
141
- `--remote-debugging-port=${port}`,
142
- `--user-data-dir=${userDataDir}`,
143
- "--no-first-run",
144
- "--no-default-browser-check",
145
- "--new-window",
146
- "about:blank",
147
- ];
148
-
149
- try {
150
- const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
151
- detached: true,
152
- stdio: "ignore",
153
- windowsHide: true,
154
- });
155
- child.unref();
156
- return { ok: true, child };
157
- } catch (err) {
158
- return { ok: false, error: `Failed to start Chrome: ${(err as Error).message}` };
159
- }
160
- }
161
-
162
- function sleep(ms: number): Promise<void> {
163
- return new Promise((resolve) => setTimeout(resolve, ms));
164
- }
165
-
166
- export async function ensureChromeCdpRunning(
167
- cfg: ChromeDevtoolsConfig = config.chromeDevtools,
168
- deps: ChromeDevtoolsGuardDeps = {},
169
- ): Promise<ChromeCdpEnsureResult> {
170
- const port = normalizePort(cfg.port);
171
- if (!cfg.enabled) return { ok: true, started: false, port };
172
-
173
- const probe = await probeChromeCdp(port, deps);
174
- if (probe === "healthy") {
175
- return { ok: true, started: false, port };
176
- }
177
- if (probe === "occupied") {
178
- return {
179
- ok: false,
180
- started: false,
181
- port,
182
- error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
183
- };
184
- }
185
-
186
- const started = startChromeForCdp({ ...cfg, port }, deps);
187
- if (!started.ok) return { ok: false, started: false, port, error: started.error };
188
-
189
- for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
190
- await sleep(START_VERIFY_DELAY_MS);
191
- if (await isChromeCdpHealthy(port, deps)) {
192
- return { ok: true, started: true, port };
193
- }
194
- }
195
-
196
- return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
197
- }
198
-
199
- async function runGuardOnce(reason: string, deps: ChromeDevtoolsGuardDeps = {}): Promise<void> {
200
- if (ensureInFlight) return;
201
- const log = deps.log ?? ((message: string) => console.log(message));
202
- ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
203
- try {
204
- const result = await ensureInFlight;
205
- appendStartupTrace("chrome-devtools-guard: ensure result", {
206
- reason,
207
- enabled: config.chromeDevtools.enabled,
208
- port: result.port,
209
- ok: result.ok,
210
- started: result.started,
211
- error: result.error,
212
- });
213
- if (!config.chromeDevtools.enabled) return;
214
- if (result.ok && result.started) {
215
- log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
216
- } else if (!result.ok) {
217
- log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
218
- }
219
- } finally {
220
- ensureInFlight = null;
221
- }
222
- }
223
-
224
- export function startChromeDevtoolsGuard(deps: ChromeDevtoolsGuardDeps = {}): void {
225
- stopChromeDevtoolsGuard();
226
- if (!config.chromeDevtools.enabled) {
227
- appendStartupTrace("chrome-devtools-guard: disabled");
228
- return;
229
- }
230
-
231
- void runGuardOnce("startup", deps);
232
- guardTimer = setInterval(() => {
233
- void runGuardOnce("interval", deps);
234
- }, GUARD_INTERVAL_MS);
235
- }
236
-
237
- export function stopChromeDevtoolsGuard(): void {
238
- if (guardTimer) {
239
- clearInterval(guardTimer);
240
- guardTimer = null;
241
- }
242
- }
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
+ }