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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/.env.example +27 -0
  2. package/CHANGELOG.md +495 -0
  3. package/LICENSE +674 -0
  4. package/README.md +106 -2
  5. package/bin/claudex-web.mjs +129 -0
  6. package/build-info.json +8 -0
  7. package/client/dist/_baseMerge.js +1 -0
  8. package/client/dist/abnfDiagram-WEYOIA3C.js +1 -0
  9. package/client/dist/apl.js +1 -0
  10. package/client/dist/app.js +392 -0
  11. package/client/dist/apple-touch-icon.png +0 -0
  12. package/client/dist/arc.js +1 -0
  13. package/client/dist/architectureDiagram-ZHVYKT53.js +36 -0
  14. package/client/dist/asciiarmor.js +1 -0
  15. package/client/dist/asn1.js +1 -0
  16. package/client/dist/asterisk.js +1 -0
  17. package/client/dist/blockDiagram-RJAE7QA3.js +140 -0
  18. package/client/dist/brainfuck.js +1 -0
  19. package/client/dist/c4Diagram-XDPPPE54.js +38 -0
  20. package/client/dist/channel.js +1 -0
  21. package/client/dist/chunk-2E7WHVMD.js +88 -0
  22. package/client/dist/chunk-2Q5K7J3B.js +1 -0
  23. package/client/dist/chunk-4EMNKR2T.js +1 -0
  24. package/client/dist/chunk-55XCU76K.js +1 -0
  25. package/client/dist/chunk-5VM5RSS4.js +15 -0
  26. package/client/dist/chunk-JWPE2WC7.js +1 -0
  27. package/client/dist/chunk-VQ5W62QI.js +1 -0
  28. package/client/dist/chunk-XXDRQBXY.js +1 -0
  29. package/client/dist/chunk-ZCHMQSOR.js +2 -0
  30. package/client/dist/classDiagram-v2-4MYWR3UA.js +217 -0
  31. package/client/dist/clike.js +1 -0
  32. package/client/dist/clojure.js +1 -0
  33. package/client/dist/cmake.js +1 -0
  34. package/client/dist/cobol.js +1 -0
  35. package/client/dist/code-highlight-style.js +13 -0
  36. package/client/dist/coffeescript.js +1 -0
  37. package/client/dist/commonlisp.js +1 -0
  38. package/client/dist/cose-bilkent-JH36ORCC.js +1 -0
  39. package/client/dist/crystal.js +1 -0
  40. package/client/dist/css.js +1 -0
  41. package/client/dist/cynefin-EF2NZ3EQ.js +141 -0
  42. package/client/dist/cynefinDiagram-WF24UDRP.js +62 -0
  43. package/client/dist/cypher.js +1 -0
  44. package/client/dist/cytoscape.esm.js +321 -0
  45. package/client/dist/d.js +1 -0
  46. package/client/dist/dagre-NK4GIZVX.js +4 -0
  47. package/client/dist/defaultLocale.js +1 -0
  48. package/client/dist/diagram-CBK3MWTC.js +24 -0
  49. package/client/dist/diagram-I5XIIV2D.js +24 -0
  50. package/client/dist/diagram-ODIL2UCW.js +30 -0
  51. package/client/dist/diagram-PFBEJUXE.js +3 -0
  52. package/client/dist/diagram-RJA3I4VV.js +41 -0
  53. package/client/dist/diagram-TYUNFSNR.js +200 -0
  54. package/client/dist/diff.js +1 -0
  55. package/client/dist/dockerfile.js +1 -0
  56. package/client/dist/document-editor.js +1040 -0
  57. package/client/dist/dtd.js +1 -0
  58. package/client/dist/dylan.js +1 -0
  59. package/client/dist/ebnf.js +1 -0
  60. package/client/dist/ebnfDiagram-V4P3TTPT.js +1 -0
  61. package/client/dist/ecl.js +1 -0
  62. package/client/dist/eiffel.js +1 -0
  63. package/client/dist/elk-QONTBCTQ.js +27 -0
  64. package/client/dist/elm.js +1 -0
  65. package/client/dist/erDiagram-KYQIGQAA.js +99 -0
  66. package/client/dist/erlang.js +1 -0
  67. package/client/dist/factor.js +1 -0
  68. package/client/dist/favicon.ico +0 -0
  69. package/client/dist/favicon.png +0 -0
  70. package/client/dist/fcl.js +1 -0
  71. package/client/dist/file-panel.js +1 -0
  72. package/client/dist/flowDiagram-IUGLLWBU.js +213 -0
  73. package/client/dist/forth.js +1 -0
  74. package/client/dist/fortran.js +1 -0
  75. package/client/dist/ganttDiagram-R7GPNTJY.js +292 -0
  76. package/client/dist/gas.js +1 -0
  77. package/client/dist/gherkin.js +1 -0
  78. package/client/dist/gitGraphDiagram-PDYL7XHY.js +106 -0
  79. package/client/dist/graph.js +1 -0
  80. package/client/dist/groovy.js +1 -0
  81. package/client/dist/haskell.js +1 -0
  82. package/client/dist/haxe.js +1 -0
  83. package/client/dist/http.js +1 -0
  84. package/client/dist/idl.js +1 -0
  85. package/client/dist/index.html +25 -0
  86. package/client/dist/index.js +2 -0
  87. package/client/dist/index10.js +1 -0
  88. package/client/dist/index11.js +1 -0
  89. package/client/dist/index12.js +1 -0
  90. package/client/dist/index13.js +7 -0
  91. package/client/dist/index14.js +1 -0
  92. package/client/dist/index15.js +1 -0
  93. package/client/dist/index16.js +6 -0
  94. package/client/dist/index17.js +1 -0
  95. package/client/dist/index18.js +3 -0
  96. package/client/dist/index19.js +1 -0
  97. package/client/dist/index2.js +1 -0
  98. package/client/dist/index20.js +1 -0
  99. package/client/dist/index21.js +1 -0
  100. package/client/dist/index22.js +1 -0
  101. package/client/dist/index3.js +1 -0
  102. package/client/dist/index4.js +1 -0
  103. package/client/dist/index5.js +1 -0
  104. package/client/dist/index6.js +13 -0
  105. package/client/dist/index7.js +1 -0
  106. package/client/dist/index8.js +1 -0
  107. package/client/dist/index9.js +1 -0
  108. package/client/dist/infoDiagram-MVDRKAX5.js +2 -0
  109. package/client/dist/init.js +1 -0
  110. package/client/dist/isArrayLikeObject.js +1 -0
  111. package/client/dist/ishikawaDiagram-HPEHV2GE.js +70 -0
  112. package/client/dist/javascript.js +1 -0
  113. package/client/dist/journeyDiagram-BOSHW7O7.js +139 -0
  114. package/client/dist/julia.js +1 -0
  115. package/client/dist/kanban-definition-FNSA4HC5.js +89 -0
  116. package/client/dist/katex.js +257 -0
  117. package/client/dist/linear.js +1 -0
  118. package/client/dist/livescript.js +1 -0
  119. package/client/dist/lua.js +1 -0
  120. package/client/dist/mathematica.js +1 -0
  121. package/client/dist/mbox.js +1 -0
  122. package/client/dist/mermaid.core.js +310 -0
  123. package/client/dist/mindmap-definition-6OY57UG3.js +98 -0
  124. package/client/dist/mirc.js +1 -0
  125. package/client/dist/mllike.js +1 -0
  126. package/client/dist/modelica.js +1 -0
  127. package/client/dist/mscgen.js +1 -0
  128. package/client/dist/mumps.js +1 -0
  129. package/client/dist/nginx.js +1 -0
  130. package/client/dist/notification-worker.js +45 -0
  131. package/client/dist/nsis.js +1 -0
  132. package/client/dist/ntriples.js +1 -0
  133. package/client/dist/octave.js +1 -0
  134. package/client/dist/ordinal.js +1 -0
  135. package/client/dist/oz.js +1 -0
  136. package/client/dist/pascal.js +1 -0
  137. package/client/dist/pegDiagram-ECIUJNBX.js +1 -0
  138. package/client/dist/perl.js +1 -0
  139. package/client/dist/pieDiagram-GNMPY74T.js +39 -0
  140. package/client/dist/pig.js +1 -0
  141. package/client/dist/powershell.js +1 -0
  142. package/client/dist/properties.js +1 -0
  143. package/client/dist/protobuf.js +1 -0
  144. package/client/dist/pug.js +1 -0
  145. package/client/dist/puppet.js +1 -0
  146. package/client/dist/purify.es.js +3 -0
  147. package/client/dist/python.js +1 -0
  148. package/client/dist/q.js +1 -0
  149. package/client/dist/quadrantDiagram-D57K4MC3.js +7 -0
  150. package/client/dist/r.js +1 -0
  151. package/client/dist/railroadDiagram-Y72NRBL7.js +1 -0
  152. package/client/dist/requirementDiagram-EQYSW5RA.js +84 -0
  153. package/client/dist/rpm.js +1 -0
  154. package/client/dist/ruby.js +1 -0
  155. package/client/dist/sankeyDiagram-SY24JHO5.js +40 -0
  156. package/client/dist/sas.js +1 -0
  157. package/client/dist/scheme.js +1 -0
  158. package/client/dist/sequenceDiagram-BLEHNHQU.js +169 -0
  159. package/client/dist/shell.js +1 -0
  160. package/client/dist/sieve.js +1 -0
  161. package/client/dist/simple-mode.js +1 -0
  162. package/client/dist/sizeCapture-INFHLROL.js +1 -0
  163. package/client/dist/smalltalk.js +1 -0
  164. package/client/dist/solr.js +1 -0
  165. package/client/dist/sparql.js +1 -0
  166. package/client/dist/spreadsheet.js +1 -0
  167. package/client/dist/sql.js +1 -0
  168. package/client/dist/stateDiagram-v2-A6IESKWZ.js +291 -0
  169. package/client/dist/stex.js +1 -0
  170. package/client/dist/style.css +1 -0
  171. package/client/dist/stylus.js +1 -0
  172. package/client/dist/swift.js +1 -0
  173. package/client/dist/swimlanes-B3ENRKFQ.js +1 -0
  174. package/client/dist/swimlanesDiagram-AYQRV4AK.js +8 -0
  175. package/client/dist/tcl.js +1 -0
  176. package/client/dist/terminal-panel.js +18 -0
  177. package/client/dist/textile.js +1 -0
  178. package/client/dist/tiddlywiki.js +1 -0
  179. package/client/dist/tiki.js +1 -0
  180. package/client/dist/timeline-definition-JXYKGLGB.js +120 -0
  181. package/client/dist/toml.js +1 -0
  182. package/client/dist/troff.js +1 -0
  183. package/client/dist/ttcn-cfg.js +1 -0
  184. package/client/dist/ttcn.js +1 -0
  185. package/client/dist/turtle.js +1 -0
  186. package/client/dist/usecaseDiagram-WPOLBNNX.js +370 -0
  187. package/client/dist/vb.js +1 -0
  188. package/client/dist/vbscript.js +1 -0
  189. package/client/dist/velocity.js +1 -0
  190. package/client/dist/vennDiagram-Q3Y3IDCW.js +34 -0
  191. package/client/dist/verilog.js +1 -0
  192. package/client/dist/vhdl.js +1 -0
  193. package/client/dist/wardleyDiagram-IVAIDKWA.js +78 -0
  194. package/client/dist/webidl.js +1 -0
  195. package/client/dist/xquery.js +1 -0
  196. package/client/dist/xychartDiagram-4URNHDU4.js +7 -0
  197. package/client/dist/yacas.js +1 -0
  198. package/client/dist/z80.js +1 -0
  199. package/docs/architecture/backend-regressions.md +53 -0
  200. package/docs/architecture/backends.md +115 -0
  201. package/docs/architecture/behavior.md +228 -0
  202. package/docs/architecture.md +335 -0
  203. package/docs/background-tasks.md +39 -0
  204. package/docs/cli-command-coverage.md +60 -0
  205. package/docs/deployment.md +289 -0
  206. package/docs/development.md +396 -0
  207. package/docs/images/desktop-dark.png +0 -0
  208. package/docs/images/desktop-light.png +0 -0
  209. package/docs/images/mobile-sidebar.png +0 -0
  210. package/docs/images/mobile.png +0 -0
  211. package/docs/releases/v2.0.0.md +5 -0
  212. package/docs/releases/v2.1.0.md +6 -0
  213. package/docs/releases/v2.1.1.md +6 -0
  214. package/docs/releases/v2.1.2.md +8 -0
  215. package/docs/releases/v2.2.0.md +11 -0
  216. package/docs/releases/v2.3.0.md +12 -0
  217. package/docs/releases/v2.3.1.md +8 -0
  218. package/docs/releases/v2.4.0.md +8 -0
  219. package/docs/releases/v2.4.1.md +8 -0
  220. package/docs/releases/v2.4.2.md +8 -0
  221. package/docs/releases/v3.0.0.md +9 -0
  222. package/docs/releases/v3.1.0.md +10 -0
  223. package/docs/releases/v3.1.1.md +7 -0
  224. package/docs/releases/v4.0.0-beta.1.md +10 -0
  225. package/docs/releases/v4.0.0.md +20 -0
  226. package/docs/releases/v4.0.1.md +10 -0
  227. package/docs/releases/v4.1.0.md +21 -0
  228. package/docs/versioning.md +129 -0
  229. package/package.json +87 -4
  230. package/packages/translation-engine/LICENSE +674 -0
  231. package/packages/translation-engine/README.md +69 -0
  232. package/packages/translation-engine/bin/tokenizer-linux-x64 +0 -0
  233. package/packages/translation-engine/bin/translate.mjs +29 -0
  234. package/packages/translation-engine/native/build.mjs +15 -0
  235. package/packages/translation-engine/native/tokenizer.c +73 -0
  236. package/packages/translation-engine/package.json +29 -0
  237. package/packages/translation-engine/src/catalog.mjs +103 -0
  238. package/packages/translation-engine/src/cpu-runtime.mjs +90 -0
  239. package/packages/translation-engine/src/download.mjs +94 -0
  240. package/packages/translation-engine/src/index.mjs +70 -0
  241. package/packages/translation-engine/src/inference.mjs +177 -0
  242. package/packages/translation-engine/src/model-store.mjs +197 -0
  243. package/packages/translation-engine/src/tokenizer.mjs +77 -0
  244. package/packages/translation-engine/src/worker.mjs +83 -0
  245. package/scripts/install-services.mjs +135 -0
  246. package/scripts/restart-when-idle.mjs +125 -0
  247. package/scripts/start-backend.mjs +29 -0
  248. package/server/src/agent-messages.mjs +124 -0
  249. package/server/src/application.mjs +168 -0
  250. package/server/src/auth.mjs +328 -0
  251. package/server/src/backends/claude/account.mjs +171 -0
  252. package/server/src/backends/claude/adapter.mjs +366 -0
  253. package/server/src/backends/claude/agent-history.mjs +70 -0
  254. package/server/src/backends/claude/background-tasks.mjs +168 -0
  255. package/server/src/backends/claude/catalogue.mjs +268 -0
  256. package/server/src/backends/claude/execution-errors.mjs +44 -0
  257. package/server/src/backends/claude/execution-session.mjs +396 -0
  258. package/server/src/backends/claude/git-tool-changes.mjs +77 -0
  259. package/server/src/backends/claude/goals.mjs +319 -0
  260. package/server/src/backends/claude/history-actions.mjs +170 -0
  261. package/server/src/backends/claude/history.mjs +65 -0
  262. package/server/src/backends/claude/hooks.mjs +232 -0
  263. package/server/src/backends/claude/input-stream.mjs +24 -0
  264. package/server/src/backends/claude/messages-request.mjs +34 -0
  265. package/server/src/backends/claude/messages.mjs +301 -0
  266. package/server/src/backends/claude/model-options.mjs +18 -0
  267. package/server/src/backends/claude/native-commands.mjs +48 -0
  268. package/server/src/backends/claude/native-records.mjs +76 -0
  269. package/server/src/backends/claude/process-ownership.mjs +82 -0
  270. package/server/src/backends/claude/project-instructions.mjs +40 -0
  271. package/server/src/backends/claude/provider-balance.mjs +40 -0
  272. package/server/src/backends/claude/provider-environment.mjs +95 -0
  273. package/server/src/backends/claude/provider-transport.mjs +70 -0
  274. package/server/src/backends/claude/recovery.mjs +54 -0
  275. package/server/src/backends/claude/runtime.mjs +463 -0
  276. package/server/src/backends/claude/session-worker.mjs +32 -0
  277. package/server/src/backends/claude/sessions.mjs +348 -0
  278. package/server/src/backends/claude/token-usage.mjs +98 -0
  279. package/server/src/backends/claude/worker-client.mjs +351 -0
  280. package/server/src/backends/claude/worker-launcher.mjs +119 -0
  281. package/server/src/backends/claude/worker-location.mjs +43 -0
  282. package/server/src/backends/claude/worker-revision.mjs +45 -0
  283. package/server/src/backends/claude/worker-server.mjs +290 -0
  284. package/server/src/backends/cli-installation.mjs +140 -0
  285. package/server/src/backends/codex/adapter.mjs +155 -0
  286. package/server/src/backends/codex/compaction-recovery.mjs +78 -0
  287. package/server/src/backends/codex/events.mjs +125 -0
  288. package/server/src/backends/codex/methods.mjs +17 -0
  289. package/server/src/backends/codex/reference-mcp.mjs +97 -0
  290. package/server/src/backends/codex/reference-tools.mjs +71 -0
  291. package/server/src/backends/codex/requests.mjs +170 -0
  292. package/server/src/backends/codex/subscriptions.mjs +91 -0
  293. package/server/src/backends/codex/token-usage.mjs +140 -0
  294. package/server/src/backends/codex/upstream.mjs +148 -0
  295. package/server/src/backends/configuration.mjs +122 -0
  296. package/server/src/backends/identity-mapping.mjs +87 -0
  297. package/server/src/backends/manager.mjs +478 -0
  298. package/server/src/backends/network-proxy.mjs +55 -0
  299. package/server/src/backends/provider-presets.mjs +45 -0
  300. package/server/src/backends/providers.mjs +135 -0
  301. package/server/src/backends/storage.mjs +39 -0
  302. package/server/src/bridge/conversation-policy.mjs +29 -0
  303. package/server/src/bridge/file-operations.mjs +47 -0
  304. package/server/src/bridge/product-methods.mjs +66 -0
  305. package/server/src/compaction.mjs +82 -0
  306. package/server/src/config.mjs +64 -0
  307. package/server/src/file-content.mjs +99 -0
  308. package/server/src/file-undo.mjs +142 -0
  309. package/server/src/http/maintenance.mjs +28 -0
  310. package/server/src/http/router.mjs +98 -0
  311. package/server/src/http/static.mjs +62 -0
  312. package/server/src/product-config.mjs +80 -0
  313. package/server/src/project-models.mjs +59 -0
  314. package/server/src/rpc-transport.mjs +21 -0
  315. package/server/src/server.mjs +29 -0
  316. package/server/src/service-maintenance-worker.mjs +124 -0
  317. package/server/src/service-maintenance.mjs +222 -0
  318. package/server/src/summary-translation.mjs +71 -0
  319. package/server/src/system-auth.mjs +45 -0
  320. package/server/src/thread-folders.mjs +76 -0
  321. package/server/src/thread-names.mjs +264 -0
  322. package/server/src/thread-projects.mjs +36 -0
  323. package/server/src/tls.mjs +87 -0
  324. package/server/src/token-usage-reconciliation.mjs +105 -0
  325. package/server/src/token-usage.mjs +208 -0
  326. package/server/src/translation-service.mjs +133 -0
  327. package/server/src/version.mjs +55 -0
  328. package/server/src/web-config-migration.mjs +48 -0
  329. package/server/src/workspace/commands.mjs +33 -0
  330. package/server/src/workspace/files.mjs +44 -0
  331. package/server/src/workspace/service.mjs +27 -0
  332. package/server/src/workspace/terminals.mjs +122 -0
  333. package/shared/backend-activity.mjs +13 -0
  334. package/shared/backend-capabilities.mjs +33 -0
  335. package/shared/backend-identity.mjs +17 -0
  336. package/shared/compaction-state.mjs +49 -0
  337. package/shared/file-types.mjs +82 -0
  338. package/shared/product-contract.mjs +26 -0
  339. package/shared/rpc-limits.mjs +2 -0
  340. package/shared/terminal-workspace.mjs +26 -0
