@waq666/pneuma 0.0.0-stage → 0.7.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 (687) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -2
  3. package/bin/dsc.js +91 -0
  4. package/bin/headless.cjs +40 -0
  5. package/lib/adapter/core-runtime.d.ts +11 -0
  6. package/lib/adapter/core-runtime.js +259 -0
  7. package/lib/adapter/host.d.ts +18 -0
  8. package/lib/adapter/host.js +14 -0
  9. package/lib/adapter/runtime.d.ts +15 -0
  10. package/lib/adapter/runtime.js +290 -0
  11. package/lib/adapter/transcript.d.ts +184 -0
  12. package/lib/adapter/transcript.js +605 -0
  13. package/lib/app/AgentsOverlay.d.ts +18 -0
  14. package/lib/app/AgentsOverlay.js +63 -0
  15. package/lib/app/App.d.ts +13 -0
  16. package/lib/app/App.js +1498 -0
  17. package/lib/app/ApprovalCard.d.ts +12 -0
  18. package/lib/app/ApprovalCard.js +76 -0
  19. package/lib/app/AskCard.d.ts +20 -0
  20. package/lib/app/AskCard.js +45 -0
  21. package/lib/app/ChatView.d.ts +32 -0
  22. package/lib/app/ChatView.js +198 -0
  23. package/lib/app/Composer.d.ts +50 -0
  24. package/lib/app/Composer.js +282 -0
  25. package/lib/app/DiffBlock.d.ts +6 -0
  26. package/lib/app/DiffBlock.js +37 -0
  27. package/lib/app/MarkdownView.d.ts +6 -0
  28. package/lib/app/MarkdownView.js +99 -0
  29. package/lib/app/ModelPicker.d.ts +7 -0
  30. package/lib/app/ModelPicker.js +18 -0
  31. package/lib/app/PlanReviewCard.d.ts +13 -0
  32. package/lib/app/PlanReviewCard.js +54 -0
  33. package/lib/app/PresetPicker.d.ts +11 -0
  34. package/lib/app/PresetPicker.js +19 -0
  35. package/lib/app/PreviewOverlay.d.ts +14 -0
  36. package/lib/app/PreviewOverlay.js +22 -0
  37. package/lib/app/SessionPicker.d.ts +43 -0
  38. package/lib/app/SessionPicker.js +56 -0
  39. package/lib/app/SettingsOverlay.d.ts +32 -0
  40. package/lib/app/SettingsOverlay.js +157 -0
  41. package/lib/app/SkillsPicker.d.ts +7 -0
  42. package/lib/app/SkillsPicker.js +19 -0
  43. package/lib/app/StatusBar.d.ts +22 -0
  44. package/lib/app/StatusBar.js +272 -0
  45. package/lib/app/TaskStrips.d.ts +13 -0
  46. package/lib/app/TaskStrips.js +40 -0
  47. package/lib/app/ToolCard.d.ts +5 -0
  48. package/lib/app/ToolCard.js +40 -0
  49. package/lib/app/TranscriptOverlay.d.ts +12 -0
  50. package/lib/app/TranscriptOverlay.js +17 -0
  51. package/lib/app/Welcome.d.ts +6 -0
  52. package/lib/app/Welcome.js +66 -0
  53. package/lib/app/attach.d.ts +16 -0
  54. package/lib/app/attach.js +58 -0
  55. package/lib/app/click.d.ts +27 -0
  56. package/lib/app/click.js +89 -0
  57. package/lib/app/clipboard-image.d.ts +11 -0
  58. package/lib/app/clipboard-image.js +66 -0
  59. package/lib/app/cursor.d.ts +4 -0
  60. package/lib/app/cursor.js +24 -0
  61. package/lib/app/hello.d.ts +11 -0
  62. package/lib/app/hello.js +8 -0
  63. package/lib/app/history-store.d.ts +4 -0
  64. package/lib/app/history-store.js +41 -0
  65. package/lib/app/image-blocks.d.ts +12 -0
  66. package/lib/app/image-blocks.js +125 -0
  67. package/lib/app/markdown.d.ts +54 -0
  68. package/lib/app/markdown.js +189 -0
  69. package/lib/app/settings-model.d.ts +69 -0
  70. package/lib/app/settings-model.js +114 -0
  71. package/lib/app/theme.d.ts +166 -0
  72. package/lib/app/theme.js +141 -0
  73. package/lib/boot.d.ts +1 -0
  74. package/lib/boot.js +34 -0
  75. package/lib/commands.d.ts +49 -0
  76. package/lib/commands.js +115 -0
  77. package/lib/contract.d.ts +1973 -0
  78. package/lib/contract.js +36 -0
  79. package/lib/core/agent-roles.d.ts +52 -0
  80. package/lib/core/agent-roles.js +274 -0
  81. package/lib/core/approval-floor.d.ts +183 -0
  82. package/lib/core/approval-floor.js +679 -0
  83. package/lib/core/approval.d.ts +42 -0
  84. package/lib/core/approval.js +8 -0
  85. package/lib/core/audit.d.ts +61 -0
  86. package/lib/core/audit.js +59 -0
  87. package/lib/core/boot-notices.d.ts +6 -0
  88. package/lib/core/boot-notices.js +61 -0
  89. package/lib/core/cdp/actions.d.ts +182 -0
  90. package/lib/core/cdp/actions.js +649 -0
  91. package/lib/core/cdp/launch.d.ts +192 -0
  92. package/lib/core/cdp/launch.js +491 -0
  93. package/lib/core/cdp/snapshot.d.ts +139 -0
  94. package/lib/core/cdp/snapshot.js +316 -0
  95. package/lib/core/cdp/transport.d.ts +160 -0
  96. package/lib/core/cdp/transport.js +359 -0
  97. package/lib/core/command-policy.d.ts +108 -0
  98. package/lib/core/command-policy.js +580 -0
  99. package/lib/core/commands-completion.d.ts +78 -0
  100. package/lib/core/commands-completion.js +167 -0
  101. package/lib/core/compact-anchors.d.ts +76 -0
  102. package/lib/core/compact-anchors.js +284 -0
  103. package/lib/core/compact.d.ts +110 -0
  104. package/lib/core/compact.js +210 -0
  105. package/lib/core/config-store.d.ts +38 -0
  106. package/lib/core/config-store.js +307 -0
  107. package/lib/core/config.d.ts +36 -0
  108. package/lib/core/config.js +124 -0
  109. package/lib/core/connection-test.d.ts +60 -0
  110. package/lib/core/connection-test.js +84 -0
  111. package/lib/core/desktop-control.d.ts +298 -0
  112. package/lib/core/desktop-control.js +1311 -0
  113. package/lib/core/diff-text.d.ts +74 -0
  114. package/lib/core/diff-text.js +257 -0
  115. package/lib/core/dock-browser.d.ts +137 -0
  116. package/lib/core/dock-browser.js +146 -0
  117. package/lib/core/dock-ops.d.ts +59 -0
  118. package/lib/core/dock-ops.js +104 -0
  119. package/lib/core/dock-session.d.ts +39 -0
  120. package/lib/core/dock-session.js +28 -0
  121. package/lib/core/dsh-compat/hook.d.ts +18 -0
  122. package/lib/core/dsh-compat/hook.js +52 -0
  123. package/lib/core/dsh-compat/resolve-hook.d.ts +5 -0
  124. package/lib/core/dsh-compat/resolve-hook.js +59 -0
  125. package/lib/core/dsh-compat/tools-facade.d.ts +47 -0
  126. package/lib/core/dsh-compat/tools-facade.js +108 -0
  127. package/lib/core/err-text.d.ts +13 -0
  128. package/lib/core/err-text.js +15 -0
  129. package/lib/core/events.d.ts +149 -0
  130. package/lib/core/events.js +1 -0
  131. package/lib/core/git-exec.d.ts +23 -0
  132. package/lib/core/git-exec.js +72 -0
  133. package/lib/core/git-info.d.ts +47 -0
  134. package/lib/core/git-info.js +157 -0
  135. package/lib/core/goal.d.ts +89 -0
  136. package/lib/core/goal.js +189 -0
  137. package/lib/core/hooks.d.ts +272 -0
  138. package/lib/core/hooks.js +818 -0
  139. package/lib/core/host-browser-link.d.ts +59 -0
  140. package/lib/core/host-browser-link.js +9 -0
  141. package/lib/core/host-methods.d.ts +25 -0
  142. package/lib/core/host-methods.js +103 -0
  143. package/lib/core/image-diet.d.ts +77 -0
  144. package/lib/core/image-diet.js +127 -0
  145. package/lib/core/learnings/ledger.d.ts +73 -0
  146. package/lib/core/learnings/ledger.js +273 -0
  147. package/lib/core/learnings/skill-write.d.ts +250 -0
  148. package/lib/core/learnings/skill-write.js +854 -0
  149. package/lib/core/learnings/store.d.ts +102 -0
  150. package/lib/core/learnings/store.js +266 -0
  151. package/lib/core/lifecycle-hooks.d.ts +189 -0
  152. package/lib/core/lifecycle-hooks.js +576 -0
  153. package/lib/core/llm.d.ts +272 -0
  154. package/lib/core/llm.js +548 -0
  155. package/lib/core/lockfile.d.ts +17 -0
  156. package/lib/core/lockfile.js +110 -0
  157. package/lib/core/loop.d.ts +185 -0
  158. package/lib/core/loop.js +587 -0
  159. package/lib/core/lsp/client.d.ts +189 -0
  160. package/lib/core/lsp/client.js +690 -0
  161. package/lib/core/lsp/framing.d.ts +84 -0
  162. package/lib/core/lsp/framing.js +181 -0
  163. package/lib/core/lsp/line-shift.d.ts +28 -0
  164. package/lib/core/lsp/line-shift.js +127 -0
  165. package/lib/core/lsp/manager.d.ts +93 -0
  166. package/lib/core/lsp/manager.js +418 -0
  167. package/lib/core/lsp/normalize.d.ts +32 -0
  168. package/lib/core/lsp/normalize.js +139 -0
  169. package/lib/core/lsp/servers.d.ts +106 -0
  170. package/lib/core/lsp/servers.js +352 -0
  171. package/lib/core/lsp/uri.d.ts +76 -0
  172. package/lib/core/lsp/uri.js +179 -0
  173. package/lib/core/market.d.ts +51 -0
  174. package/lib/core/market.js +358 -0
  175. package/lib/core/mcp.d.ts +201 -0
  176. package/lib/core/mcp.js +836 -0
  177. package/lib/core/memory-eval.d.ts +158 -0
  178. package/lib/core/memory-eval.js +215 -0
  179. package/lib/core/memory.d.ts +266 -0
  180. package/lib/core/memory.js +703 -0
  181. package/lib/core/mention.d.ts +57 -0
  182. package/lib/core/mention.js +129 -0
  183. package/lib/core/microcompact.d.ts +48 -0
  184. package/lib/core/microcompact.js +79 -0
  185. package/lib/core/migrate.d.ts +56 -0
  186. package/lib/core/migrate.js +134 -0
  187. package/lib/core/model-caps.d.ts +83 -0
  188. package/lib/core/model-caps.js +150 -0
  189. package/lib/core/model-discovery.d.ts +19 -0
  190. package/lib/core/model-discovery.js +69 -0
  191. package/lib/core/modes.d.ts +72 -0
  192. package/lib/core/modes.js +152 -0
  193. package/lib/core/native-bridge.d.ts +135 -0
  194. package/lib/core/native-bridge.js +563 -0
  195. package/lib/core/path-policy.d.ts +32 -0
  196. package/lib/core/path-policy.js +248 -0
  197. package/lib/core/permission-presets.d.ts +67 -0
  198. package/lib/core/permission-presets.js +75 -0
  199. package/lib/core/plugin-loader.d.ts +36 -0
  200. package/lib/core/plugin-loader.js +294 -0
  201. package/lib/core/plugin-registry.d.ts +113 -0
  202. package/lib/core/plugin-registry.js +256 -0
  203. package/lib/core/prefs.d.ts +82 -0
  204. package/lib/core/prefs.js +372 -0
  205. package/lib/core/presets.d.ts +80 -0
  206. package/lib/core/presets.js +373 -0
  207. package/lib/core/pricing.d.ts +90 -0
  208. package/lib/core/pricing.js +126 -0
  209. package/lib/core/prompt.d.ts +92 -0
  210. package/lib/core/prompt.js +339 -0
  211. package/lib/core/ptc.d.ts +66 -0
  212. package/lib/core/ptc.js +70 -0
  213. package/lib/core/remote/frames.d.ts +91 -0
  214. package/lib/core/remote/frames.js +174 -0
  215. package/lib/core/remote/notify.d.ts +54 -0
  216. package/lib/core/remote/notify.js +77 -0
  217. package/lib/core/remote/owner.d.ts +32 -0
  218. package/lib/core/remote/owner.js +75 -0
  219. package/lib/core/remote/pairing.d.ts +104 -0
  220. package/lib/core/remote/pairing.js +261 -0
  221. package/lib/core/remote/push.d.ts +80 -0
  222. package/lib/core/remote/push.js +222 -0
  223. package/lib/core/remote/store.d.ts +18 -0
  224. package/lib/core/remote/store.js +59 -0
  225. package/lib/core/remote/tickets.d.ts +20 -0
  226. package/lib/core/remote/tickets.js +49 -0
  227. package/lib/core/remote/uploads.d.ts +63 -0
  228. package/lib/core/remote/uploads.js +161 -0
  229. package/lib/core/request-attribution.d.ts +26 -0
  230. package/lib/core/request-attribution.js +86 -0
  231. package/lib/core/request-invariant.d.ts +61 -0
  232. package/lib/core/request-invariant.js +199 -0
  233. package/lib/core/sandbox/backends.d.ts +64 -0
  234. package/lib/core/sandbox/backends.js +194 -0
  235. package/lib/core/sandbox/execpolicy.d.ts +93 -0
  236. package/lib/core/sandbox/execpolicy.js +452 -0
  237. package/lib/core/sandbox/net-proxy.d.ts +31 -0
  238. package/lib/core/sandbox/net-proxy.js +162 -0
  239. package/lib/core/sandbox/policy.d.ts +211 -0
  240. package/lib/core/sandbox/policy.js +559 -0
  241. package/lib/core/sandbox/win/abi.d.ts +161 -0
  242. package/lib/core/sandbox/win/abi.js +169 -0
  243. package/lib/core/sandbox/win/account.d.ts +71 -0
  244. package/lib/core/sandbox/win/account.js +206 -0
  245. package/lib/core/sandbox/win/acl.d.ts +54 -0
  246. package/lib/core/sandbox/win/acl.js +339 -0
  247. package/lib/core/sandbox/win/backend.d.ts +61 -0
  248. package/lib/core/sandbox/win/backend.js +249 -0
  249. package/lib/core/sandbox/win/doctor.d.ts +24 -0
  250. package/lib/core/sandbox/win/doctor.js +272 -0
  251. package/lib/core/sandbox/win/ffi.d.ts +107 -0
  252. package/lib/core/sandbox/win/ffi.js +166 -0
  253. package/lib/core/sandbox/win/net-abi.d.ts +154 -0
  254. package/lib/core/sandbox/win/net-abi.js +316 -0
  255. package/lib/core/sandbox/win/runner-entry.d.ts +35 -0
  256. package/lib/core/sandbox/win/runner-entry.js +391 -0
  257. package/lib/core/sandbox/win/setup.d.ts +60 -0
  258. package/lib/core/sandbox/win/setup.js +986 -0
  259. package/lib/core/sandbox/win/token.d.ts +35 -0
  260. package/lib/core/sandbox/win/token.js +238 -0
  261. package/lib/core/sandbox/win/wfp.d.ts +41 -0
  262. package/lib/core/sandbox/win/wfp.js +200 -0
  263. package/lib/core/sandbox/win/workspace-sid.d.ts +9 -0
  264. package/lib/core/sandbox/win/workspace-sid.js +45 -0
  265. package/lib/core/schedule/rule.d.ts +184 -0
  266. package/lib/core/schedule/rule.js +745 -0
  267. package/lib/core/schedule/runner.d.ts +185 -0
  268. package/lib/core/schedule/runner.js +678 -0
  269. package/lib/core/schedule/store.d.ts +182 -0
  270. package/lib/core/schedule/store.js +455 -0
  271. package/lib/core/secrets.d.ts +41 -0
  272. package/lib/core/secrets.js +150 -0
  273. package/lib/core/session-export.d.ts +18 -0
  274. package/lib/core/session-export.js +73 -0
  275. package/lib/core/session-index.d.ts +159 -0
  276. package/lib/core/session-index.js +683 -0
  277. package/lib/core/session-meta.d.ts +41 -0
  278. package/lib/core/session-meta.js +97 -0
  279. package/lib/core/session.d.ts +356 -0
  280. package/lib/core/session.js +998 -0
  281. package/lib/core/skills.d.ts +60 -0
  282. package/lib/core/skills.js +171 -0
  283. package/lib/core/spill.d.ts +159 -0
  284. package/lib/core/spill.js +329 -0
  285. package/lib/core/surface-registry.d.ts +45 -0
  286. package/lib/core/surface-registry.js +67 -0
  287. package/lib/core/team-board.d.ts +95 -0
  288. package/lib/core/team-board.js +316 -0
  289. package/lib/core/throughput.d.ts +46 -0
  290. package/lib/core/throughput.js +40 -0
  291. package/lib/core/todo-reminder.d.ts +44 -0
  292. package/lib/core/todo-reminder.js +55 -0
  293. package/lib/core/todo.d.ts +81 -0
  294. package/lib/core/todo.js +222 -0
  295. package/lib/core/token-estimate.d.ts +55 -0
  296. package/lib/core/token-estimate.js +82 -0
  297. package/lib/core/tool-guards.d.ts +103 -0
  298. package/lib/core/tool-guards.js +77 -0
  299. package/lib/core/tool-search.d.ts +152 -0
  300. package/lib/core/tool-search.js +311 -0
  301. package/lib/core/tools/bash.d.ts +281 -0
  302. package/lib/core/tools/bash.js +871 -0
  303. package/lib/core/tools/command-runner.d.ts +84 -0
  304. package/lib/core/tools/command-runner.js +68 -0
  305. package/lib/core/tools/fs-tools.d.ts +23 -0
  306. package/lib/core/tools/fs-tools.js +247 -0
  307. package/lib/core/tools/index.d.ts +8 -0
  308. package/lib/core/tools/index.js +4 -0
  309. package/lib/core/tools/sandbox-args.d.ts +51 -0
  310. package/lib/core/tools/sandbox-args.js +90 -0
  311. package/lib/core/tools/search-tools.d.ts +3 -0
  312. package/lib/core/tools/search-tools.js +153 -0
  313. package/lib/core/tools.d.ts +96 -0
  314. package/lib/core/tools.js +53 -0
  315. package/lib/core/ui-boot-source.d.ts +71 -0
  316. package/lib/core/ui-boot-source.js +121 -0
  317. package/lib/core/ui-bundles.d.ts +249 -0
  318. package/lib/core/ui-bundles.js +830 -0
  319. package/lib/core/ui-combo.d.ts +49 -0
  320. package/lib/core/ui-combo.js +55 -0
  321. package/lib/core/ui-events.d.ts +81 -0
  322. package/lib/core/ui-events.js +364 -0
  323. package/lib/core/ui-hmr.d.ts +36 -0
  324. package/lib/core/ui-hmr.js +128 -0
  325. package/lib/core/ui-methods.d.ts +69 -0
  326. package/lib/core/ui-methods.js +341 -0
  327. package/lib/core/ui-route.d.ts +69 -0
  328. package/lib/core/ui-route.js +122 -0
  329. package/lib/core/ui-server.d.ts +75 -0
  330. package/lib/core/ui-server.js +369 -0
  331. package/lib/core/ui-trust.d.ts +47 -0
  332. package/lib/core/ui-trust.js +164 -0
  333. package/lib/core/untrusted.d.ts +30 -0
  334. package/lib/core/untrusted.js +48 -0
  335. package/lib/core/update-check.d.ts +81 -0
  336. package/lib/core/update-check.js +177 -0
  337. package/lib/core/usage-log.d.ts +82 -0
  338. package/lib/core/usage-log.js +306 -0
  339. package/lib/core/version.d.ts +1 -0
  340. package/lib/core/version.js +37 -0
  341. package/lib/core/web-http.d.ts +57 -0
  342. package/lib/core/web-http.js +137 -0
  343. package/lib/core/web-static.d.ts +31 -0
  344. package/lib/core/web-static.js +75 -0
  345. package/lib/headless.d.ts +1 -0
  346. package/lib/headless.js +31 -0
  347. package/lib/host/kernel.d.ts +33 -0
  348. package/lib/host/kernel.js +451 -0
  349. package/lib/index.d.ts +41 -0
  350. package/lib/index.js +35 -0
  351. package/lib/plugins/agent.d.ts +2 -0
  352. package/lib/plugins/agent.js +274 -0
  353. package/lib/plugins/approval-floor.d.ts +2 -0
  354. package/lib/plugins/approval-floor.js +223 -0
  355. package/lib/plugins/approval.d.ts +16 -0
  356. package/lib/plugins/approval.js +674 -0
  357. package/lib/plugins/ask.d.ts +2 -0
  358. package/lib/plugins/ask.js +245 -0
  359. package/lib/plugins/browser.d.ts +68 -0
  360. package/lib/plugins/browser.js +1341 -0
  361. package/lib/plugins/commands.d.ts +23 -0
  362. package/lib/plugins/commands.js +498 -0
  363. package/lib/plugins/compact.d.ts +21 -0
  364. package/lib/plugins/compact.js +274 -0
  365. package/lib/plugins/computer-use.d.ts +47 -0
  366. package/lib/plugins/computer-use.js +539 -0
  367. package/lib/plugins/desktop-dock.d.ts +2 -0
  368. package/lib/plugins/desktop-dock.js +626 -0
  369. package/lib/plugins/dock-browser.d.ts +34 -0
  370. package/lib/plugins/dock-browser.js +765 -0
  371. package/lib/plugins/dsh-compat.d.ts +25 -0
  372. package/lib/plugins/dsh-compat.js +37 -0
  373. package/lib/plugins/file-review.d.ts +108 -0
  374. package/lib/plugins/file-review.js +393 -0
  375. package/lib/plugins/git.d.ts +26 -0
  376. package/lib/plugins/git.js +132 -0
  377. package/lib/plugins/goal.d.ts +20 -0
  378. package/lib/plugins/goal.js +245 -0
  379. package/lib/plugins/guards.d.ts +14 -0
  380. package/lib/plugins/guards.js +18 -0
  381. package/lib/plugins/hooks.d.ts +19 -0
  382. package/lib/plugins/hooks.js +583 -0
  383. package/lib/plugins/host-stdio.d.ts +88 -0
  384. package/lib/plugins/host-stdio.js +317 -0
  385. package/lib/plugins/image-diet.d.ts +17 -0
  386. package/lib/plugins/image-diet.js +85 -0
  387. package/lib/plugins/lifecycle-hooks.d.ts +26 -0
  388. package/lib/plugins/lifecycle-hooks.js +338 -0
  389. package/lib/plugins/llm.d.ts +13 -0
  390. package/lib/plugins/llm.js +215 -0
  391. package/lib/plugins/lsp.d.ts +54 -0
  392. package/lib/plugins/lsp.js +608 -0
  393. package/lib/plugins/mcp.d.ts +16 -0
  394. package/lib/plugins/mcp.js +673 -0
  395. package/lib/plugins/memory.d.ts +17 -0
  396. package/lib/plugins/memory.js +858 -0
  397. package/lib/plugins/microcompact.d.ts +18 -0
  398. package/lib/plugins/microcompact.js +119 -0
  399. package/lib/plugins/mode.d.ts +18 -0
  400. package/lib/plugins/mode.js +115 -0
  401. package/lib/plugins/permission-presets.d.ts +18 -0
  402. package/lib/plugins/permission-presets.js +135 -0
  403. package/lib/plugins/plan.d.ts +2 -0
  404. package/lib/plugins/plan.js +192 -0
  405. package/lib/plugins/plugin-manager.d.ts +2 -0
  406. package/lib/plugins/plugin-manager.js +165 -0
  407. package/lib/plugins/presets.d.ts +2 -0
  408. package/lib/plugins/presets.js +182 -0
  409. package/lib/plugins/prompt.d.ts +2 -0
  410. package/lib/plugins/prompt.js +264 -0
  411. package/lib/plugins/ptc.d.ts +2 -0
  412. package/lib/plugins/ptc.js +272 -0
  413. package/lib/plugins/remote/http.d.ts +11 -0
  414. package/lib/plugins/remote/http.js +11 -0
  415. package/lib/plugins/remote/routes.d.ts +24 -0
  416. package/lib/plugins/remote/routes.js +384 -0
  417. package/lib/plugins/remote/types.d.ts +135 -0
  418. package/lib/plugins/remote/types.js +87 -0
  419. package/lib/plugins/remote.d.ts +17 -0
  420. package/lib/plugins/remote.js +1028 -0
  421. package/lib/plugins/runtime-api.d.ts +16 -0
  422. package/lib/plugins/runtime-api.js +99 -0
  423. package/lib/plugins/runtime.d.ts +10 -0
  424. package/lib/plugins/runtime.js +451 -0
  425. package/lib/plugins/sandbox.d.ts +2 -0
  426. package/lib/plugins/sandbox.js +761 -0
  427. package/lib/plugins/schedule.d.ts +26 -0
  428. package/lib/plugins/schedule.js +538 -0
  429. package/lib/plugins/self-improve.d.ts +61 -0
  430. package/lib/plugins/self-improve.js +953 -0
  431. package/lib/plugins/session-search.d.ts +16 -0
  432. package/lib/plugins/session-search.js +308 -0
  433. package/lib/plugins/session-title.d.ts +19 -0
  434. package/lib/plugins/session-title.js +109 -0
  435. package/lib/plugins/session.d.ts +7 -0
  436. package/lib/plugins/session.js +296 -0
  437. package/lib/plugins/settings.d.ts +3 -0
  438. package/lib/plugins/settings.js +705 -0
  439. package/lib/plugins/skills.d.ts +2 -0
  440. package/lib/plugins/skills.js +360 -0
  441. package/lib/plugins/spill.d.ts +16 -0
  442. package/lib/plugins/spill.js +200 -0
  443. package/lib/plugins/subagent.d.ts +2 -0
  444. package/lib/plugins/subagent.js +862 -0
  445. package/lib/plugins/surfaces.d.ts +11 -0
  446. package/lib/plugins/surfaces.js +20 -0
  447. package/lib/plugins/team.d.ts +16 -0
  448. package/lib/plugins/team.js +149 -0
  449. package/lib/plugins/todo.d.ts +19 -0
  450. package/lib/plugins/todo.js +188 -0
  451. package/lib/plugins/tool-search.d.ts +2 -0
  452. package/lib/plugins/tool-search.js +425 -0
  453. package/lib/plugins/tools-default.d.ts +12 -0
  454. package/lib/plugins/tools-default.js +275 -0
  455. package/lib/plugins/tools.d.ts +16 -0
  456. package/lib/plugins/tools.js +62 -0
  457. package/lib/plugins/transcript.d.ts +15 -0
  458. package/lib/plugins/transcript.js +311 -0
  459. package/lib/plugins/tui.d.ts +2 -0
  460. package/lib/plugins/tui.js +98 -0
  461. package/lib/plugins/waiting.d.ts +12 -0
  462. package/lib/plugins/waiting.js +34 -0
  463. package/lib/plugins/web-search.d.ts +14 -0
  464. package/lib/plugins/web-search.js +263 -0
  465. package/lib/plugins/webserver.d.ts +48 -0
  466. package/lib/plugins/webserver.js +228 -0
  467. package/lib/remote/assets/app-DAcUCOEn.js +14 -0
  468. package/lib/remote/assets/icon-192.png +0 -0
  469. package/lib/remote/assets/icon-512.png +0 -0
  470. package/lib/remote/assets/index.html +34 -0
  471. package/lib/remote/assets/manifest.json +27 -0
  472. package/lib/remote/assets/style-DIB6729x.css +1 -0
  473. package/lib/remote/assets/sw.js +66 -0
  474. package/lib/services/types.d.ts +1228 -0
  475. package/lib/services/types.js +1 -0
  476. package/lib/tools/config-cli.d.ts +1 -0
  477. package/lib/tools/config-cli.js +89 -0
  478. package/lib/ui/arrival.d.ts +72 -0
  479. package/lib/ui/arrival.js +105 -0
  480. package/lib/ui/assets/app-B70nVIKd.js +69 -0
  481. package/lib/ui/assets/chunk-2UxHyX5q.js +1 -0
  482. package/lib/ui/assets/chunk-B1dDrJ26.js +1 -0
  483. package/lib/ui/assets/chunk-B6aJPvgy.js +1 -0
  484. package/lib/ui/assets/chunk-BEwlwnbL.js +1 -0
  485. package/lib/ui/assets/chunk-BGcgwlCI.js +12 -0
  486. package/lib/ui/assets/chunk-BIGW1oBm.js +1 -0
  487. package/lib/ui/assets/chunk-BPQ3VLAy.js +1 -0
  488. package/lib/ui/assets/chunk-BRH0KZbk.js +141 -0
  489. package/lib/ui/assets/chunk-BX6H_ySx.js +1 -0
  490. package/lib/ui/assets/chunk-B_P3UbPa.js +1 -0
  491. package/lib/ui/assets/chunk-B_TYUkTI.js +1 -0
  492. package/lib/ui/assets/chunk-B_vNuMnf.js +1 -0
  493. package/lib/ui/assets/chunk-BajyYBss.js +10 -0
  494. package/lib/ui/assets/chunk-BdnUsdx6.js +1 -0
  495. package/lib/ui/assets/chunk-Buea-lGh.js +1 -0
  496. package/lib/ui/assets/chunk-C0PvZCCE.js +1 -0
  497. package/lib/ui/assets/chunk-C0m74zRD.js +1 -0
  498. package/lib/ui/assets/chunk-C27-OAKa.js +1 -0
  499. package/lib/ui/assets/chunk-C2oV4EkX.js +1 -0
  500. package/lib/ui/assets/chunk-C7zT0LnQ.js +1 -0
  501. package/lib/ui/assets/chunk-C9GSunVT.js +1 -0
  502. package/lib/ui/assets/chunk-C9tS-k6U.js +1 -0
  503. package/lib/ui/assets/chunk-CHLpvVh8.js +1 -0
  504. package/lib/ui/assets/chunk-CLxacb5B.js +1 -0
  505. package/lib/ui/assets/chunk-COt5Ahok.js +1 -0
  506. package/lib/ui/assets/chunk-CPTIWCL2.js +1 -0
  507. package/lib/ui/assets/chunk-CQLl-L-p.js +1 -0
  508. package/lib/ui/assets/chunk-CUWRgxuq.js +55 -0
  509. package/lib/ui/assets/chunk-CWanVSXC.js +1 -0
  510. package/lib/ui/assets/chunk-Cf5RLm7j.js +1 -0
  511. package/lib/ui/assets/chunk-CickPsom.js +1 -0
  512. package/lib/ui/assets/chunk-Cj5Yp3dK.js +1 -0
  513. package/lib/ui/assets/chunk-Cmh6b_Ma.js +1 -0
  514. package/lib/ui/assets/chunk-Cp-IABpG.js +1 -0
  515. package/lib/ui/assets/chunk-CqE71os6.js +1 -0
  516. package/lib/ui/assets/chunk-CtKP3W-j.js +1 -0
  517. package/lib/ui/assets/chunk-Cvjx9yec.js +1 -0
  518. package/lib/ui/assets/chunk-CxGP3dtY.js +1 -0
  519. package/lib/ui/assets/chunk-CylS5w8V.js +1 -0
  520. package/lib/ui/assets/chunk-D38fbIBN.js +1 -0
  521. package/lib/ui/assets/chunk-D97Zzqfu.js +1 -0
  522. package/lib/ui/assets/chunk-DAi9KRSo.js +1 -0
  523. package/lib/ui/assets/chunk-DHK4yRfg.js +1 -0
  524. package/lib/ui/assets/chunk-DJeabLx-.js +1 -0
  525. package/lib/ui/assets/chunk-DNRxmY5a.js +1 -0
  526. package/lib/ui/assets/chunk-DNSN1z5r.js +1 -0
  527. package/lib/ui/assets/chunk-DNasK_ZG.js +1 -0
  528. package/lib/ui/assets/chunk-DPvrY3IQ.js +1 -0
  529. package/lib/ui/assets/chunk-DXmwc3jG.js +1 -0
  530. package/lib/ui/assets/chunk-Dd0kTxKP.js +1 -0
  531. package/lib/ui/assets/chunk-De0Btta0.js +1 -0
  532. package/lib/ui/assets/chunk-Des-eS-w.js +1 -0
  533. package/lib/ui/assets/chunk-Df6bDoY_.js +1 -0
  534. package/lib/ui/assets/chunk-DijEV5ha.js +1 -0
  535. package/lib/ui/assets/chunk-DkvoVjww.js +1 -0
  536. package/lib/ui/assets/chunk-DlC-OlHO.js +1 -0
  537. package/lib/ui/assets/chunk-DnzrXTVv.js +1 -0
  538. package/lib/ui/assets/chunk-Dualf0xi.js +1 -0
  539. package/lib/ui/assets/chunk-EXT84bkm.js +1 -0
  540. package/lib/ui/assets/chunk-GwR3hkPK.js +1 -0
  541. package/lib/ui/assets/chunk-P80f7IUj.js +1 -0
  542. package/lib/ui/assets/chunk-VOosw3JB.js +1 -0
  543. package/lib/ui/assets/chunk-YQ4lDkt_.js +140 -0
  544. package/lib/ui/assets/chunk-Yzrsuije.js +1 -0
  545. package/lib/ui/assets/chunk-Z72CF80r.js +1 -0
  546. package/lib/ui/assets/chunk-g9-lgVsj.js +1 -0
  547. package/lib/ui/assets/chunk-vGWfd6FD.js +1 -0
  548. package/lib/ui/assets/chunk-wDzz0qaB.js +1 -0
  549. package/lib/ui/assets/chunk-ySF7HWmS.js +1 -0
  550. package/lib/ui/assets/icon.png +0 -0
  551. package/lib/ui/assets/index.html +14 -0
  552. package/lib/ui/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
  553. package/lib/ui/assets/style-Bq01xH_b.css +1 -0
  554. package/lib/ui/frames.d.ts +67 -0
  555. package/lib/ui/frames.js +146 -0
  556. package/lib/ui/index.d.ts +59 -0
  557. package/lib/ui/index.js +50 -0
  558. package/lib/ui/manifest.d.ts +172 -0
  559. package/lib/ui/manifest.js +158 -0
  560. package/lib/ui/plugin.d.ts +161 -0
  561. package/lib/ui/plugin.js +7 -0
  562. package/lib/ui/plugins/browser/client.js +290 -0
  563. package/lib/ui/plugins/browser/icon.png +0 -0
  564. package/lib/ui/plugins/composer/client.js +1843 -0
  565. package/lib/ui/plugins/composer/icon.png +0 -0
  566. package/lib/ui/plugins/files/client.js +646 -0
  567. package/lib/ui/plugins/files/icon.png +0 -0
  568. package/lib/ui/plugins/manifest.json +107 -0
  569. package/lib/ui/plugins/plugins/client.js +682 -0
  570. package/lib/ui/plugins/plugins/icon.png +0 -0
  571. package/lib/ui/plugins/preview/client.js +197 -0
  572. package/lib/ui/plugins/preview/icon.png +0 -0
  573. package/lib/ui/plugins/prompt/client.js +653 -0
  574. package/lib/ui/plugins/prompt/icon.png +0 -0
  575. package/lib/ui/plugins/sessions/client.js +1577 -0
  576. package/lib/ui/plugins/sessions/icon.png +0 -0
  577. package/lib/ui/plugins/settings/client.js +5470 -0
  578. package/lib/ui/plugins/settings/icon.png +0 -0
  579. package/lib/ui/plugins/skills/client.js +485 -0
  580. package/lib/ui/plugins/skills/icon.png +0 -0
  581. package/lib/ui/plugins/status/client.js +1420 -0
  582. package/lib/ui/plugins/status/icon.png +0 -0
  583. package/lib/ui/plugins/statusbar/client.js +504 -0
  584. package/lib/ui/plugins/statusbar/icon.png +0 -0
  585. package/lib/ui/plugins/tasks/client.js +52 -0
  586. package/lib/ui/plugins/tasks/icon.png +0 -0
  587. package/lib/ui/plugins/team/client.js +527 -0
  588. package/lib/ui/plugins/team/icon.png +0 -0
  589. package/lib/ui/plugins/terminal/client.js +232 -0
  590. package/lib/ui/plugins/terminal/icon.png +0 -0
  591. package/lib/ui/plugins/trace/client.js +1376 -0
  592. package/lib/ui/plugins/trace/icon.png +0 -0
  593. package/lib/ui/plugins/transcript/client.js +2661 -0
  594. package/lib/ui/plugins/transcript/icon.png +0 -0
  595. package/lib/ui/scoped-slots.d.ts +20 -0
  596. package/lib/ui/scoped-slots.js +21 -0
  597. package/lib/ui/sdk/@dsc/ui/index.d.ts +242 -0
  598. package/lib/ui/sdk/@dsc/ui/package.json +16 -0
  599. package/lib/ui/sdk/@dsc/ui-core/contract.d.ts +1973 -0
  600. package/lib/ui/sdk/@dsc/ui-core/core/diff-text.d.ts +74 -0
  601. package/lib/ui/sdk/@dsc/ui-core/core/dock-browser.d.ts +137 -0
  602. package/lib/ui/sdk/@dsc/ui-core/core/dock-ops.d.ts +59 -0
  603. package/lib/ui/sdk/@dsc/ui-core/core/model-caps.d.ts +83 -0
  604. package/lib/ui/sdk/@dsc/ui-core/core/native-bridge.d.ts +135 -0
  605. package/lib/ui/sdk/@dsc/ui-core/core/token-estimate.d.ts +55 -0
  606. package/lib/ui/sdk/@dsc/ui-core/package.json +16 -0
  607. package/lib/ui/sdk/@dsc/ui-core/ui/arrival.d.ts +72 -0
  608. package/lib/ui/sdk/@dsc/ui-core/ui/frames.d.ts +67 -0
  609. package/lib/ui/sdk/@dsc/ui-core/ui/index.d.ts +59 -0
  610. package/lib/ui/sdk/@dsc/ui-core/ui/manifest.d.ts +172 -0
  611. package/lib/ui/sdk/@dsc/ui-core/ui/plugin.d.ts +161 -0
  612. package/lib/ui/sdk/@dsc/ui-core/ui/scoped-slots.d.ts +20 -0
  613. package/lib/ui/sdk/@dsc/ui-core/ui/services-react.d.ts +27 -0
  614. package/lib/ui/sdk/@dsc/ui-core/ui/services.d.ts +63 -0
  615. package/lib/ui/sdk/@dsc/ui-core/ui/slots-react.d.ts +28 -0
  616. package/lib/ui/sdk/@dsc/ui-core/ui/slots.d.ts +481 -0
  617. package/lib/ui/sdk/@dsc/ui-core/ui/store.d.ts +89 -0
  618. package/lib/ui/sdk/@dsc/ui-dockkit/dock-model.d.ts +238 -0
  619. package/lib/ui/sdk/@dsc/ui-dockkit/dock-state.d.ts +163 -0
  620. package/lib/ui/sdk/@dsc/ui-dockkit/dock.d.ts +24 -0
  621. package/lib/ui/sdk/@dsc/ui-dockkit/index.d.ts +15 -0
  622. package/lib/ui/sdk/@dsc/ui-dockkit/package.json +16 -0
  623. package/lib/ui/sdk/@dsc/ui-layout/app.d.ts +74 -0
  624. package/lib/ui/sdk/@dsc/ui-layout/appearance.d.ts +70 -0
  625. package/lib/ui/sdk/@dsc/ui-layout/host-channel.d.ts +112 -0
  626. package/lib/ui/sdk/@dsc/ui-layout/index.d.ts +34 -0
  627. package/lib/ui/sdk/@dsc/ui-layout/package.json +16 -0
  628. package/lib/ui/sdk/@dsc/ui-layout/page-state.d.ts +14 -0
  629. package/lib/ui/sdk/@dsc/ui-layout/review-pane.d.ts +21 -0
  630. package/lib/ui/sdk/@dsc/ui-layout/runtime-context.d.ts +44 -0
  631. package/lib/ui/sdk/@dsc/ui-layout/thread-view.d.ts +28 -0
  632. package/lib/ui/sdk/@dsc/ui-layout/update-button.d.ts +21 -0
  633. package/lib/ui/sdk/@dsc/ui-primitives/code-file-icon-artwork.d.ts +53 -0
  634. package/lib/ui/sdk/@dsc/ui-primitives/code-view.d.ts +15 -0
  635. package/lib/ui/sdk/@dsc/ui-primitives/compat.d.ts +27 -0
  636. package/lib/ui/sdk/@dsc/ui-primitives/completion-sound.d.ts +24 -0
  637. package/lib/ui/sdk/@dsc/ui-primitives/confirm.d.ts +33 -0
  638. package/lib/ui/sdk/@dsc/ui-primitives/css.d.ts +47 -0
  639. package/lib/ui/sdk/@dsc/ui-primitives/diff-rows.d.ts +20 -0
  640. package/lib/ui/sdk/@dsc/ui-primitives/file-icons.d.ts +38 -0
  641. package/lib/ui/sdk/@dsc/ui-primitives/file-type-classify.d.ts +66 -0
  642. package/lib/ui/sdk/@dsc/ui-primitives/file-type-icon.d.ts +57 -0
  643. package/lib/ui/sdk/@dsc/ui-primitives/highlight.d.ts +24 -0
  644. package/lib/ui/sdk/@dsc/ui-primitives/hover-delay.d.ts +17 -0
  645. package/lib/ui/sdk/@dsc/ui-primitives/icons.d.ts +109 -0
  646. package/lib/ui/sdk/@dsc/ui-primitives/index.d.ts +55 -0
  647. package/lib/ui/sdk/@dsc/ui-primitives/lang-table.d.ts +10 -0
  648. package/lib/ui/sdk/@dsc/ui-primitives/markdown.d.ts +20 -0
  649. package/lib/ui/sdk/@dsc/ui-primitives/native.d.ts +41 -0
  650. package/lib/ui/sdk/@dsc/ui-primitives/package.json +16 -0
  651. package/lib/ui/sdk/@dsc/ui-primitives/panels.d.ts +86 -0
  652. package/lib/ui/sdk/@dsc/ui-primitives/paths.d.ts +11 -0
  653. package/lib/ui/sdk/@dsc/ui-primitives/pdf-view.d.ts +13 -0
  654. package/lib/ui/sdk/@dsc/ui-primitives/plugin-text.d.ts +15 -0
  655. package/lib/ui/sdk/@dsc/ui-primitives/select.d.ts +35 -0
  656. package/lib/ui/sdk/@dsc/ui-primitives/table-view.d.ts +23 -0
  657. package/lib/ui/sdk/@dsc/ui-primitives/thread-resizer.d.ts +22 -0
  658. package/lib/ui/sdk/@dsc/ui-primitives/time.d.ts +33 -0
  659. package/lib/ui/sdk/@dsc/ui-primitives/toast.d.ts +16 -0
  660. package/lib/ui/sdk/@dsc/ui-primitives/tokens.d.ts +14 -0
  661. package/lib/ui/sdk/@dsc/ui-primitives/tool-args.d.ts +49 -0
  662. package/lib/ui/sdk/@dsc/ui-primitives/tool-summary.d.ts +64 -0
  663. package/lib/ui/sdk/@dsc/ui-renderer/boot.d.ts +121 -0
  664. package/lib/ui/sdk/@dsc/ui-renderer/hmr.d.ts +43 -0
  665. package/lib/ui/sdk/@dsc/ui-renderer/index.d.ts +20 -0
  666. package/lib/ui/sdk/@dsc/ui-renderer/package.json +16 -0
  667. package/lib/ui/sdk/@dsc/ui-slots/index.d.ts +19 -0
  668. package/lib/ui/sdk/@dsc/ui-slots/package.json +16 -0
  669. package/lib/ui/sdk/@dsc/ui-slots/slots-react.d.ts +48 -0
  670. package/lib/ui/sdk/@dsc/ui-slots/slots.d.ts +102 -0
  671. package/lib/ui/services-react.d.ts +27 -0
  672. package/lib/ui/services-react.js +32 -0
  673. package/lib/ui/services.d.ts +63 -0
  674. package/lib/ui/services.js +121 -0
  675. package/lib/ui/slots-ink.d.ts +26 -0
  676. package/lib/ui/slots-ink.js +78 -0
  677. package/lib/ui/slots-react.d.ts +28 -0
  678. package/lib/ui/slots-react.js +88 -0
  679. package/lib/ui/slots.d.ts +481 -0
  680. package/lib/ui/slots.js +550 -0
  681. package/lib/ui/store.d.ts +89 -0
  682. package/lib/ui/store.js +62 -0
  683. package/lib/ui/tui-plugin-api.d.ts +23 -0
  684. package/lib/ui/tui-plugin-api.js +23 -0
  685. package/lib/ui/tui-plugins.d.ts +47 -0
  686. package/lib/ui/tui-plugins.js +220 -0
  687. package/package.json +58 -6
