@hjd-hitsz/claudex-web 0.0.0-stage → 4.1.0

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 (340) hide show
  1. package/.env.example +27 -0
  2. package/CHANGELOG.md +495 -0
  3. package/LICENSE +674 -0
  4. package/README.md +106 -2
  5. package/bin/claudex-web.mjs +129 -0
  6. package/build-info.json +8 -0
  7. package/client/dist/_baseMerge.js +1 -0
  8. package/client/dist/abnfDiagram-WEYOIA3C.js +1 -0
  9. package/client/dist/apl.js +1 -0
  10. package/client/dist/app.js +392 -0
  11. package/client/dist/apple-touch-icon.png +0 -0
  12. package/client/dist/arc.js +1 -0
  13. package/client/dist/architectureDiagram-ZHVYKT53.js +36 -0
  14. package/client/dist/asciiarmor.js +1 -0
  15. package/client/dist/asn1.js +1 -0
  16. package/client/dist/asterisk.js +1 -0
  17. package/client/dist/blockDiagram-RJAE7QA3.js +140 -0
  18. package/client/dist/brainfuck.js +1 -0
  19. package/client/dist/c4Diagram-XDPPPE54.js +38 -0
  20. package/client/dist/channel.js +1 -0
  21. package/client/dist/chunk-2E7WHVMD.js +88 -0
  22. package/client/dist/chunk-2Q5K7J3B.js +1 -0
  23. package/client/dist/chunk-4EMNKR2T.js +1 -0
  24. package/client/dist/chunk-55XCU76K.js +1 -0
  25. package/client/dist/chunk-5VM5RSS4.js +15 -0
  26. package/client/dist/chunk-JWPE2WC7.js +1 -0
  27. package/client/dist/chunk-VQ5W62QI.js +1 -0
  28. package/client/dist/chunk-XXDRQBXY.js +1 -0
  29. package/client/dist/chunk-ZCHMQSOR.js +2 -0
  30. package/client/dist/classDiagram-v2-4MYWR3UA.js +217 -0
  31. package/client/dist/clike.js +1 -0
  32. package/client/dist/clojure.js +1 -0
  33. package/client/dist/cmake.js +1 -0
  34. package/client/dist/cobol.js +1 -0
  35. package/client/dist/code-highlight-style.js +13 -0
  36. package/client/dist/coffeescript.js +1 -0
  37. package/client/dist/commonlisp.js +1 -0
  38. package/client/dist/cose-bilkent-JH36ORCC.js +1 -0
  39. package/client/dist/crystal.js +1 -0
  40. package/client/dist/css.js +1 -0
  41. package/client/dist/cynefin-EF2NZ3EQ.js +141 -0
  42. package/client/dist/cynefinDiagram-WF24UDRP.js +62 -0
  43. package/client/dist/cypher.js +1 -0
  44. package/client/dist/cytoscape.esm.js +321 -0
  45. package/client/dist/d.js +1 -0
  46. package/client/dist/dagre-NK4GIZVX.js +4 -0
  47. package/client/dist/defaultLocale.js +1 -0
  48. package/client/dist/diagram-CBK3MWTC.js +24 -0
  49. package/client/dist/diagram-I5XIIV2D.js +24 -0
  50. package/client/dist/diagram-ODIL2UCW.js +30 -0
  51. package/client/dist/diagram-PFBEJUXE.js +3 -0
  52. package/client/dist/diagram-RJA3I4VV.js +41 -0
  53. package/client/dist/diagram-TYUNFSNR.js +200 -0
  54. package/client/dist/diff.js +1 -0
  55. package/client/dist/dockerfile.js +1 -0
  56. package/client/dist/document-editor.js +1040 -0
  57. package/client/dist/dtd.js +1 -0
  58. package/client/dist/dylan.js +1 -0
  59. package/client/dist/ebnf.js +1 -0
  60. package/client/dist/ebnfDiagram-V4P3TTPT.js +1 -0
  61. package/client/dist/ecl.js +1 -0
  62. package/client/dist/eiffel.js +1 -0
  63. package/client/dist/elk-QONTBCTQ.js +27 -0
  64. package/client/dist/elm.js +1 -0
  65. package/client/dist/erDiagram-KYQIGQAA.js +99 -0
  66. package/client/dist/erlang.js +1 -0
  67. package/client/dist/factor.js +1 -0
  68. package/client/dist/favicon.ico +0 -0
  69. package/client/dist/favicon.png +0 -0
  70. package/client/dist/fcl.js +1 -0
  71. package/client/dist/file-panel.js +1 -0
  72. package/client/dist/flowDiagram-IUGLLWBU.js +213 -0
  73. package/client/dist/forth.js +1 -0
  74. package/client/dist/fortran.js +1 -0
  75. package/client/dist/ganttDiagram-R7GPNTJY.js +292 -0
  76. package/client/dist/gas.js +1 -0
  77. package/client/dist/gherkin.js +1 -0
  78. package/client/dist/gitGraphDiagram-PDYL7XHY.js +106 -0
  79. package/client/dist/graph.js +1 -0
  80. package/client/dist/groovy.js +1 -0
  81. package/client/dist/haskell.js +1 -0
  82. package/client/dist/haxe.js +1 -0
  83. package/client/dist/http.js +1 -0
  84. package/client/dist/idl.js +1 -0
  85. package/client/dist/index.html +25 -0
  86. package/client/dist/index.js +2 -0
  87. package/client/dist/index10.js +1 -0
  88. package/client/dist/index11.js +1 -0
  89. package/client/dist/index12.js +1 -0
  90. package/client/dist/index13.js +7 -0
  91. package/client/dist/index14.js +1 -0
  92. package/client/dist/index15.js +1 -0
  93. package/client/dist/index16.js +6 -0
  94. package/client/dist/index17.js +1 -0
  95. package/client/dist/index18.js +3 -0
  96. package/client/dist/index19.js +1 -0
  97. package/client/dist/index2.js +1 -0
  98. package/client/dist/index20.js +1 -0
  99. package/client/dist/index21.js +1 -0
  100. package/client/dist/index22.js +1 -0
  101. package/client/dist/index3.js +1 -0
  102. package/client/dist/index4.js +1 -0
  103. package/client/dist/index5.js +1 -0
  104. package/client/dist/index6.js +13 -0
  105. package/client/dist/index7.js +1 -0
  106. package/client/dist/index8.js +1 -0
  107. package/client/dist/index9.js +1 -0
  108. package/client/dist/infoDiagram-MVDRKAX5.js +2 -0
  109. package/client/dist/init.js +1 -0
  110. package/client/dist/isArrayLikeObject.js +1 -0
  111. package/client/dist/ishikawaDiagram-HPEHV2GE.js +70 -0
  112. package/client/dist/javascript.js +1 -0
  113. package/client/dist/journeyDiagram-BOSHW7O7.js +139 -0
  114. package/client/dist/julia.js +1 -0
  115. package/client/dist/kanban-definition-FNSA4HC5.js +89 -0
  116. package/client/dist/katex.js +257 -0
  117. package/client/dist/linear.js +1 -0
  118. package/client/dist/livescript.js +1 -0
  119. package/client/dist/lua.js +1 -0
  120. package/client/dist/mathematica.js +1 -0
  121. package/client/dist/mbox.js +1 -0
  122. package/client/dist/mermaid.core.js +310 -0
  123. package/client/dist/mindmap-definition-6OY57UG3.js +98 -0
  124. package/client/dist/mirc.js +1 -0
  125. package/client/dist/mllike.js +1 -0
  126. package/client/dist/modelica.js +1 -0
  127. package/client/dist/mscgen.js +1 -0
  128. package/client/dist/mumps.js +1 -0
  129. package/client/dist/nginx.js +1 -0
  130. package/client/dist/notification-worker.js +45 -0
  131. package/client/dist/nsis.js +1 -0
  132. package/client/dist/ntriples.js +1 -0
  133. package/client/dist/octave.js +1 -0
  134. package/client/dist/ordinal.js +1 -0
  135. package/client/dist/oz.js +1 -0
  136. package/client/dist/pascal.js +1 -0
  137. package/client/dist/pegDiagram-ECIUJNBX.js +1 -0
  138. package/client/dist/perl.js +1 -0
  139. package/client/dist/pieDiagram-GNMPY74T.js +39 -0
  140. package/client/dist/pig.js +1 -0
  141. package/client/dist/powershell.js +1 -0
  142. package/client/dist/properties.js +1 -0
  143. package/client/dist/protobuf.js +1 -0
  144. package/client/dist/pug.js +1 -0
  145. package/client/dist/puppet.js +1 -0
  146. package/client/dist/purify.es.js +3 -0
  147. package/client/dist/python.js +1 -0
  148. package/client/dist/q.js +1 -0
  149. package/client/dist/quadrantDiagram-D57K4MC3.js +7 -0
  150. package/client/dist/r.js +1 -0
  151. package/client/dist/railroadDiagram-Y72NRBL7.js +1 -0
  152. package/client/dist/requirementDiagram-EQYSW5RA.js +84 -0
  153. package/client/dist/rpm.js +1 -0
  154. package/client/dist/ruby.js +1 -0
  155. package/client/dist/sankeyDiagram-SY24JHO5.js +40 -0
  156. package/client/dist/sas.js +1 -0
  157. package/client/dist/scheme.js +1 -0
  158. package/client/dist/sequenceDiagram-BLEHNHQU.js +169 -0
  159. package/client/dist/shell.js +1 -0
  160. package/client/dist/sieve.js +1 -0
  161. package/client/dist/simple-mode.js +1 -0
  162. package/client/dist/sizeCapture-INFHLROL.js +1 -0
  163. package/client/dist/smalltalk.js +1 -0
  164. package/client/dist/solr.js +1 -0
  165. package/client/dist/sparql.js +1 -0
  166. package/client/dist/spreadsheet.js +1 -0
  167. package/client/dist/sql.js +1 -0
  168. package/client/dist/stateDiagram-v2-A6IESKWZ.js +291 -0
  169. package/client/dist/stex.js +1 -0
  170. package/client/dist/style.css +1 -0
  171. package/client/dist/stylus.js +1 -0
  172. package/client/dist/swift.js +1 -0
  173. package/client/dist/swimlanes-B3ENRKFQ.js +1 -0
  174. package/client/dist/swimlanesDiagram-AYQRV4AK.js +8 -0
  175. package/client/dist/tcl.js +1 -0
  176. package/client/dist/terminal-panel.js +18 -0
  177. package/client/dist/textile.js +1 -0
  178. package/client/dist/tiddlywiki.js +1 -0
  179. package/client/dist/tiki.js +1 -0
  180. package/client/dist/timeline-definition-JXYKGLGB.js +120 -0
  181. package/client/dist/toml.js +1 -0
  182. package/client/dist/troff.js +1 -0
  183. package/client/dist/ttcn-cfg.js +1 -0
  184. package/client/dist/ttcn.js +1 -0
  185. package/client/dist/turtle.js +1 -0
  186. package/client/dist/usecaseDiagram-WPOLBNNX.js +370 -0
  187. package/client/dist/vb.js +1 -0
  188. package/client/dist/vbscript.js +1 -0
  189. package/client/dist/velocity.js +1 -0
  190. package/client/dist/vennDiagram-Q3Y3IDCW.js +34 -0
  191. package/client/dist/verilog.js +1 -0
  192. package/client/dist/vhdl.js +1 -0
  193. package/client/dist/wardleyDiagram-IVAIDKWA.js +78 -0
  194. package/client/dist/webidl.js +1 -0
  195. package/client/dist/xquery.js +1 -0
  196. package/client/dist/xychartDiagram-4URNHDU4.js +7 -0
  197. package/client/dist/yacas.js +1 -0
  198. package/client/dist/z80.js +1 -0
  199. package/docs/architecture/backend-regressions.md +53 -0
  200. package/docs/architecture/backends.md +115 -0
  201. package/docs/architecture/behavior.md +228 -0
  202. package/docs/architecture.md +335 -0
  203. package/docs/background-tasks.md +39 -0
  204. package/docs/cli-command-coverage.md +60 -0
  205. package/docs/deployment.md +289 -0
  206. package/docs/development.md +396 -0
  207. package/docs/images/desktop-dark.png +0 -0
  208. package/docs/images/desktop-light.png +0 -0
  209. package/docs/images/mobile-sidebar.png +0 -0
  210. package/docs/images/mobile.png +0 -0
  211. package/docs/releases/v2.0.0.md +5 -0
  212. package/docs/releases/v2.1.0.md +6 -0
  213. package/docs/releases/v2.1.1.md +6 -0
  214. package/docs/releases/v2.1.2.md +8 -0
  215. package/docs/releases/v2.2.0.md +11 -0
  216. package/docs/releases/v2.3.0.md +12 -0
  217. package/docs/releases/v2.3.1.md +8 -0
  218. package/docs/releases/v2.4.0.md +8 -0
  219. package/docs/releases/v2.4.1.md +8 -0
  220. package/docs/releases/v2.4.2.md +8 -0
  221. package/docs/releases/v3.0.0.md +9 -0
  222. package/docs/releases/v3.1.0.md +10 -0
  223. package/docs/releases/v3.1.1.md +7 -0
  224. package/docs/releases/v4.0.0-beta.1.md +10 -0
  225. package/docs/releases/v4.0.0.md +20 -0
  226. package/docs/releases/v4.0.1.md +10 -0
  227. package/docs/releases/v4.1.0.md +21 -0
  228. package/docs/versioning.md +129 -0
  229. package/package.json +87 -4
  230. package/packages/translation-engine/LICENSE +674 -0
  231. package/packages/translation-engine/README.md +69 -0
  232. package/packages/translation-engine/bin/tokenizer-linux-x64 +0 -0
  233. package/packages/translation-engine/bin/translate.mjs +29 -0
  234. package/packages/translation-engine/native/build.mjs +15 -0
  235. package/packages/translation-engine/native/tokenizer.c +73 -0
  236. package/packages/translation-engine/package.json +29 -0
  237. package/packages/translation-engine/src/catalog.mjs +103 -0
  238. package/packages/translation-engine/src/cpu-runtime.mjs +90 -0
  239. package/packages/translation-engine/src/download.mjs +94 -0
  240. package/packages/translation-engine/src/index.mjs +70 -0
  241. package/packages/translation-engine/src/inference.mjs +177 -0
  242. package/packages/translation-engine/src/model-store.mjs +197 -0
  243. package/packages/translation-engine/src/tokenizer.mjs +77 -0
  244. package/packages/translation-engine/src/worker.mjs +83 -0
  245. package/scripts/install-services.mjs +135 -0
  246. package/scripts/restart-when-idle.mjs +125 -0
  247. package/scripts/start-backend.mjs +29 -0
  248. package/server/src/agent-messages.mjs +124 -0
  249. package/server/src/application.mjs +168 -0
  250. package/server/src/auth.mjs +328 -0
  251. package/server/src/backends/claude/account.mjs +171 -0
  252. package/server/src/backends/claude/adapter.mjs +366 -0
  253. package/server/src/backends/claude/agent-history.mjs +70 -0
  254. package/server/src/backends/claude/background-tasks.mjs +168 -0
  255. package/server/src/backends/claude/catalogue.mjs +268 -0
  256. package/server/src/backends/claude/execution-errors.mjs +44 -0
  257. package/server/src/backends/claude/execution-session.mjs +396 -0
  258. package/server/src/backends/claude/git-tool-changes.mjs +77 -0
  259. package/server/src/backends/claude/goals.mjs +319 -0
  260. package/server/src/backends/claude/history-actions.mjs +170 -0
  261. package/server/src/backends/claude/history.mjs +65 -0
  262. package/server/src/backends/claude/hooks.mjs +232 -0
  263. package/server/src/backends/claude/input-stream.mjs +24 -0
  264. package/server/src/backends/claude/messages-request.mjs +34 -0
  265. package/server/src/backends/claude/messages.mjs +301 -0
  266. package/server/src/backends/claude/model-options.mjs +18 -0
  267. package/server/src/backends/claude/native-commands.mjs +48 -0
  268. package/server/src/backends/claude/native-records.mjs +76 -0
  269. package/server/src/backends/claude/process-ownership.mjs +82 -0
  270. package/server/src/backends/claude/project-instructions.mjs +40 -0
  271. package/server/src/backends/claude/provider-balance.mjs +40 -0
  272. package/server/src/backends/claude/provider-environment.mjs +95 -0
  273. package/server/src/backends/claude/provider-transport.mjs +70 -0
  274. package/server/src/backends/claude/recovery.mjs +54 -0
  275. package/server/src/backends/claude/runtime.mjs +463 -0
  276. package/server/src/backends/claude/session-worker.mjs +32 -0
  277. package/server/src/backends/claude/sessions.mjs +348 -0
  278. package/server/src/backends/claude/token-usage.mjs +98 -0
  279. package/server/src/backends/claude/worker-client.mjs +351 -0
  280. package/server/src/backends/claude/worker-launcher.mjs +119 -0
  281. package/server/src/backends/claude/worker-location.mjs +43 -0
  282. package/server/src/backends/claude/worker-revision.mjs +45 -0
  283. package/server/src/backends/claude/worker-server.mjs +290 -0
  284. package/server/src/backends/cli-installation.mjs +140 -0
  285. package/server/src/backends/codex/adapter.mjs +155 -0
  286. package/server/src/backends/codex/compaction-recovery.mjs +78 -0
  287. package/server/src/backends/codex/events.mjs +125 -0
  288. package/server/src/backends/codex/methods.mjs +17 -0
  289. package/server/src/backends/codex/reference-mcp.mjs +97 -0
  290. package/server/src/backends/codex/reference-tools.mjs +71 -0
  291. package/server/src/backends/codex/requests.mjs +170 -0
  292. package/server/src/backends/codex/subscriptions.mjs +91 -0
  293. package/server/src/backends/codex/token-usage.mjs +140 -0
  294. package/server/src/backends/codex/upstream.mjs +148 -0
  295. package/server/src/backends/configuration.mjs +122 -0
  296. package/server/src/backends/identity-mapping.mjs +87 -0
  297. package/server/src/backends/manager.mjs +478 -0
  298. package/server/src/backends/network-proxy.mjs +55 -0
  299. package/server/src/backends/provider-presets.mjs +45 -0
  300. package/server/src/backends/providers.mjs +135 -0
  301. package/server/src/backends/storage.mjs +39 -0
  302. package/server/src/bridge/conversation-policy.mjs +29 -0
  303. package/server/src/bridge/file-operations.mjs +47 -0
  304. package/server/src/bridge/product-methods.mjs +66 -0
  305. package/server/src/compaction.mjs +82 -0
  306. package/server/src/config.mjs +64 -0
  307. package/server/src/file-content.mjs +99 -0
  308. package/server/src/file-undo.mjs +142 -0
  309. package/server/src/http/maintenance.mjs +28 -0
  310. package/server/src/http/router.mjs +98 -0
  311. package/server/src/http/static.mjs +62 -0
  312. package/server/src/product-config.mjs +80 -0
  313. package/server/src/project-models.mjs +59 -0
  314. package/server/src/rpc-transport.mjs +21 -0
  315. package/server/src/server.mjs +29 -0
  316. package/server/src/service-maintenance-worker.mjs +124 -0
  317. package/server/src/service-maintenance.mjs +222 -0
  318. package/server/src/summary-translation.mjs +71 -0
  319. package/server/src/system-auth.mjs +45 -0
  320. package/server/src/thread-folders.mjs +76 -0
  321. package/server/src/thread-names.mjs +264 -0
  322. package/server/src/thread-projects.mjs +36 -0
  323. package/server/src/tls.mjs +87 -0
  324. package/server/src/token-usage-reconciliation.mjs +105 -0
  325. package/server/src/token-usage.mjs +208 -0
  326. package/server/src/translation-service.mjs +133 -0
  327. package/server/src/version.mjs +55 -0
  328. package/server/src/web-config-migration.mjs +48 -0
  329. package/server/src/workspace/commands.mjs +33 -0
  330. package/server/src/workspace/files.mjs +44 -0
  331. package/server/src/workspace/service.mjs +27 -0
  332. package/server/src/workspace/terminals.mjs +122 -0
  333. package/shared/backend-activity.mjs +13 -0
  334. package/shared/backend-capabilities.mjs +33 -0
  335. package/shared/backend-identity.mjs +17 -0
  336. package/shared/compaction-state.mjs +49 -0
  337. package/shared/file-types.mjs +82 -0
  338. package/shared/product-contract.mjs +26 -0
  339. package/shared/rpc-limits.mjs +2 -0
  340. package/shared/terminal-workspace.mjs +26 -0
