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

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 (317) hide show
  1. package/.env.example +27 -0
  2. package/CHANGELOG.md +449 -0
  3. package/LICENSE +674 -0
  4. package/README.md +128 -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 +393 -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 +113 -0
  201. package/docs/architecture/behavior.md +206 -0
  202. package/docs/architecture.md +306 -0
  203. package/docs/background-tasks.md +39 -0
  204. package/docs/cli-command-coverage.md +60 -0
  205. package/docs/deployment.md +269 -0
  206. package/docs/development.md +385 -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/versioning.md +119 -0
  228. package/package.json +70 -4
  229. package/scripts/install-services.mjs +134 -0
  230. package/scripts/restart-when-idle.mjs +125 -0
  231. package/scripts/start-backend.mjs +29 -0
  232. package/server/src/agent-messages.mjs +124 -0
  233. package/server/src/application.mjs +133 -0
  234. package/server/src/auth.mjs +328 -0
  235. package/server/src/backends/claude/account.mjs +171 -0
  236. package/server/src/backends/claude/adapter.mjs +366 -0
  237. package/server/src/backends/claude/agent-history.mjs +70 -0
  238. package/server/src/backends/claude/background-tasks.mjs +168 -0
  239. package/server/src/backends/claude/catalogue.mjs +266 -0
  240. package/server/src/backends/claude/execution-errors.mjs +44 -0
  241. package/server/src/backends/claude/execution-session.mjs +390 -0
  242. package/server/src/backends/claude/git-tool-changes.mjs +77 -0
  243. package/server/src/backends/claude/goals.mjs +319 -0
  244. package/server/src/backends/claude/history-actions.mjs +170 -0
  245. package/server/src/backends/claude/history.mjs +65 -0
  246. package/server/src/backends/claude/hooks.mjs +232 -0
  247. package/server/src/backends/claude/input-stream.mjs +24 -0
  248. package/server/src/backends/claude/messages-request.mjs +34 -0
  249. package/server/src/backends/claude/messages.mjs +300 -0
  250. package/server/src/backends/claude/model-options.mjs +18 -0
  251. package/server/src/backends/claude/native-commands.mjs +48 -0
  252. package/server/src/backends/claude/native-records.mjs +76 -0
  253. package/server/src/backends/claude/process-ownership.mjs +82 -0
  254. package/server/src/backends/claude/project-instructions.mjs +40 -0
  255. package/server/src/backends/claude/provider-balance.mjs +40 -0
  256. package/server/src/backends/claude/provider-environment.mjs +93 -0
  257. package/server/src/backends/claude/provider-transport.mjs +70 -0
  258. package/server/src/backends/claude/recovery.mjs +54 -0
  259. package/server/src/backends/claude/runtime.mjs +463 -0
  260. package/server/src/backends/claude/session-worker.mjs +32 -0
  261. package/server/src/backends/claude/sessions.mjs +347 -0
  262. package/server/src/backends/claude/token-usage.mjs +98 -0
  263. package/server/src/backends/claude/worker-client.mjs +344 -0
  264. package/server/src/backends/claude/worker-launcher.mjs +119 -0
  265. package/server/src/backends/claude/worker-location.mjs +31 -0
  266. package/server/src/backends/claude/worker-revision.mjs +45 -0
  267. package/server/src/backends/claude/worker-server.mjs +290 -0
  268. package/server/src/backends/cli-installation.mjs +140 -0
  269. package/server/src/backends/codex/adapter.mjs +153 -0
  270. package/server/src/backends/codex/compaction-recovery.mjs +78 -0
  271. package/server/src/backends/codex/events.mjs +125 -0
  272. package/server/src/backends/codex/methods.mjs +17 -0
  273. package/server/src/backends/codex/reference-mcp.mjs +97 -0
  274. package/server/src/backends/codex/reference-tools.mjs +71 -0
  275. package/server/src/backends/codex/requests.mjs +170 -0
  276. package/server/src/backends/codex/subscriptions.mjs +91 -0
  277. package/server/src/backends/codex/upstream.mjs +148 -0
  278. package/server/src/backends/configuration.mjs +122 -0
  279. package/server/src/backends/identity-mapping.mjs +87 -0
  280. package/server/src/backends/manager.mjs +412 -0
  281. package/server/src/backends/network-proxy.mjs +55 -0
  282. package/server/src/backends/provider-presets.mjs +45 -0
  283. package/server/src/backends/providers.mjs +132 -0
  284. package/server/src/backends/storage.mjs +35 -0
  285. package/server/src/bridge/conversation-policy.mjs +29 -0
  286. package/server/src/bridge/file-operations.mjs +47 -0
  287. package/server/src/bridge/product-methods.mjs +66 -0
  288. package/server/src/compaction.mjs +82 -0
  289. package/server/src/config.mjs +57 -0
  290. package/server/src/file-content.mjs +99 -0
  291. package/server/src/file-undo.mjs +142 -0
  292. package/server/src/http/router.mjs +80 -0
  293. package/server/src/http/static.mjs +62 -0
  294. package/server/src/product-config.mjs +80 -0
  295. package/server/src/project-models.mjs +59 -0
  296. package/server/src/rpc-transport.mjs +21 -0
  297. package/server/src/server.mjs +20 -0
  298. package/server/src/summary-translation.mjs +82 -0
  299. package/server/src/system-auth.mjs +45 -0
  300. package/server/src/thread-folders.mjs +76 -0
  301. package/server/src/thread-names.mjs +264 -0
  302. package/server/src/thread-projects.mjs +36 -0
  303. package/server/src/tls.mjs +87 -0
  304. package/server/src/version.mjs +55 -0
  305. package/server/src/web-config-migration.mjs +48 -0
  306. package/server/src/workspace/commands.mjs +33 -0
  307. package/server/src/workspace/files.mjs +44 -0
  308. package/server/src/workspace/service.mjs +27 -0
  309. package/server/src/workspace/terminals.mjs +122 -0
  310. package/shared/backend-activity.mjs +13 -0
  311. package/shared/backend-capabilities.mjs +33 -0
  312. package/shared/backend-identity.mjs +17 -0
  313. package/shared/compaction-state.mjs +49 -0
  314. package/shared/file-types.mjs +82 -0
  315. package/shared/product-contract.mjs +26 -0
  316. package/shared/rpc-limits.mjs +2 -0
  317. package/shared/terminal-workspace.mjs +26 -0
