chatccc 0.2.252 → 0.2.253

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 (280) hide show
  1. package/README.md +1 -1
  2. package/bin/cccagent.mjs +12 -3
  3. package/bin/chatccc.mjs +15 -6
  4. package/deepccc-agent/os-prompts/darwin.md +8 -8
  5. package/deepccc-agent/os-prompts/linux.md +8 -8
  6. package/deepccc-agent/os-prompts/win32.md +11 -11
  7. package/deepccc-agent/package.json +65 -65
  8. package/dist/deepccc-agent/src/cli.js +634 -0
  9. package/dist/deepccc-agent/src/config.js +76 -0
  10. package/dist/deepccc-agent/src/context.js +348 -0
  11. package/dist/deepccc-agent/src/file-log.js +34 -0
  12. package/dist/deepccc-agent/src/file-tools.js +1208 -0
  13. package/dist/deepccc-agent/src/index.js +571 -0
  14. package/dist/deepccc-agent/src/permissions.js +170 -0
  15. package/dist/deepccc-agent/src/privacy.js +124 -0
  16. package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
  17. package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
  18. package/dist/deepccc-agent/src/progress/reducer.js +102 -0
  19. package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
  20. package/dist/deepccc-agent/src/progress/view.js +30 -0
  21. package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
  22. package/dist/deepccc-agent/src/session-search.js +276 -0
  23. package/dist/deepccc-agent/src/session-select.js +23 -0
  24. package/dist/deepccc-agent/src/sigint.js +26 -0
  25. package/dist/deepccc-agent/src/skills.js +178 -0
  26. package/dist/deepccc-agent/src/web-tools.js +246 -0
  27. package/dist/src/adapters/adapter-interface.js +19 -0
  28. package/dist/src/adapters/ccc-adapter.js +112 -0
  29. package/dist/src/adapters/claude-adapter.js +497 -0
  30. package/dist/src/adapters/claude-session-meta-store.js +92 -0
  31. package/dist/src/adapters/codex-adapter.js +279 -0
  32. package/dist/src/adapters/codex-session-meta-store.js +94 -0
  33. package/dist/src/adapters/cursor-adapter.js +491 -0
  34. package/dist/src/adapters/cursor-session-meta-store.js +116 -0
  35. package/dist/src/adapters/jsonl-stream.js +104 -0
  36. package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
  37. package/dist/src/adapters/raw-stream-log.js +106 -0
  38. package/dist/src/adapters/resource-monitor.js +113 -0
  39. package/dist/src/agent-activity.js +133 -0
  40. package/dist/src/agent-delegate-task-rpc.js +129 -0
  41. package/dist/src/agent-delegate-task.js +48 -0
  42. package/dist/src/agent-file-rpc.js +152 -0
  43. package/dist/src/agent-image-rpc.js +148 -0
  44. package/dist/src/agent-platform-routing.js +13 -0
  45. package/dist/src/agent-reload-config-rpc.js +23 -0
  46. package/dist/src/agent-rpc-body.js +87 -0
  47. package/dist/src/agent-stop-stuck.js +110 -0
  48. package/dist/src/card-action-routing.js +7 -0
  49. package/dist/src/card-plain-text.js +101 -0
  50. package/dist/src/cardkit.js +158 -0
  51. package/dist/src/cards.js +573 -0
  52. package/dist/src/chatgpt-subscription-rpc.js +18 -0
  53. package/dist/src/chatgpt-subscription.js +199 -0
  54. package/dist/src/chrome-devtools-guard.js +238 -0
  55. package/dist/src/claude-sdk-installer.js +249 -0
  56. package/dist/src/codex-reset-actions.js +143 -0
  57. package/dist/src/config-utils.js +149 -0
  58. package/dist/src/config.js +804 -0
  59. package/dist/src/cursor-usage.js +77 -0
  60. package/dist/src/exit-banner.js +28 -0
  61. package/dist/src/feishu-api.js +1404 -0
  62. package/dist/src/feishu-message-ingress.js +137 -0
  63. package/dist/src/feishu-platform.js +97 -0
  64. package/dist/src/format-message.js +252 -0
  65. package/dist/src/git-command.js +155 -0
  66. package/dist/src/im-skills.js +121 -0
  67. package/dist/src/index.js +833 -0
  68. package/dist/src/litellm-proxy.js +300 -0
  69. package/dist/src/orchestrator.js +2078 -0
  70. package/dist/src/package-root.js +26 -0
  71. package/dist/src/platform-adapter.js +7 -0
  72. package/dist/src/platform-startup.js +6 -0
  73. package/dist/src/privacy.js +100 -0
  74. package/dist/src/progress/reducer.js +102 -0
  75. package/dist/src/progress/terminal-renderer.js +264 -0
  76. package/dist/src/progress/view.js +30 -0
  77. package/dist/src/response-stall.js +14 -0
  78. package/dist/src/runtime-entry.js +13 -0
  79. package/dist/src/runtime-reload.js +19 -0
  80. package/dist/src/session-chat-binding.js +183 -0
  81. package/dist/src/session-name.js +7 -0
  82. package/dist/src/session.js +2144 -0
  83. package/dist/src/shared-prefix.js +16 -0
  84. package/dist/src/shared.js +493 -0
  85. package/dist/src/sim-agent.js +105 -0
  86. package/dist/src/sim-platform.js +142 -0
  87. package/dist/src/sim-store.js +231 -0
  88. package/dist/src/simplify.js +99 -0
  89. package/dist/src/startup-lifecycle.js +209 -0
  90. package/dist/src/stream-state.js +141 -0
  91. package/dist/src/terminal-error.js +100 -0
  92. package/dist/src/trace.js +50 -0
  93. package/dist/src/turn-cards.js +92 -0
  94. package/dist/src/update-command-guard.js +114 -0
  95. package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
  96. package/dist/src/wechat-platform.js +545 -0
  97. package/package.json +76 -74
  98. package/deepccc-agent/LICENSE +0 -201
  99. package/deepccc-agent/bin/deepccc.mjs +0 -26
  100. package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
  101. package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
  102. package/deepccc-agent/package-lock.json +0 -2027
  103. package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -877
  104. package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
  105. package/deepccc-agent/src/__tests__/config.test.ts +0 -34
  106. package/deepccc-agent/src/__tests__/context.test.ts +0 -341
  107. package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
  108. package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
  109. package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
  110. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
  111. package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
  112. package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
  113. package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
  114. package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
  115. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
  116. package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
  117. package/deepccc-agent/src/cli.ts +0 -682
  118. package/deepccc-agent/src/config.ts +0 -101
  119. package/deepccc-agent/src/context.ts +0 -465
  120. package/deepccc-agent/src/file-log.ts +0 -38
  121. package/deepccc-agent/src/file-tools.ts +0 -1493
  122. package/deepccc-agent/src/index.ts +0 -710
  123. package/deepccc-agent/src/permissions.ts +0 -226
  124. package/deepccc-agent/src/privacy.ts +0 -141
  125. package/deepccc-agent/src/proc-tree-kill.ts +0 -61
  126. package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
  127. package/deepccc-agent/src/progress/reducer.ts +0 -113
  128. package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
  129. package/deepccc-agent/src/progress/view.ts +0 -77
  130. package/deepccc-agent/src/raw-stream-log.ts +0 -124
  131. package/deepccc-agent/src/session-search.ts +0 -370
  132. package/deepccc-agent/src/session-select.ts +0 -48
  133. package/deepccc-agent/src/sigint.ts +0 -50
  134. package/deepccc-agent/src/skills.ts +0 -205
  135. package/deepccc-agent/src/web-tools.ts +0 -313
  136. package/deepccc-agent/tsconfig.build.json +0 -13
  137. package/deepccc-agent/tsconfig.json +0 -13
  138. package/deepccc-agent/vitest.config.ts +0 -7
  139. package/src/__tests__/adapter-interface.test.ts +0 -152
  140. package/src/__tests__/agent-activity.test.ts +0 -86
  141. package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
  142. package/src/__tests__/agent-image-rpc.test.ts +0 -34
  143. package/src/__tests__/agent-platform-routing.test.ts +0 -26
  144. package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
  145. package/src/__tests__/agent-rpc-body.test.ts +0 -42
  146. package/src/__tests__/builtin-chat-session.test.ts +0 -532
  147. package/src/__tests__/builtin-cli-json.test.ts +0 -39
  148. package/src/__tests__/builtin-config.test.ts +0 -26
  149. package/src/__tests__/builtin-context.test.ts +0 -319
  150. package/src/__tests__/builtin-file-tools.test.ts +0 -240
  151. package/src/__tests__/builtin-permissions.test.ts +0 -219
  152. package/src/__tests__/builtin-session-search.test.ts +0 -262
  153. package/src/__tests__/builtin-session-select.test.ts +0 -116
  154. package/src/__tests__/builtin-sigint.test.ts +0 -56
  155. package/src/__tests__/builtin-skills.test.ts +0 -284
  156. package/src/__tests__/builtin-web-tools.test.ts +0 -220
  157. package/src/__tests__/card-action-routing.test.ts +0 -18
  158. package/src/__tests__/card-plain-text.test.ts +0 -45
  159. package/src/__tests__/cardkit.test.ts +0 -60
  160. package/src/__tests__/cards.test.ts +0 -607
  161. package/src/__tests__/ccc-adapter.test.ts +0 -194
  162. package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
  163. package/src/__tests__/chatgpt-subscription.test.ts +0 -135
  164. package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
  165. package/src/__tests__/claude-adapter.test.ts +0 -614
  166. package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
  167. package/src/__tests__/claude-sdk-installer.test.ts +0 -285
  168. package/src/__tests__/codex-adapter.test.ts +0 -331
  169. package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
  170. package/src/__tests__/codex-reset-actions.test.ts +0 -146
  171. package/src/__tests__/config-reload.test.ts +0 -284
  172. package/src/__tests__/config-sample.test.ts +0 -97
  173. package/src/__tests__/config-utils.test.ts +0 -40
  174. package/src/__tests__/config.test.ts +0 -395
  175. package/src/__tests__/crash-logging.test.ts +0 -360
  176. package/src/__tests__/cursor-adapter.test.ts +0 -890
  177. package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
  178. package/src/__tests__/feishu-api.test.ts +0 -60
  179. package/src/__tests__/feishu-avatar.test.ts +0 -504
  180. package/src/__tests__/feishu-message-ingress.test.ts +0 -138
  181. package/src/__tests__/feishu-platform.test.ts +0 -75
  182. package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
  183. package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
  184. package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
  185. package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
  186. package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
  187. package/src/__tests__/format-message.test.ts +0 -316
  188. package/src/__tests__/git-command.test.ts +0 -288
  189. package/src/__tests__/im-skills.test.ts +0 -125
  190. package/src/__tests__/jsonl-stream.test.ts +0 -79
  191. package/src/__tests__/orchestrator.test.ts +0 -1268
  192. package/src/__tests__/package-files.test.ts +0 -24
  193. package/src/__tests__/platform-startup.test.ts +0 -19
  194. package/src/__tests__/privacy.test.ts +0 -198
  195. package/src/__tests__/proc-tree-kill.test.ts +0 -108
  196. package/src/__tests__/progress-reducer.test.ts +0 -121
  197. package/src/__tests__/raw-stream-log.test.ts +0 -106
  198. package/src/__tests__/response-stall.test.ts +0 -49
  199. package/src/__tests__/restart.test.ts +0 -232
  200. package/src/__tests__/session-ccc-config.test.ts +0 -66
  201. package/src/__tests__/session.test.ts +0 -3004
  202. package/src/__tests__/shared-prefix.test.ts +0 -36
  203. package/src/__tests__/sim-agent.test.ts +0 -174
  204. package/src/__tests__/sim-platform.test.ts +0 -93
  205. package/src/__tests__/sim-store.test.ts +0 -214
  206. package/src/__tests__/simplify.test.ts +0 -283
  207. package/src/__tests__/startup-lifecycle.test.ts +0 -231
  208. package/src/__tests__/stop-session.test.ts +0 -162
  209. package/src/__tests__/stream-state.test.ts +0 -164
  210. package/src/__tests__/terminal-error.test.ts +0 -54
  211. package/src/__tests__/terminal-renderer.test.ts +0 -247
  212. package/src/__tests__/update-command-guard.test.ts +0 -144
  213. package/src/__tests__/web-ui.test.ts +0 -438
  214. package/src/__tests__/wechat-platform.test.ts +0 -111
  215. package/src/adapters/adapter-interface.ts +0 -217
  216. package/src/adapters/ccc-adapter.ts +0 -150
  217. package/src/adapters/claude-adapter.ts +0 -673
  218. package/src/adapters/claude-session-meta-store.ts +0 -120
  219. package/src/adapters/codex-adapter.ts +0 -426
  220. package/src/adapters/codex-session-meta-store.ts +0 -131
  221. package/src/adapters/cursor-adapter.ts +0 -681
  222. package/src/adapters/cursor-session-meta-store.ts +0 -154
  223. package/src/adapters/jsonl-stream.ts +0 -157
  224. package/src/adapters/raw-stream-log.ts +0 -124
  225. package/src/adapters/resource-monitor.ts +0 -141
  226. package/src/agent-activity.ts +0 -175
  227. package/src/agent-delegate-task-rpc.ts +0 -153
  228. package/src/agent-delegate-task.ts +0 -91
  229. package/src/agent-file-rpc.ts +0 -172
  230. package/src/agent-image-rpc.ts +0 -168
  231. package/src/agent-platform-routing.ts +0 -28
  232. package/src/agent-reload-config-rpc.ts +0 -34
  233. package/src/agent-rpc-body.ts +0 -92
  234. package/src/agent-stop-stuck.ts +0 -129
  235. package/src/card-action-routing.ts +0 -14
  236. package/src/card-plain-text.ts +0 -108
  237. package/src/cardkit.ts +0 -179
  238. package/src/cards.ts +0 -684
  239. package/src/chatgpt-subscription-rpc.ts +0 -27
  240. package/src/chatgpt-subscription.ts +0 -299
  241. package/src/chrome-devtools-guard.ts +0 -318
  242. package/src/claude-sdk-installer.ts +0 -324
  243. package/src/codex-reset-actions.ts +0 -184
  244. package/src/config-utils.ts +0 -211
  245. package/src/config.ts +0 -1063
  246. package/src/cursor-usage.ts +0 -128
  247. package/src/exit-banner.ts +0 -33
  248. package/src/feishu-api.ts +0 -1616
  249. package/src/feishu-message-ingress.ts +0 -195
  250. package/src/feishu-platform.ts +0 -159
  251. package/src/format-message.ts +0 -293
  252. package/src/git-command.ts +0 -202
  253. package/src/im-skills.ts +0 -149
  254. package/src/index.ts +0 -1089
  255. package/src/litellm-proxy.ts +0 -374
  256. package/src/orchestrator.ts +0 -2543
  257. package/src/platform-adapter.ts +0 -70
  258. package/src/platform-startup.ts +0 -16
  259. package/src/privacy.ts +0 -118
  260. package/src/progress/reducer.ts +0 -113
  261. package/src/progress/terminal-renderer.ts +0 -294
  262. package/src/progress/view.ts +0 -77
  263. package/src/response-stall.ts +0 -28
  264. package/src/runtime-reload.ts +0 -34
  265. package/src/session-chat-binding.ts +0 -292
  266. package/src/session-name.ts +0 -8
  267. package/src/session.ts +0 -2659
  268. package/src/shared-prefix.ts +0 -29
  269. package/src/shared.ts +0 -552
  270. package/src/sim-agent.ts +0 -167
  271. package/src/sim-platform.ts +0 -177
  272. package/src/sim-store.ts +0 -317
  273. package/src/simplify.ts +0 -120
  274. package/src/startup-lifecycle.ts +0 -250
  275. package/src/stream-state.ts +0 -177
  276. package/src/terminal-error.ts +0 -129
  277. package/src/trace.ts +0 -51
  278. package/src/turn-cards.ts +0 -118
  279. package/src/update-command-guard.ts +0 -165
  280. package/src/wechat-platform.ts +0 -680