@@ -0,0 +1,142 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import {
4
+ lstat,
5
+ readFile,
6
+ writeFile,
7
+ unlink,
8
+ mkdtemp,
9
+ rm,
10
+ } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join, resolve } from "node:path";
13
+
14
+ const exec = promisify(execFile);
15
+
16
+ export function changesForPath(items, cwd, path) {
17
+ const files = new Map();
18
+ for (const item of items) {
19
+ if (item.type !== "fileChange" || item.status !== "completed") continue;
20
+ for (const change of item.changes || []) {
21
+ const before = resolve(cwd, change.path);
22
+ const after = resolve(cwd, change.kind?.move_path || change.path);
23
+ const changes = files.get(before) || [];
24
+ if (before !== after) files.delete(before);
25
+ files.set(after, [...changes, change]);
26
+ }
27
+ }
28
+ return files.get(resolve(cwd, path)) || [];
29
+ }
30
+
31
+ async function snapshot(path) {
32
+ try {
33
+ const info = await lstat(path);
34
+ if (!info.isFile()) throw new Error("仅支持撤销普通文本文件的修改。");
35
+ const data = await readFile(path);
36
+ if (data.includes(0) || !Buffer.from(data.toString("utf8")).equals(data))
37
+ throw new Error("此文件包含二进制内容,请在文件面板检查。");
38
+ return { data, mode: info.mode };
39
+ } catch (error) {
40
+ if (error.code === "ENOENT") return { data: null };
41
+ throw error;
42
+ }
43
+ }
44
+
45
+ function equal(a, b) {
46
+ return a === null ? b === null : b !== null && a.equals(b);
47
+ }
48
+
49
+ // 在临时文件上逆序校验每次补丁,再核对源文件快照,最后写回单个文件的结果。
50
+ export async function undoFileChanges({
51
+ cwd,
52
+ changes,
53
+ isActive = () => false,
54
+ }) {
55
+ if (!changes.length) throw new Error("此轮没有可撤销的文件修改。");
56
+ const paths = [
57
+ ...new Set(
58
+ changes.flatMap((c) => [
59
+ resolve(cwd, c.path),
60
+ resolve(cwd, c.kind?.move_path || c.path),
61
+ ]),
62
+ ),
63
+ ];
64
+ const snapshots = new Map();
65
+ for (const path of paths) snapshots.set(path, await snapshot(path));
66
+ const last = changes.at(-1);
67
+ const currentPath = resolve(cwd, last.kind?.move_path || last.path);
68
+ let path = currentPath;
69
+ let data = snapshots.get(currentPath).data;
70
+ const scratch = await mkdtemp(join(tmpdir(), "claudex-web-undo-"));
71
+ try {
72
+ for (const change of changes.slice().reverse()) {
73
+ const before = resolve(cwd, change.path);
74
+ const after = resolve(cwd, change.kind?.move_path || change.path);
75
+ if (path !== after)
76
+ throw new Error("文件移动记录不完整,请重新加载对话。");
77
+ const kind = change.kind?.type;
78
+ const hunk =
79
+ kind === "update" || /^--- .+\n\+\+\+ .+\n/m.test(change.diff)
80
+ ? change.diff.search(/^@@ /m)
81
+ : -1;
82
+ if (hunk >= 0) {
83
+ const oldName = kind === "add" ? "/dev/null" : "a/file";
84
+ const newName = kind === "delete" ? "/dev/null" : "b/file";
85
+ await rm(join(scratch, "file"), { force: true });
86
+ if (data !== null) await writeFile(join(scratch, "file"), data);
87
+ await writeFile(
88
+ join(scratch, "patch"),
89
+ `--- ${oldName}\n+++ ${newName}\n${change.diff.slice(hunk)}`,
90
+ );
91
+ try {
92
+ await exec(
93
+ "git",
94
+ [
95
+ "apply",
96
+ "--reverse",
97
+ "--unidiff-zero",
98
+ "--whitespace=nowarn",
99
+ "patch",
100
+ ],
101
+ { cwd: scratch, timeout: 30000 },
102
+ );
103
+ } catch (error) {
104
+ if (error.code === "ENOENT")
105
+ throw new Error("服务环境缺少 Git,请安装 Git 后重试。");
106
+ throw new Error(
107
+ "撤销补丁校验失败,差异格式或当前内容存在冲突。已保留当前文件,请查看变更后处理。",
108
+ );
109
+ }
110
+ data = (await snapshot(join(scratch, "file"))).data;
111
+ } else if (kind === "add") {
112
+ if (!equal(data, Buffer.from(change.diff)))
113
+ throw new Error("新增文件已有后续修改,已保留当前内容。");
114
+ data = null;
115
+ } else if (kind === "delete") {
116
+ if (data !== null) throw new Error("原路径已有文件,已保留当前内容。");
117
+ data = Buffer.from(change.diff);
118
+ } else if (before === after || change.diff.trim()) {
119
+ throw new Error("此修改缺少可撤销的统一差异,请在文件面板检查。");
120
+ }
121
+ path = before;
122
+ }
123
+ if (path !== currentPath && snapshots.get(path).data !== null)
124
+ throw new Error("原路径已有文件,已保留当前内容。");
125
+ if (isActive()) throw new Error("任务正在运行,请在结束后撤销修改。");
126
+ for (const [file, saved] of snapshots) {
127
+ if (!equal(saved.data, (await snapshot(file)).data))
128
+ throw new Error("校验期间文件发生变化,请检查内容后重试。");
129
+ }
130
+ if (data !== null)
131
+ await writeFile(path, data, {
132
+ flag: snapshots.get(path).data === null ? "wx" : "w",
133
+ mode: snapshots.get(currentPath).mode,
134
+ });
135
+ if (currentPath !== path || data === null) {
136
+ if (snapshots.get(currentPath).data !== null) await unlink(currentPath);
137
+ }
138
+ return { path, currentPath };
139
+ } finally {
140
+ await rm(scratch, { recursive: true, force: true });
141
+ }
142
+ }
@@ -0,0 +1,28 @@
1
+ export function createMaintenanceHandler(service) {
2
+ return async (request, response, path) => {
3
+ response.setHeader("Content-Type", "application/json; charset=utf-8");
4
+ try {
5
+ let result;
6
+ if (path === "/api/maintenance" && request.method === "GET")
7
+ result = await service.status();
8
+ else if (request.method === "POST" && path === "/api/maintenance/check") {
9
+ await service.check();
10
+ result = await service.status();
11
+ } else if (
12
+ request.method === "POST" &&
13
+ ["/api/maintenance/update", "/api/maintenance/restart"].includes(path)
14
+ ) {
15
+ result = await service.start(path.split("/").at(-1));
16
+ } else {
17
+ response.writeHead(405);
18
+ response.end(JSON.stringify({ error: "请求方法或维护操作无效" }));
19
+ return;
20
+ }
21
+ response.writeHead(200);
22
+ response.end(JSON.stringify(result));
23
+ } catch (error) {
24
+ response.writeHead(409);
25
+ response.end(JSON.stringify({ error: error.message }));
26
+ }
27
+ };
28
+ }
@@ -0,0 +1,98 @@
1
+ import { createMaintenanceHandler } from "./maintenance.mjs";
2
+ import { X509Certificate } from "node:crypto";
3
+ import {
4
+ createSummaryTranslationHandler,
5
+ createTranslationSettingsHandler,
6
+ } from "../summary-translation.mjs";
7
+ import { serveFile } from "../file-content.mjs";
8
+ import { createStaticHandler } from "./static.mjs";
9
+ export function createHttpHandler({
10
+ config,
11
+ tls,
12
+ authentication,
13
+ version,
14
+ isReady,
15
+ translation,
16
+ maintenance,
17
+ }) {
18
+ const handleMaintenance = createMaintenanceHandler(maintenance);
19
+ const publicCertificate = new X509Certificate(tls.cert);
20
+ const translateSummary = createSummaryTranslationHandler(
21
+ translation.translate,
22
+ );
23
+ const translationSettings = createTranslationSettingsHandler(translation);
24
+ const serveStatic = createStaticHandler(config.staticDir);
25
+ return async function handleHttp(request, response) {
26
+ const ready = isReady();
27
+ response.setHeader("X-Content-Type-Options", "nosniff");
28
+ response.setHeader("Referrer-Policy", "no-referrer");
29
+ response.setHeader(
30
+ "Content-Security-Policy",
31
+ "frame-ancestors 'self'; base-uri 'self'; object-src 'self'; upgrade-insecure-requests",
32
+ );
33
+ response.setHeader("Cache-Control", "no-store");
34
+ const path = new URL(request.url, "http://localhost").pathname;
35
+ if (["/api/tls/info", "/api/tls/certificate"].includes(path)) {
36
+ if (!["GET", "HEAD"].includes(request.method)) {
37
+ response.writeHead(405, { Allow: "GET, HEAD" });
38
+ response.end();
39
+ return;
40
+ }
41
+ const download = path === "/api/tls/certificate";
42
+ const body = download
43
+ ? publicCertificate.raw
44
+ : Buffer.from(
45
+ JSON.stringify({
46
+ fingerprint: publicCertificate.fingerprint256,
47
+ validTo: publicCertificate.validTo,
48
+ selfSigned:
49
+ publicCertificate.subject === publicCertificate.issuer &&
50
+ publicCertificate.verify(publicCertificate.publicKey),
51
+ }),
52
+ );
53
+ response.writeHead(200, {
54
+ "Content-Type": download
55
+ ? "application/pkix-cert"
56
+ : "application/json; charset=utf-8",
57
+ "Content-Length": body.length,
58
+ ...(download
59
+ ? { "Content-Disposition": 'attachment; filename="claudex-web.cer"' }
60
+ : {}),
61
+ });
62
+ response.end(request.method === "HEAD" ? undefined : body);
63
+ return;
64
+ }
65
+ if (await authentication.handle(request, response, path)) return;
66
+ if (
67
+ path.startsWith("/api/") &&
68
+ !authentication.authorize(request, response)
69
+ )
70
+ return;
71
+ if (path.startsWith("/api/maintenance")) {
72
+ await handleMaintenance(request, response, path);
73
+ return;
74
+ }
75
+ if (["/api/files", "/api/media"].includes(path)) {
76
+ await serveFile(request, response);
77
+ return;
78
+ }
79
+ if (path === "/api/translation") {
80
+ await translationSettings(request, response);
81
+ return;
82
+ }
83
+ if (path === "/api/translate") {
84
+ await translateSummary(request, response);
85
+ return;
86
+ }
87
+ if (path === "/healthz") {
88
+ response.writeHead(ready ? 200 : 503, {
89
+ "Content-Type": "application/json",
90
+ "Cache-Control": "no-store",
91
+ });
92
+ response.end(JSON.stringify({ ready, version }));
93
+ return;
94
+ }
95
+
96
+ await serveStatic(request, response, path);
97
+ };
98
+ }
@@ -0,0 +1,62 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { gzipSync } from "node:zlib";
4
+ const files = new Map([
5
+ ["/", ["index.html", "text/html; charset=utf-8"]],
6
+ ["/app.js", ["app.js", "text/javascript; charset=utf-8"]],
7
+ ["/style.css", ["style.css", "text/css; charset=utf-8"]],
8
+ ["/favicon.ico", ["favicon.ico", "image/x-icon"]],
9
+ ["/favicon.png", ["favicon.png", "image/png"]],
10
+ ["/apple-touch-icon.png", ["apple-touch-icon.png", "image/png"]],
11
+ ]);
12
+ export function createStaticHandler(staticDir) {
13
+ const staticCache = new Map();
14
+ return async function serveStatic(request, response, path) {
15
+ const asset = path.match(/^\/([\w.-]+\.(js|css))$/);
16
+ const file =
17
+ files.get(path) ||
18
+ (asset && [
19
+ asset[1],
20
+ asset[2] === "js"
21
+ ? "text/javascript; charset=utf-8"
22
+ : "text/css; charset=utf-8",
23
+ ]);
24
+ if (!file) {
25
+ response.writeHead(404);
26
+ response.end("Not found");
27
+ return;
28
+ }
29
+ try {
30
+ const metadata = await stat(join(staticDir, file[0]));
31
+ if (staticCache.get(path)?.modified !== metadata.mtimeMs) {
32
+ const raw = await readFile(join(staticDir, file[0]));
33
+ staticCache.set(path, {
34
+ raw,
35
+ gzip: gzipSync(raw),
36
+ modified: metadata.mtimeMs,
37
+ });
38
+ }
39
+ const content = staticCache.get(path);
40
+ const compressed = /\bgzip\b/.test(
41
+ request.headers["accept-encoding"] || "",
42
+ );
43
+ response.writeHead(200, {
44
+ "Content-Type": file[1],
45
+ "Cache-Control": "no-store",
46
+ Vary: "Accept-Encoding",
47
+ ...(compressed ? { "Content-Encoding": "gzip" } : {}),
48
+ });
49
+ response.end(compressed ? content.gzip : content.raw);
50
+ } catch (error) {
51
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
52
+ staticCache.delete(path);
53
+ response.writeHead(404);
54
+ response.end("Not found");
55
+ return;
56
+ }
57
+ console.error("Static file:", error.message);
58
+ response.writeHead(500);
59
+ response.end("Unable to load page");
60
+ }
61
+ };
62
+ }
@@ -0,0 +1,80 @@
1
+ import { constants } from "node:fs";
2
+ import {
3
+ chmod,
4
+ copyFile,
5
+ cp,
6
+ lstat,
7
+ mkdir,
8
+ mkdtemp,
9
+ rename,
10
+ rm,
11
+ stat,
12
+ } from "node:fs/promises";
13
+ import { homedir } from "node:os";
14
+ import { dirname, join, resolve } from "node:path";
15
+
16
+ export function productDirectories(env = process.env) {
17
+ const base = env.XDG_CONFIG_HOME || join(homedir(), ".config");
18
+ return {
19
+ configDir: resolve(env.CLAUDEX_WEB_CONFIG_DIR || join(base, "claudex-web")),
20
+ legacyConfigDir: resolve(
21
+ env.CODEX_WEB_CONFIG_DIR || join(base, "codex-web"),
22
+ ),
23
+ };
24
+ }
25
+
26
+ // 首次升级以完整目录快照迁移网页配置;原目录与已存在的新配置保持原样。
27
+ export async function migrateProductConfig({ configDir, legacyConfigDir }) {
28
+ if (!legacyConfigDir || configDir === legacyConfigDir) return;
29
+ try {
30
+ await stat(configDir);
31
+ return;
32
+ } catch (error) {
33
+ if (error.code !== "ENOENT") throw error;
34
+ }
35
+ try {
36
+ const source = await stat(legacyConfigDir);
37
+ if (!source.isDirectory()) throw new Error("旧网页配置路径必须是目录");
38
+ } catch (error) {
39
+ if (error.code === "ENOENT") return;
40
+ throw error;
41
+ }
42
+ await mkdir(dirname(configDir), { recursive: true, mode: 0o700 });
43
+ const temporary = await mkdtemp(
44
+ join(dirname(configDir), ".claudex-migrate-"),
45
+ );
46
+ const snapshot = join(temporary, "config");
47
+ try {
48
+ await cp(legacyConfigDir, snapshot, {
49
+ recursive: true,
50
+ mode: constants.COPYFILE_EXCL,
51
+ errorOnExist: true,
52
+ force: false,
53
+ filter: async (path) => !(await lstat(path)).isSocket(),
54
+ });
55
+ await chmod(snapshot, 0o700);
56
+ const oldIndex = join(
57
+ snapshot,
58
+ "backends",
59
+ "claude",
60
+ "codex-web-index.json",
61
+ );
62
+ try {
63
+ await copyFile(
64
+ oldIndex,
65
+ join(snapshot, "backends", "claude", "claudex-web-index.json"),
66
+ constants.COPYFILE_EXCL,
67
+ );
68
+ } catch (error) {
69
+ if (!["ENOENT", "EEXIST"].includes(error.code)) throw error;
70
+ }
71
+ await rm(oldIndex, { force: true });
72
+ try {
73
+ await rename(snapshot, configDir);
74
+ } catch (error) {
75
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code)) throw error;
76
+ }
77
+ } finally {
78
+ await rm(temporary, { recursive: true, force: true });
79
+ }
80
+ }
@@ -0,0 +1,59 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+
4
+ export function createProjectModels(directory, legacyDirectory) {
5
+ const path = join(directory, "project-models.json");
6
+ let writing = Promise.resolve();
7
+ async function read() {
8
+ try {
9
+ return JSON.parse(await readFile(path, "utf8"));
10
+ } catch (error) {
11
+ if (error.code !== "ENOENT") throw error;
12
+ if (legacyDirectory && legacyDirectory !== directory) {
13
+ try {
14
+ return JSON.parse(
15
+ await readFile(
16
+ join(legacyDirectory, "project-models.json"),
17
+ "utf8",
18
+ ),
19
+ );
20
+ } catch (legacyError) {
21
+ if (legacyError.code !== "ENOENT") throw legacyError;
22
+ }
23
+ }
24
+ return {};
25
+ }
26
+ }
27
+ function set({ cwd, model, effort, ifAbsent = false }) {
28
+ if (
29
+ typeof cwd !== "string" ||
30
+ (cwd !== "" && !isAbsolute(cwd)) ||
31
+ typeof model !== "string" ||
32
+ !model ||
33
+ typeof effort !== "string"
34
+ )
35
+ return Promise.reject(new Error("项目目录、模型或思考强度无效"));
36
+ const operation = writing.then(async () => {
37
+ const projects = await read();
38
+ if (ifAbsent && Object.hasOwn(projects, cwd)) return projects;
39
+ const next = { ...projects, [cwd]: { model, effort } };
40
+ await mkdir(directory, { recursive: true, mode: 0o700 });
41
+ const temporary = path + ".tmp";
42
+ await writeFile(temporary, JSON.stringify(next, null, 2) + "\n", {
43
+ mode: 0o600,
44
+ });
45
+ await rename(temporary, path);
46
+ return next;
47
+ });
48
+ writing = operation.catch(() => {});
49
+ return operation;
50
+ }
51
+ return {
52
+ read: () => {
53
+ const operation = writing.then(read);
54
+ writing = operation.catch(() => {});
55
+ return operation;
56
+ },
57
+ set,
58
+ };
59
+ }
@@ -0,0 +1,21 @@
1
+ import WebSocket from "ws";
2
+ import { RPC_FRAME_BYTES } from "../../shared/rpc-limits.mjs";
3
+ export {
4
+ MAX_RPC_MESSAGE_BYTES,
5
+ RPC_FRAME_BYTES,
6
+ } from "../../shared/rpc-limits.mjs";
7
+
8
+ // Codex 的 WebSocket 接口分别限制单帧与完整消息的大小。
9
+ export function sendRpcText(socket, text) {
10
+ if (socket.readyState !== WebSocket.OPEN) return;
11
+ if (Buffer.byteLength(text) <= RPC_FRAME_BYTES) {
12
+ socket.send(text);
13
+ return;
14
+ }
15
+ const bytes = Buffer.from(text);
16
+ for (let offset = 0; offset < bytes.length; offset += RPC_FRAME_BYTES)
17
+ socket.send(bytes.subarray(offset, offset + RPC_FRAME_BYTES), {
18
+ binary: false,
19
+ fin: offset + RPC_FRAME_BYTES >= bytes.length,
20
+ });
21
+ }
@@ -0,0 +1,29 @@
1
+ import { readConfig } from "./config.mjs";
2
+ import { readTls } from "./tls.mjs";
3
+ import { createAuthentication } from "./auth.mjs";
4
+ import { readVersion } from "./version.mjs";
5
+ import { createWebApplication } from "./application.mjs";
6
+ import { migrateProductConfig } from "./product-config.mjs";
7
+ const config = readConfig();
8
+ await migrateProductConfig(config);
9
+ const tls = await readTls(config);
10
+ const authentication = await createAuthentication(config);
11
+ const application = createWebApplication({
12
+ config,
13
+ tls,
14
+ authentication,
15
+ version: readVersion(),
16
+ });
17
+ await application.start();
18
+ let closing;
19
+ function shutdown() {
20
+ closing ||= application.close().catch((error) => {
21
+ console.error(error);
22
+ process.exitCode = 1;
23
+ });
24
+ }
25
+ process.once("SIGTERM", shutdown);
26
+ process.once("SIGINT", shutdown);
27
+ console.log(
28
+ `Claudex Web listening on https://${config.host}:${application.server.address().port}`,
29
+ );
@@ -0,0 +1,124 @@
1
+ import { X509Certificate } from "node:crypto";
2
+ // 此入口复制到配置目录后由独立 systemd 单元执行,更新期间保持可运行。
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import https from "node:https";
8
+ const execute = promisify(execFile);
9
+ const job = JSON.parse(await readFile(process.argv[2], "utf8"));
10
+ const save = async (state, error = "") => {
11
+ await writeFile(
12
+ job.statusFile + ".tmp",
13
+ JSON.stringify({ ...job.task, state, error }),
14
+ { mode: 0o600 },
15
+ );
16
+ await rename(job.statusFile + ".tmp", job.statusFile);
17
+ };
18
+ const health = async () => {
19
+ const ca = await readFile(job.cert);
20
+ return new Promise((resolve) => {
21
+ const request = https.get(
22
+ {
23
+ hostname: "127.0.0.1",
24
+ port: job.port,
25
+ path: "/healthz",
26
+ ca,
27
+ allowPartialTrustChain: true,
28
+ checkServerIdentity(_hostname, peer) {
29
+ if (peer.fingerprint256 !== new X509Certificate(ca).fingerprint256)
30
+ return new Error("本机服务证书与配置不匹配");
31
+ },
32
+ },
33
+ (response) => {
34
+ let body = "";
35
+ response.on("data", (chunk) => {
36
+ body += chunk;
37
+ });
38
+ response.on("end", () => {
39
+ try {
40
+ resolve(JSON.parse(body));
41
+ } catch {
42
+ resolve(null);
43
+ }
44
+ });
45
+ },
46
+ );
47
+ request.setTimeout(3000, () => request.destroy());
48
+ request.on("error", () => resolve(null));
49
+ });
50
+ };
51
+ let stage,
52
+ backup,
53
+ replaced = false;
54
+ try {
55
+ // 留出 HTTP 确认响应和浏览器开始轮询的时间。
56
+ await new Promise((resolve) => setTimeout(resolve, 1500));
57
+ if (job.action === "update") {
58
+ stage = await mkdtemp(join(job.prefix, ".claudex-update-"));
59
+ await execute(
60
+ "npm",
61
+ [
62
+ "install",
63
+ "--global",
64
+ "--prefix",
65
+ stage,
66
+ `${job.packageName}@${job.task.target}`,
67
+ "--registry=https://registry.npmjs.org",
68
+ "--engine-strict",
69
+ ],
70
+ { timeout: 600000, maxBuffer: 4 * 1024 * 1024 },
71
+ );
72
+ const installed = join(stage, "lib/node_modules", job.packageName);
73
+ const manifest = JSON.parse(
74
+ await readFile(join(installed, "package.json"), "utf8"),
75
+ );
76
+ if (manifest.version !== job.task.target)
77
+ throw new Error("安装包版本校验失败");
78
+ await readFile(join(installed, "client/dist/index.html"));
79
+ backup = job.root + ".maintenance-backup";
80
+ await rename(job.root, backup);
81
+ try {
82
+ await rename(installed, job.root);
83
+ replaced = true;
84
+ } catch (error) {
85
+ await rename(backup, job.root);
86
+ backup = null;
87
+ throw error;
88
+ }
89
+ }
90
+ await save("restarting");
91
+ await execute("systemctl", ["--user", "restart", "claudex-web.service"], {
92
+ timeout: 90000,
93
+ });
94
+ let healthy = false;
95
+ for (let attempt = 0; attempt < 60; attempt++) {
96
+ const status = await health();
97
+ if (status?.version?.version === job.task.target) {
98
+ healthy = true;
99
+ break;
100
+ }
101
+ await new Promise((resolve) => setTimeout(resolve, 1000));
102
+ }
103
+ if (!healthy)
104
+ throw new Error(
105
+ "服务启动检查超时,请查看 journalctl --user -u claudex-web.service",
106
+ );
107
+ await save("completed");
108
+ replaced = false;
109
+ if (backup) await rm(backup, { recursive: true, force: true });
110
+ } catch (error) {
111
+ if (replaced) {
112
+ await rm(job.root, { recursive: true, force: true });
113
+ await rename(backup, job.root);
114
+ await execute("systemctl", [
115
+ "--user",
116
+ "restart",
117
+ "claudex-web.service",
118
+ ]).catch(() => {});
119
+ }
120
+ await save("failed", error.message);
121
+ process.exitCode = 1;
122
+ } finally {
123
+ if (stage) await rm(stage, { recursive: true, force: true });
124
+ }