chatccc 0.2.251 → 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 (277) 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/package.json +1 -1
  5. package/dist/deepccc-agent/src/cli.js +634 -0
  6. package/dist/deepccc-agent/src/config.js +76 -0
  7. package/dist/deepccc-agent/src/context.js +348 -0
  8. package/dist/deepccc-agent/src/file-log.js +34 -0
  9. package/dist/deepccc-agent/src/file-tools.js +1208 -0
  10. package/dist/deepccc-agent/src/index.js +571 -0
  11. package/dist/deepccc-agent/src/permissions.js +170 -0
  12. package/dist/deepccc-agent/src/privacy.js +124 -0
  13. package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
  14. package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
  15. package/dist/deepccc-agent/src/progress/reducer.js +102 -0
  16. package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
  17. package/dist/deepccc-agent/src/progress/view.js +30 -0
  18. package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
  19. package/dist/deepccc-agent/src/session-search.js +276 -0
  20. package/dist/deepccc-agent/src/session-select.js +23 -0
  21. package/dist/deepccc-agent/src/sigint.js +26 -0
  22. package/dist/deepccc-agent/src/skills.js +178 -0
  23. package/dist/deepccc-agent/src/web-tools.js +246 -0
  24. package/dist/src/adapters/adapter-interface.js +19 -0
  25. package/dist/src/adapters/ccc-adapter.js +112 -0
  26. package/dist/src/adapters/claude-adapter.js +497 -0
  27. package/dist/src/adapters/claude-session-meta-store.js +92 -0
  28. package/dist/src/adapters/codex-adapter.js +279 -0
  29. package/dist/src/adapters/codex-session-meta-store.js +94 -0
  30. package/dist/src/adapters/cursor-adapter.js +491 -0
  31. package/dist/src/adapters/cursor-session-meta-store.js +116 -0
  32. package/dist/src/adapters/jsonl-stream.js +104 -0
  33. package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
  34. package/dist/src/adapters/raw-stream-log.js +106 -0
  35. package/dist/src/adapters/resource-monitor.js +113 -0
  36. package/dist/src/agent-activity.js +133 -0
  37. package/dist/src/agent-delegate-task-rpc.js +129 -0
  38. package/dist/src/agent-delegate-task.js +48 -0
  39. package/dist/src/agent-file-rpc.js +152 -0
  40. package/dist/src/agent-image-rpc.js +148 -0
  41. package/dist/src/agent-platform-routing.js +13 -0
  42. package/dist/src/agent-reload-config-rpc.js +23 -0
  43. package/dist/src/agent-rpc-body.js +87 -0
  44. package/dist/src/agent-stop-stuck.js +110 -0
  45. package/dist/src/card-action-routing.js +7 -0
  46. package/dist/src/card-plain-text.js +101 -0
  47. package/dist/src/cardkit.js +158 -0
  48. package/dist/src/cards.js +573 -0
  49. package/dist/src/chatgpt-subscription-rpc.js +18 -0
  50. package/dist/src/chatgpt-subscription.js +199 -0
  51. package/dist/src/chrome-devtools-guard.js +238 -0
  52. package/dist/src/claude-sdk-installer.js +249 -0
  53. package/dist/src/codex-reset-actions.js +143 -0
  54. package/dist/src/config-utils.js +149 -0
  55. package/dist/src/config.js +804 -0
  56. package/dist/src/cursor-usage.js +77 -0
  57. package/dist/src/exit-banner.js +28 -0
  58. package/dist/src/feishu-api.js +1404 -0
  59. package/dist/src/feishu-message-ingress.js +137 -0
  60. package/dist/src/feishu-platform.js +97 -0
  61. package/dist/src/format-message.js +252 -0
  62. package/dist/src/git-command.js +155 -0
  63. package/dist/src/im-skills.js +121 -0
  64. package/dist/src/index.js +833 -0
  65. package/dist/src/litellm-proxy.js +300 -0
  66. package/dist/src/orchestrator.js +2078 -0
  67. package/dist/src/package-root.js +26 -0
  68. package/dist/src/platform-adapter.js +7 -0
  69. package/dist/src/platform-startup.js +6 -0
  70. package/dist/src/privacy.js +100 -0
  71. package/dist/src/progress/reducer.js +102 -0
  72. package/dist/src/progress/terminal-renderer.js +264 -0
  73. package/dist/src/progress/view.js +30 -0
  74. package/dist/src/response-stall.js +14 -0
  75. package/dist/src/runtime-entry.js +13 -0
  76. package/dist/src/runtime-reload.js +19 -0
  77. package/dist/src/session-chat-binding.js +183 -0
  78. package/dist/src/session-name.js +7 -0
  79. package/dist/src/session.js +2144 -0
  80. package/dist/src/shared-prefix.js +16 -0
  81. package/dist/src/shared.js +493 -0
  82. package/dist/src/sim-agent.js +105 -0
  83. package/dist/src/sim-platform.js +142 -0
  84. package/dist/src/sim-store.js +231 -0
  85. package/dist/src/simplify.js +99 -0
  86. package/dist/src/startup-lifecycle.js +209 -0
  87. package/dist/src/stream-state.js +141 -0
  88. package/dist/src/terminal-error.js +100 -0
  89. package/dist/src/trace.js +50 -0
  90. package/dist/src/turn-cards.js +92 -0
  91. package/dist/src/update-command-guard.js +114 -0
  92. package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
  93. package/dist/src/wechat-platform.js +545 -0
  94. package/package.json +7 -5
  95. package/deepccc-agent/LICENSE +0 -201
  96. package/deepccc-agent/bin/deepccc.mjs +0 -26
  97. package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
  98. package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
  99. package/deepccc-agent/package-lock.json +0 -2027
  100. package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -852
  101. package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
  102. package/deepccc-agent/src/__tests__/config.test.ts +0 -34
  103. package/deepccc-agent/src/__tests__/context.test.ts +0 -341
  104. package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
  105. package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
  106. package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
  107. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
  108. package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
  109. package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
  110. package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
  111. package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
  112. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
  113. package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
  114. package/deepccc-agent/src/cli.ts +0 -682
  115. package/deepccc-agent/src/config.ts +0 -101
  116. package/deepccc-agent/src/context.ts +0 -465
  117. package/deepccc-agent/src/file-log.ts +0 -38
  118. package/deepccc-agent/src/file-tools.ts +0 -1493
  119. package/deepccc-agent/src/index.ts +0 -676
  120. package/deepccc-agent/src/permissions.ts +0 -226
  121. package/deepccc-agent/src/privacy.ts +0 -141
  122. package/deepccc-agent/src/proc-tree-kill.ts +0 -61
  123. package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
  124. package/deepccc-agent/src/progress/reducer.ts +0 -113
  125. package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
  126. package/deepccc-agent/src/progress/view.ts +0 -77
  127. package/deepccc-agent/src/raw-stream-log.ts +0 -124
  128. package/deepccc-agent/src/session-search.ts +0 -370
  129. package/deepccc-agent/src/session-select.ts +0 -48
  130. package/deepccc-agent/src/sigint.ts +0 -50
  131. package/deepccc-agent/src/skills.ts +0 -205
  132. package/deepccc-agent/src/web-tools.ts +0 -313
  133. package/deepccc-agent/tsconfig.build.json +0 -13
  134. package/deepccc-agent/tsconfig.json +0 -13
  135. package/deepccc-agent/vitest.config.ts +0 -7
  136. package/src/__tests__/adapter-interface.test.ts +0 -152
  137. package/src/__tests__/agent-activity.test.ts +0 -86
  138. package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
  139. package/src/__tests__/agent-image-rpc.test.ts +0 -34
  140. package/src/__tests__/agent-platform-routing.test.ts +0 -26
  141. package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
  142. package/src/__tests__/agent-rpc-body.test.ts +0 -42
  143. package/src/__tests__/builtin-chat-session.test.ts +0 -532
  144. package/src/__tests__/builtin-cli-json.test.ts +0 -39
  145. package/src/__tests__/builtin-config.test.ts +0 -26
  146. package/src/__tests__/builtin-context.test.ts +0 -319
  147. package/src/__tests__/builtin-file-tools.test.ts +0 -240
  148. package/src/__tests__/builtin-permissions.test.ts +0 -219
  149. package/src/__tests__/builtin-session-search.test.ts +0 -262
  150. package/src/__tests__/builtin-session-select.test.ts +0 -116
  151. package/src/__tests__/builtin-sigint.test.ts +0 -56
  152. package/src/__tests__/builtin-skills.test.ts +0 -284
  153. package/src/__tests__/builtin-web-tools.test.ts +0 -220
  154. package/src/__tests__/card-action-routing.test.ts +0 -18
  155. package/src/__tests__/card-plain-text.test.ts +0 -45
  156. package/src/__tests__/cardkit.test.ts +0 -60
  157. package/src/__tests__/cards.test.ts +0 -607
  158. package/src/__tests__/ccc-adapter.test.ts +0 -194
  159. package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
  160. package/src/__tests__/chatgpt-subscription.test.ts +0 -135
  161. package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
  162. package/src/__tests__/claude-adapter.test.ts +0 -614
  163. package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
  164. package/src/__tests__/claude-sdk-installer.test.ts +0 -285
  165. package/src/__tests__/codex-adapter.test.ts +0 -331
  166. package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
  167. package/src/__tests__/codex-reset-actions.test.ts +0 -146
  168. package/src/__tests__/config-reload.test.ts +0 -284
  169. package/src/__tests__/config-sample.test.ts +0 -97
  170. package/src/__tests__/config-utils.test.ts +0 -40
  171. package/src/__tests__/config.test.ts +0 -395
  172. package/src/__tests__/crash-logging.test.ts +0 -360
  173. package/src/__tests__/cursor-adapter.test.ts +0 -890
  174. package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
  175. package/src/__tests__/feishu-api.test.ts +0 -60
  176. package/src/__tests__/feishu-avatar.test.ts +0 -504
  177. package/src/__tests__/feishu-message-ingress.test.ts +0 -138
  178. package/src/__tests__/feishu-platform.test.ts +0 -75
  179. package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
  180. package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
  181. package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
  182. package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
  183. package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
  184. package/src/__tests__/format-message.test.ts +0 -316
  185. package/src/__tests__/git-command.test.ts +0 -288
  186. package/src/__tests__/im-skills.test.ts +0 -125
  187. package/src/__tests__/jsonl-stream.test.ts +0 -79
  188. package/src/__tests__/orchestrator.test.ts +0 -1268
  189. package/src/__tests__/package-files.test.ts +0 -24
  190. package/src/__tests__/platform-startup.test.ts +0 -19
  191. package/src/__tests__/privacy.test.ts +0 -198
  192. package/src/__tests__/proc-tree-kill.test.ts +0 -108
  193. package/src/__tests__/progress-reducer.test.ts +0 -121
  194. package/src/__tests__/raw-stream-log.test.ts +0 -106
  195. package/src/__tests__/response-stall.test.ts +0 -49
  196. package/src/__tests__/restart.test.ts +0 -232
  197. package/src/__tests__/session-ccc-config.test.ts +0 -66
  198. package/src/__tests__/session.test.ts +0 -3004
  199. package/src/__tests__/shared-prefix.test.ts +0 -36
  200. package/src/__tests__/sim-agent.test.ts +0 -174
  201. package/src/__tests__/sim-platform.test.ts +0 -93
  202. package/src/__tests__/sim-store.test.ts +0 -214
  203. package/src/__tests__/simplify.test.ts +0 -283
  204. package/src/__tests__/startup-lifecycle.test.ts +0 -231
  205. package/src/__tests__/stop-session.test.ts +0 -162
  206. package/src/__tests__/stream-state.test.ts +0 -164
  207. package/src/__tests__/terminal-error.test.ts +0 -54
  208. package/src/__tests__/terminal-renderer.test.ts +0 -247
  209. package/src/__tests__/update-command-guard.test.ts +0 -144
  210. package/src/__tests__/web-ui.test.ts +0 -438
  211. package/src/__tests__/wechat-platform.test.ts +0 -111
  212. package/src/adapters/adapter-interface.ts +0 -217
  213. package/src/adapters/ccc-adapter.ts +0 -150
  214. package/src/adapters/claude-adapter.ts +0 -673
  215. package/src/adapters/claude-session-meta-store.ts +0 -120
  216. package/src/adapters/codex-adapter.ts +0 -426
  217. package/src/adapters/codex-session-meta-store.ts +0 -131
  218. package/src/adapters/cursor-adapter.ts +0 -681
  219. package/src/adapters/cursor-session-meta-store.ts +0 -154
  220. package/src/adapters/jsonl-stream.ts +0 -157
  221. package/src/adapters/raw-stream-log.ts +0 -124
  222. package/src/adapters/resource-monitor.ts +0 -141
  223. package/src/agent-activity.ts +0 -175
  224. package/src/agent-delegate-task-rpc.ts +0 -153
  225. package/src/agent-delegate-task.ts +0 -91
  226. package/src/agent-file-rpc.ts +0 -172
  227. package/src/agent-image-rpc.ts +0 -168
  228. package/src/agent-platform-routing.ts +0 -28
  229. package/src/agent-reload-config-rpc.ts +0 -34
  230. package/src/agent-rpc-body.ts +0 -92
  231. package/src/agent-stop-stuck.ts +0 -129
  232. package/src/card-action-routing.ts +0 -14
  233. package/src/card-plain-text.ts +0 -108
  234. package/src/cardkit.ts +0 -179
  235. package/src/cards.ts +0 -684
  236. package/src/chatgpt-subscription-rpc.ts +0 -27
  237. package/src/chatgpt-subscription.ts +0 -299
  238. package/src/chrome-devtools-guard.ts +0 -318
  239. package/src/claude-sdk-installer.ts +0 -324
  240. package/src/codex-reset-actions.ts +0 -184
  241. package/src/config-utils.ts +0 -211
  242. package/src/config.ts +0 -1063
  243. package/src/cursor-usage.ts +0 -128
  244. package/src/exit-banner.ts +0 -33
  245. package/src/feishu-api.ts +0 -1616
  246. package/src/feishu-message-ingress.ts +0 -195
  247. package/src/feishu-platform.ts +0 -159
  248. package/src/format-message.ts +0 -293
  249. package/src/git-command.ts +0 -202
  250. package/src/im-skills.ts +0 -149
  251. package/src/index.ts +0 -1089
  252. package/src/litellm-proxy.ts +0 -374
  253. package/src/orchestrator.ts +0 -2543
  254. package/src/platform-adapter.ts +0 -70
  255. package/src/platform-startup.ts +0 -16
  256. package/src/privacy.ts +0 -118
  257. package/src/progress/reducer.ts +0 -113
  258. package/src/progress/terminal-renderer.ts +0 -294
  259. package/src/progress/view.ts +0 -77
  260. package/src/response-stall.ts +0 -28
  261. package/src/runtime-reload.ts +0 -34
  262. package/src/session-chat-binding.ts +0 -292
  263. package/src/session-name.ts +0 -8
  264. package/src/session.ts +0 -2659
  265. package/src/shared-prefix.ts +0 -29
  266. package/src/shared.ts +0 -552
  267. package/src/sim-agent.ts +0 -167
  268. package/src/sim-platform.ts +0 -177
  269. package/src/sim-store.ts +0 -317
  270. package/src/simplify.ts +0 -120
  271. package/src/startup-lifecycle.ts +0 -250
  272. package/src/stream-state.ts +0 -177
  273. package/src/terminal-error.ts +0 -129
  274. package/src/trace.ts +0 -51
  275. package/src/turn-cards.ts +0 -118
  276. package/src/update-command-guard.ts +0 -165
  277. package/src/wechat-platform.ts +0 -680