@@ -0,0 +1,548 @@
1
+ /**
2
+ * OpenAI chat-completions 流式客户端(协议事实已对齐 dsh llm-deepseek 的
3
+ * chat-completions 实现):SSE 手写解析;`delta.reasoning_content` → 思考流、
4
+ * `delta.content` → 正文、`delta.tool_calls` 按 index 聚合、
5
+ * `stream_options.include_usage` 末块 usage;assistant 重放时回传
6
+ * `reasoning_content`。
7
+ *
8
+ * 重试策略(T33 修订):连接/HTTP 失败在**尚未收到任何流数据**前指数退避重试 2 次,
9
+ * 可重试的:fetch 抛出的连接失败(`LlmError.retryable`)、429 / 408 / 5xx 的 HTTP 响应、
10
+ * 以及「流已开始但一个字节都没到」的中断(同样归一成 retryable)。已经收到内容的流中断
11
+ * 打包成 {@link StreamInterruptedError} 交上层落库,不在这一层自动重试(重发是另一条新流,
12
+ * 界面上会出现重复正文)。用户取消(signal 已 abort)不重试。
13
+ *
14
+ * @module dsc/core/llm
15
+ */
16
+ import { sessionAttributionHeaders } from './request-attribution.js';
17
+ /** 取消息的纯文本(content 为数组时拼接 text 片段,图像不计入)。 */
18
+ export function contentText(content) {
19
+ // undefined 也要兜:类型上写着非可缺,但**从盘上读回来的老日志**可能整条没有 content
20
+ // (2026-10 自检里撞到过一次:一条 tool 记录没带正文,重放整段抛异常,用户打开那条
21
+ // 会话看到的是一片空白——历史看起来像丢了)。这里退成空串,界面照常显示其余条目。
22
+ if (content === null || content === undefined)
23
+ return '';
24
+ if (typeof content === 'string')
25
+ return content;
26
+ // 认不出形状(数字、对象、被写坏的那一行)也退成空串:这一层的职责是「取文本」,
27
+ // 取不到就交白卷,绝不该把「打开一条会话」这种动作炸掉。
28
+ if (!Array.isArray(content))
29
+ return '';
30
+ return content.map((part) => (part.type === 'text' ? part.text : '')).join('');
31
+ }
32
+ /** 取消息里的图像清单(data URL;给界面渲染缩略图用)。 */
33
+ export function contentImages(content) {
34
+ if (typeof content === 'string' || content === null || content === undefined)
35
+ return [];
36
+ return content.flatMap((part) => (part.type === 'image_url' ? [part.image_url.url] : []));
37
+ }
38
+ /**
39
+ * 把散落在历史里的 system 消息全部并进开头那条系统提示。
40
+ *
41
+ * 为什么要合并:不少 OpenAI 兼容网关(litellm 系的 hy3-a 就是)只认「第一条可以是
42
+ * system」,历史中间再冒一条 system 就直接 HTTP 400 `System message must be at the
43
+ * beginning`。外部插件(例如装进 ~/.dsc/plugins 的长期记忆插件)习惯用
44
+ * `transformMessages` 往末尾补一条 system,内容本身是有用的,所以不能丢——
45
+ * 并进头部既保住内容,也让任何插件都没法再把请求结构弄坏。
46
+ *
47
+ * @param messages - 组装好的请求消息;原数组不动。
48
+ * @returns 至多一条 system、且它排在最前的消息数组。
49
+ */
50
+ export function foldSystemMessages(messages) {
51
+ let head;
52
+ const rest = [];
53
+ for (const message of messages) {
54
+ if (message.role !== 'system') {
55
+ rest.push(message);
56
+ continue;
57
+ }
58
+ const text = contentText(message.content);
59
+ if (head === undefined) {
60
+ head = text === '' ? { ...message, content: '' } : message;
61
+ continue;
62
+ }
63
+ if (text === '')
64
+ continue;
65
+ head = { ...head, content: `${contentText(head.content)}\n\n${text}` };
66
+ }
67
+ return head === undefined ? messages : [head, ...rest];
68
+ }
69
+ /**
70
+ * 把消息里的图像全部换成一句说明(当前模型没声明照片输入时用)。
71
+ * 整条删掉会让工具结果读起来缺一块,所以把原因留在正文里,模型知道自己是"没看到图"。
72
+ * @param messages - 组装好的请求消息;原数组不动。
73
+ * @param note - 替换进去的说明文字。
74
+ */
75
+ export function dropImageParts(messages, note) {
76
+ return messages.map((message) => {
77
+ if (typeof message.content !== 'object' || message.content === null)
78
+ return message;
79
+ if (!message.content.some((part) => part.type === 'image_url'))
80
+ return message;
81
+ const text = contentText(message.content);
82
+ return { ...message, content: [{ type: 'text', text: text === '' ? note : `${text}\n${note}` }] };
83
+ });
84
+ }
85
+ /**
86
+ * 剔除历史里配不上对的工具调用与工具结果(协议守门:assistant 的每个 `tool_call`
87
+ * 必须有跟随的 tool 消息回应,反之亦然,否则 OpenAI 系网关直接 HTTP 400)。
88
+ *
89
+ * 孤儿从哪来:进程在「assistant 的 tool_calls 已落盘、工具结果还没写」之间被杀
90
+ * (崩溃、强退),会话日志里就永久留下孤儿调用;`Session.load` 原样重建,之后这个
91
+ * 会话**每一次请求都被 400 拒掉,用户没有自救手段**(运行中的打断不需要这里管——
92
+ * loop.ts 会给没跑完的调用补合成结果)。清洗只动传入的这份请求副本,落盘历史保持
93
+ * 原样,损坏的会话恢复后即可直接继续用。
94
+ *
95
+ * 配对按全文 id 集合判断,不要求 tool 消息紧邻:正常历史里 call id 唯一,全文判断
96
+ * 不会误删;而「调用与回应隔着别的消息」的畸形顺序本身就只在损坏日志里出现。
97
+ *
98
+ * 同一 callId 只放行第一条结果:一条 tool_call 在协议上只能被应答一次,第二条在
99
+ * 网关眼里就是「没有前置 tool_calls 可应答的 tool 消息」(DeepSeek 的 400 原文)。
100
+ * 重复从哪来:中断修复先落盘「结果未知」合成件,紧接着被打断的那一轮又把真实结果
101
+ * 写了进来(两件事在 session.open 重开同一会话时先后必然发生,见 plugins/session)。
102
+ * 保留首条而不是末条是刻意的保守取舍:首条是合成件时模型会先去核查副作用,不会
103
+ * 被后到的「用户取消」之类措辞误导成「什么都没发生」。
104
+ *
105
+ * @param messages - 组装好的请求消息;原数组不动。
106
+ * @returns 配对完整(或已剔除孤儿)的消息数组。
107
+ */
108
+ export function sanitizeToolOrphans(messages) {
109
+ return sanitizeToolOrphansWithReport(messages).messages;
110
+ }
111
+ /**
112
+ * {@link sanitizeToolOrphans} 的带账版本:清洗逻辑完全一样,另报「动了哪里」。
113
+ * 为什么要有账:清洗一直是静默的,2026-10-03 那次 400 事故就是它补不上且没人知道。
114
+ * llm 插件把这份报告接成 `dsc/notice`,「日志有病、请求侧兜底」就不再是暗箱。
115
+ */
116
+ export function sanitizeToolOrphansWithReport(messages) {
117
+ const called = new Set();
118
+ const answered = new Set();
119
+ for (const message of messages) {
120
+ if (message.role === 'assistant') {
121
+ for (const call of message.tool_calls ?? [])
122
+ called.add(call.id);
123
+ }
124
+ else if (message.role === 'tool' && message.tool_call_id !== undefined) {
125
+ answered.add(message.tool_call_id);
126
+ }
127
+ }
128
+ const replied = new Set();
129
+ const report = { droppedResults: 0, droppedCalls: 0, droppedMessages: 0, reordered: 0 };
130
+ const cleaned = messages.flatMap((message) => {
131
+ if (message.role === 'tool') {
132
+ if (message.tool_call_id === undefined)
133
+ return [message];
134
+ if (!called.has(message.tool_call_id) || replied.has(message.tool_call_id)) {
135
+ report.droppedResults += 1;
136
+ return [];
137
+ }
138
+ replied.add(message.tool_call_id);
139
+ return [message];
140
+ }
141
+ if (message.role !== 'assistant' || message.tool_calls === undefined)
142
+ return [message];
143
+ const kept = message.tool_calls.filter((call) => answered.has(call.id));
144
+ if (kept.length === message.tool_calls.length)
145
+ return [message];
146
+ report.droppedCalls += message.tool_calls.length - kept.length;
147
+ if (kept.length > 0)
148
+ return [{ ...message, tool_calls: kept }];
149
+ // 调用全被剔掉、正文又是空的:这条 assistant 已经不表达任何内容,整条删
150
+ if (contentText(message.content) === '') {
151
+ report.droppedMessages += 1;
152
+ return [];
153
+ }
154
+ return [{ ...message, tool_calls: undefined }];
155
+ });
156
+ // 邻接修复:网关不光要求「有来有回」,还要求结果**紧跟** tool_calls。异步输入
157
+ // (作业完成通知、轮中途插话)在 0.6.46 及更早的日志里可能落在两者中间——重放后
158
+ // 每轮请求都带着这个夹层,网关 400 且重试无效(会话卡死)。这里把夹在中间的
159
+ // 消息整块后移到结果闭合之后(组间相对顺序不动),dsh 靠 inbox 从源头不产生
160
+ // 这种历史,它的 serialize 校验对应的就是这道兜底位。
161
+ const aligned = [];
162
+ let cursor = 0;
163
+ while (cursor < cleaned.length) {
164
+ const message = cleaned[cursor];
165
+ if (message.role === 'assistant' && (message.tool_calls?.length ?? 0) > 0) {
166
+ const pending = new Set(message.tool_calls.map((call) => call.id));
167
+ aligned.push(message);
168
+ cursor += 1;
169
+ const deferred = [];
170
+ while (cursor < cleaned.length && pending.size > 0) {
171
+ const next = cleaned[cursor];
172
+ if (next.role === 'tool' && next.tool_call_id !== undefined && pending.delete(next.tool_call_id)) {
173
+ aligned.push(next);
174
+ }
175
+ else {
176
+ deferred.push(next);
177
+ }
178
+ cursor += 1;
179
+ }
180
+ if (deferred.length > 0) {
181
+ report.reordered += deferred.length;
182
+ aligned.push(...deferred);
183
+ }
184
+ continue;
185
+ }
186
+ aligned.push(message);
187
+ cursor += 1;
188
+ }
189
+ return { messages: aligned, report };
190
+ }
191
+ /** 内置协议 id:OpenAI chat-completions(DeepSeek/GLM 系 thinking 扩展同属此协议)。 */
192
+ export const OPENAI_COMPLETIONS_API = 'openai-completions';
193
+ export class LlmError extends Error {
194
+ /** HTTP 状态码;fetch 自己抛的异常(连不上、DNS 失败、连接被切断)没有这个值。 */
195
+ status;
196
+ /**
197
+ * 是否值得重试。true 只有一种情况:请求还没连上就失败(`streamOnce` 里 fetch 的 catch),
198
+ * 此时一个字节都没收到,重发是安全的。HTTP 429 / 5xx 由 `status` 判定,不看这个标记。
199
+ */
200
+ retryable;
201
+ /** 服务端 Retry-After 头解析出来的毫秒数(要求等多久再试);没有就是 undefined。 */
202
+ retryAfterMs;
203
+ constructor(message, status, retryable = false, retryAfterMs) {
204
+ super(message);
205
+ this.name = 'LlmError';
206
+ this.status = status;
207
+ this.retryable = retryable;
208
+ this.retryAfterMs = retryAfterMs;
209
+ }
210
+ }
211
+ /**
212
+ * T33:流已经开始之后被打断(网络断、网关挂起、连接被切),且已经收到了内容。
213
+ * `partial` 是到断点为止攒下的半截结果——调用方(loop)负责把它落库成一条截断的
214
+ * assistant 记录,用户看到的半截回复与上下文才不会两张皮。本错误不重试(重发是
215
+ * 另一条新流),「保留已收内容再续一条」还是「就此报错」由循环层取舍。
216
+ */
217
+ export class StreamInterruptedError extends LlmError {
218
+ partial;
219
+ constructor(message, partial) {
220
+ super(message, undefined, false);
221
+ this.name = 'StreamInterruptedError';
222
+ this.partial = partial;
223
+ }
224
+ }
225
+ const MAX_ATTEMPTS = 3;
226
+ /** 发起一次流式对话(openai-completions 适配器的实现;经 LlmService.stream 派发)。 */
227
+ export async function streamChat(request, handlers) {
228
+ let attempt = 0;
229
+ for (;;) {
230
+ attempt += 1;
231
+ try {
232
+ return await streamOnce(request, handlers);
233
+ }
234
+ catch (error) {
235
+ const retryable = attempt < MAX_ATTEMPTS &&
236
+ request.signal?.aborted !== true &&
237
+ error instanceof LlmError &&
238
+ // 408 = 请求超时(服务端排队没排上),与 429/5xx 一样值得再试(T33 纳入可重试清单)
239
+ (error.retryable || (error.status !== undefined && (error.status === 408 || error.status === 429 || error.status >= 500)));
240
+ if (!retryable)
241
+ throw error;
242
+ handlers.onRetry?.(attempt + 1, error instanceof Error ? error.message : String(error));
243
+ // 服务端明确要求等多久(Retry-After)就至少等那么久;没有才用指数退避。
244
+ await delay(Math.max(500 * 2 ** (attempt - 1), error.retryAfterMs ?? 0), request.signal);
245
+ }
246
+ }
247
+ }
248
+ async function streamOnce(request, handlers) {
249
+ // 工具孤儿是协议层面的硬伤(配不上对就 400),在这里——离 wire 最近的
250
+ // 一站——统一守门,循环轮次与压缩等所有调用方都自动受益;剔了什么报给上层。
251
+ const sanitized = sanitizeToolOrphansWithReport(request.messages);
252
+ if (sanitized.report.droppedResults + sanitized.report.droppedCalls + sanitized.report.droppedMessages > 0) {
253
+ handlers.onSanitize?.(sanitized.report);
254
+ }
255
+ const serialized = serializeMessages(sanitized.messages);
256
+ const body = {
257
+ model: request.model,
258
+ // 消息按调用方给的原样发:历史里混进多条 system 的合并是 prompt 层的
259
+ // 命名投影(fold-system)该做的事,协议适配器只认一条流水线形状。
260
+ // 显式缓存断点只在端点声明支持时才打(缺省 false):不开的端点走原路,
261
+ // 请求体与以前逐字节相同——DeepSeek 系靠网关自动缓存,别动它。
262
+ messages: request.cacheControl === true ? applyExplicitCache(serialized) : serialized,
263
+ stream: true,
264
+ stream_options: { include_usage: true },
265
+ };
266
+ if (request.tools !== undefined && request.tools.length > 0) {
267
+ body.tools = request.tools.map((tool) => ({
268
+ type: 'function',
269
+ function: { name: tool.name, description: tool.description, parameters: tool.parameters },
270
+ }));
271
+ }
272
+ if (request.maxTokens !== undefined)
273
+ body.max_tokens = request.maxTokens;
274
+ if (request.temperature !== undefined)
275
+ body.temperature = request.temperature;
276
+ if (request.thinking !== undefined)
277
+ body.thinking = { type: request.thinking };
278
+ if (request.reasoningEffort !== undefined)
279
+ body.reasoning_effort = request.reasoningEffort;
280
+ // 建连与响应头阶段单独设超时(2026-09-29):端点卡死不能把整轮拖成永久等待。
281
+ // request.signal 的取消经桥接传进 controller,流读完才拆桥。
282
+ const controller = new AbortController();
283
+ const onOuterAbort = () => controller.abort();
284
+ if (request.signal?.aborted === true)
285
+ controller.abort();
286
+ request.signal?.addEventListener('abort', onOuterAbort, { once: true });
287
+ const connectTimer = setTimeout(() => controller.abort(new LlmError(`连接超时(${Math.round(CONNECT_TIMEOUT_MS / 1000)} 秒无响应)`, undefined, true)), CONNECT_TIMEOUT_MS);
288
+ let response;
289
+ try {
290
+ response = await fetch(`${request.baseUrl}/chat/completions`, {
291
+ method: 'POST',
292
+ headers: {
293
+ 'content-type': 'application/json',
294
+ authorization: `Bearer ${request.apiKey}`,
295
+ // 端点点名要的归因头(当前只有 opencode Go:自标识 UA + 会话头)。
296
+ // 不命中门控就是空表,别家端点发出去的头和以前逐字节一样。
297
+ ...sessionAttributionHeaders(request.baseUrl, request.sessionId),
298
+ },
299
+ body: JSON.stringify(body),
300
+ signal: controller.signal,
301
+ }).catch((error) => {
302
+ // 连接超时是 LlmError(retryable),原样上抛给 streamChat 的重试环;其余按连接失败归一。
303
+ if (error instanceof LlmError)
304
+ throw error;
305
+ throw new LlmError(`连接失败:${error instanceof Error ? error.message : String(error)}`, undefined, true);
306
+ });
307
+ }
308
+ finally {
309
+ clearTimeout(connectTimer);
310
+ }
311
+ if (!response.ok || response.body === null) {
312
+ const detail = await response.text().catch(() => '');
313
+ throw new LlmError(`HTTP ${response.status}${detail === '' ? '' : `:${detail.slice(0, 300)}`}`, response.status, false, retryAfterMs(response.headers.get('retry-after')));
314
+ }
315
+ const result = {
316
+ text: '',
317
+ reasoning: '',
318
+ toolCalls: [],
319
+ usage: null,
320
+ finishReason: null,
321
+ };
322
+ const callsByIndex = new Map();
323
+ // 打断时保留已收到的部分内容(半截回复对"取消后接着看"有价值);
324
+ // 一字节未得的中途取消则照常抛错。
325
+ try {
326
+ for await (const data of sseData(response.body, STREAM_IDLE_TIMEOUT_MS)) {
327
+ if (data === '[DONE]')
328
+ break;
329
+ let chunk;
330
+ try {
331
+ chunk = JSON.parse(data);
332
+ }
333
+ catch {
334
+ continue;
335
+ }
336
+ const choice = chunk.choices?.[0];
337
+ const delta = choice?.delta;
338
+ if (delta?.reasoning_content) {
339
+ result.reasoning += delta.reasoning_content;
340
+ handlers.onDelta('reasoning', delta.reasoning_content);
341
+ }
342
+ if (delta?.content) {
343
+ result.text += delta.content;
344
+ handlers.onDelta('text', delta.content);
345
+ }
346
+ for (const call of delta?.tool_calls ?? []) {
347
+ const existing = callsByIndex.get(call.index);
348
+ if (existing === undefined) {
349
+ const name = call.function?.name ?? '';
350
+ callsByIndex.set(call.index, {
351
+ id: call.id ?? '',
352
+ name,
353
+ arguments: call.function?.arguments ?? '',
354
+ });
355
+ // 首次拿到工具名就报一声「准备中」——参数这会儿多半还没开始到
356
+ if (name !== '')
357
+ handlers.onToolPrepare?.(name);
358
+ }
359
+ else {
360
+ if (call.id !== undefined && call.id !== '')
361
+ existing.id = call.id;
362
+ const name = call.function?.name;
363
+ if (name !== undefined && name !== '') {
364
+ // 名字也可能被分片切开:只在「从没有名字变成有名字」那一次报
365
+ if (existing.name === '')
366
+ handlers.onToolPrepare?.(name);
367
+ existing.name = name;
368
+ }
369
+ if (call.function?.arguments !== undefined)
370
+ existing.arguments += call.function.arguments;
371
+ }
372
+ }
373
+ if (choice?.finish_reason != null)
374
+ result.finishReason = choice.finish_reason;
375
+ if (chunk.usage != null) {
376
+ const input = chunk.usage.prompt_tokens ?? 0;
377
+ // 前缀缓存明细:DeepSeek 直接给 hit/miss 两个数;OpenAI 只给 cached_tokens,miss 自己减。
378
+ const hit = chunk.usage.prompt_cache_hit_tokens ?? chunk.usage.prompt_tokens_details?.cached_tokens;
379
+ const miss = chunk.usage.prompt_cache_miss_tokens ?? (hit === undefined ? undefined : Math.max(input - hit, 0));
380
+ result.usage = {
381
+ inputTokens: input,
382
+ outputTokens: chunk.usage.completion_tokens ?? 0,
383
+ ...(hit === undefined ? {} : { cacheHitTokens: hit }),
384
+ ...(miss === undefined ? {} : { cacheMissTokens: miss }),
385
+ };
386
+ }
387
+ }
388
+ }
389
+ catch (error) {
390
+ const partial = result.text !== '' || result.reasoning !== '' || callsByIndex.size > 0;
391
+ if (request.signal?.aborted !== true) {
392
+ // T33:流中断分两半——一个字节都没收到的按「连接失败」在 streamChat 重试;
393
+ // 已经收到内容的打包成 StreamInterruptedError 交上层落库,半截回复不能凭空消失。
394
+ const message = error instanceof Error ? error.message : String(error);
395
+ if (partial) {
396
+ throw new StreamInterruptedError(`流中断:${message}`, {
397
+ ...result,
398
+ toolCalls: [...callsByIndex.entries()].sort(([a], [b]) => a - b).map(([, call]) => call),
399
+ });
400
+ }
401
+ throw error instanceof LlmError
402
+ ? new LlmError(error.message, error.status, true, error.retryAfterMs)
403
+ : new LlmError(`流中断:${message}`, undefined, true);
404
+ }
405
+ if (!partial)
406
+ throw error;
407
+ result.finishReason = 'aborted';
408
+ }
409
+ finally {
410
+ request.signal?.removeEventListener('abort', onOuterAbort);
411
+ }
412
+ result.toolCalls = [...callsByIndex.entries()].sort(([a], [b]) => a - b).map(([, call]) => call);
413
+ return result;
414
+ }
415
+ /** assistant 消息重放:reasoning_content 回传保持模型思路连贯(dsh 同款)。 */
416
+ export function serializeMessages(messages) {
417
+ return messages.map((message) => {
418
+ // ts 是 dsc 自己记的时间戳(见 ChatMessage.ts):协议里没这一项,
419
+ // 整条透传会把它发给端点,挑字段的网关会判 400。其余字段照旧原样过,
420
+ // 不动别的插件往消息上挂的东西。
421
+ const wire = { ...message };
422
+ delete wire.ts;
423
+ if (wire.role !== 'assistant')
424
+ return wire;
425
+ return {
426
+ role: wire.role,
427
+ content: wire.content,
428
+ ...(wire.reasoning_content !== undefined && wire.reasoning_content !== ''
429
+ ? { reasoning_content: wire.reasoning_content }
430
+ : {}),
431
+ ...(wire.tool_calls !== undefined ? { tool_calls: wire.tool_calls } : {}),
432
+ };
433
+ });
434
+ }
435
+ /** 显式缓存断点的线上形状(Anthropic 系惯例)。 */
436
+ const EPHEMERAL = { type: 'ephemeral' };
437
+ /**
438
+ * 给已经序列化的消息打**显式前缀缓存**断点:Anthropic 系把缓存范围记在内容块的
439
+ * `cache_control: {type:'ephemeral'}` 上,命中到哪个块为止由它决定(ZCode 的做法:
440
+ * 稳定 system 一个 + 对话末尾一个,正好两处)。dsc 的系统提示词是一整条(fold-system
441
+ * 之后的形状),所以「稳定 / 动态」两个断点合并成头部这一个。
442
+ *
443
+ * 为什么单独一个函数而不是塞进 {@link serializeMessages}:只有**端点声明支持**时才该
444
+ * 打点。不开显式缓存的端点(当前唯一的 DeepSeek 系路由)走的是原路,请求体逐字节不变;
445
+ * 这条纪律由 `Request.cacheControl`(缺省 false)与探针钉死。
446
+ *
447
+ * 纯函数:不改输入数组与其中的消息对象,返回新数组。
448
+ *
449
+ * @param messages - {@link serializeMessages} 的输出(尚未 stringify)。
450
+ * @returns 打了断点的新数组;没有可打点的消息(空数组 / 全是角色不支持的消息)时原样返回。
451
+ */
452
+ export function applyExplicitCache(messages) {
453
+ if (messages.length === 0)
454
+ return messages;
455
+ // 断点位置:头部第一条 system(稳定前缀)与最后一条(对话末尾,缓存到本轮为止)。
456
+ const marks = new Set([messages.length - 1]);
457
+ for (let index = 0; index < messages.length; index += 1) {
458
+ const message = messages[index];
459
+ if (message?.role === 'system') {
460
+ marks.add(index);
461
+ break;
462
+ }
463
+ }
464
+ return messages.map((message, index) => {
465
+ if (!marks.has(index))
466
+ return message;
467
+ const wire = message;
468
+ const content = wire.content;
469
+ if (typeof content === 'string' && content !== '') {
470
+ // 字符串正文包成一个 text 块再挂断点:OpenAI 兼容网关认的是块形状。
471
+ return { ...message, content: [{ type: 'text', text: content, cache_control: EPHEMERAL }] };
472
+ }
473
+ if (Array.isArray(content) && content.length > 0) {
474
+ // 已经是块数组(多模态):断点挂在最后一块上,前面的块原样不动。
475
+ const blocks = [...content];
476
+ const lastBlock = blocks[blocks.length - 1];
477
+ blocks[blocks.length - 1] = { ...lastBlock, cache_control: EPHEMERAL };
478
+ return { ...message, content: blocks };
479
+ }
480
+ // 没有正文(例如只有 tool_calls 的 assistant 条)就没处挂断点:这条不打,原样过。
481
+ return message;
482
+ });
483
+ }
484
+ /** 连接超时(建连 + 响应头):卡死的端点不能把整轮拖死。 */
485
+ const CONNECT_TIMEOUT_MS = 30_000;
486
+ /** 流空闲超时:这么久一个字节都没到就判服务端挂起(SSE 心跳也是字节,会重置计时)。 */
487
+ const STREAM_IDLE_TIMEOUT_MS = 180_000;
488
+ /** Retry-After 头:秒数或 HTTP 日期;认不出返回 undefined(封顶 2 分钟,防服务端给个大数)。 */
489
+ function retryAfterMs(value) {
490
+ if (value === null || value.trim() === '')
491
+ return undefined;
492
+ const seconds = Number(value);
493
+ if (Number.isFinite(seconds) && seconds >= 0)
494
+ return Math.min(seconds * 1000, 120_000);
495
+ const at = Date.parse(value);
496
+ if (!Number.isNaN(at))
497
+ return Math.min(Math.max(at - Date.now(), 0), 120_000);
498
+ return undefined;
499
+ }
500
+ /** 读一块流数据;超过 idleMs 一个字节都没到就算服务端挂起(LlmError,不重试)。 */
501
+ async function readWithTimeout(readPromise, idleMs) {
502
+ let timer;
503
+ const idle = new Promise((_, reject) => {
504
+ timer = setTimeout(() => reject(new LlmError(`流空闲超过 ${Math.round(idleMs / 1000)} 秒,判定服务端挂起`, undefined, false)), idleMs);
505
+ });
506
+ try {
507
+ return await Promise.race([readPromise, idle]);
508
+ }
509
+ finally {
510
+ clearTimeout(timer);
511
+ }
512
+ }
513
+ /** 把 SSE 字节流切成 data 行。 */
514
+ async function* sseData(body, idleMs) {
515
+ const reader = body.getReader();
516
+ const decoder = new TextDecoder();
517
+ let buffer = '';
518
+ try {
519
+ for (;;) {
520
+ const { done, value } = await readWithTimeout(reader.read(), idleMs);
521
+ if (done)
522
+ break;
523
+ buffer += decoder.decode(value, { stream: true });
524
+ let newline = buffer.indexOf('\n');
525
+ while (newline >= 0) {
526
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
527
+ buffer = buffer.slice(newline + 1);
528
+ if (line.startsWith('data:'))
529
+ yield line.slice(5).trim();
530
+ newline = buffer.indexOf('\n');
531
+ }
532
+ }
533
+ }
534
+ finally {
535
+ // 提前结束([DONE] 或出错)也把连接收掉:不 cancel 的话 socket 要挂到 GC 才释放。
536
+ await reader.cancel(undefined).catch(() => { });
537
+ reader.releaseLock();
538
+ }
539
+ }
540
+ function delay(ms, signal) {
541
+ return new Promise((resolve, reject) => {
542
+ const timer = setTimeout(resolve, ms);
543
+ signal?.addEventListener('abort', () => {
544
+ clearTimeout(timer);
545
+ reject(signal.reason);
546
+ }, { once: true });
547
+ });
548
+ }
@@ -0,0 +1,17 @@
1
+ /** 锁文件后缀:追加在目标路径后面(`foo.jsonl` → `foo.jsonl.lock`)。 */
2
+ export declare const LOCK_SUFFIX = ".lock";
3
+ /** 一把握在手里的锁:长期持有的写租约用它自己调 `release()` 还锁。 */
4
+ export interface FileLock {
5
+ release(): void;
6
+ }
7
+ /**
8
+ * 拿一把长期持有的锁(写租约)。拿不到(别的进程活着握着)返回 null;主人已死或
9
+ * 锁文件读不出来(半截 JSON)就清掉陈锁接管。拿到的人负责调 `release()`,进程
10
+ * 崩溃留下的陈锁由下一个来的人按「主人已死」接管。
11
+ */
12
+ export declare function acquireLock(target: string): FileLock | null;
13
+ /**
14
+ * 短临界区:拿锁 → 跑 → 还锁;拿不到就抛 `busy` 给出的错误。
15
+ * 只包同步代码——跨进程的文件移动与读改写都是同步的,这正是它的服务对象。
16
+ */
17
+ export declare function withExclusiveLock<T>(target: string, busy: string, fn: () => T): T;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * 跨进程文件锁:`O_EXCL` 独占创建锁文件 + 锁内记 `pid + 进程指纹`,主人死了就接管。
3
+ *
4
+ * 用在哪:会话 jsonl 的写租约(两个 Pneuma 进程同开一个工作区,绝不能往同一份
5
+ * 对话日志里交错 append)与 meta.json 的读改写。调度器的 `.lock`(schedule/runner.ts)
6
+ * 是同一套思路的另一个实现——那边是长持有 + 只读降级,这边提供「短临界区」与「长租约」
7
+ * 两种姿势。个人版单机语义:不跨用户、不跨机器。
8
+ *
9
+ * 同一进程内可重入(计数持有):会话恢复链路上「load 新会话时旧会话还握着同一把锁」
10
+ * 是真实场景(同进程重复打开同一个会话),没有重入计数就是自己锁死自己。
11
+ *
12
+ * @module dsc/core/lockfile
13
+ */
14
+ import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
15
+ import { dirname } from 'node:path';
16
+ /** 本进程的启动指纹(模块加载时定死,进程内恒定)。 */
17
+ const BIRTH = Math.round(Date.now() - process.uptime() * 1000);
18
+ /** 本进程当前握着的锁(锁路径 → 重入计数)。 */
19
+ const held = new Map();
20
+ /** 锁文件后缀:追加在目标路径后面(`foo.jsonl` → `foo.jsonl.lock`)。 */
21
+ export const LOCK_SUFFIX = '.lock';
22
+ function isProcessAlive(pid) {
23
+ if (pid === process.pid)
24
+ return true;
25
+ try {
26
+ process.kill(pid, 0);
27
+ return true;
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /**
34
+ * 拿一把长期持有的锁(写租约)。拿不到(别的进程活着握着)返回 null;主人已死或
35
+ * 锁文件读不出来(半截 JSON)就清掉陈锁接管。拿到的人负责调 `release()`,进程
36
+ * 崩溃留下的陈锁由下一个来的人按「主人已死」接管。
37
+ */
38
+ export function acquireLock(target) {
39
+ const path = `${target}${LOCK_SUFFIX}`;
40
+ const reentered = held.get(path);
41
+ if (reentered !== undefined) {
42
+ held.set(path, reentered + 1);
43
+ return { release: () => dropLock(path) };
44
+ }
45
+ mkdirSync(dirname(path), { recursive: true });
46
+ for (let attempt = 0; attempt < 2; attempt += 1) {
47
+ try {
48
+ writeFileSync(path, JSON.stringify({ pid: process.pid, birth: BIRTH, at: Date.now() }), {
49
+ flag: 'wx',
50
+ });
51
+ held.set(path, 1);
52
+ return { release: () => dropLock(path) };
53
+ }
54
+ catch (error) {
55
+ if (error.code !== 'EEXIST')
56
+ return null; // 目录不可写等:按拿不到锁处理
57
+ }
58
+ // 锁已被占:主人活着就认输;死了(或锁读不出来)就清掉再抢一次
59
+ let stale = true;
60
+ try {
61
+ const info = JSON.parse(readFileSync(path, 'utf8'));
62
+ if (typeof info.pid === 'number' && isProcessAlive(info.pid))
63
+ stale = false;
64
+ }
65
+ catch {
66
+ // 半截 JSON 按陈锁处理
67
+ }
68
+ if (!stale)
69
+ return null;
70
+ try {
71
+ unlinkSync(path);
72
+ }
73
+ catch {
74
+ return null; // 抢手速没抢过对方(对方刚重建了锁):认输
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+ /** 归还一次重入;计数归零才真放锁。 */
80
+ function dropLock(path) {
81
+ const count = held.get(path);
82
+ if (count === undefined)
83
+ return;
84
+ if (count > 1) {
85
+ held.set(path, count - 1);
86
+ return;
87
+ }
88
+ held.delete(path);
89
+ try {
90
+ unlinkSync(path);
91
+ }
92
+ catch {
93
+ // 删不掉就算了:下一任按「主人已死」接管
94
+ }
95
+ }
96
+ /**
97
+ * 短临界区:拿锁 → 跑 → 还锁;拿不到就抛 `busy` 给出的错误。
98
+ * 只包同步代码——跨进程的文件移动与读改写都是同步的,这正是它的服务对象。
99
+ */
100
+ export function withExclusiveLock(target, busy, fn) {
101
+ const lock = acquireLock(target);
102
+ if (lock === null)
103
+ throw new Error(busy);
104
+ try {
105
+ return fn();
106
+ }
107
+ finally {
108
+ lock.release();
109
+ }
110
+ }