@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,171 @@
1
+ import {
2
+ supportsProviderBalance,
3
+ readProviderBalance,
4
+ } from "./provider-balance.mjs";
5
+
6
+ export function claudeAccountIdentity(native, provider) {
7
+ if (provider)
8
+ return {
9
+ type: "provider",
10
+ providerId: provider.id,
11
+ providerName: provider.name,
12
+ name: provider.name,
13
+ apiProvider: "configured",
14
+ usageSupported: supportsProviderBalance(provider),
15
+ };
16
+ const hasToken = Boolean(native.tokenSource && native.tokenSource !== "none");
17
+ const hasApiKey = Boolean(
18
+ native.apiKeySource && native.apiKeySource !== "none",
19
+ );
20
+ const type =
21
+ native.apiProvider && native.apiProvider !== "firstParty"
22
+ ? "provider"
23
+ : hasToken
24
+ ? "claude"
25
+ : hasApiKey
26
+ ? "apiKey"
27
+ : null;
28
+ if (!type) return null;
29
+ return {
30
+ ...native,
31
+ type,
32
+ name: native.email || native.organization || "Claude Code",
33
+ planType: native.subscriptionType,
34
+ usageSupported: type === "claude",
35
+ };
36
+ }
37
+
38
+ export function claudeUsageSnapshot(report, account) {
39
+ const source = report?.rate_limits;
40
+ if (!report?.rate_limits_available || !source)
41
+ return { rateLimits: null, availability: "unavailable" };
42
+ const definitions = [
43
+ ["five_hour", "5 小时额度", "5h", 300],
44
+ ["seven_day", "周额度", "周", 10080],
45
+ ["seven_day_oauth_apps", "OAuth 应用周额度", "周", 10080],
46
+ ["seven_day_opus", "Opus 周额度", "周", 10080],
47
+ ["seven_day_sonnet", "Sonnet 周额度", "周", 10080],
48
+ ];
49
+ const rows = definitions
50
+ .filter(([id]) => source[id] != null)
51
+ .map(([id, label, shortLabel, windowDurationMins]) => ({
52
+ id,
53
+ label,
54
+ shortLabel,
55
+ windowDurationMins,
56
+ ...source[id],
57
+ }));
58
+ for (const [index, row] of (source.model_scoped || []).entries())
59
+ rows.push({
60
+ ...row,
61
+ id: "model_scoped:" + index + ":" + row.display_name,
62
+ label: row.display_name + "周额度",
63
+ shortLabel: "周",
64
+ windowDurationMins: 10080,
65
+ });
66
+ const windows = rows.map(({ utilization, resets_at, ...row }) => {
67
+ const parsedReset = resets_at ? Date.parse(resets_at) / 1000 : null;
68
+ return {
69
+ ...row,
70
+ usedPercent: utilization,
71
+ resetsAt: Number.isFinite(parsedReset) ? parsedReset : null,
72
+ };
73
+ });
74
+ const limits = {
75
+ limitId: "claude",
76
+ planType: account?.subscriptionType || account?.planType,
77
+ windows,
78
+ primary: windows[0] || null,
79
+ secondary: windows[1] || null,
80
+ extraUsage: source.extra_usage
81
+ ? {
82
+ enabled: source.extra_usage.is_enabled,
83
+ used: source.extra_usage.used_credits,
84
+ limit: source.extra_usage.monthly_limit,
85
+ currency: source.extra_usage.currency || null,
86
+ unit: "minor",
87
+ utilization: source.extra_usage.utilization,
88
+ }
89
+ : null,
90
+ };
91
+ return {
92
+ rateLimits: limits,
93
+ rateLimitsByLimitId: { claude: limits },
94
+ availability: "available",
95
+ };
96
+ }
97
+
98
+ export function createClaudeAccount({
99
+ backend,
100
+ providers,
101
+ catalogue,
102
+ queries = new Map(),
103
+ }) {
104
+ const pending = new Map();
105
+ const contexts = async (params) => {
106
+ const provider = await providers.get(backend.id, params.providerId);
107
+ return {
108
+ provider,
109
+ cwd: params.cwd,
110
+ providerId: provider?.id || "",
111
+ threadId: params.threadId,
112
+ };
113
+ };
114
+ async function read(params = {}) {
115
+ const context = await contexts(params);
116
+ const native = context.provider
117
+ ? {}
118
+ : (await catalogue.read(context)).account;
119
+ const account = claudeAccountIdentity(native || {}, context.provider);
120
+ return {
121
+ account,
122
+ usageSupported: account?.usageSupported === true,
123
+ requiresOpenaiAuth: false,
124
+ };
125
+ }
126
+ async function rateLimits(params = {}) {
127
+ const context = await contexts(params);
128
+ if (context.provider && supportsProviderBalance(context.provider)) {
129
+ const key = context.provider.id + ":" + context.provider.apiKey;
130
+ if (!pending.has(key))
131
+ pending.set(
132
+ key,
133
+ readProviderBalance(context.provider).finally(() =>
134
+ pending.delete(key),
135
+ ),
136
+ );
137
+ return pending.get(key);
138
+ }
139
+ if (context.provider)
140
+ return {
141
+ rateLimits: null,
142
+ availability: "external",
143
+ providerId: context.providerId,
144
+ };
145
+ const identity = (await catalogue.read(context)).account;
146
+ if (!claudeAccountIdentity(identity || {})?.usageSupported)
147
+ return { rateLimits: null, availability: "unavailable" };
148
+ const key = JSON.stringify([context.cwd, identity, context.threadId || ""]);
149
+ if (pending.has(key)) return pending.get(key);
150
+ const request = catalogue
151
+ .usage(context)
152
+ .then((report) => ({
153
+ ...claudeUsageSnapshot(report, identity),
154
+ rateLimitEvents: (context.threadId
155
+ ? [queries.get(context.threadId)].filter(Boolean)
156
+ : [...queries.values()].filter((run) => run.cwd === context.cwd)
157
+ )
158
+ .filter((run) => !run.providerId)
159
+ .flatMap((run) => [...(run.rateLimits?.values() || [])]),
160
+ }))
161
+ .finally(() => pending.delete(key));
162
+ pending.set(key, request);
163
+ return request;
164
+ }
165
+
166
+ return {
167
+ read,
168
+ rateLimits,
169
+ close() {},
170
+ };
171
+ }
@@ -0,0 +1,366 @@
1
+ import { createClaudeAccount } from "./account.mjs";
2
+ import { configuredTokenUsage } from "./token-usage.mjs";
3
+ import { createClaudeCatalogue } from "./catalogue.mjs";
4
+ import { createClaudeSessions } from "./sessions.mjs";
5
+ import { createProductMethods } from "../../bridge/product-methods.mjs";
6
+ import { assertConversationOperation } from "../../bridge/conversation-policy.mjs";
7
+ import { join } from "node:path";
8
+ import { claudeCapabilities } from "../../../../shared/backend-capabilities.mjs";
9
+ import { createStorage } from "../storage.mjs";
10
+ import { createSessionReader, page } from "./history.mjs";
11
+ import { createClaudeRuntime } from "./runtime.mjs";
12
+ import { createCompactions } from "../../compaction.mjs";
13
+ import { createWorkspace } from "../../workspace/service.mjs";
14
+
15
+ export function createClaudeAdapter({
16
+ backend,
17
+ config,
18
+ send,
19
+ broadcast,
20
+ providers,
21
+ workspace: sharedWorkspace,
22
+ }) {
23
+ const storage = createStorage(
24
+ join(backend.stateDir, "claudex-web-index.json"),
25
+ {
26
+ sessions: {},
27
+ },
28
+ );
29
+ const readSession = createSessionReader(backend);
30
+ const questions = new Map();
31
+ const compactions = createCompactions(broadcast);
32
+ const workspace = sharedWorkspace || createWorkspace({ broadcast });
33
+ const runtime = createClaudeRuntime({
34
+ backend,
35
+ storage,
36
+ providers,
37
+ broadcast,
38
+ compactions,
39
+ questions,
40
+ });
41
+ const catalogue = createClaudeCatalogue({
42
+ backend,
43
+ providers,
44
+ queries: runtime.queries,
45
+ });
46
+ const account = createClaudeAccount({
47
+ backend,
48
+ providers,
49
+ catalogue,
50
+ queries: runtime.queries,
51
+ });
52
+ const methods = createProductMethods({
53
+ config,
54
+ projectModelsDirectory: backend.stateDir,
55
+ checkCompaction: (threadId) => compactions.entries.get(threadId) || null,
56
+ readAgentMessages: (threadId) =>
57
+ sessions.request("lan/agents/messages", { threadId }),
58
+ call: dispatch,
59
+ activeTurns: runtime.running,
60
+ activeThreads: runtime.running,
61
+ broadcast,
62
+ });
63
+ const { files } = methods;
64
+ let ready = false,
65
+ version = "",
66
+ error = null;
67
+ const notify = (method, params) => broadcast({ method, params });
68
+ function state() {
69
+ return {
70
+ method: "lan/state",
71
+ params: {
72
+ ready,
73
+ runtimeVersion: version,
74
+ error,
75
+ questions: [...questions.values()].map((q) => q.question),
76
+ internalCommands: [...runtime.queries]
77
+ .filter(([, process]) => process.commands.busy)
78
+ .map(([id]) => id),
79
+ activeTurns: Object.fromEntries(
80
+ [...runtime.running]
81
+ .filter(([, r]) => r.turn)
82
+ .map(([id, r]) => [id, r.turn.id]),
83
+ ),
84
+ executionStatuses: Object.fromEntries(
85
+ [...runtime.running]
86
+ .filter(([, run]) => run.status)
87
+ .map(([id, run]) => [id, run.status]),
88
+ ),
89
+ compactions: Object.fromEntries(compactions.entries),
90
+ terminals: sharedWorkspace ? {} : workspace.snapshot(),
91
+ undoneFiles: [...files.undoneFiles.values()],
92
+ },
93
+ };
94
+ }
95
+ const assertReady = () => {
96
+ if (!ready) throw new Error(error || "Claude Code 尚未就绪");
97
+ };
98
+ const sessions = createClaudeSessions({
99
+ config,
100
+ storage,
101
+ readSession,
102
+ runtime,
103
+ compactions,
104
+ notify,
105
+ assertReady,
106
+ readTokenUsage: async (session) =>
107
+ configuredTokenUsage(
108
+ session,
109
+ (await providers.list(backend.id)).find(
110
+ (provider) => provider.id === session.providerId,
111
+ ),
112
+ ),
113
+ });
114
+ const { session, update } = sessions;
115
+ async function dispatch(method, p) {
116
+ const offline = methods.offline.get(method);
117
+ if (offline) return offline(p);
118
+ const online = methods.online.get(method);
119
+ if (online) {
120
+ assertReady();
121
+ return online(p);
122
+ }
123
+ assertConversationOperation(method, {
124
+ compacting: compactions.busy(p.threadId),
125
+ undoing: files.undoing.has(p.threadId),
126
+ active: runtime.running.has(p.threadId),
127
+ });
128
+ if (sessions.handles(method)) return sessions.request(method, p);
129
+ if (method === "fuzzyFileSearch") {
130
+ const context = p.threadId ? await session(p.threadId) : p;
131
+ const results = await Promise.all(
132
+ (p.roots || [context.cwd || config.defaultCwd]).map((cwd) =>
133
+ catalogue.fileSuggestions({
134
+ cwd,
135
+ query: p.query,
136
+ providerId: p.providerId ?? context.providerId ?? "",
137
+ threadId: p.threadId,
138
+ }),
139
+ ),
140
+ );
141
+ return { files: results.flatMap((result) => result.files) };
142
+ }
143
+ const handler =
144
+ runtime.goals.handlers.get(method) || runtime.tasks.handlers.get(method);
145
+ if (handler) return handler(p);
146
+ if (method === "review/start") {
147
+ if (p.target?.type !== "uncommittedChanges")
148
+ throw new Error("请选择未提交的项目变更");
149
+ if (!ready) throw new Error(error || "Claude Code 尚未就绪");
150
+ if (runtime.running.has(p.threadId) || compactions.busy(p.threadId))
151
+ throw new Error("请等待当前任务结束后审查代码");
152
+ return runtime.enqueue(p.threadId, {
153
+ input: [
154
+ {
155
+ type: "text",
156
+ text: "/code-review 当前项目所有未提交的变更,包含暂存、未暂存和未跟踪文件。读取项目约定及相关实现,检查正确性、回归、安全和测试缺口。按严重程度列出可核查的问题、文件位置、触发条件和修复建议;没有发现问题时明确说明。仅进行审查,保持项目文件不变。",
157
+ },
158
+ ],
159
+ review: true,
160
+ });
161
+ }
162
+ if (method === "fs/readFile") {
163
+ const context = p.threadId ? await session(p.threadId) : p;
164
+ return catalogue.readFile(
165
+ {
166
+ cwd: context.cwd || config.defaultCwd,
167
+ providerId: p.providerId ?? context.providerId ?? "",
168
+ threadId: p.threadId,
169
+ },
170
+ p.path,
171
+ );
172
+ }
173
+ if (workspace.handles(method)) return workspace.request(method, p);
174
+ if (["account/read", "account/rateLimits/read"].includes(method)) {
175
+ const context = p.threadId ? await session(p.threadId) : p;
176
+ const params = {
177
+ ...p,
178
+ cwd: context.cwd || config.defaultCwd,
179
+ providerId: p.providerId ?? context.providerId ?? "",
180
+ };
181
+ return method === "account/read"
182
+ ? account.read(params)
183
+ : account.rateLimits(params);
184
+ }
185
+ if (method === "config/read") {
186
+ const context = p.threadId ? await session(p.threadId) : p;
187
+ const settings = await catalogue.settings({
188
+ cwd: context.cwd || config.defaultCwd,
189
+ providerId: p.providerId ?? context.providerId ?? "",
190
+ threadId: p.threadId,
191
+ });
192
+ return {
193
+ config: {
194
+ model: settings.applied.model,
195
+ model_reasoning_effort: settings.applied.effort,
196
+ },
197
+ };
198
+ }
199
+ if (
200
+ [
201
+ "model/list",
202
+ "mcpServerStatus/list",
203
+ "plugin/installed",
204
+ "skills/list",
205
+ ].includes(method)
206
+ ) {
207
+ const context = p.threadId ? await session(p.threadId) : p;
208
+ const cwd = context.cwd || config.defaultCwd;
209
+ const data = await catalogue.read({
210
+ cwd,
211
+ providerId: p.providerId ?? context.providerId ?? "",
212
+ threadId: p.threadId,
213
+ });
214
+ if (method === "model/list")
215
+ return { data: data.models, nextCursor: null };
216
+ if (method === "mcpServerStatus/list") return page(data.mcp, p);
217
+ if (method === "plugin/installed")
218
+ return {
219
+ marketplaces: [{ name: "Claude Code", plugins: data.plugins }],
220
+ };
221
+ const directories = await Promise.all(
222
+ (p.cwds || [cwd]).map(async (directory) => ({
223
+ cwd: directory,
224
+ skills: (
225
+ await catalogue.skills({
226
+ cwd: directory,
227
+ providerId: p.providerId ?? context.providerId ?? "",
228
+ threadId: p.threadId,
229
+ })
230
+ ).map((skill) => ({ ...skill, native: true })),
231
+ })),
232
+ );
233
+ return {
234
+ commands: [
235
+ ...data.commands,
236
+ ...directories
237
+ .flatMap((entry) => entry.skills)
238
+ .filter(
239
+ (skill) =>
240
+ !data.commands.some((command) => command.name === skill.name),
241
+ ),
242
+ ],
243
+ agents: data.agents,
244
+ data: directories,
245
+ };
246
+ }
247
+ if (
248
+ method === "turn/start" ||
249
+ method === "turn/steer" ||
250
+ method === "thread/compact/start"
251
+ ) {
252
+ if (!ready) throw new Error(error || "Claude Code 尚未就绪");
253
+ if (method === "turn/steer") return runtime.steer(p.threadId, p);
254
+ const result = await runtime.enqueue(
255
+ p.threadId,
256
+ p,
257
+ method === "thread/compact/start",
258
+ );
259
+ return method === "turn/start" ? result : {};
260
+ }
261
+ if (method === "turn/interrupt") return runtime.interrupt(p.threadId);
262
+ if (method === "lan/inputQueue/list")
263
+ return { entries: (await session(p.threadId)).queue || [] };
264
+ if (method === "lan/inputQueue/retry") {
265
+ const s = await session(p.threadId);
266
+ if (!s.queue?.some((q) => q.id === p.id))
267
+ throw new Error("排队输入已结束");
268
+ await update(p.threadId, {
269
+ queue: s.queue.map((q) =>
270
+ q.id === p.id ? { ...q, status: "queued" } : q,
271
+ ),
272
+ });
273
+ runtime.resumeQueue(p.threadId);
274
+ return {};
275
+ }
276
+ if (method === "lan/inputQueue/cancel") {
277
+ await storage.update((data) => ({
278
+ ...data,
279
+ sessions: {
280
+ ...data.sessions,
281
+ [p.threadId]: {
282
+ ...data.sessions[p.threadId],
283
+ queue: data.sessions[p.threadId].queue.filter((q) => q.id !== p.id),
284
+ },
285
+ },
286
+ }));
287
+ notify("lan/inputQueue/updated", { threadId: p.threadId });
288
+ return {};
289
+ }
290
+ throw new Error(`Claude Code 暂不支持此操作:${method}`);
291
+ }
292
+ return {
293
+ capabilities: claudeCapabilities,
294
+ workspaceOwner: "bridge",
295
+ state,
296
+ releaseClient() {},
297
+ releaseUnusedThreads() {
298
+ runtime
299
+ .releaseUnusedThreads()
300
+ .catch((error) => console.error("Claude Code 空闲会话释放失败", error));
301
+ },
302
+ get ready() {
303
+ return ready;
304
+ },
305
+ async connect() {
306
+ try {
307
+ version = await runtime.check();
308
+ await runtime.recover();
309
+ for (const [id, s] of Object.entries((await storage.read()).sessions))
310
+ if (s.compaction) {
311
+ const entry = ["starting", "running"].includes(s.compaction.status)
312
+ ? {
313
+ ...s.compaction,
314
+ status: "interrupted",
315
+ completedAt: Date.now() / 1000,
316
+ }
317
+ : s.compaction;
318
+ compactions.entries.set(id, entry);
319
+ }
320
+ ready = true;
321
+ } catch (e) {
322
+ error = e.message;
323
+ }
324
+ broadcast(state());
325
+ },
326
+ async receive(client, message) {
327
+ if (!message.method) {
328
+ const q = questions.get(String(message.id));
329
+ if (q) {
330
+ questions.delete(String(message.id));
331
+ const answers = Object.fromEntries(
332
+ q.input.questions.map((question, i) => [
333
+ question.question,
334
+ (message.result?.answers?.[String(i)]?.answers || []).join(", "),
335
+ ]),
336
+ );
337
+ q.resolve(
338
+ message.error
339
+ ? { behavior: "deny", message: message.error.message }
340
+ : { behavior: "allow", updatedInput: { ...q.input, answers } },
341
+ );
342
+ notify("serverRequest/resolved", { requestId: message.id });
343
+ }
344
+ return;
345
+ }
346
+ try {
347
+ send(client, {
348
+ id: message.id,
349
+ result: await dispatch(message.method, message.params || {}),
350
+ });
351
+ } catch (e) {
352
+ send(client, {
353
+ id: message.id,
354
+ error: { code: -32000, message: e.message },
355
+ });
356
+ }
357
+ },
358
+ close() {
359
+ ready = false;
360
+ account.close();
361
+ catalogue.close();
362
+ runtime.close();
363
+ if (!sharedWorkspace) workspace.close();
364
+ },
365
+ };
366
+ }
@@ -0,0 +1,70 @@
1
+ import { historyTurns } from "./messages.mjs";
2
+
3
+ export async function recoverAgents(parent, records, readSession) {
4
+ const nativeId = parent.nativeSessionId || parent.id;
5
+ const ids = await readSession("listSubagents", nativeId, {
6
+ dir: parent.historySearchAll ? undefined : parent.cwd,
7
+ });
8
+ const agents = { ...parent.agents };
9
+ for (const agentId of ids) {
10
+ const id = `agent/${parent.id}/${agentId}`;
11
+ const messages = await readSession(
12
+ "getSubagentMessages",
13
+ nativeId,
14
+ agentId,
15
+ { dir: parent.historySearchAll ? undefined : parent.cwd },
16
+ );
17
+ if (!messages.length) continue;
18
+ const toolId = messages[0].parent_tool_use_id;
19
+ const turn = records.find((record) =>
20
+ record.items.some((item) => item.id === toolId),
21
+ );
22
+ const tool = turn?.items.find((item) => item.id === toolId);
23
+ const input = tool?.arguments || {};
24
+ const previous = agents[id] || {};
25
+ agents[id] = {
26
+ ...previous,
27
+ agentId,
28
+ parentNativeId: nativeId,
29
+ name:
30
+ previous.name ||
31
+ input.name ||
32
+ input.subagent_type ||
33
+ input.description ||
34
+ "子代理",
35
+ prompt: previous.prompt || previous.initialTask || input.prompt,
36
+ toolUseId: toolId,
37
+ };
38
+ const activity = turn?.items.find((item) => item.agentThreadId === id);
39
+ if (activity) {
40
+ activity.prompt = agents[id].prompt;
41
+ activity.agentPath = agents[id].name;
42
+ }
43
+ if (turn && !activity) {
44
+ turn.items.push({
45
+ id: `agent-${agentId}`,
46
+ turnId: turn.id,
47
+ type: "subAgentActivity",
48
+ kind:
49
+ messages.at(-1)?.message?.stop_reason === "end_turn"
50
+ ? "completed"
51
+ : parent.running
52
+ ? "started"
53
+ : "interrupted",
54
+ agentThreadId: id,
55
+ agentPath: agents[id].name,
56
+ prompt: agents[id].prompt,
57
+ });
58
+ }
59
+ }
60
+ return agents;
61
+ }
62
+
63
+ export function agentTurns(messages) {
64
+ return historyTurns(messages).map((turn) => ({
65
+ ...turn,
66
+ items: turn.items.map((item) =>
67
+ item.type === "userMessage" ? { ...item, authorLabel: "主代理" } : item,
68
+ ),
69
+ }));
70
+ }