@@ -0,0 +1,199 @@
1
+ import WebSocket from "ws";
2
+ import { config } from "./config.js";
3
+ import { probeChromeCdp } from "./chrome-devtools-guard.js";
4
+ const CDP_HOST = "127.0.0.1";
5
+ const DEFAULT_CDP_PORT = 15166;
6
+ const CDP_TIMEOUT_MS = 10_000;
7
+ const CHATGPT_URL = "https://chatgpt.com/";
8
+ function normalizePort(value) {
9
+ const port = Number(value);
10
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
11
+ }
12
+ function cdpBaseUrl(port) {
13
+ return `http://${CDP_HOST}:${port}`;
14
+ }
15
+ function maskEmail(value) {
16
+ if (typeof value !== "string" || !value.includes("@"))
17
+ return undefined;
18
+ const [name, domain] = value.split("@");
19
+ if (!name || !domain)
20
+ return undefined;
21
+ return `${name.slice(0, 2)}***@${domain}`;
22
+ }
23
+ function calculateRemainingDays(expiresAt, now) {
24
+ if (!expiresAt)
25
+ return null;
26
+ const expires = new Date(expiresAt).getTime();
27
+ if (!Number.isFinite(expires))
28
+ return null;
29
+ return Math.max(0, Math.ceil((expires - now.getTime()) / 86_400_000));
30
+ }
31
+ async function fetchJson(url, fetchImpl, init) {
32
+ const response = await fetchImpl(url, init);
33
+ if (!response.ok)
34
+ throw new Error(`HTTP ${response.status}`);
35
+ return await response.json();
36
+ }
37
+ async function listCdpPages(port, fetchImpl) {
38
+ const pages = await fetchJson(`${cdpBaseUrl(port)}/json/list`, fetchImpl);
39
+ return Array.isArray(pages)
40
+ ? pages.flatMap((raw) => {
41
+ if (!raw || typeof raw !== "object")
42
+ return [];
43
+ const page = raw;
44
+ if (typeof page.id !== "string" || typeof page.type !== "string" || typeof page.url !== "string")
45
+ return [];
46
+ return [{
47
+ id: page.id,
48
+ type: page.type,
49
+ title: typeof page.title === "string" ? page.title : undefined,
50
+ url: page.url,
51
+ webSocketDebuggerUrl: typeof page.webSocketDebuggerUrl === "string" ? page.webSocketDebuggerUrl : undefined,
52
+ }];
53
+ })
54
+ : [];
55
+ }
56
+ async function createChatGptPage(port, fetchImpl) {
57
+ const url = `${cdpBaseUrl(port)}/json/new?${encodeURIComponent(CHATGPT_URL)}`;
58
+ const response = await fetchImpl(url, { method: "PUT" });
59
+ if (!response.ok)
60
+ return null;
61
+ const page = await response.json();
62
+ if (typeof page.id !== "string" || typeof page.webSocketDebuggerUrl !== "string")
63
+ return null;
64
+ return {
65
+ id: page.id,
66
+ type: typeof page.type === "string" ? page.type : "page",
67
+ title: typeof page.title === "string" ? page.title : undefined,
68
+ url: typeof page.url === "string" ? page.url : CHATGPT_URL,
69
+ webSocketDebuggerUrl: page.webSocketDebuggerUrl,
70
+ };
71
+ }
72
+ async function closeCdpPage(port, pageId, fetchImpl) {
73
+ try {
74
+ await fetchImpl(`${cdpBaseUrl(port)}/json/close/${encodeURIComponent(pageId)}`);
75
+ }
76
+ catch {
77
+ // Closing a temporary tab is best effort and must not change the query result.
78
+ }
79
+ }
80
+ function subscriptionProbeExpression() {
81
+ 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)}}})()`;
82
+ }
83
+ async function evaluateInPage(webSocketDebuggerUrl, expression) {
84
+ return await new Promise((resolve, reject) => {
85
+ const ws = new WebSocket(webSocketDebuggerUrl);
86
+ const id = 1;
87
+ const timer = setTimeout(() => {
88
+ ws.close();
89
+ reject(new Error("CDP Runtime.evaluate timed out"));
90
+ }, CDP_TIMEOUT_MS);
91
+ ws.on("open", () => {
92
+ ws.send(JSON.stringify({
93
+ id,
94
+ method: "Runtime.evaluate",
95
+ params: { expression, awaitPromise: true, returnByValue: true },
96
+ }));
97
+ });
98
+ ws.on("message", (data) => {
99
+ const msg = JSON.parse(String(data));
100
+ if (msg.id !== id)
101
+ return;
102
+ clearTimeout(timer);
103
+ ws.close();
104
+ if (msg.error) {
105
+ reject(new Error(JSON.stringify(msg.error)));
106
+ }
107
+ else {
108
+ resolve(msg.result?.result?.value);
109
+ }
110
+ });
111
+ ws.on("error", (err) => {
112
+ clearTimeout(timer);
113
+ reject(err);
114
+ });
115
+ });
116
+ }
117
+ function failure(code, reason, chromeCdp, extra = {}) {
118
+ return { ok: false, code, reason, chromeCdp, ...extra };
119
+ }
120
+ export function isExpectedSubscriptionFailure(code) {
121
+ return code !== "chatgpt_subscription_failed";
122
+ }
123
+ export async function getChatGptSubscriptionStatus(deps = {}) {
124
+ const cfg = config.chromeDevtools;
125
+ const port = normalizePort(cfg.port);
126
+ const baseChromeCdp = { enabled: cfg.enabled, port };
127
+ const fetchImpl = deps.fetchImpl ?? fetch;
128
+ if (!cfg.enabled) {
129
+ return failure("chrome_cdp_disabled", "Chrome CDP guard is disabled in ChatCCC config.", {
130
+ ...baseChromeCdp,
131
+ status: "skipped",
132
+ });
133
+ }
134
+ const probe = await (deps.probeChromeCdpImpl ?? probeChromeCdp)(port, { fetchImpl });
135
+ const chromeCdp = { ...baseChromeCdp, status: probe };
136
+ if (probe === "unreachable") {
137
+ return failure("chrome_cdp_unreachable", `Chrome CDP endpoint is unreachable on port ${port}.`, chromeCdp);
138
+ }
139
+ if (probe === "occupied") {
140
+ return failure("chrome_cdp_occupied", `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`, chromeCdp);
141
+ }
142
+ let temporaryPage = null;
143
+ try {
144
+ const existingPages = await listCdpPages(port, fetchImpl);
145
+ let page = existingPages.find((p) => p.type === "page" &&
146
+ p.webSocketDebuggerUrl &&
147
+ p.url.startsWith(CHATGPT_URL)) ?? null;
148
+ if (!page) {
149
+ temporaryPage = await createChatGptPage(port, fetchImpl);
150
+ page = temporaryPage;
151
+ }
152
+ if (!page?.webSocketDebuggerUrl) {
153
+ return failure("chatgpt_page_missing", "No usable chatgpt.com page is available from Chrome CDP.", chromeCdp);
154
+ }
155
+ const raw = await (deps.evaluateInPage ?? evaluateInPage)(page.webSocketDebuggerUrl, subscriptionProbeExpression());
156
+ if (!raw || typeof raw !== "object") {
157
+ return failure("chatgpt_subscription_failed", "Chrome CDP returned an empty subscription probe result.", chromeCdp);
158
+ }
159
+ if (raw.error) {
160
+ return failure("chatgpt_subscription_failed", raw.error, chromeCdp);
161
+ }
162
+ const chatgpt = {
163
+ sessionOk: raw.sessionOk === true,
164
+ maskedEmail: raw.maskedEmail || undefined,
165
+ sessionExpiresAt: typeof raw.sessionExpires === "string" ? raw.sessionExpires : undefined,
166
+ };
167
+ if (!raw.hasAccessToken) {
168
+ return failure("chatgpt_session_missing", "ChatGPT browser session has no access token.", chromeCdp, { chatgpt });
169
+ }
170
+ if (!raw.account?.ok || !raw.account.entitlement) {
171
+ return failure("chatgpt_subscription_failed", `ChatGPT account check failed${raw.account?.status ? ` with HTTP ${raw.account.status}` : ""}.`, chromeCdp, { chatgpt });
172
+ }
173
+ const entitlement = raw.account.entitlement;
174
+ const last = raw.account.last_active_subscription;
175
+ const expiresAt = typeof entitlement.expires_at === "string" ? entitlement.expires_at : null;
176
+ return {
177
+ ok: true,
178
+ code: "ok",
179
+ chromeCdp,
180
+ chatgpt,
181
+ subscription: {
182
+ active: entitlement.has_active_subscription === true,
183
+ plan: typeof entitlement.subscription_plan === "string" ? entitlement.subscription_plan : null,
184
+ expiresAt,
185
+ willRenew: typeof last?.will_renew === "boolean" ? last.will_renew : null,
186
+ purchaseOriginPlatform: typeof last?.purchase_origin_platform === "string" ? last.purchase_origin_platform : null,
187
+ remainingDays: calculateRemainingDays(expiresAt, deps.now?.() ?? new Date()),
188
+ },
189
+ };
190
+ }
191
+ catch (err) {
192
+ return failure("chatgpt_subscription_failed", err.message, chromeCdp);
193
+ }
194
+ finally {
195
+ if (temporaryPage) {
196
+ await closeCdpPage(port, temporaryPage.id, fetchImpl);
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,238 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { appendStartupTrace } from "./shared.js";
5
+ import { config, ts, USER_DATA_DIR } from "./config.js";
6
+ const CDP_HOST = "127.0.0.1";
7
+ const DEFAULT_CDP_PORT = 15166;
8
+ const HEALTH_TIMEOUT_MS = 3000;
9
+ const START_VERIFY_ATTEMPTS = 10;
10
+ const START_VERIFY_DELAY_MS = 500;
11
+ const GUARD_INTERVAL_MS = 60_000;
12
+ let guardTimer = null;
13
+ let ensureInFlight = null;
14
+ function normalizePort(value) {
15
+ const port = Number(value);
16
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
17
+ }
18
+ function chromeCandidates(platform, env) {
19
+ if (platform === "win32") {
20
+ return [
21
+ env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
22
+ env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"], "Google", "Chrome", "Application", "chrome.exe") : "",
23
+ env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
24
+ ].filter(Boolean);
25
+ }
26
+ if (platform === "darwin") {
27
+ return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
28
+ }
29
+ return [
30
+ "/usr/bin/google-chrome",
31
+ "/usr/bin/google-chrome-stable",
32
+ "/usr/bin/chromium",
33
+ "/usr/bin/chromium-browser",
34
+ ];
35
+ }
36
+ export function resolveChromeExecutable(chromePath, deps = {}) {
37
+ const exists = deps.existsSyncImpl ?? existsSync;
38
+ const explicit = chromePath?.trim();
39
+ if (explicit)
40
+ return exists(explicit) ? explicit : null;
41
+ for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
42
+ if (exists(candidate))
43
+ return candidate;
44
+ }
45
+ return null;
46
+ }
47
+ export function resolveChromeUserDataDir(port, env = process.env) {
48
+ const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
49
+ return join(root, `chrome-cdp-${port}`);
50
+ }
51
+ async function fetchWithTimeout(url, fetchImpl, timeoutMs, init = {}) {
52
+ const controller = new AbortController();
53
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
54
+ try {
55
+ return await fetchImpl(url, { ...init, signal: controller.signal });
56
+ }
57
+ finally {
58
+ clearTimeout(timer);
59
+ }
60
+ }
61
+ export async function probeChromeCdp(port, deps = {}) {
62
+ const normalizedPort = normalizePort(port);
63
+ try {
64
+ const response = await fetchWithTimeout(`http://${CDP_HOST}:${normalizedPort}/json/version`, deps.fetchImpl ?? fetch, HEALTH_TIMEOUT_MS);
65
+ if (!response.ok)
66
+ return "occupied";
67
+ const data = await response.json();
68
+ return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
69
+ ? "healthy"
70
+ : "occupied";
71
+ }
72
+ catch {
73
+ return "unreachable";
74
+ }
75
+ }
76
+ export async function isChromeCdpHealthy(port, deps = {}) {
77
+ return (await probeChromeCdp(port, deps)) === "healthy";
78
+ }
79
+ function startChromeForCdp(cfg, deps = {}) {
80
+ const port = normalizePort(cfg.port);
81
+ const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
82
+ if (!chromeExe) {
83
+ return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
84
+ }
85
+ const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
86
+ try {
87
+ (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
88
+ }
89
+ catch (err) {
90
+ return { ok: false, error: `Cannot create Chrome user data dir: ${err.message}` };
91
+ }
92
+ const args = [
93
+ `--remote-debugging-address=${CDP_HOST}`,
94
+ `--remote-debugging-port=${port}`,
95
+ `--user-data-dir=${userDataDir}`,
96
+ "--no-first-run",
97
+ "--no-default-browser-check",
98
+ "--new-window",
99
+ "about:blank",
100
+ ];
101
+ try {
102
+ const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
103
+ detached: true,
104
+ stdio: "ignore",
105
+ windowsHide: true,
106
+ });
107
+ child.unref();
108
+ return { ok: true, child };
109
+ }
110
+ catch (err) {
111
+ return { ok: false, error: `Failed to start Chrome: ${err.message}` };
112
+ }
113
+ }
114
+ function sleep(ms) {
115
+ return new Promise((resolve) => setTimeout(resolve, ms));
116
+ }
117
+ function cdpBaseUrl(port) {
118
+ return `http://${CDP_HOST}:${port}`;
119
+ }
120
+ function isChatcccPageUrl(value, chatcccPort) {
121
+ if (!value)
122
+ return false;
123
+ try {
124
+ const url = new URL(value);
125
+ return url.protocol === "http:" &&
126
+ (url.hostname === "localhost" || url.hostname === CDP_HOST) &&
127
+ url.port === String(chatcccPort);
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
133
+ export async function ensureChatcccPageOpen(cdpPort, chatcccPort, deps = {}) {
134
+ const normalizedCdpPort = normalizePort(cdpPort);
135
+ const normalizedChatcccPort = normalizePort(chatcccPort);
136
+ const fetchImpl = deps.fetchImpl ?? fetch;
137
+ try {
138
+ const listResponse = await fetchWithTimeout(`${cdpBaseUrl(normalizedCdpPort)}/json/list`, fetchImpl, HEALTH_TIMEOUT_MS);
139
+ if (!listResponse.ok) {
140
+ return { ok: false, opened: false, error: `Cannot list Chrome CDP pages: HTTP ${listResponse.status}` };
141
+ }
142
+ const pages = await listResponse.json();
143
+ if (Array.isArray(pages) && pages.some((page) => isChatcccPageUrl(page?.url, normalizedChatcccPort))) {
144
+ return { ok: true, opened: false };
145
+ }
146
+ const targetUrl = `http://localhost:${normalizedChatcccPort}/`;
147
+ const openResponse = await fetchWithTimeout(`${cdpBaseUrl(normalizedCdpPort)}/json/new?${encodeURIComponent(targetUrl)}`, fetchImpl, HEALTH_TIMEOUT_MS, { method: "PUT" });
148
+ if (!openResponse.ok) {
149
+ return { ok: false, opened: false, error: `Cannot open ${targetUrl}: HTTP ${openResponse.status}` };
150
+ }
151
+ return { ok: true, opened: true };
152
+ }
153
+ catch (err) {
154
+ return { ok: false, opened: false, error: err.message };
155
+ }
156
+ }
157
+ export async function ensureChromeCdpRunning(cfg = config.chromeDevtools, deps = {}) {
158
+ const port = normalizePort(cfg.port);
159
+ if (!cfg.enabled)
160
+ return { ok: true, started: false, port };
161
+ const probe = await probeChromeCdp(port, deps);
162
+ if (probe === "healthy") {
163
+ return { ok: true, started: false, port };
164
+ }
165
+ if (probe === "occupied") {
166
+ return {
167
+ ok: false,
168
+ started: false,
169
+ port,
170
+ error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
171
+ };
172
+ }
173
+ const started = startChromeForCdp({ ...cfg, port }, deps);
174
+ if (!started.ok)
175
+ return { ok: false, started: false, port, error: started.error };
176
+ for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
177
+ await sleep(START_VERIFY_DELAY_MS);
178
+ if (await isChromeCdpHealthy(port, deps)) {
179
+ return { ok: true, started: true, port };
180
+ }
181
+ }
182
+ return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
183
+ }
184
+ async function runGuardOnce(reason, deps = {}) {
185
+ if (ensureInFlight)
186
+ return;
187
+ const log = deps.log ?? ((message) => console.log(message));
188
+ ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
189
+ try {
190
+ const result = await ensureInFlight;
191
+ const chatcccPage = config.chromeDevtools.enabled && result.ok
192
+ ? await ensureChatcccPageOpen(result.port, config.port, deps)
193
+ : null;
194
+ appendStartupTrace("chrome-devtools-guard: ensure result", {
195
+ reason,
196
+ enabled: config.chromeDevtools.enabled,
197
+ port: result.port,
198
+ ok: result.ok,
199
+ started: result.started,
200
+ error: result.error,
201
+ chatcccPage,
202
+ });
203
+ if (!config.chromeDevtools.enabled)
204
+ return;
205
+ if (result.ok && result.started) {
206
+ log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
207
+ }
208
+ else if (!result.ok) {
209
+ log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
210
+ }
211
+ if (chatcccPage?.opened) {
212
+ log(`[${ts()}] [Chrome CDP] Opened ChatCCC page http://localhost:${config.port}/`);
213
+ }
214
+ else if (chatcccPage && !chatcccPage.ok) {
215
+ log(`[${ts()}] [Chrome CDP] Failed to ensure ChatCCC page: ${chatcccPage.error}`);
216
+ }
217
+ }
218
+ finally {
219
+ ensureInFlight = null;
220
+ }
221
+ }
222
+ export function startChromeDevtoolsGuard(deps = {}) {
223
+ stopChromeDevtoolsGuard();
224
+ if (!config.chromeDevtools.enabled) {
225
+ appendStartupTrace("chrome-devtools-guard: disabled");
226
+ return;
227
+ }
228
+ void runGuardOnce("startup", deps);
229
+ guardTimer = setInterval(() => {
230
+ void runGuardOnce("interval", deps);
231
+ }, GUARD_INTERVAL_MS);
232
+ }
233
+ export function stopChromeDevtoolsGuard() {
234
+ if (guardTimer) {
235
+ clearInterval(guardTimer);
236
+ guardTimer = null;
237
+ }
238
+ }
@@ -0,0 +1,249 @@
1
+ // =============================================================================
2
+ // claude-sdk-installer.ts — Claude Code 引擎(Agent SDK)按需安装器
3
+ // =============================================================================
4
+ // 背景:@anthropic-ai/claude-agent-sdk 通过 optionalDependencies 内置各平台
5
+ // 的原生 CLI 二进制(Windows 上 claude.exe 约 215MB),若作为 chatccc 的硬依赖,
6
+ // 所有用户(包括不用 Claude Code 的)都要白白下载 220MB+。
7
+ //
8
+ // 方案:把 SDK 从 chatccc 的 dependencies 中移除,改为**按需安装**到
9
+ // `~/.chatccc/claude-sdk/`:
10
+ // - 用户未启用 Claude Code → 完全不下载,npm 包体积大幅下降;
11
+ // - 用户在设置页打开 Claude Code 开关时,点「安装引擎」触发后台安装,
12
+ // 带进度条(状态式:检测环境 → 下载中 → 安装中 → 完成/失败)。
13
+ //
14
+ // 设计约束:
15
+ // - **不 import config.ts**(config.ts 顶层有 loadConfig 副作用,web-ui.ts
16
+ // 依赖本模块,间接 import config.ts 会污染依赖 web-ui.ts 的单测)。
17
+ // - 始终使用 SDK 内置的 CLI 二进制(用户拍板档位 b),不依赖用户自装 CLI。
18
+ // - 安装目录可注入(dir 参数),便于单测用临时目录,不碰真实用户目录。
19
+ // =============================================================================
20
+ import { spawn } from "node:child_process";
21
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { join } from "node:path";
24
+ /** 与当前代码配套的 SDK 版本(package.json 移除依赖后此常量成为唯一版本来源) */
25
+ export const CLAUDE_SDK_VERSION = "0.2.133";
26
+ /** 按需安装目录:~/.chatccc/claude-sdk */
27
+ export const CLAUDE_SDK_DIR = join(homedir(), ".chatccc", "claude-sdk");
28
+ const SDK_PKG_REL = join("node_modules", "@anthropic-ai", "claude-agent-sdk", "package.json");
29
+ const SDK_ENTRY_REL = join("node_modules", "@anthropic-ai", "claude-agent-sdk", "sdk.mjs");
30
+ const LOCK_FILE = ".installing";
31
+ /** 估算的完整安装体积(含内置 CLI 二进制),用于进度条展示 */
32
+ export const CLAUDE_SDK_EXPECTED_BYTES = 240 * 1024 * 1024;
33
+ // ---------------------------------------------------------------------------
34
+ // 状态查询
35
+ // ---------------------------------------------------------------------------
36
+ /** SDK 入口文件绝对路径(供动态 import) */
37
+ export function getClaudeSdkEntryPath(dir = CLAUDE_SDK_DIR) {
38
+ return join(dir, SDK_ENTRY_REL);
39
+ }
40
+ /** 是否已安装(node_modules 里存在 SDK package.json 即视为已装) */
41
+ export function isClaudeSdkInstalled(dir = CLAUDE_SDK_DIR) {
42
+ return existsSync(join(dir, SDK_PKG_REL));
43
+ }
44
+ /** 已安装版本号;未安装/解析失败返回 null */
45
+ export function getClaudeSdkInstalledVersion(dir = CLAUDE_SDK_DIR) {
46
+ try {
47
+ const raw = readFileSync(join(dir, SDK_PKG_REL), "utf8");
48
+ const pkg = JSON.parse(raw);
49
+ return typeof pkg.version === "string" ? pkg.version : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ /** 是否正在安装(锁文件存在且 pid 存活);pid 已死视为过期锁并自动清理 */
56
+ export function isClaudeSdkInstalling(dir = CLAUDE_SDK_DIR) {
57
+ const lockPath = join(dir, LOCK_FILE);
58
+ if (!existsSync(lockPath))
59
+ return false;
60
+ try {
61
+ const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
62
+ if (Number.isFinite(pid) && pid > 0 && isPidAlive(pid))
63
+ return true;
64
+ }
65
+ catch {
66
+ // 锁文件损坏 → 按过期处理,走清理
67
+ }
68
+ try {
69
+ unlinkSync(lockPath);
70
+ }
71
+ catch {
72
+ // 清理失败不阻塞判断
73
+ }
74
+ return false;
75
+ }
76
+ function isPidAlive(pid) {
77
+ try {
78
+ process.kill(pid, 0);
79
+ return true;
80
+ }
81
+ catch (err) {
82
+ return err.code === "EPERM";
83
+ }
84
+ }
85
+ // ---------------------------------------------------------------------------
86
+ // 安装(后台任务 + 进度)
87
+ // ---------------------------------------------------------------------------
88
+ /** 最近一次安装的进度快照,供 web-ui 轮询 */
89
+ let lastProgress = { phase: "idle", percent: 0, message: "" };
90
+ let installInProgress = false;
91
+ export function getLastInstallProgress() {
92
+ return { ...lastProgress, ...(lastProgress.error ? { error: lastProgress.error } : {}) };
93
+ }
94
+ export function isInstallRunning() {
95
+ return installInProgress;
96
+ }
97
+ function setProgress(p, onProgress) {
98
+ lastProgress = { ...p };
99
+ onProgress?.(lastProgress);
100
+ }
101
+ /**
102
+ * 启动按需安装。返回 Promise,安装完成 resolve、失败 reject。
103
+ * 调用方通常不 await(后台执行),通过 onProgress / getLastInstallProgress() 获取进度。
104
+ */
105
+ export async function installClaudeSdk(options = {}) {
106
+ const dir = options.dir ?? CLAUDE_SDK_DIR;
107
+ const npmCommand = options.npmCommand ?? "npm";
108
+ const expected = options.expectedVersion ?? CLAUDE_SDK_VERSION;
109
+ const onProgress = options.onProgress;
110
+ if (installInProgress) {
111
+ throw new Error("Claude Code 引擎正在安装中,请等待完成后再试。");
112
+ }
113
+ if (isClaudeSdkInstalling(dir)) {
114
+ throw new Error("检测到另一个安装任务正在进行(锁文件存在),请稍后再试。");
115
+ }
116
+ const installedVersion = isClaudeSdkInstalled(dir) ? getClaudeSdkInstalledVersion(dir) : null;
117
+ if (installedVersion === expected) {
118
+ setProgress({ phase: "done", percent: 100, message: `已安装 v${installedVersion}` }, onProgress);
119
+ return;
120
+ }
121
+ if (installedVersion !== null && installedVersion !== expected) {
122
+ setProgress({
123
+ phase: "detecting",
124
+ percent: 3,
125
+ message: `已装 v${installedVersion} ≠ 期望 v${expected},开始重装…`,
126
+ }, onProgress);
127
+ }
128
+ installInProgress = true;
129
+ mkdirSync(dir, { recursive: true });
130
+ writeFileSync(join(dir, LOCK_FILE), String(process.pid), "utf8");
131
+ setProgress({ phase: "detecting", percent: 2, message: "检测环境…" }, onProgress);
132
+ return new Promise((resolve, reject) => {
133
+ const child = spawn(npmCommand, [
134
+ "install",
135
+ "--prefix",
136
+ dir,
137
+ `@anthropic-ai/claude-agent-sdk@${expected}`,
138
+ "--no-audit",
139
+ "--no-fund",
140
+ "--loglevel=http",
141
+ ], {
142
+ stdio: ["ignore", "pipe", "pipe"],
143
+ windowsHide: true,
144
+ // Windows 下 npm 是 npm.cmd,需要 shell 才能解析
145
+ shell: process.platform === "win32",
146
+ });
147
+ let stderrBuf = "";
148
+ let requestCount = 0;
149
+ let sizeTimer = null;
150
+ const updateBySize = () => {
151
+ const size = dirSizeBytes(dir);
152
+ const sizePercent = Math.min((size / CLAUDE_SDK_EXPECTED_BYTES) * 90, 90);
153
+ const requestPercent = Math.min(5 + requestCount * 4, 70);
154
+ const percent = Math.max(sizePercent, requestPercent);
155
+ const mb = (size / 1048576).toFixed(0);
156
+ setProgress({
157
+ phase: "downloading",
158
+ percent: Math.min(percent, 94),
159
+ message: `下载中… 已下载 ${mb} MB / 约 220 MB`,
160
+ }, onProgress);
161
+ };
162
+ child.stdout.on("data", (chunk) => {
163
+ const text = chunk.toString();
164
+ // npm --loglevel=http 每完成一个请求输出一行 "npm http fetch GET 200 ..."
165
+ requestCount += (text.match(/http fetch GET|GET \d{3}/g) ?? []).length;
166
+ updateBySize();
167
+ });
168
+ child.stderr.on("data", (chunk) => {
169
+ stderrBuf += chunk.toString();
170
+ });
171
+ child.on("error", (err) => {
172
+ cleanupAfterFailure(dir, err, onProgress, () => {
173
+ installInProgress = false;
174
+ reject(err);
175
+ });
176
+ });
177
+ child.on("close", (code) => {
178
+ if (sizeTimer)
179
+ clearInterval(sizeTimer);
180
+ if (code === 0 && isClaudeSdkInstalled(dir)) {
181
+ const version = getClaudeSdkInstalledVersion(dir);
182
+ installInProgress = false;
183
+ try {
184
+ unlinkSync(join(dir, LOCK_FILE));
185
+ }
186
+ catch {
187
+ // 锁文件不存在可忽略
188
+ }
189
+ setProgress({ phase: "done", percent: 100, message: `安装完成(v${version ?? expected})` }, onProgress);
190
+ resolve();
191
+ }
192
+ else {
193
+ const tail = stderrBuf.trim().split("\n").slice(-5).join(" | ");
194
+ const detail = code !== 0 ? `npm 退出码 ${code}` : "安装后校验未通过";
195
+ const message = tail ? `${detail}:${tail.slice(0, 400)}` : detail;
196
+ cleanupAfterFailure(dir, new Error(message), onProgress, () => {
197
+ installInProgress = false;
198
+ reject(new Error(message));
199
+ });
200
+ }
201
+ });
202
+ // 定期按目录体积刷新进度(大文件下载时 stdout 事件稀疏)
203
+ sizeTimer = setInterval(() => {
204
+ if (installInProgress)
205
+ updateBySize();
206
+ }, 400);
207
+ if (typeof sizeTimer.unref === "function")
208
+ sizeTimer.unref();
209
+ });
210
+ }
211
+ function cleanupAfterFailure(dir, err, onProgress, after) {
212
+ setProgress({ phase: "error", percent: 0, message: "安装失败", error: err.message.slice(0, 500) }, onProgress);
213
+ try {
214
+ rmSync(dir, { recursive: true, force: true });
215
+ }
216
+ catch {
217
+ // 清理失败不阻塞
218
+ }
219
+ after();
220
+ }
221
+ function dirSizeBytes(dir) {
222
+ let total = 0;
223
+ const stack = [dir];
224
+ while (stack.length > 0) {
225
+ const current = stack.pop();
226
+ let entries;
227
+ try {
228
+ entries = readdirSync(current, { withFileTypes: true });
229
+ }
230
+ catch {
231
+ continue;
232
+ }
233
+ for (const entry of entries) {
234
+ const full = join(current, entry.name);
235
+ if (entry.isDirectory()) {
236
+ stack.push(full);
237
+ }
238
+ else if (entry.isFile()) {
239
+ try {
240
+ total += statSync(full).size;
241
+ }
242
+ catch {
243
+ // 文件被并发删除可忽略
244
+ }
245
+ }
246
+ }
247
+ }
248
+ return total;
249
+ }