chatccc 0.2.196 → 0.2.197

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 (51) hide show
  1. package/agent-prompts/cursor_specific.md +13 -13
  2. package/bin/cccagent.mjs +17 -17
  3. package/config.sample.json +27 -27
  4. package/package.json +1 -1
  5. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -0
  6. package/src/__tests__/builtin-chat-session.test.ts +277 -181
  7. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  8. package/src/__tests__/builtin-config.test.ts +33 -33
  9. package/src/__tests__/builtin-context.test.ts +163 -163
  10. package/src/__tests__/builtin-file-tools.test.ts +224 -196
  11. package/src/__tests__/builtin-session-select.test.ts +116 -116
  12. package/src/__tests__/builtin-sigint.test.ts +56 -56
  13. package/src/__tests__/cards.test.ts +109 -109
  14. package/src/__tests__/ccc-adapter.test.ts +114 -113
  15. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  16. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  17. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  18. package/src/__tests__/claude-raw-stream-log.test.ts +87 -0
  19. package/src/__tests__/codex-raw-stream-log.test.ts +120 -0
  20. package/src/__tests__/config-reload.test.ts +10 -10
  21. package/src/__tests__/config-sample.test.ts +18 -18
  22. package/src/__tests__/cursor-adapter.test.ts +113 -113
  23. package/src/__tests__/feishu-avatar.test.ts +40 -40
  24. package/src/__tests__/orchestrator.test.ts +181 -154
  25. package/src/__tests__/raw-stream-log.test.ts +106 -106
  26. package/src/__tests__/session.test.ts +40 -40
  27. package/src/__tests__/sim-platform.test.ts +12 -12
  28. package/src/__tests__/web-ui.test.ts +209 -209
  29. package/src/adapters/ccc-adapter.ts +121 -119
  30. package/src/adapters/claude-adapter.ts +603 -566
  31. package/src/adapters/codex-adapter.ts +57 -32
  32. package/src/adapters/cursor-adapter.ts +264 -264
  33. package/src/adapters/raw-stream-log.ts +124 -124
  34. package/src/agent-reload-config-rpc.ts +34 -0
  35. package/src/builtin/cli.ts +473 -461
  36. package/src/builtin/context.ts +323 -323
  37. package/src/builtin/file-tools.ts +1072 -915
  38. package/src/builtin/index.ts +404 -353
  39. package/src/builtin/session-select.ts +48 -48
  40. package/src/builtin/sigint.ts +50 -50
  41. package/src/cards.ts +195 -195
  42. package/src/chatgpt-subscription-rpc.ts +27 -27
  43. package/src/chatgpt-subscription.ts +299 -299
  44. package/src/chrome-devtools-guard.ts +318 -318
  45. package/src/config.ts +125 -125
  46. package/src/feishu-api.ts +49 -49
  47. package/src/index.ts +8 -13
  48. package/src/orchestrator.ts +166 -145
  49. package/src/runtime-reload.ts +34 -0
  50. package/src/session.ts +141 -141
  51. package/src/web-ui.ts +205 -205
@@ -1,27 +1,27 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
-
3
- import { getChatGptSubscriptionStatus } from "./chatgpt-subscription.ts";
4
-
5
- export const CHATGPT_SUBSCRIPTION_PATH = "/api/chatgpt/subscription";
6
-
7
- function jsonReply(res: ServerResponse, code: number, data: unknown): void {
8
- res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
9
- res.end(JSON.stringify(data));
10
- }
11
-
12
- export async function handleChatGptSubscriptionRequest(
13
- req: IncomingMessage,
14
- res: ServerResponse,
15
- ): Promise<boolean> {
16
- const method = req.method ?? "GET";
17
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
18
- if (url.pathname !== CHATGPT_SUBSCRIPTION_PATH) return false;
19
-
20
- if (method !== "GET") {
21
- jsonReply(res, 405, { ok: false, code: "method_not_allowed", reason: "Use GET." });
22
- return true;
23
- }
24
-
25
- jsonReply(res, 200, await getChatGptSubscriptionStatus());
26
- return true;
27
- }
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+
3
+ import { getChatGptSubscriptionStatus } from "./chatgpt-subscription.ts";
4
+
5
+ export const CHATGPT_SUBSCRIPTION_PATH = "/api/chatgpt/subscription";
6
+
7
+ function jsonReply(res: ServerResponse, code: number, data: unknown): void {
8
+ res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
9
+ res.end(JSON.stringify(data));
10
+ }
11
+
12
+ export async function handleChatGptSubscriptionRequest(
13
+ req: IncomingMessage,
14
+ res: ServerResponse,
15
+ ): Promise<boolean> {
16
+ const method = req.method ?? "GET";
17
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
18
+ if (url.pathname !== CHATGPT_SUBSCRIPTION_PATH) return false;
19
+
20
+ if (method !== "POST") {
21
+ jsonReply(res, 405, { ok: false, code: "method_not_allowed", reason: "Use POST." });
22
+ return true;
23
+ }
24
+
25
+ jsonReply(res, 200, await getChatGptSubscriptionStatus());
26
+ return true;
27
+ }
@@ -1,299 +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
- }
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
+ }