@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,87 @@
1
+ import { migrateProductConfig } from "./product-config.mjs";
2
+ import { migrateWebDirectory } from "./web-config-migration.mjs";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { mkdir, readFile, rename, rm, mkdtemp } from "node:fs/promises";
6
+ import { hostname, networkInterfaces } from "node:os";
7
+ import { join } from "node:path";
8
+ import { X509Certificate } from "node:crypto";
9
+
10
+ const execute = promisify(execFile);
11
+ export function localTlsClient(cert) {
12
+ const fingerprint = new X509Certificate(cert).fingerprint256;
13
+ return {
14
+ ca: cert,
15
+ allowPartialTrustChain: true,
16
+ checkServerIdentity(_hostname, peer) {
17
+ if (peer.fingerprint256 !== fingerprint)
18
+ return new Error("本机网页服务证书与配置不匹配");
19
+ },
20
+ };
21
+ }
22
+ export async function readTls(config) {
23
+ await migrateProductConfig(config);
24
+ if (config.tlsCert)
25
+ return {
26
+ cert: await readFile(config.tlsCert),
27
+ key: await readFile(config.tlsKey),
28
+ minVersion: "TLSv1.2",
29
+ };
30
+ await migrateWebDirectory(config, "tls", [
31
+ "certificate.pem",
32
+ "private-key.pem",
33
+ ]);
34
+ const parent = config.configDir;
35
+ const directory = join(parent, "tls");
36
+ const certificate = join(directory, "certificate.pem");
37
+ const key = join(directory, "private-key.pem");
38
+ try {
39
+ await readFile(certificate);
40
+ } catch (error) {
41
+ if (error.code !== "ENOENT") throw error;
42
+ await mkdir(parent, { recursive: true, mode: 0o700 });
43
+ const temporary = await mkdtemp(join(parent, ".tls-"));
44
+ const names = new Set(["DNS:localhost", "IP:127.0.0.1", "IP:::1"]);
45
+ if (/^[a-zA-Z0-9.-]+$/.test(hostname())) names.add(`DNS:${hostname()}`);
46
+ for (const addresses of Object.values(networkInterfaces()))
47
+ for (const { address } of addresses || [])
48
+ if (!address.includes("%")) names.add(`IP:${address}`);
49
+ try {
50
+ await execute(
51
+ "/usr/bin/openssl",
52
+ [
53
+ "req",
54
+ "-x509",
55
+ "-newkey",
56
+ "rsa:2048",
57
+ "-nodes",
58
+ "-days",
59
+ "365",
60
+ "-subj",
61
+ "/CN=Claudex Web",
62
+ "-addext",
63
+ `subjectAltName=${[...names].join(",")}`,
64
+ "-keyout",
65
+ join(temporary, "private-key.pem"),
66
+ "-out",
67
+ join(temporary, "certificate.pem"),
68
+ ],
69
+ { timeout: 15000 },
70
+ );
71
+ try {
72
+ await rename(temporary, directory);
73
+ } catch (error) {
74
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code)) throw error;
75
+ }
76
+ } finally {
77
+ await rm(temporary, { recursive: true, force: true });
78
+ }
79
+ }
80
+ const cert = await readFile(certificate);
81
+ const parsed = new X509Certificate(cert);
82
+ if (Date.parse(parsed.validTo) <= Date.now())
83
+ throw new Error(
84
+ "自动生成的 HTTPS 证书已过期,请配置 TLS_CERT 与 TLS_KEY,或按部署文档重新生成证书。",
85
+ );
86
+ return { cert, key: await readFile(key), minVersion: "TLSv1.2" };
87
+ }
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const packageRoot = fileURLToPath(new URL("../../", import.meta.url));
7
+
8
+ export function readVersion(root = packageRoot) {
9
+ const { version } = JSON.parse(readFileSync(join(root, "package.json")));
10
+ if (!existsSync(join(root, ".git"))) {
11
+ const manifest = join(root, "build-info.json");
12
+ if (existsSync(manifest)) {
13
+ const info = JSON.parse(readFileSync(manifest));
14
+ if (info.version !== version)
15
+ throw new Error("构建信息与包版本不一致,请重新构建。");
16
+ return info;
17
+ }
18
+ } else {
19
+ const git = (...args) =>
20
+ execFileSync("git", args, {
21
+ cwd: root,
22
+ encoding: "utf8",
23
+ stdio: ["ignore", "pipe", "pipe"],
24
+ }).trim();
25
+ try {
26
+ const revision = git("rev-parse", "HEAD");
27
+ const dirty = Boolean(
28
+ git("status", "--porcelain", "--untracked-files=normal"),
29
+ );
30
+ const release =
31
+ !dirty &&
32
+ git("tag", "--points-at", "HEAD").split("\n").includes(`v${version}`);
33
+ return {
34
+ version,
35
+ displayVersion: release
36
+ ? version
37
+ : `${version}+dev.g${revision.slice(0, 7)}${dirty ? ".dirty" : ""}`,
38
+ revision,
39
+ dirty,
40
+ channel: release ? "release" : "development",
41
+ builtAt: null,
42
+ };
43
+ } catch {
44
+ // Git 不可用的源码部署仍可运行,来源显示为未知。
45
+ }
46
+ }
47
+ return {
48
+ version,
49
+ displayVersion: `${version}+unknown`,
50
+ revision: null,
51
+ dirty: null,
52
+ channel: "unknown",
53
+ builtAt: null,
54
+ };
55
+ }
@@ -0,0 +1,48 @@
1
+ import {
2
+ mkdir,
3
+ mkdtemp,
4
+ readFile,
5
+ rename,
6
+ rm,
7
+ stat,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+
12
+ // 只在目标目录尚未建立时迁移网页自有状态,现有配置始终优先。
13
+ export async function migrateWebDirectory(config, name, filenames) {
14
+ const target = join(config.configDir, name);
15
+ try {
16
+ await stat(target);
17
+ return;
18
+ } catch (error) {
19
+ if (error.code !== "ENOENT") throw error;
20
+ }
21
+ const legacy = join(config.codexHome, "codex-web", name);
22
+ const files = await Promise.all(
23
+ filenames.map(async (filename) => {
24
+ try {
25
+ return [filename, await readFile(join(legacy, filename))];
26
+ } catch (error) {
27
+ if (error.code !== "ENOENT") throw error;
28
+ return null;
29
+ }
30
+ }),
31
+ );
32
+ if (!files.some(Boolean)) return;
33
+ if (name === "tls" && files.some((file) => !file))
34
+ throw new Error("旧 HTTPS 证书或私钥缺失,请检查原网页证书目录。");
35
+ await mkdir(config.configDir, { recursive: true, mode: 0o700 });
36
+ const temporary = await mkdtemp(join(config.configDir, `.migrate-${name}-`));
37
+ try {
38
+ for (const [filename, bytes] of files.filter(Boolean))
39
+ await writeFile(join(temporary, filename), bytes, { mode: 0o600 });
40
+ try {
41
+ await rename(temporary, target);
42
+ } catch (error) {
43
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code)) throw error;
44
+ }
45
+ } finally {
46
+ await rm(temporary, { recursive: true, force: true });
47
+ }
48
+ }
@@ -0,0 +1,33 @@
1
+ import { spawn } from "node:child_process";
2
+ export function executeCommand(params) {
3
+ return new Promise((resolve, reject) => {
4
+ if (
5
+ !Array.isArray(params.command) ||
6
+ !params.command.length ||
7
+ params.command.some((p) => typeof p !== "string")
8
+ )
9
+ return reject(new Error("命令必须是参数数组"));
10
+ const child = spawn(params.command[0], params.command.slice(1), {
11
+ cwd: params.cwd,
12
+ env: { ...process.env, ...params.env },
13
+ stdio: ["ignore", "pipe", "pipe"],
14
+ });
15
+ let stdout = "",
16
+ stderr = "";
17
+ const timer = setTimeout(() => child.kill("SIGTERM"), 120000);
18
+ child.stdout.on("data", (bytes) => {
19
+ stdout = (stdout + bytes).slice(-4000000);
20
+ });
21
+ child.stderr.on("data", (bytes) => {
22
+ stderr = (stderr + bytes).slice(-4000000);
23
+ });
24
+ child.on("error", (error) => {
25
+ clearTimeout(timer);
26
+ reject(error);
27
+ });
28
+ child.on("close", (code) => {
29
+ clearTimeout(timer);
30
+ resolve({ stdout, stderr, exitCode: code ?? 1 });
31
+ });
32
+ });
33
+ }
@@ -0,0 +1,44 @@
1
+ import { readdir, writeFile, stat, mkdir } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join, isAbsolute, basename } from "node:path";
4
+ export async function fileRequest(method, params, configDir) {
5
+ if (method === "fs/uploadAttachment") {
6
+ if (
7
+ !configDir ||
8
+ typeof params.name !== "string" ||
9
+ typeof params.dataBase64 !== "string"
10
+ )
11
+ throw new Error("附件上传参数无效");
12
+ const directory = join(configDir, "attachments", randomUUID());
13
+ await mkdir(directory, { recursive: true, mode: 0o700 });
14
+ const path = join(directory, basename(params.name) || "attachment");
15
+ await writeFile(path, Buffer.from(params.dataBase64, "base64"), {
16
+ mode: 0o600,
17
+ flag: "wx",
18
+ });
19
+ return { path };
20
+ }
21
+ if (typeof params.path !== "string" || !isAbsolute(params.path))
22
+ throw new Error("请使用绝对路径");
23
+ if (method === "fs/readDirectory") {
24
+ const entries = await readdir(params.path, { withFileTypes: true });
25
+ return {
26
+ entries: await Promise.all(
27
+ entries.map(async (entry) => ({
28
+ fileName: entry.name,
29
+ isDirectory: entry.isSymbolicLink()
30
+ ? await stat(join(params.path, entry.name)).then(
31
+ (s) => s.isDirectory(),
32
+ () => false,
33
+ )
34
+ : entry.isDirectory(),
35
+ })),
36
+ ),
37
+ };
38
+ }
39
+ if (method === "fs/writeFile") {
40
+ await writeFile(params.path, Buffer.from(params.dataBase64, "base64"));
41
+ return {};
42
+ }
43
+ throw new Error(`不支持的方法:${method}`);
44
+ }
@@ -0,0 +1,27 @@
1
+ import { workspaceMethods } from "../../../shared/product-contract.mjs";
2
+ import { fileRequest } from "./files.mjs";
3
+ import { executeCommand } from "./commands.mjs";
4
+ import { createTerminals } from "./terminals.mjs";
5
+
6
+ // 网页交互终端和主机文件操作由服务持有,原生搜索由所属后端提供。
7
+ export function createWorkspace({ broadcast, configDir }) {
8
+ const terminals = createTerminals(broadcast);
9
+ const methods = new Set(workspaceMethods);
10
+ return {
11
+ handles: (method) => methods.has(method),
12
+ request(method, params) {
13
+ if (method.startsWith("fs/"))
14
+ return fileRequest(method, params, configDir);
15
+ if (method === "command/exec" && !params.tty)
16
+ return executeCommand(params);
17
+ if (
18
+ method.startsWith("command/exec") ||
19
+ method.startsWith("lan/terminal/")
20
+ )
21
+ return terminals.request(method, params);
22
+ throw new Error(`未知工作区操作:${method}`);
23
+ },
24
+ snapshot: terminals.snapshot,
25
+ close: terminals.close,
26
+ };
27
+ }
@@ -0,0 +1,122 @@
1
+ import { spawn } from "node-pty";
2
+ import { userInfo } from "node:os";
3
+ import { basename, resolve } from "node:path";
4
+
5
+ export function createTerminals(broadcast) {
6
+ const tasks = new Map();
7
+ let processTimer;
8
+ const emit = (method, params) => broadcast({ method, params });
9
+ const snapshot = () =>
10
+ Object.fromEntries(
11
+ [...tasks].map(([id, t]) => [
12
+ id,
13
+ {
14
+ buffer: t.buffer,
15
+ running: t.running,
16
+ processName: t.processName,
17
+ owner: t.owner,
18
+ cwd: t.cwd,
19
+ },
20
+ ]),
21
+ );
22
+ function updateProcesses() {
23
+ for (const [processId, task] of tasks) {
24
+ if (!task.running) continue;
25
+ const name = basename(task.child.process);
26
+ if (name === task.processName) continue;
27
+ task.processName = name;
28
+ emit("lan/terminalUpdated", { processId, processName: name });
29
+ }
30
+ if (![...tasks.values()].some((task) => task.running)) {
31
+ clearInterval(processTimer);
32
+ processTimer = undefined;
33
+ }
34
+ }
35
+ return {
36
+ snapshot,
37
+ async request(method, p) {
38
+ const web = method.startsWith("lan/terminal/");
39
+ if (method === "lan/terminal/create" || method === "command/exec") {
40
+ if (!p.processId || tasks.has(p.processId))
41
+ throw new Error("终端标识已被使用");
42
+ const shell = process.env.SHELL || userInfo().shell || "/bin/sh";
43
+ if (
44
+ !web &&
45
+ p.command &&
46
+ (!Array.isArray(p.command) ||
47
+ !p.command.length ||
48
+ p.command.some((part) => typeof part !== "string"))
49
+ )
50
+ throw new Error("终端命令必须是参数数组");
51
+ const command = web ? [shell, "-l"] : p.command || [shell, "-l"];
52
+ const cwd = resolve(p.cwd || process.cwd());
53
+ const child = spawn(command[0], command.slice(1), {
54
+ cwd,
55
+ env: web
56
+ ? { ...process.env, TERM: "xterm-256color", COLORTERM: "truecolor" }
57
+ : { ...process.env, ...p.env },
58
+ cols: p.size?.cols || 80,
59
+ rows: p.size?.rows || 24,
60
+ name: "xterm-256color",
61
+ });
62
+ const task = {
63
+ child,
64
+ cwd,
65
+ buffer: "",
66
+ running: true,
67
+ processName: basename(shell),
68
+ owner: web ? "workspace" : undefined,
69
+ };
70
+ tasks.set(p.processId, task);
71
+ emit("lan/terminalStarted", {
72
+ processId: p.processId,
73
+ processName: task.processName,
74
+ owner: task.owner,
75
+ cwd: task.cwd,
76
+ });
77
+ child.onData((text) => {
78
+ task.buffer = (task.buffer + text).slice(-200000);
79
+ emit(web ? "lan/terminalOutput" : "command/exec/outputDelta", {
80
+ processId: p.processId,
81
+ deltaBase64: Buffer.from(text).toString("base64"),
82
+ });
83
+ });
84
+ const exited = new Promise((resolve) =>
85
+ child.onExit(({ exitCode }) => {
86
+ task.running = false;
87
+ updateProcesses();
88
+ emit("lan/terminalExit", { processId: p.processId, exitCode });
89
+ resolve({ exitCode, stdout: "", stderr: "" });
90
+ }),
91
+ );
92
+ if (!processTimer) {
93
+ processTimer = setInterval(updateProcesses, 500);
94
+ processTimer.unref();
95
+ }
96
+ return web
97
+ ? { processId: p.processId, processName: task.processName }
98
+ : exited;
99
+ }
100
+ const task = tasks.get(p.processId);
101
+ if (!task?.running) throw new Error("终端已结束");
102
+ if (method === "command/exec/write" || method === "lan/terminal/write")
103
+ task.child.write(Buffer.from(p.deltaBase64, "base64").toString());
104
+ else if (
105
+ method === "command/exec/resize" ||
106
+ method === "lan/terminal/resize"
107
+ )
108
+ task.child.resize(Math.max(1, p.size.cols), Math.max(1, p.size.rows));
109
+ else if (
110
+ method === "command/exec/terminate" ||
111
+ method === "lan/terminal/terminate"
112
+ )
113
+ task.child.kill();
114
+ else throw new Error(`不支持的方法:${method}`);
115
+ return {};
116
+ },
117
+ close() {
118
+ clearInterval(processTimer);
119
+ for (const task of tasks.values()) if (task.running) task.child.kill();
120
+ },
121
+ };
122
+ }
@@ -0,0 +1,13 @@
1
+ import { isCompacting } from "./compaction-state.mjs";
2
+
3
+ // 后端快照包含原生执行与网页占用;停止前仍须在执行方原子复核。
4
+ export function hasBackendWork(state = {}) {
5
+ return Boolean(
6
+ Object.keys(state.activeTurns || {}).length ||
7
+ Object.keys(state.backgroundTasks || {}).length ||
8
+ Object.keys(state.queuedInputs || {}).length ||
9
+ state.internalCommands?.length ||
10
+ state.questions?.length ||
11
+ Object.values(state.compactions || {}).some(isCompacting),
12
+ );
13
+ }
@@ -0,0 +1,33 @@
1
+ export const codexCapabilities = Object.freeze({
2
+ compact: true,
3
+ inputMode: "steer",
4
+ questions: true,
5
+ fork: true,
6
+ editHistory: true,
7
+ subagents: true,
8
+ skills: true,
9
+ mcp: true,
10
+ fileUndo: true,
11
+ account: true,
12
+ goal: true,
13
+ backgroundTerminals: true,
14
+ review: true,
15
+ plugins: true,
16
+ });
17
+ export const claudeCapabilities = Object.freeze({
18
+ compact: true,
19
+ inputMode: "steer",
20
+ inputRecovery: true,
21
+ questions: true,
22
+ fork: true,
23
+ editHistory: true,
24
+ subagents: true,
25
+ skills: true,
26
+ mcp: true,
27
+ fileUndo: true,
28
+ account: true,
29
+ goal: true,
30
+ backgroundTerminals: true,
31
+ review: true,
32
+ plugins: true,
33
+ });
@@ -0,0 +1,17 @@
1
+ // 默认 Codex 实例沿用历史键,其他实例使用带版本前缀的可逆标识。
2
+ export function resourceId(backendId, nativeId) {
3
+ if (nativeId == null || nativeId === "") return nativeId;
4
+ if (backendId === "codex") return nativeId;
5
+ return `backend:${encodeURIComponent(backendId)}:${encodeURIComponent(String(nativeId))}`;
6
+ }
7
+
8
+ export function resourceTarget(id, fallback = "codex") {
9
+ if (typeof id !== "string" || !id.startsWith("backend:"))
10
+ return { backendId: fallback, nativeId: id };
11
+ const match = /^backend:([^:]+):(.+)$/.exec(id);
12
+ if (!match) throw new Error("资源标识无效");
13
+ return {
14
+ backendId: decodeURIComponent(match[1]),
15
+ nativeId: decodeURIComponent(match[2]),
16
+ };
17
+ }
@@ -0,0 +1,49 @@
1
+ export const isCompacting = (entry) =>
2
+ ["starting", "running", "reconnecting"].includes(entry?.status);
3
+
4
+ export function findCompactionTurn(entry, turns) {
5
+ return turns.find(
6
+ (turn) =>
7
+ !turn.items?.some((item) => item.type === "userMessage") &&
8
+ (entry.turnId
9
+ ? turn.id === entry.turnId
10
+ : turn.startedAt >= Math.floor(entry.startedAt) &&
11
+ (turn.status === "inProgress" ||
12
+ turn.items?.some((item) => item.type === "contextCompaction"))),
13
+ );
14
+ }
15
+
16
+ export function recoverCompaction(
17
+ entry,
18
+ thread,
19
+ turns,
20
+ now = Date.now() / 1000,
21
+ ) {
22
+ const turn = findCompactionTurn(entry, turns);
23
+ if (turn)
24
+ return {
25
+ ...entry,
26
+ turnId: turn.id,
27
+ status:
28
+ turn.status === "inProgress"
29
+ ? "running"
30
+ : turn.status === "completed"
31
+ ? "completed"
32
+ : turn.status === "interrupted"
33
+ ? "interrupted"
34
+ : "failed",
35
+ error: turn.error?.message,
36
+ ...(turn.status === "inProgress"
37
+ ? { completedAt: undefined }
38
+ : { completedAt: turn.completedAt ?? now }),
39
+ };
40
+ const ordinaryTurn = turns.some(
41
+ (candidate) =>
42
+ candidate.status === "inProgress" &&
43
+ candidate.items?.some((item) => item.type === "userMessage"),
44
+ );
45
+ if (entry.status === "starting" && !ordinaryTurn) return entry;
46
+ return ["idle", "notLoaded"].includes(thread.status?.type) || ordinaryTurn
47
+ ? { ...entry, status: "unconfirmed", completedAt: now, error: undefined }
48
+ : { ...entry, status: "reconnecting" };
49
+ }
@@ -0,0 +1,82 @@
1
+ const previews = {
2
+ image: {
3
+ png: "image/png",
4
+ apng: "image/apng",
5
+ jpg: "image/jpeg",
6
+ jpeg: "image/jpeg",
7
+ jfif: "image/jpeg",
8
+ gif: "image/gif",
9
+ webp: "image/webp",
10
+ svg: "image/svg+xml",
11
+ avif: "image/avif",
12
+ bmp: "image/bmp",
13
+ ico: "image/x-icon",
14
+ tif: "image/tiff",
15
+ tiff: "image/tiff",
16
+ },
17
+ audio: {
18
+ mp3: "audio/mpeg",
19
+ wav: "audio/wav",
20
+ wave: "audio/wav",
21
+ flac: "audio/flac",
22
+ ogg: "audio/ogg",
23
+ oga: "audio/ogg",
24
+ opus: "audio/ogg",
25
+ m4a: "audio/mp4",
26
+ aac: "audio/aac",
27
+ aif: "audio/aiff",
28
+ aiff: "audio/aiff",
29
+ wma: "audio/x-ms-wma",
30
+ amr: "audio/amr",
31
+ mid: "audio/midi",
32
+ midi: "audio/midi",
33
+ },
34
+ video: {
35
+ mp4: "video/mp4",
36
+ m4v: "video/mp4",
37
+ webm: "video/webm",
38
+ mov: "video/quicktime",
39
+ ogv: "video/ogg",
40
+ mkv: "video/x-matroska",
41
+ avi: "video/x-msvideo",
42
+ mpg: "video/mpeg",
43
+ mpeg: "video/mpeg",
44
+ mts: "video/mp2t",
45
+ m2ts: "video/mp2t",
46
+ "3gp": "video/3gpp",
47
+ "3g2": "video/3gpp2",
48
+ flv: "video/x-flv",
49
+ wmv: "video/x-ms-wmv",
50
+ },
51
+ pdf: { pdf: "application/pdf" },
52
+ };
53
+ const downloads = new Set(
54
+ "doc docx docm dot dotx odt xls xlsx xlsm xlsb ods ppt pptx pptm odp pages numbers key zip tar gz tgz xz bz2 7z rar zst br jar apk deb rpm exe dll so dylib wasm bin iso img dmg db sqlite sqlite3 parquet arrow feather npy npz h5 hdf5 pkl pickle pt pth onnx psd ai eps woff woff2 ttf otf".split(
55
+ " ",
56
+ ),
57
+ );
58
+
59
+ export function filePresentation(path) {
60
+ const name = path.split("/").at(-1).toLowerCase();
61
+ const extension = name.includes(".") ? name.split(".").at(-1) : "";
62
+ for (const [kind, types] of Object.entries(previews))
63
+ if (types[extension]) return { kind, mime: types[extension] };
64
+ return downloads.has(extension)
65
+ ? { kind: "download", mime: "application/octet-stream" }
66
+ : null;
67
+ }
68
+
69
+ export function decodeTextFile(bytes) {
70
+ if (
71
+ bytes.some(
72
+ (byte) =>
73
+ byte === 0 || (byte < 32 && ![9, 10, 12, 13, 27].includes(byte)),
74
+ )
75
+ )
76
+ return null;
77
+ try {
78
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
@@ -0,0 +1,26 @@
1
+ // 产品操作按状态所有者分组。现有 RPC 名称保留为浏览器的传输契约。
2
+ export const workspaceMethods = Object.freeze([
3
+ "fs/readDirectory",
4
+ "fs/writeFile",
5
+ "fs/uploadAttachment",
6
+ "command/exec",
7
+ "command/exec/write",
8
+ "command/exec/resize",
9
+ "command/exec/terminate",
10
+ ]);
11
+ export const conversationMethods = Object.freeze([
12
+ "thread/list",
13
+ "thread/start",
14
+ "thread/read",
15
+ "thread/resume",
16
+ "thread/unsubscribe",
17
+ "thread/turns/list",
18
+ "thread/items/list",
19
+ "thread/name/set",
20
+ "thread/archive",
21
+ "thread/unarchive",
22
+ "thread/delete",
23
+ "thread/fork",
24
+ "thread/revert",
25
+ "thread/rollback",
26
+ ]);
@@ -0,0 +1,2 @@
1
+ export const MAX_RPC_MESSAGE_BYTES = 64 * 1024 * 1024;
2
+ export const RPC_FRAME_BYTES = 1024 * 1024;
@@ -0,0 +1,26 @@
1
+ // 文件夹归属固定为启动目录;shell 内的 cd 不改变该终端的所属工作区。
2
+ export function terminalWorkspace(cwd = "") {
3
+ const parts = [];
4
+ for (const part of cwd.split("/")) {
5
+ if (!part || part === ".") continue;
6
+ if (part === "..") parts.pop();
7
+ else parts.push(part);
8
+ }
9
+ return cwd ? "/" + parts.join("/") : "";
10
+ }
11
+
12
+ export const terminalSelectionKey = (cwd) =>
13
+ "cx-terminal:" + encodeURIComponent(terminalWorkspace(cwd));
14
+
15
+ export function workspaceTerminalIds(terminals, cwd) {
16
+ const workspace = terminalWorkspace(cwd);
17
+ return Object.keys(terminals).filter((id) => {
18
+ const terminal = terminals[id];
19
+ return (
20
+ terminal.running &&
21
+ terminal.owner === "workspace" &&
22
+ terminal.cwd !== undefined &&
23
+ terminalWorkspace(terminal.cwd) === workspace
24
+ );
25
+ });
26
+ }