chatccc 0.2.231 → 0.2.233

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 (130) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -86
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +449 -393
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +319 -202
  28. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  29. package/src/__tests__/builtin-permissions.test.ts +211 -211
  30. package/src/__tests__/builtin-session-search.test.ts +228 -0
  31. package/src/__tests__/builtin-session-select.test.ts +116 -116
  32. package/src/__tests__/builtin-sigint.test.ts +56 -56
  33. package/src/__tests__/builtin-skills.test.ts +284 -284
  34. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  35. package/src/__tests__/card-action-routing.test.ts +18 -18
  36. package/src/__tests__/cardkit.test.ts +60 -60
  37. package/src/__tests__/ccc-adapter.test.ts +170 -170
  38. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  39. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  40. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  41. package/src/__tests__/claude-adapter.test.ts +614 -614
  42. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  43. package/src/__tests__/codex-adapter.test.ts +58 -58
  44. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  45. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  46. package/src/__tests__/crash-logging.test.ts +95 -1
  47. package/src/__tests__/cursor-adapter.test.ts +268 -268
  48. package/src/__tests__/feishu-api.test.ts +60 -60
  49. package/src/__tests__/feishu-avatar.test.ts +164 -164
  50. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  51. package/src/__tests__/feishu-platform.test.ts +22 -22
  52. package/src/__tests__/format-message.test.ts +47 -47
  53. package/src/__tests__/jsonl-stream.test.ts +79 -79
  54. package/src/__tests__/package-files.test.ts +24 -24
  55. package/src/__tests__/privacy.test.ts +198 -198
  56. package/src/__tests__/progress-reducer.test.ts +121 -121
  57. package/src/__tests__/raw-stream-log.test.ts +106 -106
  58. package/src/__tests__/response-stall.test.ts +49 -49
  59. package/src/__tests__/restart.test.ts +55 -10
  60. package/src/__tests__/session.test.ts +199 -199
  61. package/src/__tests__/shared-prefix.test.ts +36 -36
  62. package/src/__tests__/sim-platform.test.ts +16 -16
  63. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  64. package/src/__tests__/stop-session.test.ts +34 -34
  65. package/src/__tests__/stream-state.test.ts +42 -42
  66. package/src/__tests__/terminal-error.test.ts +54 -54
  67. package/src/__tests__/terminal-renderer.test.ts +247 -247
  68. package/src/__tests__/update-command-guard.test.ts +144 -144
  69. package/src/__tests__/web-ui.test.ts +326 -326
  70. package/src/adapters/adapter-interface.ts +33 -33
  71. package/src/adapters/ccc-adapter.ts +141 -141
  72. package/src/adapters/claude-adapter.ts +620 -620
  73. package/src/adapters/claude-session-meta-store.ts +120 -120
  74. package/src/adapters/codex-adapter.ts +426 -426
  75. package/src/adapters/cursor-adapter.ts +681 -681
  76. package/src/adapters/jsonl-stream.ts +157 -157
  77. package/src/adapters/raw-stream-log.ts +124 -124
  78. package/src/adapters/resource-monitor.ts +140 -140
  79. package/src/agent-activity.ts +175 -175
  80. package/src/agent-delegate-task-rpc.ts +153 -153
  81. package/src/agent-delegate-task.ts +91 -91
  82. package/src/agent-reload-config-rpc.ts +34 -34
  83. package/src/agent-stop-stuck.ts +129 -129
  84. package/src/builtin/cli.ts +6 -0
  85. package/src/builtin/config.ts +84 -84
  86. package/src/builtin/context.ts +465 -391
  87. package/src/builtin/file-log.ts +38 -38
  88. package/src/builtin/file-tools.ts +34 -0
  89. package/src/builtin/index.ts +24 -23
  90. package/src/builtin/proc-tree-kill.ts +61 -61
  91. package/src/builtin/progress/cards-helpers.ts +76 -76
  92. package/src/builtin/progress/reducer.ts +113 -113
  93. package/src/builtin/progress/terminal-renderer.ts +294 -294
  94. package/src/builtin/progress/view.ts +77 -77
  95. package/src/builtin/raw-stream-log.ts +124 -124
  96. package/src/builtin/session-search.ts +363 -0
  97. package/src/builtin/session-select.ts +48 -48
  98. package/src/builtin/sigint.ts +50 -50
  99. package/src/builtin/skills.ts +205 -205
  100. package/src/builtin/web-tools.ts +313 -313
  101. package/src/card-action-routing.ts +14 -14
  102. package/src/chatgpt-subscription-rpc.ts +27 -27
  103. package/src/chatgpt-subscription.ts +299 -299
  104. package/src/chrome-devtools-guard.ts +318 -318
  105. package/src/codex-reset-actions.ts +184 -184
  106. package/src/feishu-api.ts +193 -193
  107. package/src/feishu-message-ingress.ts +195 -195
  108. package/src/feishu-platform.ts +20 -20
  109. package/src/format-message.ts +293 -293
  110. package/src/index.ts +6 -1
  111. package/src/litellm-proxy.ts +374 -374
  112. package/src/orchestrator.ts +36 -13
  113. package/src/platform-adapter.ts +6 -6
  114. package/src/privacy.ts +118 -118
  115. package/src/progress/reducer.ts +113 -113
  116. package/src/progress/terminal-renderer.ts +294 -294
  117. package/src/progress/view.ts +77 -77
  118. package/src/response-stall.ts +28 -28
  119. package/src/runtime-reload.ts +34 -34
  120. package/src/session-chat-binding.ts +82 -82
  121. package/src/session-name.ts +8 -8
  122. package/src/session.ts +201 -201
  123. package/src/shared-prefix.ts +29 -29
  124. package/src/shared.ts +44 -0
  125. package/src/sim-platform.ts +20 -20
  126. package/src/startup-lifecycle.ts +250 -250
  127. package/src/stream-state.ts +21 -21
  128. package/src/terminal-error.ts +129 -129
  129. package/src/turn-cards.ts +117 -117
  130. package/src/update-command-guard.ts +165 -165
@@ -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 !== "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
+ 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
+ }