@@ -0,0 +1,344 @@
1
+ import { findCli } from "../cli-installation.mjs";
2
+ import net from "node:net";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { randomUUID } from "node:crypto";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { claudeCapabilities } from "../../../../shared/backend-capabilities.mjs";
7
+ import { hasBackendWork } from "../../../../shared/backend-activity.mjs";
8
+ import { launchWorker, workerLocation } from "./worker-launcher.mjs";
9
+ import { workerRevision } from "./worker-revision.mjs";
10
+ import { networkProxyEnvironment } from "../network-proxy.mjs";
11
+ import {
12
+ captureNativeProcesses,
13
+ nativeProcessesAlive,
14
+ } from "./process-ownership.mjs";
15
+ import {
16
+ prepareWorkerDirectory,
17
+ verifyWorkerSocket,
18
+ } from "./worker-location.mjs";
19
+
20
+ export function createClaudeWorkerAdapter({
21
+ backend,
22
+ config,
23
+ send,
24
+ broadcast,
25
+ }) {
26
+ const location = workerLocation(backend);
27
+ const options = {
28
+ generation: Date.now(),
29
+ backend,
30
+ runtimeEnv: {
31
+ ...Object.fromEntries(
32
+ [
33
+ "ANTHROPIC_AUTH_TOKEN",
34
+ "ANTHROPIC_API_KEY",
35
+ "ANTHROPIC_BASE_URL",
36
+ "ANTHROPIC_MODEL",
37
+ "CLAUDE_CODE_EFFORT_LEVEL",
38
+ "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
39
+ "HTTP_PROXY",
40
+ "HTTPS_PROXY",
41
+ "ALL_PROXY",
42
+ "NO_PROXY",
43
+ "http_proxy",
44
+ "https_proxy",
45
+ "all_proxy",
46
+ "no_proxy",
47
+ "SSL_CERT_FILE",
48
+ "SSL_CERT_DIR",
49
+ "NODE_EXTRA_CA_CERTS",
50
+ "NODE_USE_ENV_PROXY",
51
+ "LANG",
52
+ "LC_ALL",
53
+ ]
54
+ .filter((key) => process.env[key] !== undefined)
55
+ .map((key) => [key, process.env[key]]),
56
+ ),
57
+ ...networkProxyEnvironment(backend.proxy),
58
+ },
59
+ config: Object.fromEntries(
60
+ [
61
+ "codexHome",
62
+ "claudeHome",
63
+ "configDir",
64
+ "backendsFile",
65
+ "defaultCwd",
66
+ "projectlessRoot",
67
+ ].map((key) => [key, config[key]]),
68
+ ),
69
+ };
70
+ const pending = new Map();
71
+ let socket,
72
+ reconnect,
73
+ connecting,
74
+ closed = false,
75
+ workerPid,
76
+ workerIdentity,
77
+ stopping = false,
78
+ outdated = false,
79
+ upgrading = false,
80
+ mayUpgrade = true;
81
+ let snapshot = {
82
+ method: "lan/state",
83
+ params: {
84
+ ready: false,
85
+ error: null,
86
+ activeTurns: {},
87
+ questions: [],
88
+ compactions: {},
89
+ terminals: {},
90
+ undoneFiles: [],
91
+ backgroundTasks: {},
92
+ },
93
+ };
94
+ function publish() {
95
+ if (outdated && mayUpgrade)
96
+ snapshot = {
97
+ ...snapshot,
98
+ params: { ...snapshot.params, pendingUpdate: true },
99
+ };
100
+ broadcast(snapshot);
101
+ }
102
+ function busy() {
103
+ return hasBackendWork(snapshot.params);
104
+ }
105
+ function upgradeWhenIdle() {
106
+ if (!outdated || !mayUpgrade || upgrading || busy() || closed) return;
107
+ upgrading = true;
108
+ shutdownWorker(options)
109
+ .then(async () => {
110
+ if (connecting) await connecting.catch(() => {});
111
+ await connect();
112
+ })
113
+ .catch(() => {})
114
+ .finally(() => {
115
+ upgrading = false;
116
+ });
117
+ }
118
+ function accept(packet) {
119
+ if (packet.kind === "state") {
120
+ snapshot = packet.message;
121
+ publish();
122
+ upgradeWhenIdle();
123
+ }
124
+ if (packet.kind === "event") broadcast(packet.message);
125
+ if (packet.kind === "response") {
126
+ const request = pending.get(packet.id);
127
+ if (!request) return;
128
+ pending.delete(packet.id);
129
+ clearTimeout(request.timer);
130
+ if (packet.error) request.reject(new Error(packet.error));
131
+ else request.resolve(packet.result);
132
+ }
133
+ }
134
+ function request(kind, value = {}) {
135
+ if (!socket || socket.destroyed)
136
+ return Promise.reject(new Error("Claude 后端连接已断开"));
137
+ const id = randomUUID();
138
+ return new Promise((resolve, reject) => {
139
+ const timer = setTimeout(() => {
140
+ pending.delete(id);
141
+ reject(new Error("Claude 后端请求超时,请核对实际任务状态。"));
142
+ }, 120000);
143
+ pending.set(id, { resolve, reject, timer });
144
+ socket.write(JSON.stringify({ kind, id, ...value }) + "\n");
145
+ });
146
+ }
147
+ async function open() {
148
+ stopping = false;
149
+ await prepareWorkerDirectory(location.directory);
150
+ await verifyWorkerSocket(location.socket);
151
+ const connection = net.connect(location.socket);
152
+ await new Promise((resolve, reject) => {
153
+ connection.once("connect", resolve);
154
+ connection.once("error", reject);
155
+ });
156
+ socket = connection;
157
+ let input = "";
158
+ connection.setEncoding("utf8");
159
+ connection.on("data", (chunk) => {
160
+ input += chunk;
161
+ if (Buffer.byteLength(input) > 128 * 1024 * 1024)
162
+ return connection.destroy(new Error("Claude IPC 响应超过限制"));
163
+ let index;
164
+ while ((index = input.indexOf("\n")) >= 0) {
165
+ const line = input.slice(0, index);
166
+ input = input.slice(index + 1);
167
+ try {
168
+ accept(JSON.parse(line));
169
+ } catch (error) {
170
+ connection.destroy(error);
171
+ }
172
+ }
173
+ });
174
+ connection.on("error", () => {});
175
+ connection.on("close", () => {
176
+ if (socket !== connection) return;
177
+ socket = null;
178
+ for (const item of pending.values()) {
179
+ clearTimeout(item.timer);
180
+ item.reject(new Error("Claude 后端连接中断,请核对实际任务状态。"));
181
+ }
182
+ pending.clear();
183
+ snapshot = {
184
+ ...snapshot,
185
+ params: {
186
+ ...snapshot.params,
187
+ ready: false,
188
+ error: "正在重新连接 Claude 后端…",
189
+ },
190
+ };
191
+ if (!closed && !stopping) {
192
+ publish();
193
+ reconnect = setTimeout(() => connect().catch(() => {}), 1000);
194
+ }
195
+ });
196
+ options.revision = await workerRevision();
197
+ let initialized;
198
+ try {
199
+ initialized = await request("initialize", { options });
200
+ } catch (error) {
201
+ connection.destroy();
202
+ throw error;
203
+ }
204
+ workerPid = initialized.pid;
205
+ workerIdentity = (await captureNativeProcesses(workerPid)).owner;
206
+ snapshot = initialized.state;
207
+ outdated =
208
+ initialized.revision?.entry !== options.revision.entry ||
209
+ initialized.revision?.hash !== options.revision.hash ||
210
+ (initialized.configuration &&
211
+ !isDeepStrictEqual(initialized.configuration, {
212
+ backend: options.backend,
213
+ config: options.config,
214
+ runtimeEnv: options.runtimeEnv,
215
+ }));
216
+ mayUpgrade =
217
+ !initialized.generation || options.generation > initialized.generation;
218
+ publish();
219
+ if (outdated && mayUpgrade && !initialized.busy) {
220
+ await shutdownWorker(options);
221
+ const error = new Error("Claude 后端代码更新,正在重新启动。");
222
+ error.code = "EWORKERUPDATE";
223
+ throw error;
224
+ }
225
+ }
226
+ async function connect() {
227
+ options.backend = {
228
+ ...backend,
229
+ executable:
230
+ backend.executable === "claude"
231
+ ? await findCli("claude")
232
+ : backend.executable,
233
+ };
234
+ if (closed) return;
235
+ if (connecting) return connecting;
236
+ if (socket && !socket.destroyed) return;
237
+ connecting = (async () => {
238
+ try {
239
+ await open();
240
+ return;
241
+ } catch (error) {
242
+ if (
243
+ !["ENOENT", "ECONNREFUSED", "ECONNRESET", "EWORKERUPDATE"].includes(
244
+ error.code,
245
+ )
246
+ )
247
+ throw error;
248
+ }
249
+ await launchWorker(backend, options);
250
+ let lastError;
251
+ for (let attempt = 0; attempt < 100; attempt++) {
252
+ if (closed) return;
253
+ try {
254
+ await open();
255
+ return;
256
+ } catch (error) {
257
+ lastError = error;
258
+ if (error.code === "EWORKERUPDATE")
259
+ await launchWorker(backend, options);
260
+ }
261
+ await delay(100);
262
+ }
263
+ throw lastError;
264
+ })();
265
+ try {
266
+ await connecting;
267
+ } catch (error) {
268
+ snapshot = {
269
+ ...snapshot,
270
+ params: { ...snapshot.params, ready: false, error: error.message },
271
+ };
272
+ publish();
273
+ if (!closed)
274
+ reconnect = setTimeout(() => connect().catch(() => {}), 1000);
275
+ throw error;
276
+ } finally {
277
+ connecting = null;
278
+ }
279
+ }
280
+ async function shutdownWorker(replacement) {
281
+ if (!socket || socket.destroyed) return;
282
+ const connection = socket;
283
+ let onClose;
284
+ const ended = new Promise((resolve) => {
285
+ onClose = resolve;
286
+ connection.once("close", onClose);
287
+ });
288
+ stopping = true;
289
+ try {
290
+ await request("shutdown", replacement ? { replacement } : {});
291
+ await ended;
292
+ for (let attempt = 0; attempt < 250; attempt++) {
293
+ if (
294
+ !workerIdentity ||
295
+ !(await nativeProcessesAlive({ nativeProcess: workerIdentity }))
296
+ )
297
+ return;
298
+ await delay(20);
299
+ }
300
+ throw new Error("Claude 后端停止超时,请核对后端服务状态。");
301
+ } catch (error) {
302
+ connection.removeListener("close", onClose);
303
+ stopping = false;
304
+ if (!closed && (!socket || socket.destroyed))
305
+ reconnect = setTimeout(() => connect().catch(() => {}), 1000);
306
+ throw error;
307
+ }
308
+ }
309
+ return {
310
+ capabilities: claudeCapabilities,
311
+ workspaceOwner: "bridge",
312
+ releaseClient() {},
313
+ state: () => snapshot,
314
+ get ready() {
315
+ return Boolean(socket && !socket.destroyed && snapshot.params.ready);
316
+ },
317
+ get workerPid() {
318
+ return workerPid;
319
+ },
320
+ connect,
321
+ async receive(client, message) {
322
+ try {
323
+ const response = await request("rpc", { message });
324
+ if (response) send(client, response);
325
+ } catch (error) {
326
+ if (message.method)
327
+ send(client, {
328
+ id: message.id,
329
+ error: { code: -32000, message: error.message },
330
+ });
331
+ }
332
+ },
333
+ releaseUnusedThreads() {
334
+ if (socket && !socket.destroyed)
335
+ socket.write(JSON.stringify({ kind: "release" }) + "\n");
336
+ },
337
+ shutdown: shutdownWorker,
338
+ close() {
339
+ closed = true;
340
+ clearTimeout(reconnect);
341
+ socket?.destroy();
342
+ },
343
+ };
344
+ }
@@ -0,0 +1,119 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { randomUUID } from "node:crypto";
7
+ import { mkdir, open, readFile, writeFile, unlink } from "node:fs/promises";
8
+
9
+ import { workerLocation, prepareWorkerDirectory } from "./worker-location.mjs";
10
+ export { workerLocation } from "./worker-location.mjs";
11
+ const execute = promisify(execFile);
12
+ export async function launchWorker(backend, desired) {
13
+ const { socket, unit, directory } = workerLocation(backend);
14
+ await prepareWorkerDirectory(directory);
15
+ await mkdir(backend.stateDir, { recursive: true, mode: 0o700 });
16
+ let entry = fileURLToPath(new URL("./worker-server.mjs", import.meta.url));
17
+ let runtimeEnv = desired?.runtimeEnv || {};
18
+ try {
19
+ const saved = JSON.parse(
20
+ await readFile(join(backend.stateDir, "worker-options.json"), "utf8"),
21
+ );
22
+ if (
23
+ saved.preferredEntry &&
24
+ (!desired || saved.generation >= desired.generation)
25
+ ) {
26
+ entry = saved.preferredEntry;
27
+ runtimeEnv = saved.runtimeEnv || {};
28
+ }
29
+ } catch (error) {
30
+ if (error.code !== "ENOENT") throw error;
31
+ }
32
+ const envPath = join(backend.stateDir, `worker-environment-${randomUUID()}`);
33
+ const args = [entry, socket, backend.stateDir, envPath];
34
+ const quote = (value) =>
35
+ '"' + String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
36
+ const environment = { ...runtimeEnv, PATH: process.env.PATH };
37
+ await writeFile(
38
+ envPath,
39
+ Object.entries(environment)
40
+ .map(([key, value]) => `${key}=${quote(value)}`)
41
+ .join("\n") + "\n",
42
+ { mode: 0o600, flag: "wx" },
43
+ );
44
+ let userManager = false;
45
+ try {
46
+ await execute("systemctl", ["--user", "show-environment"], {
47
+ timeout: 5000,
48
+ });
49
+ userManager = true;
50
+ } catch (error) {
51
+ if (process.env.INVOCATION_ID) {
52
+ await unlink(envPath);
53
+ throw new Error(`无法启动独立 Claude 后端服务:${error.message}`);
54
+ }
55
+ }
56
+ if (userManager) {
57
+ for (let attempt = 0; attempt < 50; attempt++) {
58
+ try {
59
+ await execute(
60
+ "systemd-run",
61
+ [
62
+ "--user",
63
+ "--quiet",
64
+ `--unit=${unit}`,
65
+ "--collect",
66
+ "--property=Type=exec",
67
+ "--property=Restart=on-failure",
68
+ "--property=RestartSec=2",
69
+ `--property=EnvironmentFile=${envPath.replace(/%/g, "%%")}`,
70
+ process.execPath,
71
+ ...args,
72
+ ],
73
+ { timeout: 10000 },
74
+ );
75
+ return;
76
+ } catch (error) {
77
+ const { stdout } = await execute(
78
+ "systemctl",
79
+ ["--user", "show", unit, "--property=ActiveState", "--value"],
80
+ { timeout: 5000 },
81
+ );
82
+ if (["active", "activating"].includes(stdout.trim())) {
83
+ const current = await execute(
84
+ "systemctl",
85
+ ["--user", "show", unit, "--property=EnvironmentFiles", "--value"],
86
+ { timeout: 5000 },
87
+ );
88
+ if (!current.stdout.includes(envPath)) await unlink(envPath);
89
+ return;
90
+ }
91
+ if (
92
+ !["deactivating", "inactive", "failed", ""].includes(stdout.trim()) ||
93
+ attempt === 49
94
+ ) {
95
+ await unlink(envPath);
96
+ throw error;
97
+ }
98
+ await delay(100);
99
+ }
100
+ }
101
+ return;
102
+ }
103
+ await mkdir(backend.stateDir, { recursive: true, mode: 0o700 });
104
+ const log = await open(join(backend.stateDir, "worker.log"), "a", 0o600);
105
+ try {
106
+ const child = spawn(process.execPath, args, {
107
+ detached: true,
108
+ stdio: ["ignore", log.fd, log.fd],
109
+ env: { ...process.env, ...runtimeEnv },
110
+ });
111
+ await new Promise((resolve, reject) => {
112
+ child.once("spawn", resolve);
113
+ child.once("error", reject);
114
+ });
115
+ child.unref();
116
+ } finally {
117
+ await log.close();
118
+ }
119
+ }
@@ -0,0 +1,31 @@
1
+ import { createHash } from "node:crypto";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { mkdir, lstat } from "node:fs/promises";
5
+
6
+ export function workerLocation(backend) {
7
+ const key = createHash("sha256")
8
+ .update(resolve(backend.stateDir))
9
+ .digest("hex")
10
+ .slice(0, 20);
11
+ const directory = join(
12
+ process.env.XDG_RUNTIME_DIR || tmpdir(),
13
+ `claudex-web-claude-${process.getuid()}`,
14
+ );
15
+ return {
16
+ directory,
17
+ socket: join(directory, `${key}.sock`),
18
+ unit: `claudex-web-claude-${key}`,
19
+ };
20
+ }
21
+ export async function prepareWorkerDirectory(directory) {
22
+ await mkdir(directory, { recursive: true, mode: 0o700 });
23
+ const info = await lstat(directory);
24
+ if (!info.isDirectory() || info.uid !== process.getuid() || info.mode & 0o077)
25
+ throw new Error("Claude IPC 目录必须由当前用户持有并使用0700权限。");
26
+ }
27
+ export async function verifyWorkerSocket(path) {
28
+ const info = await lstat(path);
29
+ if (!info.isSocket() || info.uid !== process.getuid() || info.mode & 0o077)
30
+ throw new Error("Claude IPC socket 必须由当前用户持有并使用0600权限。");
31
+ }
@@ -0,0 +1,45 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { join, relative } from "node:path";
5
+
6
+ const root = fileURLToPath(new URL("../../../../", import.meta.url));
7
+ const loadedAt = Date.now();
8
+ async function files(directory) {
9
+ const entries = await readdir(directory, { withFileTypes: true });
10
+ const nested = await Promise.all(
11
+ entries
12
+ .filter((entry) => !entry.name.startsWith("."))
13
+ .map((entry) => {
14
+ const path = join(directory, entry.name);
15
+ return entry.isDirectory()
16
+ ? files(path)
17
+ : entry.name.endsWith(".mjs")
18
+ ? [path]
19
+ : [];
20
+ }),
21
+ );
22
+ return nested.flat();
23
+ }
24
+ async function revision() {
25
+ const paths = [
26
+ ...(await files(join(root, "server", "src"))),
27
+ ...(await files(join(root, "shared"))),
28
+ join(root, "package.json"),
29
+ ].sort();
30
+ const content = await Promise.all(paths.map((path) => readFile(path)));
31
+ const hash = createHash("sha256");
32
+ paths.forEach((path, index) => {
33
+ hash.update(relative(root, path));
34
+ hash.update(content[index]);
35
+ });
36
+ return {
37
+ loadedAt,
38
+ entry: fileURLToPath(new URL("./worker-server.mjs", import.meta.url)),
39
+ hash: hash.digest("hex"),
40
+ version: JSON.parse(await readFile(join(root, "package.json"), "utf8"))
41
+ .version,
42
+ };
43
+ }
44
+ const current = revision();
45
+ export const workerRevision = () => current;