chatccc 0.2.184 → 0.2.185
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.
- package/README.md +88 -69
- package/config.sample.json +5 -0
- package/im-skills/feishu-skill/skill.md +3 -3
- package/package.json +1 -1
- package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
- package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -0
- package/src/__tests__/chatgpt-subscription.test.ts +135 -0
- package/src/__tests__/chrome-devtools-guard.test.ts +125 -0
- package/src/__tests__/config-reload.test.ts +13 -0
- package/src/__tests__/config-sample.test.ts +11 -0
- package/src/__tests__/orchestrator.test.ts +162 -117
- package/src/__tests__/web-ui.test.ts +16 -0
- package/src/agent-delegate-task-rpc.ts +153 -153
- package/src/agent-delegate-task.ts +81 -81
- package/src/chatgpt-subscription-rpc.ts +27 -0
- package/src/chatgpt-subscription.ts +299 -0
- package/src/chrome-devtools-guard.ts +242 -0
- package/src/config.ts +21 -0
- package/src/index.ts +12 -4
- package/src/orchestrator.ts +41 -4
- package/src/session-name.ts +8 -8
- package/src/session.ts +6 -6
- package/src/web-ui.ts +136 -6
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import WebSocket from "ws";
|
|
2
|
+
|
|
3
|
+
import { config } from "./config.ts";
|
|
4
|
+
import { probeChromeCdp, type ChromeCdpProbeStatus } from "./chrome-devtools-guard.ts";
|
|
5
|
+
|
|
6
|
+
const CDP_HOST = "127.0.0.1";
|
|
7
|
+
const DEFAULT_CDP_PORT = 15166;
|
|
8
|
+
const CDP_TIMEOUT_MS = 10_000;
|
|
9
|
+
const CHATGPT_URL = "https://chatgpt.com/";
|
|
10
|
+
|
|
11
|
+
type FetchLike = typeof fetch;
|
|
12
|
+
|
|
13
|
+
export type ChatGptSubscriptionCode =
|
|
14
|
+
| "ok"
|
|
15
|
+
| "chrome_cdp_disabled"
|
|
16
|
+
| "chrome_cdp_unreachable"
|
|
17
|
+
| "chrome_cdp_occupied"
|
|
18
|
+
| "chatgpt_page_missing"
|
|
19
|
+
| "chatgpt_session_missing"
|
|
20
|
+
| "chatgpt_subscription_failed";
|
|
21
|
+
|
|
22
|
+
export interface ChatGptSubscriptionResult {
|
|
23
|
+
ok: boolean;
|
|
24
|
+
code: ChatGptSubscriptionCode;
|
|
25
|
+
reason?: string;
|
|
26
|
+
chromeCdp: {
|
|
27
|
+
enabled: boolean;
|
|
28
|
+
port: number;
|
|
29
|
+
status: ChromeCdpProbeStatus | "skipped";
|
|
30
|
+
};
|
|
31
|
+
chatgpt?: {
|
|
32
|
+
sessionOk: boolean;
|
|
33
|
+
maskedEmail?: string;
|
|
34
|
+
sessionExpiresAt?: string;
|
|
35
|
+
};
|
|
36
|
+
subscription?: {
|
|
37
|
+
active: boolean;
|
|
38
|
+
plan: string | null;
|
|
39
|
+
expiresAt: string | null;
|
|
40
|
+
willRenew: boolean | null;
|
|
41
|
+
purchaseOriginPlatform: string | null;
|
|
42
|
+
remainingDays: number | null;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface ChromeCdpPage {
|
|
47
|
+
id: string;
|
|
48
|
+
type: string;
|
|
49
|
+
title?: string;
|
|
50
|
+
url: string;
|
|
51
|
+
webSocketDebuggerUrl?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface BrowserProbeValue {
|
|
55
|
+
sessionStatus?: number;
|
|
56
|
+
sessionOk?: boolean;
|
|
57
|
+
hasAccessToken?: boolean;
|
|
58
|
+
maskedEmail?: string;
|
|
59
|
+
sessionExpires?: string;
|
|
60
|
+
account?: {
|
|
61
|
+
status: number;
|
|
62
|
+
ok: boolean;
|
|
63
|
+
entitlement: {
|
|
64
|
+
has_active_subscription?: unknown;
|
|
65
|
+
subscription_plan?: unknown;
|
|
66
|
+
expires_at?: unknown;
|
|
67
|
+
} | null;
|
|
68
|
+
last_active_subscription: {
|
|
69
|
+
will_renew?: unknown;
|
|
70
|
+
purchase_origin_platform?: unknown;
|
|
71
|
+
} | null;
|
|
72
|
+
detail?: unknown;
|
|
73
|
+
bodyPrefix?: string;
|
|
74
|
+
};
|
|
75
|
+
error?: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ChatGptSubscriptionDeps {
|
|
79
|
+
fetchImpl?: FetchLike;
|
|
80
|
+
probeChromeCdpImpl?: typeof probeChromeCdp;
|
|
81
|
+
evaluateInPage?: (webSocketDebuggerUrl: string, expression: string) => Promise<unknown>;
|
|
82
|
+
now?: () => Date;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function normalizePort(value: unknown): number {
|
|
86
|
+
const port = Number(value);
|
|
87
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function cdpBaseUrl(port: number): string {
|
|
91
|
+
return `http://${CDP_HOST}:${port}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function maskEmail(value: unknown): string | undefined {
|
|
95
|
+
if (typeof value !== "string" || !value.includes("@")) return undefined;
|
|
96
|
+
const [name, domain] = value.split("@");
|
|
97
|
+
if (!name || !domain) return undefined;
|
|
98
|
+
return `${name.slice(0, 2)}***@${domain}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function calculateRemainingDays(expiresAt: string | null, now: Date): number | null {
|
|
102
|
+
if (!expiresAt) return null;
|
|
103
|
+
const expires = new Date(expiresAt).getTime();
|
|
104
|
+
if (!Number.isFinite(expires)) return null;
|
|
105
|
+
return Math.max(0, Math.ceil((expires - now.getTime()) / 86_400_000));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fetchJson<T>(url: string, fetchImpl: FetchLike, init?: RequestInit): Promise<T> {
|
|
109
|
+
const response = await fetchImpl(url, init);
|
|
110
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
111
|
+
return await response.json() as T;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function listCdpPages(port: number, fetchImpl: FetchLike): Promise<ChromeCdpPage[]> {
|
|
115
|
+
const pages = await fetchJson<unknown>(`${cdpBaseUrl(port)}/json/list`, fetchImpl);
|
|
116
|
+
return Array.isArray(pages)
|
|
117
|
+
? pages.flatMap((raw): ChromeCdpPage[] => {
|
|
118
|
+
if (!raw || typeof raw !== "object") return [];
|
|
119
|
+
const page = raw as Partial<ChromeCdpPage>;
|
|
120
|
+
if (typeof page.id !== "string" || typeof page.type !== "string" || typeof page.url !== "string") return [];
|
|
121
|
+
return [{
|
|
122
|
+
id: page.id,
|
|
123
|
+
type: page.type,
|
|
124
|
+
title: typeof page.title === "string" ? page.title : undefined,
|
|
125
|
+
url: page.url,
|
|
126
|
+
webSocketDebuggerUrl: typeof page.webSocketDebuggerUrl === "string" ? page.webSocketDebuggerUrl : undefined,
|
|
127
|
+
}];
|
|
128
|
+
})
|
|
129
|
+
: [];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function createChatGptPage(port: number, fetchImpl: FetchLike): Promise<ChromeCdpPage | null> {
|
|
133
|
+
const url = `${cdpBaseUrl(port)}/json/new?${encodeURIComponent(CHATGPT_URL)}`;
|
|
134
|
+
const response = await fetchImpl(url, { method: "PUT" });
|
|
135
|
+
if (!response.ok) return null;
|
|
136
|
+
const page = await response.json() as Partial<ChromeCdpPage>;
|
|
137
|
+
if (typeof page.id !== "string" || typeof page.webSocketDebuggerUrl !== "string") return null;
|
|
138
|
+
return {
|
|
139
|
+
id: page.id,
|
|
140
|
+
type: typeof page.type === "string" ? page.type : "page",
|
|
141
|
+
title: typeof page.title === "string" ? page.title : undefined,
|
|
142
|
+
url: typeof page.url === "string" ? page.url : CHATGPT_URL,
|
|
143
|
+
webSocketDebuggerUrl: page.webSocketDebuggerUrl,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function closeCdpPage(port: number, pageId: string, fetchImpl: FetchLike): Promise<void> {
|
|
148
|
+
try {
|
|
149
|
+
await fetchImpl(`${cdpBaseUrl(port)}/json/close/${encodeURIComponent(pageId)}`);
|
|
150
|
+
} catch {
|
|
151
|
+
// Closing a temporary tab is best effort and must not change the query result.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function subscriptionProbeExpression(): string {
|
|
156
|
+
return `(async()=>{try{const sResp=await fetch('/api/auth/session',{credentials:'include',headers:{Accept:'application/json'}});const sText=await sResp.text();let s=null;try{s=JSON.parse(sText)}catch{}const token=s&&typeof s.accessToken==='string'?s.accessToken:'';const email=s&&s.user&&typeof s.user.email==='string'?s.user.email:'';let account=null;if(token){const r=await fetch('/backend-api/accounts/check/v4-2023-04-27?timezone_offset_min=-480',{credentials:'include',headers:{Accept:'application/json',Authorization:'Bearer '+token}});const text=await r.text();let data=null;try{data=JSON.parse(text)}catch{}const accounts=data&&data.accounts&&typeof data.accounts==='object'?data.accounts:null;const keys=accounts?Object.keys(accounts):[];const acc=accounts&&(accounts.default||accounts[keys[0]]);const ent=acc&&acc.entitlement;const last=acc&&acc.last_active_subscription;account={status:r.status,ok:r.ok,entitlement:ent?{has_active_subscription:ent.has_active_subscription,subscription_plan:ent.subscription_plan,expires_at:ent.expires_at}:null,last_active_subscription:last?{will_renew:last.will_renew,purchase_origin_platform:last.purchase_origin_platform}:null,detail:data&&data.detail?data.detail:undefined,bodyPrefix:data?undefined:text.slice(0,120)};}return {sessionStatus:sResp.status,sessionOk:sResp.ok,hasAccessToken:!!token,maskedEmail:(${maskEmail.toString()})(email),sessionExpires:s&&s.expires,account};}catch(e){return {error:String(e&&e.message||e)}}})()`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function evaluateInPage(webSocketDebuggerUrl: string, expression: string): Promise<unknown> {
|
|
160
|
+
return await new Promise((resolve, reject) => {
|
|
161
|
+
const ws = new WebSocket(webSocketDebuggerUrl);
|
|
162
|
+
const id = 1;
|
|
163
|
+
const timer = setTimeout(() => {
|
|
164
|
+
ws.close();
|
|
165
|
+
reject(new Error("CDP Runtime.evaluate timed out"));
|
|
166
|
+
}, CDP_TIMEOUT_MS);
|
|
167
|
+
|
|
168
|
+
ws.on("open", () => {
|
|
169
|
+
ws.send(JSON.stringify({
|
|
170
|
+
id,
|
|
171
|
+
method: "Runtime.evaluate",
|
|
172
|
+
params: { expression, awaitPromise: true, returnByValue: true },
|
|
173
|
+
}));
|
|
174
|
+
});
|
|
175
|
+
ws.on("message", (data) => {
|
|
176
|
+
const msg = JSON.parse(String(data)) as {
|
|
177
|
+
id?: number;
|
|
178
|
+
error?: unknown;
|
|
179
|
+
result?: { result?: { value?: unknown } };
|
|
180
|
+
};
|
|
181
|
+
if (msg.id !== id) return;
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
ws.close();
|
|
184
|
+
if (msg.error) {
|
|
185
|
+
reject(new Error(JSON.stringify(msg.error)));
|
|
186
|
+
} else {
|
|
187
|
+
resolve(msg.result?.result?.value);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
ws.on("error", (err) => {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
reject(err);
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function failure(
|
|
198
|
+
code: Exclude<ChatGptSubscriptionCode, "ok">,
|
|
199
|
+
reason: string,
|
|
200
|
+
chromeCdp: ChatGptSubscriptionResult["chromeCdp"],
|
|
201
|
+
extra: Partial<ChatGptSubscriptionResult> = {},
|
|
202
|
+
): ChatGptSubscriptionResult {
|
|
203
|
+
return { ok: false, code, reason, chromeCdp, ...extra };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function isExpectedSubscriptionFailure(code: ChatGptSubscriptionCode): boolean {
|
|
207
|
+
return code !== "chatgpt_subscription_failed";
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export async function getChatGptSubscriptionStatus(
|
|
211
|
+
deps: ChatGptSubscriptionDeps = {},
|
|
212
|
+
): Promise<ChatGptSubscriptionResult> {
|
|
213
|
+
const cfg = config.chromeDevtools;
|
|
214
|
+
const port = normalizePort(cfg.port);
|
|
215
|
+
const baseChromeCdp = { enabled: cfg.enabled, port };
|
|
216
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
217
|
+
|
|
218
|
+
if (!cfg.enabled) {
|
|
219
|
+
return failure("chrome_cdp_disabled", "Chrome CDP guard is disabled in ChatCCC config.", {
|
|
220
|
+
...baseChromeCdp,
|
|
221
|
+
status: "skipped",
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const probe = await (deps.probeChromeCdpImpl ?? probeChromeCdp)(port, { fetchImpl });
|
|
226
|
+
const chromeCdp = { ...baseChromeCdp, status: probe };
|
|
227
|
+
if (probe === "unreachable") {
|
|
228
|
+
return failure("chrome_cdp_unreachable", `Chrome CDP endpoint is unreachable on port ${port}.`, chromeCdp);
|
|
229
|
+
}
|
|
230
|
+
if (probe === "occupied") {
|
|
231
|
+
return failure("chrome_cdp_occupied", `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`, chromeCdp);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
let temporaryPage: ChromeCdpPage | null = null;
|
|
235
|
+
try {
|
|
236
|
+
const existingPages = await listCdpPages(port, fetchImpl);
|
|
237
|
+
let page = existingPages.find((p) =>
|
|
238
|
+
p.type === "page" &&
|
|
239
|
+
p.webSocketDebuggerUrl &&
|
|
240
|
+
p.url.startsWith(CHATGPT_URL)
|
|
241
|
+
) ?? null;
|
|
242
|
+
if (!page) {
|
|
243
|
+
temporaryPage = await createChatGptPage(port, fetchImpl);
|
|
244
|
+
page = temporaryPage;
|
|
245
|
+
}
|
|
246
|
+
if (!page?.webSocketDebuggerUrl) {
|
|
247
|
+
return failure("chatgpt_page_missing", "No usable chatgpt.com page is available from Chrome CDP.", chromeCdp);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const raw = await (deps.evaluateInPage ?? evaluateInPage)(page.webSocketDebuggerUrl, subscriptionProbeExpression()) as BrowserProbeValue;
|
|
251
|
+
if (!raw || typeof raw !== "object") {
|
|
252
|
+
return failure("chatgpt_subscription_failed", "Chrome CDP returned an empty subscription probe result.", chromeCdp);
|
|
253
|
+
}
|
|
254
|
+
if (raw.error) {
|
|
255
|
+
return failure("chatgpt_subscription_failed", raw.error, chromeCdp);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const chatgpt = {
|
|
259
|
+
sessionOk: raw.sessionOk === true,
|
|
260
|
+
maskedEmail: raw.maskedEmail || undefined,
|
|
261
|
+
sessionExpiresAt: typeof raw.sessionExpires === "string" ? raw.sessionExpires : undefined,
|
|
262
|
+
};
|
|
263
|
+
if (!raw.hasAccessToken) {
|
|
264
|
+
return failure("chatgpt_session_missing", "ChatGPT browser session has no access token.", chromeCdp, { chatgpt });
|
|
265
|
+
}
|
|
266
|
+
if (!raw.account?.ok || !raw.account.entitlement) {
|
|
267
|
+
return failure(
|
|
268
|
+
"chatgpt_subscription_failed",
|
|
269
|
+
`ChatGPT account check failed${raw.account?.status ? ` with HTTP ${raw.account.status}` : ""}.`,
|
|
270
|
+
chromeCdp,
|
|
271
|
+
{ chatgpt },
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const entitlement = raw.account.entitlement;
|
|
276
|
+
const last = raw.account.last_active_subscription;
|
|
277
|
+
const expiresAt = typeof entitlement.expires_at === "string" ? entitlement.expires_at : null;
|
|
278
|
+
return {
|
|
279
|
+
ok: true,
|
|
280
|
+
code: "ok",
|
|
281
|
+
chromeCdp,
|
|
282
|
+
chatgpt,
|
|
283
|
+
subscription: {
|
|
284
|
+
active: entitlement.has_active_subscription === true,
|
|
285
|
+
plan: typeof entitlement.subscription_plan === "string" ? entitlement.subscription_plan : null,
|
|
286
|
+
expiresAt,
|
|
287
|
+
willRenew: typeof last?.will_renew === "boolean" ? last.will_renew : null,
|
|
288
|
+
purchaseOriginPlatform: typeof last?.purchase_origin_platform === "string" ? last.purchase_origin_platform : null,
|
|
289
|
+
remainingDays: calculateRemainingDays(expiresAt, deps.now?.() ?? new Date()),
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
} catch (err) {
|
|
293
|
+
return failure("chatgpt_subscription_failed", (err as Error).message, chromeCdp);
|
|
294
|
+
} finally {
|
|
295
|
+
if (temporaryPage) {
|
|
296
|
+
await closeCdpPage(port, temporaryPage.id, fetchImpl);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
@@ -0,0 +1,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
|
+
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
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -113,9 +113,19 @@ export interface PlatformsConfig {
|
|
|
113
113
|
ilink: PlatformConfig;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
export interface ChromeDevtoolsConfig {
|
|
117
|
+
/** 是否由 ChatCCC 守护一个常驻 Chrome CDP 实例 */
|
|
118
|
+
enabled: boolean;
|
|
119
|
+
/** Chrome remote debugging 端口,默认 15166 */
|
|
120
|
+
port: number;
|
|
121
|
+
/** Chrome 可执行文件路径;留空时按常见安装位置自动探测 */
|
|
122
|
+
chromePath: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
116
125
|
export interface AppConfig {
|
|
117
126
|
feishu: FeishuConfig;
|
|
118
127
|
platforms: PlatformsConfig;
|
|
128
|
+
chromeDevtools: ChromeDevtoolsConfig;
|
|
119
129
|
port: number;
|
|
120
130
|
gitTimeoutSeconds: number;
|
|
121
131
|
/** 若为 false,AI 生成过程中用户发送消息不会打断,须先点「停止」再发送新消息 */
|
|
@@ -342,6 +352,7 @@ function loadConfig(): AppConfig {
|
|
|
342
352
|
const defaults: AppConfig = {
|
|
343
353
|
feishu: { appId: "", appSecret: "" },
|
|
344
354
|
platforms: { feishu: { enabled: true }, ilink: { enabled: true } },
|
|
355
|
+
chromeDevtools: { enabled: false, port: 15166, chromePath: "" },
|
|
345
356
|
port: 18080,
|
|
346
357
|
gitTimeoutSeconds: 180,
|
|
347
358
|
allowInterrupt: false,
|
|
@@ -406,6 +417,7 @@ function loadConfig(): AppConfig {
|
|
|
406
417
|
onDemandMonthlyBudget?: unknown;
|
|
407
418
|
};
|
|
408
419
|
codex?: { enabled?: unknown; defaultAgent?: unknown; path?: unknown; command?: unknown; model?: unknown; effort?: unknown };
|
|
420
|
+
chromeDevtools?: { enabled?: unknown; port?: unknown; chromePath?: unknown };
|
|
409
421
|
};
|
|
410
422
|
try {
|
|
411
423
|
parsed = JSON.parse(raw);
|
|
@@ -418,6 +430,7 @@ function loadConfig(): AppConfig {
|
|
|
418
430
|
const claude = parsed.claude ?? {} as Partial<ClaudeConfig>;
|
|
419
431
|
const cursorRaw = (parsed.cursor ?? {}) as NonNullable<typeof parsed.cursor>;
|
|
420
432
|
const codexRaw = (parsed.codex ?? {}) as NonNullable<typeof parsed.codex>;
|
|
433
|
+
const chromeDevtoolsRaw = (parsed.chromeDevtools ?? {}) as NonNullable<typeof parsed.chromeDevtools>;
|
|
421
434
|
|
|
422
435
|
// 兼容旧字段 `command`:命中时打印一次性 warning 提示用户改名
|
|
423
436
|
const onLegacyField = (label: string, value: string): void => {
|
|
@@ -461,6 +474,7 @@ function loadConfig(): AppConfig {
|
|
|
461
474
|
const claudeEnabled = resolveEnabled(claude.enabled, claudeNonEmpty);
|
|
462
475
|
const cursorEnabled = resolveEnabled(cursorRaw.enabled, cursorNonEmpty);
|
|
463
476
|
const codexEnabled = resolveEnabled(codexRaw.enabled, codexNonEmpty);
|
|
477
|
+
const chromeDevtoolsPort = Number(chromeDevtoolsRaw.port);
|
|
464
478
|
const explicitDefaultTool: AgentTool | null =
|
|
465
479
|
typeof claude.defaultAgent === "boolean" && claude.defaultAgent && claudeEnabled ? "claude" :
|
|
466
480
|
typeof cursorRaw.defaultAgent === "boolean" && cursorRaw.defaultAgent && cursorEnabled ? "cursor" :
|
|
@@ -498,6 +512,13 @@ function loadConfig(): AppConfig {
|
|
|
498
512
|
: true,
|
|
499
513
|
},
|
|
500
514
|
},
|
|
515
|
+
chromeDevtools: {
|
|
516
|
+
enabled: typeof chromeDevtoolsRaw.enabled === "boolean" ? chromeDevtoolsRaw.enabled : false,
|
|
517
|
+
port: Number.isInteger(chromeDevtoolsPort) && chromeDevtoolsPort >= 1 && chromeDevtoolsPort <= 65535
|
|
518
|
+
? chromeDevtoolsPort
|
|
519
|
+
: 15166,
|
|
520
|
+
chromePath: normalizeOptionalConfigField(chromeDevtoolsRaw.chromePath, { label: "chromeDevtools.chromePath" }),
|
|
521
|
+
},
|
|
501
522
|
port: typeof parsed.port === "number" ? parsed.port : 18080,
|
|
502
523
|
gitTimeoutSeconds: typeof parsed.gitTimeoutSeconds === "number" ? parsed.gitTimeoutSeconds : 180,
|
|
503
524
|
allowInterrupt: typeof parsed.allowInterrupt === "boolean" ? parsed.allowInterrupt : false,
|
package/src/index.ts
CHANGED
|
@@ -82,6 +82,7 @@ import { handleAgentImageRequest } from "./agent-image-rpc.ts";
|
|
|
82
82
|
import { handleAgentFileRequest } from "./agent-file-rpc.ts";
|
|
83
83
|
import { handleAgentDelegateTaskRequest } from "./agent-delegate-task-rpc.ts";
|
|
84
84
|
import { handleAgentStopStuckRequest } from "./agent-stop-stuck.ts";
|
|
85
|
+
import { handleChatGptSubscriptionRequest } from "./chatgpt-subscription-rpc.ts";
|
|
85
86
|
import { applyPrivacy } from "./privacy.ts";
|
|
86
87
|
import {
|
|
87
88
|
createCardKitCard,
|
|
@@ -98,6 +99,7 @@ import {
|
|
|
98
99
|
setSessionPlatform,
|
|
99
100
|
startUnifiedDisplayLoop,
|
|
100
101
|
} from "./session.ts";
|
|
102
|
+
import { startChromeDevtoolsGuard, stopChromeDevtoolsGuard } from "./chrome-devtools-guard.ts";
|
|
101
103
|
import {
|
|
102
104
|
rebuildSessionChatsFromRegistry,
|
|
103
105
|
setQueueConsumer,
|
|
@@ -711,7 +713,8 @@ async function main(): Promise<void> {
|
|
|
711
713
|
return (await handleAgentImageRequest(req, res))
|
|
712
714
|
|| (await handleAgentFileRequest(req, res))
|
|
713
715
|
|| (await handleAgentDelegateTaskRequest(req, res, feishuPlatform))
|
|
714
|
-
|| (await handleAgentStopStuckRequest(req, res))
|
|
716
|
+
|| (await handleAgentStopStuckRequest(req, res))
|
|
717
|
+
|| (await handleChatGptSubscriptionRequest(req, res));
|
|
715
718
|
});
|
|
716
719
|
|
|
717
720
|
const simServer = createServer(createUiRouter());
|
|
@@ -765,6 +768,7 @@ async function main(): Promise<void> {
|
|
|
765
768
|
setReloadConfigHook(() => {
|
|
766
769
|
reloadConfigFromDisk();
|
|
767
770
|
clearAdapterCache();
|
|
771
|
+
startChromeDevtoolsGuard();
|
|
768
772
|
appendStartupTrace("reload-from-ui: config reloaded", {
|
|
769
773
|
appIdMask: maskAppId(APP_ID),
|
|
770
774
|
});
|
|
@@ -773,7 +777,8 @@ async function main(): Promise<void> {
|
|
|
773
777
|
return (await handleAgentImageRequest(req, res))
|
|
774
778
|
|| (await handleAgentFileRequest(req, res))
|
|
775
779
|
|| (await handleAgentDelegateTaskRequest(req, res, feishuPlatform))
|
|
776
|
-
|| (await handleAgentStopStuckRequest(req, res))
|
|
780
|
+
|| (await handleAgentStopStuckRequest(req, res))
|
|
781
|
+
|| (await handleChatGptSubscriptionRequest(req, res));
|
|
777
782
|
});
|
|
778
783
|
|
|
779
784
|
console.log(`[启动 2/7] 环境与凭证检查`);
|
|
@@ -793,6 +798,7 @@ async function main(): Promise<void> {
|
|
|
793
798
|
onActivate: async (httpServer: Server) => {
|
|
794
799
|
reloadConfigFromDisk();
|
|
795
800
|
clearAdapterCache();
|
|
801
|
+
startChromeDevtoolsGuard();
|
|
796
802
|
appendStartupTrace("setup-activate: reloaded config from disk", {
|
|
797
803
|
appIdMaskAfterReload: maskAppId(APP_ID),
|
|
798
804
|
});
|
|
@@ -817,6 +823,8 @@ async function main(): Promise<void> {
|
|
|
817
823
|
appendStartupTrace("main: feishu disabled", {});
|
|
818
824
|
}
|
|
819
825
|
|
|
826
|
+
startChromeDevtoolsGuard();
|
|
827
|
+
|
|
820
828
|
// 启动 HTTP server(同时挂 UI router,供 dashboard / setup / agent image/file 使用)
|
|
821
829
|
appendStartupTrace("main: before freeRelayListenPort", { CHATCCC_PORT });
|
|
822
830
|
const killed = freeRelayListenPort(CHATCCC_PORT);
|
|
@@ -877,8 +885,8 @@ async function listenWithRetry(
|
|
|
877
885
|
* 先写盘,再走这里。
|
|
878
886
|
*/
|
|
879
887
|
function installShutdownHandlers(httpServer: Server): void {
|
|
880
|
-
process.on("SIGINT", () => { console.log("\nShutting down..."); wechatSignal.stopped = true; httpServer.close(); process.exit(0); });
|
|
881
|
-
process.on("SIGTERM", () => { wechatSignal.stopped = true; httpServer.close(); process.exit(0); });
|
|
888
|
+
process.on("SIGINT", () => { console.log("\nShutting down..."); wechatSignal.stopped = true; stopChromeDevtoolsGuard(); httpServer.close(); process.exit(0); });
|
|
889
|
+
process.on("SIGTERM", () => { wechatSignal.stopped = true; stopChromeDevtoolsGuard(); httpServer.close(); process.exit(0); });
|
|
882
890
|
}
|
|
883
891
|
|
|
884
892
|
main().catch((err: Error) => {
|