@@ -0,0 +1,232 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { snapshotToolWorkspace } from "./git-tool-changes.mjs";
5
+ import { readProjectInstructions } from "./project-instructions.mjs";
6
+
7
+ async function contents(path) {
8
+ try {
9
+ return await readFile(path, "utf8");
10
+ } catch (error) {
11
+ if (error.code === "ENOENT") return null;
12
+ throw error;
13
+ }
14
+ }
15
+ function patch(before, after) {
16
+ const lines = (text, prefix) => {
17
+ const rows = text.split("\n");
18
+ if (rows.at(-1) === "") rows.pop();
19
+ return (
20
+ rows.map((line) => prefix + line + "\n").join("") +
21
+ (text && !text.endsWith("\n") ? "\\n" : "")
22
+ );
23
+ };
24
+ const count = (text) =>
25
+ text ? text.split("\n").length - Number(text.endsWith("\n")) : 0;
26
+ return `--- a/file\n+++ b/file\n@@ -${before ? 1 : 0},${count(before)} +${after ? 1 : 0},${count(after)} @@\n${lines(before, "-")}${lines(after, "+")}`;
27
+ }
28
+ export function createRunHooks({
29
+ threadId,
30
+ context,
31
+ save,
32
+ broadcast,
33
+ questions,
34
+ goalBeforeTool,
35
+ onPromptFailure,
36
+ }) {
37
+ const snapshots = new Map();
38
+ async function record(item) {
39
+ const { turnId } = context();
40
+ await save(threadId, (s) => ({
41
+ ...s,
42
+ extraItems: { ...s.extraItems, [item.id]: item },
43
+ }));
44
+ broadcast({ method: "item/completed", params: { threadId, turnId, item } });
45
+ }
46
+ async function before(input, toolId, { signal }) {
47
+ const { turnId } = context();
48
+ if (input.tool_name === "Bash" && !context().readOnly) {
49
+ const workspace = await snapshotToolWorkspace(input.cwd);
50
+ if (workspace) snapshots.set(input.tool_use_id, { workspace });
51
+ }
52
+ if (input.tool_name === "Agent")
53
+ await save(threadId, (s) => ({
54
+ ...s,
55
+ agentCalls: {
56
+ ...s.agentCalls,
57
+ [input.tool_use_id]: {
58
+ toolUseId: input.tool_use_id,
59
+ initialTask: input.tool_input.prompt,
60
+ name: input.tool_input.name || input.tool_input.description,
61
+ agentType: input.tool_input.subagent_type,
62
+ },
63
+ },
64
+ }));
65
+ if (input.tool_name === "AskUserQuestion") {
66
+ const id = randomUUID(),
67
+ value = input.tool_input;
68
+ const question = {
69
+ id,
70
+ method: "item/tool/requestUserInput",
71
+ params: {
72
+ threadId,
73
+ turnId,
74
+ itemId: input.tool_use_id,
75
+ questions: value.questions.map((q, i) => ({
76
+ ...q,
77
+ id: String(i),
78
+ isOther: true,
79
+ isSecret: false,
80
+ })),
81
+ },
82
+ };
83
+ const answer = await new Promise((resolve) => {
84
+ const abort = () => {
85
+ questions.delete(id);
86
+ resolve({ behavior: "deny", message: "提问已取消" });
87
+ };
88
+ questions.set(id, {
89
+ threadId,
90
+ input: value,
91
+ question,
92
+ resolve: (result) => {
93
+ signal.removeEventListener("abort", abort);
94
+ resolve(result);
95
+ },
96
+ });
97
+ signal.addEventListener("abort", abort, { once: true });
98
+ if (signal.aborted) abort();
99
+ else broadcast(question);
100
+ });
101
+ return {
102
+ hookSpecificOutput: {
103
+ hookEventName: "PreToolUse",
104
+ permissionDecision: answer.behavior === "allow" ? "allow" : "deny",
105
+ updatedInput: answer.updatedInput,
106
+ permissionDecisionReason: answer.message,
107
+ },
108
+ };
109
+ }
110
+ const path = input.tool_input.file_path || input.tool_input.notebook_path;
111
+ if (path)
112
+ snapshots.set(input.tool_use_id, {
113
+ path: resolve(input.cwd, path),
114
+ before: await contents(resolve(input.cwd, path)),
115
+ });
116
+ return {};
117
+ }
118
+ async function after(input) {
119
+ const { turnId } = context();
120
+ const previous = snapshots.get(input.tool_use_id);
121
+ if (!previous) return {};
122
+ snapshots.delete(input.tool_use_id);
123
+ if (previous.workspace) {
124
+ try {
125
+ const changes = await previous.workspace.changes();
126
+ if (changes.length)
127
+ await record({
128
+ id: `file-${input.tool_use_id}`,
129
+ turnId,
130
+ type: "fileChange",
131
+ status: "completed",
132
+ changes,
133
+ });
134
+ } finally {
135
+ await previous.workspace.close();
136
+ }
137
+ return {};
138
+ }
139
+ const after = await contents(previous.path);
140
+ if (previous.before === after || after === null) return {};
141
+ await record({
142
+ id: `file-${input.tool_use_id}`,
143
+ turnId,
144
+ type: "fileChange",
145
+ status: "completed",
146
+ changes: [
147
+ {
148
+ path: previous.path,
149
+ kind: { type: previous.before === null ? "add" : "update" },
150
+ diff:
151
+ previous.before === null ? after : patch(previous.before, after),
152
+ },
153
+ ],
154
+ });
155
+ return {};
156
+ }
157
+ async function agent(input) {
158
+ const { turnId } = context();
159
+ const id = `agent/${threadId}/${input.agent_id}`;
160
+ let details;
161
+ await save(threadId, (s) => {
162
+ details = {
163
+ ...s.agents?.[id],
164
+ agentId: input.agent_id,
165
+ name: s.agents?.[id]?.name || input.agent_type,
166
+ agentType: input.agent_type,
167
+ parentNativeId: input.session_id,
168
+ };
169
+ return { ...s, agents: { ...s.agents, [id]: details } };
170
+ });
171
+ await record({
172
+ id: `agent-${input.agent_id}`,
173
+ turnId,
174
+ type: "subAgentActivity",
175
+ kind: input.hook_event_name === "SubagentStart" ? "started" : "completed",
176
+ agentThreadId: id,
177
+ agentPath: details.name,
178
+ prompt: details.initialTask,
179
+ });
180
+ return {};
181
+ }
182
+ async function instructions(input) {
183
+ try {
184
+ return {
185
+ hookSpecificOutput: {
186
+ hookEventName: "UserPromptSubmit",
187
+ additionalContext: await readProjectInstructions(input.cwd),
188
+ },
189
+ };
190
+ } catch (error) {
191
+ onPromptFailure(error);
192
+ throw error;
193
+ }
194
+ }
195
+ return {
196
+ UserPromptSubmit: [
197
+ {
198
+ onFailure: "block",
199
+ hooks: [instructions],
200
+ },
201
+ ],
202
+ PreToolUse: [
203
+ { hooks: [goalBeforeTool] },
204
+ {
205
+ matcher: "AskUserQuestion|Write|Edit|NotebookEdit|Agent|Bash",
206
+ hooks: [before],
207
+ timeout: 86400,
208
+ },
209
+ ],
210
+ PostToolUse: [{ matcher: "Write|Edit|NotebookEdit|Bash", hooks: [after] }],
211
+ PostToolUseFailure: [
212
+ { matcher: "Write|Edit|NotebookEdit|Bash", hooks: [after] },
213
+ ],
214
+ SubagentStart: [{ hooks: [agent] }],
215
+ SubagentStop: [{ hooks: [agent] }],
216
+ SessionEnd: [
217
+ {
218
+ hooks: [
219
+ async () => {
220
+ await Promise.all(
221
+ [...snapshots.values()].map((snapshot) =>
222
+ snapshot.workspace?.close(),
223
+ ),
224
+ );
225
+ snapshots.clear();
226
+ return {};
227
+ },
228
+ ],
229
+ },
230
+ ],
231
+ };
232
+ }
@@ -0,0 +1,24 @@
1
+ // CLI 会话持续持有输入流,轮次空闲时保持打开,直到显式关闭。
2
+ export function createInputStream() {
3
+ const pending = [];
4
+ let wake;
5
+ let closed = false;
6
+ return {
7
+ push(message) {
8
+ if (closed) throw new Error("Claude 会话已关闭");
9
+ pending.push(message);
10
+ wake?.();
11
+ },
12
+ close() {
13
+ closed = true;
14
+ wake?.();
15
+ },
16
+ async *[Symbol.asyncIterator]() {
17
+ while (!closed) {
18
+ if (!pending.length) await new Promise((resolve) => (wake = resolve));
19
+ wake = null;
20
+ while (pending.length) yield pending.shift();
21
+ }
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,34 @@
1
+ // 标准 Messages 端点通过顶层 system 接收系统上下文,指令优先级保持为系统级。
2
+ export function messagesRequest(value) {
3
+ if (!Array.isArray(value.messages)) return value;
4
+ const system =
5
+ typeof value.system === "string"
6
+ ? [{ type: "text", text: value.system }]
7
+ : [...(value.system || [])];
8
+ const messages = [];
9
+ for (const message of value.messages) {
10
+ if (message.role !== "system") {
11
+ messages.push(message);
12
+ continue;
13
+ }
14
+ const blocks =
15
+ typeof message.content === "string"
16
+ ? [{ type: "text", text: message.content }]
17
+ : message.content;
18
+ for (const block of blocks) {
19
+ if (block.type !== "text")
20
+ throw new Error(
21
+ `标准 Messages 系统上下文包含未适配的内容类型:${block.type}`,
22
+ );
23
+ system.push(block);
24
+ }
25
+ }
26
+ // Anthropic 省略 thinking 表示关闭;明确传递该语义,保留原生主请求的 adaptive。
27
+ const result = {
28
+ ...value,
29
+ messages,
30
+ ...(value.thinking === undefined && { thinking: { type: "disabled" } }),
31
+ ...(system.length && { system }),
32
+ };
33
+ return result;
34
+ }
@@ -0,0 +1,301 @@
1
+ import { executionError } from "./execution-errors.mjs";
2
+
3
+ function imageUrl(block) {
4
+ return block.source?.type === "base64"
5
+ ? `data:${block.source.media_type};base64,${block.source.data}`
6
+ : block.source?.url;
7
+ }
8
+
9
+ export function contentBlocks(message) {
10
+ const content = message.message?.content;
11
+ return typeof content === "string"
12
+ ? [{ type: "text", text: content }]
13
+ : content || [];
14
+ }
15
+ export function visibleSessionMessages(messages, internalInputIds = {}) {
16
+ const promptIds = new Set(
17
+ messages
18
+ .filter((message) => internalInputIds[message.uuid])
19
+ .map((message) => message.promptId)
20
+ .filter(Boolean),
21
+ );
22
+ return messages.filter(
23
+ (message) =>
24
+ !internalInputIds[message.uuid] &&
25
+ !promptIds.has(message.promptId) &&
26
+ !(
27
+ message.type === "system" &&
28
+ message.subtype === "local_command" &&
29
+ internalInputIds[message.parentUuid]
30
+ ),
31
+ );
32
+ }
33
+ export function convertMessage(
34
+ message,
35
+ turnId,
36
+ tools = new Map(),
37
+ mode = "default",
38
+ blockOffset = 0,
39
+ ) {
40
+ if (
41
+ message.isApiErrorMessage ||
42
+ message.isMeta ||
43
+ message.is_meta ||
44
+ message.isCompactSummary ||
45
+ message.isVisibleInTranscriptOnly ||
46
+ (message.type === "assistant" && message.error)
47
+ )
48
+ return [];
49
+ const blocks = contentBlocks(message),
50
+ items = [];
51
+ const messageId = message.message?.id || message.uuid;
52
+ if (message.type === "user") {
53
+ const content = blocks
54
+ .filter((b) => ["text", "image"].includes(b.type))
55
+ .map((b) =>
56
+ b.type === "text"
57
+ ? b
58
+ : {
59
+ type: "image",
60
+ url: imageUrl(b),
61
+ },
62
+ );
63
+ if (content.length && isUserPrompt(message))
64
+ items.push({ id: message.uuid, turnId, type: "userMessage", content });
65
+ for (const block of blocks.filter((b) => b.type === "tool_result")) {
66
+ const prior = tools.get(block.tool_use_id);
67
+ if (prior) {
68
+ const text =
69
+ typeof block.content === "string"
70
+ ? block.content
71
+ : JSON.stringify(block.content || []);
72
+ const item = {
73
+ ...prior,
74
+ status: block.is_error ? "failed" : "completed",
75
+ ...(prior.type === "commandExecution"
76
+ ? { aggregatedOutput: text, exitCode: block.is_error ? 1 : 0 }
77
+ : {
78
+ result: block.content,
79
+ contentItems:
80
+ typeof block.content === "string"
81
+ ? [{ type: "text", text: block.content }]
82
+ : (block.content || []).map((content) =>
83
+ content.type === "image"
84
+ ? { ...content, url: imageUrl(content) }
85
+ : content,
86
+ ),
87
+ error: block.is_error ? text : null,
88
+ }),
89
+ };
90
+ tools.set(item.id, item);
91
+ items.push(item);
92
+ }
93
+ }
94
+ return items;
95
+ }
96
+ if (message.type === "system" && message.subtype === "compact_boundary")
97
+ return [
98
+ {
99
+ id: message.uuid,
100
+ turnId,
101
+ type: "contextCompaction",
102
+ status: "completed",
103
+ },
104
+ ];
105
+ if (message.type !== "assistant") return items;
106
+ blocks.forEach((block, index) => {
107
+ const id = `${messageId}-${blockOffset + index}`;
108
+ if (block.type === "text")
109
+ items.push({
110
+ id,
111
+ turnId,
112
+ type:
113
+ mode === "plan" && message.message?.stop_reason === "end_turn"
114
+ ? "plan"
115
+ : "agentMessage",
116
+ text: block.text,
117
+ phase:
118
+ message.message?.stop_reason === "end_turn"
119
+ ? "final_answer"
120
+ : "commentary",
121
+ });
122
+ if (block.type === "thinking")
123
+ items.push({
124
+ id,
125
+ turnId,
126
+ type: "reasoning",
127
+ summary: [{ title: "思考", text: block.thinking }],
128
+ });
129
+ if (block.type === "redacted_thinking")
130
+ items.push({
131
+ id,
132
+ turnId,
133
+ type: "reasoning",
134
+ summary: [{ title: "思考", text: "思考内容已加密" }],
135
+ });
136
+ if (block.type === "tool_use") {
137
+ const item =
138
+ block.name === "Bash"
139
+ ? {
140
+ id: block.id,
141
+ turnId,
142
+ type: "commandExecution",
143
+ command: block.input.command,
144
+ cwd: "",
145
+ status: "inProgress",
146
+ aggregatedOutput: "",
147
+ }
148
+ : {
149
+ id: block.id,
150
+ turnId,
151
+ type: "dynamicToolCall",
152
+ tool: block.name,
153
+ arguments: block.input,
154
+ status: "inProgress",
155
+ contentItems: [],
156
+ };
157
+ tools.set(block.id, item);
158
+ items.push(item);
159
+ }
160
+ });
161
+ return items;
162
+ }
163
+ export function isUserPrompt(message) {
164
+ return (
165
+ message.type === "user" &&
166
+ !message.isMeta &&
167
+ !message.is_meta &&
168
+ !message.isCompactSummary &&
169
+ !message.isVisibleInTranscriptOnly &&
170
+ !message.isSynthetic &&
171
+ message.origin?.kind !== "task-notification" &&
172
+ // SDK 主对话附加记录仅继承入口;原生子代理任务由侧链及代理标识确认来源。
173
+ !(
174
+ message.entrypoint === "sdk-ts" &&
175
+ !(message.isSidechain === true && message.agentId) &&
176
+ message.promptId &&
177
+ !message.promptSource &&
178
+ !message.turnOrigin &&
179
+ !message.turnPosition &&
180
+ !message.origin
181
+ ) &&
182
+ contentBlocks(message).some((block) =>
183
+ ["text", "image"].includes(block.type),
184
+ )
185
+ );
186
+ }
187
+ export function historyTurns(
188
+ messages,
189
+ savedTurns = {},
190
+ turnIds = {},
191
+ inputTurns = {},
192
+ ) {
193
+ const turns = [],
194
+ tools = new Map(),
195
+ blockOffsets = new Map();
196
+ const anchors = new Map(
197
+ Object.values(savedTurns).flatMap((saved) =>
198
+ [saved.nativeAnchorId, ...(saved.nativeMessageIds || [])]
199
+ .filter(Boolean)
200
+ .map((id) => [id, saved.id]),
201
+ ),
202
+ );
203
+ let turn;
204
+ for (const message of messages) {
205
+ const anchorId = anchors.get(message.uuid);
206
+ if (isUserPrompt(message) || anchorId) {
207
+ const id =
208
+ anchorId ||
209
+ turnIds[message.uuid] ||
210
+ inputTurns[message.uuid] ||
211
+ message.uuid;
212
+ turn = turns.find((existing) => existing.id === id);
213
+ if (!turn) {
214
+ turn = {
215
+ id,
216
+ status: "completed",
217
+ startedAt: message.timestamp
218
+ ? Date.parse(message.timestamp) / 1000
219
+ : undefined,
220
+ ...savedTurns[id],
221
+ items: [],
222
+ };
223
+ turns.push(turn);
224
+ }
225
+ }
226
+ if (!turn) continue;
227
+ if (
228
+ message.isApiErrorMessage ||
229
+ (message.type === "assistant" && message.error)
230
+ ) {
231
+ turn.status = "failed";
232
+ turn.error = executionError({
233
+ message: contentBlocks(message)
234
+ .filter((b) => b.type === "text")
235
+ .map((b) => b.text)
236
+ .join("\n"),
237
+ });
238
+ }
239
+ if (
240
+ message.type === "assistant" &&
241
+ !message.isApiErrorMessage &&
242
+ !message.error &&
243
+ message.message?.stop_reason === "end_turn" &&
244
+ savedTurns[turn.id]?.status !== "failed"
245
+ ) {
246
+ turn.status = savedTurns[turn.id]?.status || "completed";
247
+ delete turn.error;
248
+ }
249
+ const converted = convertMessage(
250
+ message,
251
+ turn.id,
252
+ tools,
253
+ turn.mode,
254
+ blockOffsets.get(message.message?.id || message.uuid) || 0,
255
+ );
256
+ if (
257
+ (converted.length || message.isApiErrorMessage || message.error) &&
258
+ message.timestamp &&
259
+ ["completed", "failed", "interrupted"].includes(turn.status) &&
260
+ !Number.isFinite(savedTurns[turn.id]?.completedAt)
261
+ )
262
+ turn.completedAt = Date.parse(message.timestamp) / 1000;
263
+ const messageId = message.message?.id || message.uuid;
264
+ const blockOffset = blockOffsets.get(messageId) || 0;
265
+ if (message.type === "assistant")
266
+ blockOffsets.set(messageId, blockOffset + contentBlocks(message).length);
267
+ for (const item of converted) {
268
+ if (["agentMessage", "plan"].includes(item.type)) {
269
+ const saved = savedTurns[turn.id]?.items?.find(
270
+ (entry) => entry.id === item.id,
271
+ );
272
+ if (saved && ["agentMessage", "plan"].includes(saved.type)) {
273
+ item.type = saved.type;
274
+ item.phase = saved.phase;
275
+ }
276
+ }
277
+ if (item.type === "userMessage" && turnIds[item.id])
278
+ item.id = turnIds[item.id];
279
+ const existing = turn.items.findIndex((i) => i.id === item.id);
280
+ if (existing >= 0) turn.items[existing] = item;
281
+ else turn.items.push(item);
282
+ }
283
+ }
284
+ return turns;
285
+ }
286
+ export function inputMessage(input) {
287
+ return input.map((part) => {
288
+ if (part.type === "text") return { type: "text", text: part.text };
289
+ if (part.type === "image") {
290
+ const match = /^data:([^;]+);base64,(.+)$/s.exec(part.url);
291
+ if (!match) throw new Error("Claude 图片需要内嵌图片数据");
292
+ return {
293
+ type: "image",
294
+ source: { type: "base64", media_type: match[1], data: match[2] },
295
+ };
296
+ }
297
+ if (part.type === "skill")
298
+ throw new Error("请移除旧技能附件,并从技能菜单重新选择原生命令。");
299
+ throw new Error(`Claude 暂不支持此附件类型:${part.type}`);
300
+ });
301
+ }
@@ -0,0 +1,18 @@
1
+ export function modelOptions(provider, model, input) {
2
+ const standard = provider && (provider.protocol || "messages") === "messages";
3
+ const capabilities = provider?.modelCapabilities?.[model] || {};
4
+ const effort = input.effort || undefined;
5
+ const fastMode = ["fast", "priority"].includes(input.serviceTier);
6
+ if (
7
+ standard &&
8
+ effort &&
9
+ !capabilities.supportedEffortLevels?.includes(effort)
10
+ )
11
+ throw new Error("所选模型尚未配置此思考强度,请检查模型参数。");
12
+ if (standard && fastMode && !capabilities.supportsFastMode)
13
+ throw new Error("所选模型尚未配置快速模式,请检查模型参数。");
14
+ return {
15
+ ...(effort && { effort }),
16
+ settings: { fastMode },
17
+ };
18
+ }
@@ -0,0 +1,48 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ // 原生本地命令共用输入流,按独立 UUID 结算;命令确认与用户轮次、模型输入分别处理。
4
+ export function createNativeCommands(input, sessionId, record) {
5
+ const pending = new Map();
6
+ return {
7
+ get busy() {
8
+ return pending.size > 0;
9
+ },
10
+ async run(text) {
11
+ const uuid = randomUUID();
12
+ await record(uuid);
13
+ return new Promise((resolve, reject) => {
14
+ pending.set(uuid, { resolve, reject });
15
+ input.push({
16
+ type: "user",
17
+ uuid,
18
+ session_id: sessionId,
19
+ parent_tool_use_id: null,
20
+ isSynthetic: true,
21
+ message: { role: "user", content: text },
22
+ });
23
+ });
24
+ },
25
+ accept(message) {
26
+ if (message.type === "result") {
27
+ const ids = message.user_message_uuids || [message.user_message_uuid];
28
+ const matches = ids.filter((id) => pending.has(id));
29
+ if (!matches.length) return false;
30
+ for (const id of matches) {
31
+ const request = pending.get(id);
32
+ pending.delete(id);
33
+ if (message.is_error || message.subtype !== "success")
34
+ request.reject(
35
+ new Error(message.result || message.errors?.join("\n")),
36
+ );
37
+ else request.resolve(message);
38
+ }
39
+ return true;
40
+ }
41
+ return message.type === "user" && pending.has(message.uuid);
42
+ },
43
+ close(error) {
44
+ for (const request of pending.values()) request.reject(error);
45
+ pending.clear();
46
+ },
47
+ };
48
+ }