@@ -1,27 +0,0 @@
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 +0,0 @@
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,318 +0,0 @@
1
- import { spawn, type ChildProcess } from "node:child_process";
2
- import { existsSync, mkdirSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- import { appendStartupTrace } from "./shared.ts";
6
- import { config, ts, USER_DATA_DIR, type ChromeDevtoolsConfig } from "./config.ts";
7
-
8
- const CDP_HOST = "127.0.0.1";
9
- const DEFAULT_CDP_PORT = 15166;
10
- const HEALTH_TIMEOUT_MS = 3000;
11
- const START_VERIFY_ATTEMPTS = 10;
12
- const START_VERIFY_DELAY_MS = 500;
13
- const GUARD_INTERVAL_MS = 60_000;
14
-
15
- type FetchLike = typeof fetch;
16
-
17
- export interface ChromeDevtoolsGuardDeps {
18
- fetchImpl?: FetchLike;
19
- spawnImpl?: typeof spawn;
20
- existsSyncImpl?: typeof existsSync;
21
- mkdirSyncImpl?: typeof mkdirSync;
22
- platform?: NodeJS.Platform;
23
- env?: NodeJS.ProcessEnv;
24
- log?: (message: string) => void;
25
- }
26
-
27
- export interface ChromeCdpEnsureResult {
28
- ok: boolean;
29
- started: boolean;
30
- port: number;
31
- error?: string;
32
- }
33
-
34
- export type ChromeCdpProbeStatus = "healthy" | "occupied" | "unreachable";
35
-
36
- interface ChromeCdpPage {
37
- id?: string;
38
- type?: string;
39
- url?: string;
40
- }
41
-
42
- export interface EnsureChatcccPageResult {
43
- ok: boolean;
44
- opened: boolean;
45
- error?: string;
46
- }
47
-
48
- let guardTimer: ReturnType<typeof setInterval> | null = null;
49
- let ensureInFlight: Promise<ChromeCdpEnsureResult> | null = null;
50
-
51
- function normalizePort(value: unknown): number {
52
- const port = Number(value);
53
- return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
54
- }
55
-
56
- function chromeCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
57
- if (platform === "win32") {
58
- return [
59
- env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
60
- env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"]!, "Google", "Chrome", "Application", "chrome.exe") : "",
61
- env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
62
- ].filter(Boolean);
63
- }
64
-
65
- if (platform === "darwin") {
66
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
67
- }
68
-
69
- return [
70
- "/usr/bin/google-chrome",
71
- "/usr/bin/google-chrome-stable",
72
- "/usr/bin/chromium",
73
- "/usr/bin/chromium-browser",
74
- ];
75
- }
76
-
77
- export function resolveChromeExecutable(
78
- chromePath: string | undefined,
79
- deps: Pick<ChromeDevtoolsGuardDeps, "existsSyncImpl" | "platform" | "env"> = {},
80
- ): string | null {
81
- const exists = deps.existsSyncImpl ?? existsSync;
82
- const explicit = chromePath?.trim();
83
- if (explicit) return exists(explicit) ? explicit : null;
84
-
85
- for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
86
- if (exists(candidate)) return candidate;
87
- }
88
- return null;
89
- }
90
-
91
- export function resolveChromeUserDataDir(port: number, env: NodeJS.ProcessEnv = process.env): string {
92
- const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
93
- return join(root, `chrome-cdp-${port}`);
94
- }
95
-
96
- async function fetchWithTimeout(url: string, fetchImpl: FetchLike, timeoutMs: number, init: RequestInit = {}): Promise<Response> {
97
- const controller = new AbortController();
98
- const timer = setTimeout(() => controller.abort(), timeoutMs);
99
- try {
100
- return await fetchImpl(url, { ...init, signal: controller.signal });
101
- } finally {
102
- clearTimeout(timer);
103
- }
104
- }
105
-
106
- export async function probeChromeCdp(
107
- port: number,
108
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
109
- ): Promise<ChromeCdpProbeStatus> {
110
- const normalizedPort = normalizePort(port);
111
- try {
112
- const response = await fetchWithTimeout(
113
- `http://${CDP_HOST}:${normalizedPort}/json/version`,
114
- deps.fetchImpl ?? fetch,
115
- HEALTH_TIMEOUT_MS,
116
- );
117
- if (!response.ok) return "occupied";
118
- const data = await response.json() as Record<string, unknown>;
119
- return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
120
- ? "healthy"
121
- : "occupied";
122
- } catch {
123
- return "unreachable";
124
- }
125
- }
126
-
127
- export async function isChromeCdpHealthy(
128
- port: number,
129
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
130
- ): Promise<boolean> {
131
- return (await probeChromeCdp(port, deps)) === "healthy";
132
- }
133
-
134
- function startChromeForCdp(
135
- cfg: ChromeDevtoolsConfig,
136
- deps: ChromeDevtoolsGuardDeps = {},
137
- ): { ok: true; child: ChildProcess } | { ok: false; error: string } {
138
- const port = normalizePort(cfg.port);
139
- const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
140
- if (!chromeExe) {
141
- return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
142
- }
143
-
144
- const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
145
- try {
146
- (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
147
- } catch (err) {
148
- return { ok: false, error: `Cannot create Chrome user data dir: ${(err as Error).message}` };
149
- }
150
-
151
- const args = [
152
- `--remote-debugging-address=${CDP_HOST}`,
153
- `--remote-debugging-port=${port}`,
154
- `--user-data-dir=${userDataDir}`,
155
- "--no-first-run",
156
- "--no-default-browser-check",
157
- "--new-window",
158
- "about:blank",
159
- ];
160
-
161
- try {
162
- const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
163
- detached: true,
164
- stdio: "ignore",
165
- windowsHide: true,
166
- });
167
- child.unref();
168
- return { ok: true, child };
169
- } catch (err) {
170
- return { ok: false, error: `Failed to start Chrome: ${(err as Error).message}` };
171
- }
172
- }
173
-
174
- function sleep(ms: number): Promise<void> {
175
- return new Promise((resolve) => setTimeout(resolve, ms));
176
- }
177
-
178
- function cdpBaseUrl(port: number): string {
179
- return `http://${CDP_HOST}:${port}`;
180
- }
181
-
182
- function isChatcccPageUrl(value: string | undefined, chatcccPort: number): boolean {
183
- if (!value) return false;
184
- try {
185
- const url = new URL(value);
186
- return url.protocol === "http:" &&
187
- (url.hostname === "localhost" || url.hostname === CDP_HOST) &&
188
- url.port === String(chatcccPort);
189
- } catch {
190
- return false;
191
- }
192
- }
193
-
194
- export async function ensureChatcccPageOpen(
195
- cdpPort: number,
196
- chatcccPort: number,
197
- deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
198
- ): Promise<EnsureChatcccPageResult> {
199
- const normalizedCdpPort = normalizePort(cdpPort);
200
- const normalizedChatcccPort = normalizePort(chatcccPort);
201
- const fetchImpl = deps.fetchImpl ?? fetch;
202
-
203
- try {
204
- const listResponse = await fetchWithTimeout(
205
- `${cdpBaseUrl(normalizedCdpPort)}/json/list`,
206
- fetchImpl,
207
- HEALTH_TIMEOUT_MS,
208
- );
209
- if (!listResponse.ok) {
210
- return { ok: false, opened: false, error: `Cannot list Chrome CDP pages: HTTP ${listResponse.status}` };
211
- }
212
- const pages = await listResponse.json() as unknown;
213
- if (Array.isArray(pages) && pages.some((page: ChromeCdpPage) => isChatcccPageUrl(page?.url, normalizedChatcccPort))) {
214
- return { ok: true, opened: false };
215
- }
216
-
217
- const targetUrl = `http://localhost:${normalizedChatcccPort}/`;
218
- const openResponse = await fetchWithTimeout(
219
- `${cdpBaseUrl(normalizedCdpPort)}/json/new?${encodeURIComponent(targetUrl)}`,
220
- fetchImpl,
221
- HEALTH_TIMEOUT_MS,
222
- { method: "PUT" },
223
- );
224
- if (!openResponse.ok) {
225
- return { ok: false, opened: false, error: `Cannot open ${targetUrl}: HTTP ${openResponse.status}` };
226
- }
227
- return { ok: true, opened: true };
228
- } catch (err) {
229
- return { ok: false, opened: false, error: (err as Error).message };
230
- }
231
- }
232
-
233
- export async function ensureChromeCdpRunning(
234
- cfg: ChromeDevtoolsConfig = config.chromeDevtools,
235
- deps: ChromeDevtoolsGuardDeps = {},
236
- ): Promise<ChromeCdpEnsureResult> {
237
- const port = normalizePort(cfg.port);
238
- if (!cfg.enabled) return { ok: true, started: false, port };
239
-
240
- const probe = await probeChromeCdp(port, deps);
241
- if (probe === "healthy") {
242
- return { ok: true, started: false, port };
243
- }
244
- if (probe === "occupied") {
245
- return {
246
- ok: false,
247
- started: false,
248
- port,
249
- error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
250
- };
251
- }
252
-
253
- const started = startChromeForCdp({ ...cfg, port }, deps);
254
- if (!started.ok) return { ok: false, started: false, port, error: started.error };
255
-
256
- for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
257
- await sleep(START_VERIFY_DELAY_MS);
258
- if (await isChromeCdpHealthy(port, deps)) {
259
- return { ok: true, started: true, port };
260
- }
261
- }
262
-
263
- return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
264
- }
265
-
266
- async function runGuardOnce(reason: string, deps: ChromeDevtoolsGuardDeps = {}): Promise<void> {
267
- if (ensureInFlight) return;
268
- const log = deps.log ?? ((message: string) => console.log(message));
269
- ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
270
- try {
271
- const result = await ensureInFlight;
272
- const chatcccPage = config.chromeDevtools.enabled && result.ok
273
- ? await ensureChatcccPageOpen(result.port, config.port, deps)
274
- : null;
275
- appendStartupTrace("chrome-devtools-guard: ensure result", {
276
- reason,
277
- enabled: config.chromeDevtools.enabled,
278
- port: result.port,
279
- ok: result.ok,
280
- started: result.started,
281
- error: result.error,
282
- chatcccPage,
283
- });
284
- if (!config.chromeDevtools.enabled) return;
285
- if (result.ok && result.started) {
286
- log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
287
- } else if (!result.ok) {
288
- log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
289
- }
290
- if (chatcccPage?.opened) {
291
- log(`[${ts()}] [Chrome CDP] Opened ChatCCC page http://localhost:${config.port}/`);
292
- } else if (chatcccPage && !chatcccPage.ok) {
293
- log(`[${ts()}] [Chrome CDP] Failed to ensure ChatCCC page: ${chatcccPage.error}`);
294
- }
295
- } finally {
296
- ensureInFlight = null;
297
- }
298
- }
299
-
300
- export function startChromeDevtoolsGuard(deps: ChromeDevtoolsGuardDeps = {}): void {
301
- stopChromeDevtoolsGuard();
302
- if (!config.chromeDevtools.enabled) {
303
- appendStartupTrace("chrome-devtools-guard: disabled");
304
- return;
305
- }
306
-
307
- void runGuardOnce("startup", deps);
308
- guardTimer = setInterval(() => {
309
- void runGuardOnce("interval", deps);
310
- }, GUARD_INTERVAL_MS);
311
- }
312
-
313
- export function stopChromeDevtoolsGuard(): void {
314
- if (guardTimer) {
315
- clearInterval(guardTimer);
316
- guardTimer = null;
317
- }
318
- }