@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,319 @@
1
+ import { createSessionReader } from "./history.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ function tokens(usage = {}) {
5
+ return (
6
+ (usage.input_tokens || 0) +
7
+ (usage.output_tokens || 0) +
8
+ (usage.cache_creation_input_tokens || 0) +
9
+ (usage.cache_read_input_tokens || 0)
10
+ );
11
+ }
12
+ function modelTokens(usage = {}) {
13
+ return Object.values(usage).reduce(
14
+ (sum, model) =>
15
+ sum +
16
+ (model.inputTokens || 0) +
17
+ (model.outputTokens || 0) +
18
+ (model.cacheReadInputTokens || 0) +
19
+ (model.cacheCreationInputTokens || 0),
20
+ 0,
21
+ );
22
+ }
23
+ export function createGoals({
24
+ storage,
25
+ save,
26
+ emit,
27
+ start,
28
+ interrupt,
29
+ running,
30
+ backend,
31
+ queries,
32
+ command,
33
+ }) {
34
+ const readSession = createSessionReader(backend);
35
+ const read = async (id) => {
36
+ const session = (await storage.read()).sessions[id];
37
+ if (!session) throw new Error("对话不存在");
38
+ return session.goal || null;
39
+ };
40
+ async function change(id, edit) {
41
+ let goal;
42
+ await save(id, (s) => {
43
+ if (!s) throw new Error("对话不存在");
44
+ goal = edit(s.goal || null);
45
+ return { ...s, goal };
46
+ });
47
+ emit("thread/goal/updated", { threadId: id, goal });
48
+ return goal;
49
+ }
50
+ async function set(p) {
51
+ const previous = await read(p.threadId);
52
+ const objective =
53
+ p.objective === undefined ? previous?.objective : p.objective.trim();
54
+ if (!objective) throw new Error("请填写目标");
55
+ if (objective.length > 4000)
56
+ throw new Error("Claude Code 的目标条件最多为 4000 个字符。");
57
+ if (
58
+ ["clear", "stop", "off", "reset", "none", "cancel"].includes(
59
+ objective.toLowerCase(),
60
+ )
61
+ )
62
+ throw new Error("请填写具体的目标完成条件;清除目标请使用清除操作。");
63
+ const budget =
64
+ p.tokenBudget === undefined
65
+ ? (previous?.tokenBudget ?? null)
66
+ : p.tokenBudget;
67
+ if (budget !== null && (!Number.isSafeInteger(budget) || budget <= 0))
68
+ throw new Error("Token 预算须为正整数");
69
+ if (p.status !== undefined && !["active", "paused"].includes(p.status))
70
+ throw new Error("目标状态无效");
71
+ const goal = await change(p.threadId, (old) => ({
72
+ id: old?.id || randomUUID(),
73
+ tokensUsed: old?.tokensUsed || 0,
74
+ timeUsedSeconds: old?.timeUsedSeconds || 0,
75
+ createdAt: old?.createdAt || Date.now() / 1000,
76
+ ...old,
77
+ objective,
78
+ tokenBudget: budget,
79
+ status: p.status || "active",
80
+ origin: p.origin || "user",
81
+ error: null,
82
+ updatedAt: Date.now() / 1000,
83
+ }));
84
+ if (goal.status === "paused") {
85
+ if (running.get(p.threadId)?.goalId === goal.id)
86
+ await interrupt(p.threadId);
87
+ await command(p.threadId, "/goal clear");
88
+ } else {
89
+ if (running.has(p.threadId)) await interrupt(p.threadId);
90
+ await command(p.threadId, "/goal clear");
91
+ await change(p.threadId, (g) => ({ ...g, status: "active" }));
92
+ await kick(p.threadId);
93
+ }
94
+ return { goal: await read(p.threadId) };
95
+ }
96
+ async function kick(id) {
97
+ const goal = await read(id);
98
+ if (goal?.status !== "active") return;
99
+ if (goal.tokenBudget !== null && goal.tokensUsed >= goal.tokenBudget) {
100
+ await change(id, (g) => ({ ...g, status: "budgetLimited" }));
101
+ return;
102
+ }
103
+ const session = (await storage.read()).sessions[id];
104
+ const baseline = session.initialized
105
+ ? await readSession(
106
+ "getNativeGoalStatus",
107
+ session.nativeSessionId || id,
108
+ { dir: session.historySearchAll ? undefined : session.cwd },
109
+ )
110
+ : null;
111
+ await change(id, (g) => ({
112
+ ...g,
113
+ nativeBaselineId: baseline?.nativeRecordId || null,
114
+ }));
115
+ await start(id, {
116
+ model: session.model,
117
+ providerId: session.providerId,
118
+ effort: session.effort,
119
+ serviceTier: session.serviceTier,
120
+ goalId: goal.id,
121
+ input: [
122
+ {
123
+ type: "text",
124
+ text: `/goal ${goal.objective}`,
125
+ },
126
+ ],
127
+ });
128
+ }
129
+ async function observe(id, message, process) {
130
+ const active = running.get(id);
131
+ if (!active) return;
132
+ let delta = 0;
133
+ let sample;
134
+ if (message.type === "stream_event") {
135
+ process.streamUsage ||= new Map();
136
+ const stream = message.parent_tool_use_id || "main";
137
+ if (message.event.type === "message_start") {
138
+ process.streamUsage.set(stream, {
139
+ id: message.event.message.id,
140
+ usage: message.event.message.usage,
141
+ });
142
+ }
143
+ sample = process.streamUsage.get(stream);
144
+ if (message.event.type === "message_delta" && sample)
145
+ sample.usage = { ...sample.usage, ...message.event.usage };
146
+ }
147
+ if (message.type === "assistant" && !message.isReplay)
148
+ sample = {
149
+ id: message.message?.id || message.uuid,
150
+ usage: message.message?.usage,
151
+ };
152
+ if (sample) {
153
+ const key = sample.id;
154
+ process.observed ||= new Map();
155
+ const total = Math.max(
156
+ tokens(sample.usage),
157
+ process.observed.get(key) || 0,
158
+ );
159
+ delta = total - (process.observed.get(key) || 0);
160
+ process.observed.set(key, total);
161
+ active.observedTokens = (active.observedTokens || 0) + delta;
162
+ }
163
+ if (message.type === "result") {
164
+ const cumulative = modelTokens(message.modelUsage);
165
+ const actual = cumulative - (process.modelTokens || 0);
166
+ process.modelTokens = cumulative;
167
+ delta =
168
+ Math.max(active.observedTokens || 0, actual) -
169
+ (active.observedTokens || 0);
170
+ await save(id, (s) => ({ ...s, modelTokens: cumulative }));
171
+ }
172
+ if (!delta) return;
173
+ let exhausted = false;
174
+ await change(id, (goal) => {
175
+ if (!goal || (goal.status !== "active" && active.goalId !== goal.id))
176
+ return goal;
177
+ const used = Math.max(0, goal.tokensUsed + delta);
178
+ exhausted =
179
+ goal.status === "active" &&
180
+ goal.tokenBudget !== null &&
181
+ used >= goal.tokenBudget;
182
+ return {
183
+ ...goal,
184
+ tokensUsed: used,
185
+ status: exhausted ? "budgetLimited" : goal.status,
186
+ };
187
+ });
188
+ if (exhausted && message.type !== "result") await interrupt(id);
189
+ }
190
+ async function beforeTool(id) {
191
+ const goal = await read(id);
192
+ if (goal?.status !== "budgetLimited" || running.get(id)?.goalId !== goal.id)
193
+ return {};
194
+ return {
195
+ hookSpecificOutput: {
196
+ hookEventName: "PreToolUse",
197
+ permissionDecision: "deny",
198
+ permissionDecisionReason:
199
+ "目标的 Token 预算已达上限,请等待用户调整预算。",
200
+ },
201
+ };
202
+ }
203
+ async function prepare(id, process) {
204
+ const goal = await read(id);
205
+ if (goal?.status === "active") return;
206
+ const listing = await process.query.getHooksListing();
207
+ if (
208
+ listing.hooks.some(
209
+ (hook) =>
210
+ hook.event === "Stop" &&
211
+ hook.source === "sessionHook" &&
212
+ hook.type === "prompt",
213
+ )
214
+ )
215
+ await process.commands.run("/goal clear");
216
+ }
217
+ async function synchronize(id) {
218
+ const goal = await read(id);
219
+ if (goal?.status !== "active") return goal;
220
+ const process = queries.get(id);
221
+ if (!process || process.ended) return goal;
222
+ const listing = await process.query.getHooksListing();
223
+ const present = listing.hooks.some(
224
+ (hook) =>
225
+ hook.event === "Stop" &&
226
+ hook.source === "sessionHook" &&
227
+ hook.type === "prompt",
228
+ );
229
+ const session = (await storage.read()).sessions[id];
230
+ const native = await readSession(
231
+ "getNativeGoalStatus",
232
+ session.nativeSessionId || id,
233
+ { dir: session.historySearchAll ? undefined : session.cwd },
234
+ );
235
+ const current =
236
+ native?.condition === goal.objective &&
237
+ native?.nativeRecordId !== goal.nativeBaselineId;
238
+ const backgroundRunning = Object.values(session.backgroundTasks || {}).some(
239
+ (task) => ["running", "pending"].includes(task.status),
240
+ );
241
+ if (present && backgroundRunning)
242
+ return change(id, (g) => ({
243
+ ...g,
244
+ nativeStatus: native,
245
+ lastCheckedAt: Date.now() / 1000,
246
+ }));
247
+ return change(id, (g) => ({
248
+ ...g,
249
+ status:
250
+ present || (current && native?.failed)
251
+ ? "blocked"
252
+ : current && native?.met && !native.sentinel
253
+ ? "complete"
254
+ : "blocked",
255
+ nativeStatus: native,
256
+ ...(present && {
257
+ error: {
258
+ message:
259
+ native?.evaluationError?.stderr ||
260
+ native?.evaluationError?.content ||
261
+ native?.reason ||
262
+ "目标检查未完成,请继续执行以重新检查目标。",
263
+ },
264
+ }),
265
+ updatedAt: Date.now() / 1000,
266
+ }));
267
+ }
268
+ async function settled(id, active, turn) {
269
+ await change(id, (goal) => {
270
+ if (!goal || (goal.status !== "active" && active.goalId !== goal.id))
271
+ return goal;
272
+ const status =
273
+ turn.status === "failed" && goal.status === "active"
274
+ ? "blocked"
275
+ : turn.status === "interrupted" && goal.status === "active"
276
+ ? "paused"
277
+ : goal.status;
278
+ return {
279
+ ...goal,
280
+ status,
281
+ timeUsedSeconds:
282
+ goal.timeUsedSeconds + Math.max(0, turn.completedAt - turn.startedAt),
283
+ };
284
+ });
285
+ if (turn.status === "completed") await synchronize(id);
286
+ }
287
+ return {
288
+ read,
289
+ prepare,
290
+ synchronize,
291
+ kick,
292
+ observe,
293
+ beforeTool,
294
+ settled,
295
+ async afterSettled(id) {
296
+ if (
297
+ ["budgetLimited", "paused", "blocked"].includes(
298
+ (await read(id))?.status,
299
+ )
300
+ )
301
+ await command(id, "/goal clear");
302
+ },
303
+ handlers: new Map([
304
+ ["thread/goal/get", async (p) => ({ goal: await read(p.threadId) })],
305
+ ["thread/goal/set", set],
306
+ [
307
+ "thread/goal/clear",
308
+ async (p) => {
309
+ const goal = await read(p.threadId);
310
+ await change(p.threadId, () => null);
311
+ if (goal && running.get(p.threadId)?.goalId === goal.id)
312
+ await interrupt(p.threadId);
313
+ await command(p.threadId, "/goal clear");
314
+ return { goal: null };
315
+ },
316
+ ],
317
+ ]),
318
+ };
319
+ }
@@ -0,0 +1,170 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isUserPrompt, visibleSessionMessages } from "./messages.mjs";
3
+
4
+ export async function forkHistory(readSession, session, retained) {
5
+ const sourceId = session.nativeSessionId || session.id;
6
+ if (!retained.length)
7
+ return {
8
+ nativeSessionId: randomUUID(),
9
+ turnIds: {},
10
+ inputTurns: {},
11
+ internalInputIds: {},
12
+ historyAnchors: {},
13
+ initialized: false,
14
+ };
15
+ const messages = await readSession("getSessionMessages", sourceId, {
16
+ dir: session.historySearchAll ? undefined : session.cwd,
17
+ });
18
+ const anchors = new Map(
19
+ Object.values(session.turns || {}).flatMap((turn) =>
20
+ [turn.nativeAnchorId, ...(turn.nativeMessageIds || [])]
21
+ .filter(Boolean)
22
+ .map((id) => [id, turn.id]),
23
+ ),
24
+ );
25
+ const markers = visibleSessionMessages(
26
+ messages,
27
+ session.internalInputIds,
28
+ ).filter((message) => isUserPrompt(message) || anchors.has(message.uuid));
29
+ const retainedIds = new Set(retained.map((turn) => turn.id));
30
+ const sourceTurn = (message) =>
31
+ anchors.get(message.uuid) ||
32
+ session.turnIds?.[message.uuid] ||
33
+ session.inputTurns?.[message.uuid] ||
34
+ message.uuid;
35
+ const retainedPrompts = markers.filter((message) =>
36
+ retainedIds.has(sourceTurn(message)),
37
+ );
38
+ const next = markers[retainedPrompts.length];
39
+ const boundary = next
40
+ ? messages.findIndex((m) => m.uuid === next.uuid)
41
+ : messages.length;
42
+ if (!retainedPrompts.length || boundary <= 0)
43
+ throw new Error("历史分支起点已变化,请刷新后重试");
44
+ if (next && !next.parentUuid)
45
+ throw new Error("Claude 原生历史缺少分支链边界");
46
+ const { sessionId } = await readSession("forkSession", sourceId, {
47
+ dir: session.historySearchAll ? undefined : session.cwd,
48
+ // A turn may end on an attachment omitted by the SDK's message projection.
49
+ // Its next prompt retains the exact native chain boundary.
50
+ ...(next && { upToMessageId: next.parentUuid }),
51
+ });
52
+ const forked = await readSession("getSessionMessages", sessionId, {
53
+ dir: session.historySearchAll ? undefined : session.cwd,
54
+ });
55
+ const original = messages.slice(0, boundary);
56
+ const copiedIds = new Map(
57
+ forked
58
+ .filter((message) => message.forkedFrom?.sessionId === sourceId)
59
+ .map((message) => [message.forkedFrom.messageUuid, message.uuid]),
60
+ );
61
+ if (original.some((message) => !copiedIds.has(message.uuid)))
62
+ throw new Error("Claude 原生历史分支的消息来源不一致");
63
+ const turnIds = {},
64
+ inputTurns = {},
65
+ historyAnchors = {},
66
+ seen = new Set();
67
+ for (const message of retainedPrompts.filter(isUserPrompt)) {
68
+ const id = sourceTurn(message),
69
+ uuid = copiedIds.get(message.uuid);
70
+ if (seen.has(id)) inputTurns[uuid] = id;
71
+ else {
72
+ turnIds[uuid] = id;
73
+ seen.add(id);
74
+ }
75
+ }
76
+ for (const turn of retained) {
77
+ if (!turn.nativeAnchorId && !turn.nativeMessageIds?.length) continue;
78
+ historyAnchors[turn.id] = {
79
+ nativeAnchorId: copiedIds.get(turn.nativeAnchorId),
80
+ nativeMessageIds: (turn.nativeMessageIds || [])
81
+ .map((id) => copiedIds.get(id))
82
+ .filter(Boolean),
83
+ };
84
+ }
85
+ return {
86
+ nativeSessionId: sessionId,
87
+ initialized: true,
88
+ turnIds,
89
+ inputTurns,
90
+ internalInputIds: Object.fromEntries(
91
+ Object.keys(session.internalInputIds || {})
92
+ .filter((uuid) => copiedIds.has(uuid))
93
+ .map((uuid) => [copiedIds.get(uuid), true]),
94
+ ),
95
+ historyAnchors,
96
+ };
97
+ }
98
+
99
+ export function retainedDetails(session, retained, threadId = session.id) {
100
+ const ids = new Set(retained.map((turn) => turn.id));
101
+ const entries = [
102
+ ...Object.values(session.extraItems || {}).filter(
103
+ (item) =>
104
+ ids.has(item.turnId) &&
105
+ !(item.type === "userMessage" && session.inputTurns?.[item.id]),
106
+ ),
107
+ ...retained.flatMap((turn) =>
108
+ turn.items.filter((item) => item.type === "subAgentActivity"),
109
+ ),
110
+ ];
111
+ const agents = {};
112
+ const extraItems = {};
113
+ for (const original of entries) {
114
+ const item = { ...original };
115
+ if (item.agentThreadId) {
116
+ const agent = session.agents?.[item.agentThreadId];
117
+ if (agent) {
118
+ item.agentThreadId = `agent/${threadId}/${agent.agentId}`;
119
+ agents[item.agentThreadId] = {
120
+ ...agent,
121
+ parentNativeId:
122
+ agent.parentNativeId || session.nativeSessionId || session.id,
123
+ };
124
+ }
125
+ }
126
+ extraItems[item.id] = item;
127
+ }
128
+ return { agents, extraItems };
129
+ }
130
+
131
+ export function createHistoryActions({
132
+ session,
133
+ turns,
134
+ update,
135
+ readSession,
136
+ notify,
137
+ }) {
138
+ return async function revert(params) {
139
+ const s = await session(params.threadId);
140
+ const records = await turns(s.id);
141
+ const index = params.beforeTurnId
142
+ ? records.findIndex((turn) => turn.id === params.beforeTurnId)
143
+ : records.length - params.numTurns;
144
+ if (!Number.isInteger(index) || index < 0 || index >= records.length)
145
+ throw new Error("编辑起点已变化,请刷新历史后重试");
146
+ const retained = records.slice(0, index);
147
+ const fork = await forkHistory(readSession, s, retained);
148
+ await update(s.id, {
149
+ ...fork,
150
+ nativeAliases: [
151
+ ...new Set([
152
+ ...(s.nativeAliases || []),
153
+ s.nativeSessionId || s.id,
154
+ fork.nativeSessionId,
155
+ ]),
156
+ ],
157
+ turns: Object.fromEntries(
158
+ retained.map((turn) => [
159
+ turn.id,
160
+ { ...turn, ...fork.historyAnchors?.[turn.id] },
161
+ ]),
162
+ ),
163
+ ...retainedDetails(await session(s.id), retained),
164
+ active: null,
165
+ queue: [],
166
+ });
167
+ notify("thread/reverted", { threadId: s.id });
168
+ return {};
169
+ };
170
+ }
@@ -0,0 +1,65 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { claudeRuntimeEnvironment } from "./provider-environment.mjs";
4
+
5
+ // 会话 API 在独立进程中读取实例目录,避免 SDK 的全局环境缓存串用数据。
6
+ export function createSessionReader(backend) {
7
+ return (operation, ...args) =>
8
+ new Promise((resolve, reject) => {
9
+ const child = spawn(
10
+ process.execPath,
11
+ [fileURLToPath(new URL("./session-worker.mjs", import.meta.url))],
12
+ {
13
+ env: claudeRuntimeEnvironment(backend),
14
+ stdio: ["pipe", "pipe", "pipe"],
15
+ },
16
+ );
17
+ let output = "",
18
+ stderr = "",
19
+ settled = false;
20
+ const timer = setTimeout(() => {
21
+ child.kill();
22
+ finish(new Error("读取 Claude 历史超时"));
23
+ }, 30000);
24
+ function finish(error, value) {
25
+ if (settled) return;
26
+ settled = true;
27
+ clearTimeout(timer);
28
+ if (error) reject(error);
29
+ else resolve(value);
30
+ }
31
+ child.on("error", (error) => finish(error));
32
+ child.stdout.on("data", (chunk) => {
33
+ output += chunk;
34
+ });
35
+ child.stderr.on("data", (chunk) => {
36
+ stderr = (stderr + chunk).slice(-4000);
37
+ });
38
+ child.stdin.on("error", () => {});
39
+ child.on("close", (code) => {
40
+ if (settled) return;
41
+ try {
42
+ if (code !== 0) throw new Error(stderr || "读取 Claude 历史失败");
43
+ const message = JSON.parse(output);
44
+ if (message.error) throw new Error(message.error);
45
+ finish(null, message.result);
46
+ } catch (error) {
47
+ finish(error);
48
+ }
49
+ });
50
+ child.stdin.end(JSON.stringify({ operation, args }));
51
+ });
52
+ }
53
+
54
+ export function page(records, params) {
55
+ const values =
56
+ params.sortDirection === "asc" ? records : records.toReversed();
57
+ const offset = Number(params.cursor || 0),
58
+ limit = Math.min(100, Math.max(1, Number(params.limit) || 100));
59
+ if (!Number.isSafeInteger(offset) || offset < 0)
60
+ throw new Error("分页位置无效");
61
+ return {
62
+ data: values.slice(offset, offset + limit),
63
+ nextCursor: offset + limit < values.length ? String(offset + limit) : null,
64
+ };
65
+ }