@uncarved/jade 0.1.2 → 0.2.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 (436) hide show
  1. package/bin/jade.js +5 -4
  2. package/dist/api.d.ts +266 -0
  3. package/dist/api.js +38 -0
  4. package/dist/api.js.map +1 -0
  5. package/dist/config.d.ts +13 -32
  6. package/dist/config.js +39 -121
  7. package/dist/config.js.map +1 -1
  8. package/dist/fetch.d.ts +20 -0
  9. package/dist/fetch.js +190 -0
  10. package/dist/fetch.js.map +1 -0
  11. package/dist/hash.d.ts +2 -0
  12. package/dist/hash.js +42 -0
  13. package/dist/hash.js.map +1 -0
  14. package/dist/host.d.ts +71 -0
  15. package/dist/host.js +400 -0
  16. package/dist/host.js.map +1 -0
  17. package/dist/index.d.ts +11 -28
  18. package/dist/index.js +11 -28
  19. package/dist/index.js.map +1 -1
  20. package/dist/install.d.ts +78 -0
  21. package/dist/install.js +292 -0
  22. package/dist/install.js.map +1 -0
  23. package/dist/main.d.ts +1 -2
  24. package/dist/main.js +156 -1223
  25. package/dist/main.js.map +1 -1
  26. package/dist/manifest.d.ts +23 -0
  27. package/dist/manifest.js +159 -0
  28. package/dist/manifest.js.map +1 -0
  29. package/dist/membrane.d.ts +33 -0
  30. package/dist/membrane.js +140 -0
  31. package/dist/membrane.js.map +1 -0
  32. package/dist/remote.d.ts +10 -0
  33. package/dist/remote.js +292 -0
  34. package/dist/remote.js.map +1 -0
  35. package/dist/rescue.d.ts +10 -0
  36. package/dist/rescue.js +216 -0
  37. package/dist/rescue.js.map +1 -0
  38. package/dist/resolve.d.ts +34 -0
  39. package/dist/resolve.js +178 -0
  40. package/dist/resolve.js.map +1 -0
  41. package/dist/rpc.d.ts +26 -0
  42. package/dist/rpc.js +144 -0
  43. package/dist/rpc.js.map +1 -0
  44. package/dist/secrets.d.ts +12 -0
  45. package/dist/secrets.js +125 -0
  46. package/dist/secrets.js.map +1 -0
  47. package/dist/session.d.ts +45 -0
  48. package/dist/session.js +401 -0
  49. package/dist/session.js.map +1 -0
  50. package/dist/source.d.ts +12 -0
  51. package/dist/source.js +72 -0
  52. package/dist/source.js.map +1 -0
  53. package/dist/state.d.ts +37 -0
  54. package/dist/state.js +93 -0
  55. package/dist/state.js.map +1 -0
  56. package/dist/update.d.ts +55 -0
  57. package/dist/update.js +258 -0
  58. package/dist/update.js.map +1 -0
  59. package/package.json +12 -9
  60. package/plugins/approval/index.ts +297 -0
  61. package/plugins/approval/plugin.json +18 -0
  62. package/{src/plugins → plugins/approval}/policy.ts +21 -84
  63. package/plugins/approval/review.ts +192 -0
  64. package/plugins/ask/index.ts +159 -0
  65. package/plugins/ask/plugin.json +8 -0
  66. package/plugins/budget/index.ts +38 -0
  67. package/plugins/budget/plugin.json +13 -0
  68. package/{src/plugins → plugins/checks}/checks.ts +68 -39
  69. package/plugins/checks/index.ts +158 -0
  70. package/plugins/checks/plugin.json +14 -0
  71. package/plugins/checks/project.ts +81 -0
  72. package/plugins/commands/index.ts +76 -0
  73. package/plugins/commands/plugin.json +7 -0
  74. package/{src/plugins → plugins/compact}/compact.ts +112 -38
  75. package/plugins/compact/index.ts +115 -0
  76. package/plugins/compact/plugin.json +17 -0
  77. package/plugins/compact/style.ts +17 -0
  78. package/plugins/continue/index.ts +58 -0
  79. package/plugins/continue/plugin.json +13 -0
  80. package/{src/ui → plugins/fs}/diff.ts +3 -4
  81. package/{src/tools → plugins/fs}/fs.ts +64 -46
  82. package/{src/tools → plugins/fs}/grep.ts +4 -3
  83. package/plugins/fs/index.ts +34 -0
  84. package/plugins/fs/plugin.json +7 -0
  85. package/plugins/fs/renderers.ts +138 -0
  86. package/plugins/fs/style.ts +18 -0
  87. package/plugins/fs/sys.ts +81 -0
  88. package/plugins/keys/index.ts +53 -0
  89. package/plugins/keys/plugin.json +7 -0
  90. package/plugins/mcp/index.ts +192 -0
  91. package/{src → plugins/mcp}/mcp.ts +32 -32
  92. package/plugins/mcp/plugin.json +7 -0
  93. package/plugins/mcp/project.ts +93 -0
  94. package/plugins/memory/index.ts +105 -0
  95. package/{src → plugins/memory}/memory.ts +20 -2
  96. package/plugins/memory/notes.ts +43 -0
  97. package/plugins/memory/plugin.json +7 -0
  98. package/plugins/memory/style.ts +17 -0
  99. package/plugins/mentions/attach.ts +127 -0
  100. package/plugins/mentions/index.ts +79 -0
  101. package/plugins/mentions/plugin.json +7 -0
  102. package/plugins/mentions/style.ts +17 -0
  103. package/plugins/models/config.ts +53 -0
  104. package/plugins/models/configure.ts +455 -0
  105. package/plugins/models/context.ts +32 -0
  106. package/plugins/models/index.ts +198 -0
  107. package/plugins/models/plugin.json +8 -0
  108. package/{src → plugins/models}/provider.ts +23 -27
  109. package/plugins/models/saved.ts +94 -0
  110. package/plugins/modes/index.ts +222 -0
  111. package/plugins/modes/plugin.json +9 -0
  112. package/plugins/plugins/index.ts +38 -0
  113. package/plugins/plugins/plugin.json +7 -0
  114. package/plugins/print/index.ts +142 -0
  115. package/plugins/print/plugin.json +8 -0
  116. package/plugins/prompts/index.ts +83 -0
  117. package/plugins/prompts/plugin.json +8 -0
  118. package/plugins/prompts/prompts.ts +253 -0
  119. package/plugins/prompts/sys.ts +72 -0
  120. package/plugins/renderers/index.ts +78 -0
  121. package/plugins/renderers/plugin.json +7 -0
  122. package/plugins/repeats/index.ts +165 -0
  123. package/plugins/repeats/plugin.json +6 -0
  124. package/plugins/schedule/cron.ts +74 -0
  125. package/plugins/schedule/index.ts +292 -0
  126. package/plugins/schedule/plugin.json +13 -0
  127. package/plugins/schedule/store.ts +149 -0
  128. package/plugins/scratch/index.ts +31 -0
  129. package/plugins/scratch/plugin.json +7 -0
  130. package/plugins/screenshot/index.ts +40 -0
  131. package/plugins/screenshot/plugin.json +7 -0
  132. package/plugins/screenshot/sys.ts +84 -0
  133. package/{src/tools/screenshot.ts → plugins/screenshot/tool.ts} +6 -6
  134. package/plugins/sessions/index.ts +148 -0
  135. package/plugins/sessions/plugin.json +8 -0
  136. package/plugins/shell/index.ts +33 -0
  137. package/plugins/shell/plugin.json +17 -0
  138. package/plugins/shell/renderers.ts +45 -0
  139. package/plugins/shell/service.ts +44 -0
  140. package/{src/tools → plugins/shell}/shell.ts +36 -21
  141. package/{src → plugins/shell}/sys.ts +19 -43
  142. package/plugins/skills/index.ts +96 -0
  143. package/plugins/skills/plugin.json +7 -0
  144. package/plugins/skills/project.ts +49 -0
  145. package/{src → plugins/skills}/skills.ts +4 -11
  146. package/plugins/suggest/index.ts +286 -0
  147. package/plugins/suggest/plugin.json +18 -0
  148. package/plugins/task/index.ts +167 -0
  149. package/plugins/task/plugin.json +15 -0
  150. package/plugins/task/style.ts +17 -0
  151. package/plugins/task/subagent.ts +257 -0
  152. package/{src/tools/todo.ts → plugins/todo/index.ts} +33 -7
  153. package/plugins/todo/plugin.json +7 -0
  154. package/{src/ui → plugins/tui}/editor.ts +53 -1
  155. package/plugins/tui/frontend.ts +596 -0
  156. package/plugins/tui/index.ts +37 -0
  157. package/{src/ui → plugins/tui}/markdown.ts +258 -219
  158. package/plugins/tui/mentions.ts +113 -0
  159. package/plugins/tui/plugin.json +10 -0
  160. package/plugins/tui/render.ts +67 -0
  161. package/plugins/tui/screen.ts +268 -0
  162. package/{src/ui → plugins/tui}/transcript.ts +179 -111
  163. package/{src/ui/tui.tsx → plugins/tui/tui.ts} +684 -418
  164. package/{src/tools → plugins/undo}/checkpoint.ts +21 -60
  165. package/plugins/undo/index.ts +139 -0
  166. package/plugins/undo/notes.ts +43 -0
  167. package/plugins/undo/plugin.json +7 -0
  168. package/plugins/undo/style.ts +17 -0
  169. package/plugins/update/index.ts +40 -0
  170. package/plugins/update/plugin.json +13 -0
  171. package/plugins/web/env.ts +78 -0
  172. package/plugins/web/index.ts +133 -0
  173. package/plugins/web/plugin.json +15 -0
  174. package/plugins/web/renderers.ts +11 -0
  175. package/plugins/web/web.ts +713 -0
  176. package/plugins-dist/approval/index.js +271 -0
  177. package/plugins-dist/approval/plugin.json +24 -0
  178. package/{dist/plugins → plugins-dist/approval}/policy.js +15 -65
  179. package/plugins-dist/approval/review.js +176 -0
  180. package/{dist/plugins → plugins-dist/approval}/schema.js +0 -1
  181. package/plugins-dist/ask/index.js +145 -0
  182. package/plugins-dist/ask/plugin.json +12 -0
  183. package/plugins-dist/budget/index.js +37 -0
  184. package/plugins-dist/budget/plugin.json +15 -0
  185. package/{dist/plugins → plugins-dist/checks}/checks.js +65 -34
  186. package/plugins-dist/checks/index.js +150 -0
  187. package/plugins-dist/checks/plugin.json +21 -0
  188. package/plugins-dist/checks/project.js +76 -0
  189. package/plugins-dist/commands/index.js +33 -0
  190. package/plugins-dist/commands/plugin.json +9 -0
  191. package/{dist/plugins → plugins-dist/compact}/compact.js +95 -33
  192. package/plugins-dist/compact/index.js +100 -0
  193. package/plugins-dist/compact/plugin.json +25 -0
  194. package/plugins-dist/compact/style.js +14 -0
  195. package/plugins-dist/continue/index.js +57 -0
  196. package/plugins-dist/continue/plugin.json +15 -0
  197. package/{dist/ui → plugins-dist/fs}/diff.js +3 -5
  198. package/{dist/tools → plugins-dist/fs}/fs.js +62 -46
  199. package/{dist/tools → plugins-dist/fs}/grep.js +4 -4
  200. package/plugins-dist/fs/index.js +36 -0
  201. package/plugins-dist/fs/plugin.json +10 -0
  202. package/plugins-dist/fs/renderers.js +132 -0
  203. package/plugins-dist/fs/style.js +15 -0
  204. package/plugins-dist/fs/sys.js +54 -0
  205. package/plugins-dist/keys/index.js +36 -0
  206. package/plugins-dist/keys/plugin.json +9 -0
  207. package/plugins-dist/mcp/index.js +187 -0
  208. package/{dist → plugins-dist/mcp}/mcp.js +34 -30
  209. package/plugins-dist/mcp/plugin.json +12 -0
  210. package/plugins-dist/mcp/project.js +90 -0
  211. package/plugins-dist/memory/index.js +94 -0
  212. package/{dist → plugins-dist/memory}/memory.js +21 -3
  213. package/plugins-dist/memory/notes.js +36 -0
  214. package/plugins-dist/memory/plugin.json +11 -0
  215. package/plugins-dist/memory/style.js +14 -0
  216. package/plugins-dist/mentions/attach.js +120 -0
  217. package/plugins-dist/mentions/index.js +69 -0
  218. package/plugins-dist/mentions/plugin.json +9 -0
  219. package/plugins-dist/mentions/style.js +14 -0
  220. package/plugins-dist/models/config.js +53 -0
  221. package/plugins-dist/models/configure.js +415 -0
  222. package/plugins-dist/models/context.js +27 -0
  223. package/plugins-dist/models/index.js +167 -0
  224. package/plugins-dist/models/plugin.json +14 -0
  225. package/{dist → plugins-dist/models}/provider.js +22 -19
  226. package/plugins-dist/models/saved.js +80 -0
  227. package/plugins-dist/modes/index.js +190 -0
  228. package/plugins-dist/modes/plugin.json +18 -0
  229. package/plugins-dist/plugins/index.js +37 -0
  230. package/plugins-dist/plugins/plugin.json +10 -0
  231. package/plugins-dist/print/index.js +153 -0
  232. package/plugins-dist/print/plugin.json +14 -0
  233. package/plugins-dist/prompts/index.js +57 -0
  234. package/plugins-dist/prompts/plugin.json +13 -0
  235. package/plugins-dist/prompts/prompts.js +227 -0
  236. package/plugins-dist/prompts/sys.js +46 -0
  237. package/plugins-dist/renderers/index.js +36 -0
  238. package/plugins-dist/renderers/plugin.json +9 -0
  239. package/plugins-dist/repeats/index.js +165 -0
  240. package/plugins-dist/repeats/plugin.json +6 -0
  241. package/plugins-dist/schedule/cron.js +67 -0
  242. package/plugins-dist/schedule/index.js +281 -0
  243. package/plugins-dist/schedule/plugin.json +16 -0
  244. package/plugins-dist/schedule/store.js +125 -0
  245. package/plugins-dist/scratch/index.js +26 -0
  246. package/plugins-dist/scratch/plugin.json +10 -0
  247. package/plugins-dist/screenshot/index.js +35 -0
  248. package/plugins-dist/screenshot/plugin.json +11 -0
  249. package/plugins-dist/screenshot/sys.js +76 -0
  250. package/{dist/tools/screenshot.js → plugins-dist/screenshot/tool.js} +5 -4
  251. package/plugins-dist/sessions/index.js +136 -0
  252. package/plugins-dist/sessions/plugin.json +12 -0
  253. package/plugins-dist/shell/index.js +33 -0
  254. package/plugins-dist/shell/plugin.json +19 -0
  255. package/plugins-dist/shell/renderers.js +40 -0
  256. package/plugins-dist/shell/service.js +29 -0
  257. package/{dist/tools → plugins-dist/shell}/shell.js +36 -23
  258. package/{dist → plugins-dist/shell}/sys.js +20 -44
  259. package/plugins-dist/skills/index.js +90 -0
  260. package/plugins-dist/skills/plugin.json +12 -0
  261. package/plugins-dist/skills/project.js +47 -0
  262. package/{dist → plugins-dist/skills}/skills.js +3 -7
  263. package/plugins-dist/suggest/index.js +282 -0
  264. package/plugins-dist/suggest/plugin.json +23 -0
  265. package/plugins-dist/task/index.js +151 -0
  266. package/plugins-dist/task/plugin.json +23 -0
  267. package/plugins-dist/task/style.js +14 -0
  268. package/plugins-dist/task/subagent.js +208 -0
  269. package/{dist/tools/todo.js → plugins-dist/todo/index.js} +29 -7
  270. package/plugins-dist/todo/plugin.json +9 -0
  271. package/{dist/ui → plugins-dist/tui}/editor.js +53 -2
  272. package/plugins-dist/tui/frontend.js +586 -0
  273. package/{dist → plugins-dist/tui}/history.js +0 -1
  274. package/plugins-dist/tui/index.js +21 -0
  275. package/{dist/ui → plugins-dist/tui}/markdown.js +57 -20
  276. package/plugins-dist/tui/mentions.js +115 -0
  277. package/plugins-dist/tui/plugin.json +25 -0
  278. package/plugins-dist/tui/render.js +61 -0
  279. package/plugins-dist/tui/screen.js +201 -0
  280. package/{dist/ui → plugins-dist/tui}/transcript.js +179 -111
  281. package/{dist/ui → plugins-dist/tui}/tui.js +484 -101
  282. package/{dist/tools → plugins-dist/undo}/checkpoint.js +21 -55
  283. package/plugins-dist/undo/index.js +140 -0
  284. package/plugins-dist/undo/notes.js +36 -0
  285. package/plugins-dist/undo/plugin.json +9 -0
  286. package/plugins-dist/undo/style.js +14 -0
  287. package/plugins-dist/update/index.js +34 -0
  288. package/plugins-dist/update/plugin.json +15 -0
  289. package/plugins-dist/web/env.js +80 -0
  290. package/plugins-dist/web/index.js +124 -0
  291. package/plugins-dist/web/plugin.json +21 -0
  292. package/plugins-dist/web/renderers.js +7 -0
  293. package/plugins-dist/web/web.js +660 -0
  294. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  295. package/sdk/python/jade_plugin.py +380 -0
  296. package/src/api.ts +298 -0
  297. package/src/config.ts +32 -134
  298. package/src/fetch.ts +216 -0
  299. package/src/hash.ts +39 -0
  300. package/src/host.ts +429 -0
  301. package/src/index.ts +23 -28
  302. package/src/install.ts +355 -0
  303. package/src/main.ts +152 -1263
  304. package/src/manifest.ts +160 -0
  305. package/src/membrane.ts +142 -0
  306. package/src/remote.ts +288 -0
  307. package/src/rescue.ts +217 -0
  308. package/src/resolve.ts +199 -0
  309. package/src/rpc.ts +144 -0
  310. package/src/secrets.ts +122 -0
  311. package/src/session.ts +458 -0
  312. package/src/source.ts +83 -0
  313. package/src/state.ts +120 -0
  314. package/src/update.ts +265 -0
  315. package/LICENSE +0 -21
  316. package/README.md +0 -198
  317. package/dist/commands.d.ts +0 -30
  318. package/dist/commands.js +0 -106
  319. package/dist/commands.js.map +0 -1
  320. package/dist/context.d.ts +0 -17
  321. package/dist/context.js +0 -53
  322. package/dist/context.js.map +0 -1
  323. package/dist/distro.d.ts +0 -104
  324. package/dist/distro.js +0 -312
  325. package/dist/distro.js.map +0 -1
  326. package/dist/history.d.ts +0 -10
  327. package/dist/history.js.map +0 -1
  328. package/dist/mcp.d.ts +0 -114
  329. package/dist/mcp.js.map +0 -1
  330. package/dist/memory.d.ts +0 -19
  331. package/dist/memory.js.map +0 -1
  332. package/dist/mentions.d.ts +0 -35
  333. package/dist/mentions.js +0 -130
  334. package/dist/mentions.js.map +0 -1
  335. package/dist/plugin-cli.d.ts +0 -16
  336. package/dist/plugin-cli.js +0 -251
  337. package/dist/plugin-cli.js.map +0 -1
  338. package/dist/plugins/budget.d.ts +0 -9
  339. package/dist/plugins/budget.js +0 -30
  340. package/dist/plugins/budget.js.map +0 -1
  341. package/dist/plugins/builtins.d.ts +0 -10
  342. package/dist/plugins/builtins.js +0 -22
  343. package/dist/plugins/builtins.js.map +0 -1
  344. package/dist/plugins/checks.d.ts +0 -70
  345. package/dist/plugins/checks.js.map +0 -1
  346. package/dist/plugins/compact.d.ts +0 -26
  347. package/dist/plugins/compact.js.map +0 -1
  348. package/dist/plugins/core.d.ts +0 -42
  349. package/dist/plugins/core.js +0 -190
  350. package/dist/plugins/core.js.map +0 -1
  351. package/dist/plugins/install.d.ts +0 -68
  352. package/dist/plugins/install.js +0 -377
  353. package/dist/plugins/install.js.map +0 -1
  354. package/dist/plugins/loader.d.ts +0 -182
  355. package/dist/plugins/loader.js +0 -253
  356. package/dist/plugins/loader.js.map +0 -1
  357. package/dist/plugins/policy.d.ts +0 -96
  358. package/dist/plugins/policy.js.map +0 -1
  359. package/dist/plugins/prompts.d.ts +0 -38
  360. package/dist/plugins/prompts.js +0 -196
  361. package/dist/plugins/prompts.js.map +0 -1
  362. package/dist/plugins/repeats.d.ts +0 -9
  363. package/dist/plugins/repeats.js +0 -90
  364. package/dist/plugins/repeats.js.map +0 -1
  365. package/dist/plugins/review.d.ts +0 -16
  366. package/dist/plugins/review.js +0 -92
  367. package/dist/plugins/review.js.map +0 -1
  368. package/dist/plugins/schema.d.ts +0 -2
  369. package/dist/plugins/schema.js.map +0 -1
  370. package/dist/provider.d.ts +0 -111
  371. package/dist/provider.js.map +0 -1
  372. package/dist/sessions.d.ts +0 -22
  373. package/dist/sessions.js +0 -53
  374. package/dist/sessions.js.map +0 -1
  375. package/dist/skills.d.ts +0 -37
  376. package/dist/skills.js.map +0 -1
  377. package/dist/sys.d.ts +0 -48
  378. package/dist/sys.js.map +0 -1
  379. package/dist/tools/checkpoint.d.ts +0 -43
  380. package/dist/tools/checkpoint.js.map +0 -1
  381. package/dist/tools/fs.d.ts +0 -35
  382. package/dist/tools/fs.js.map +0 -1
  383. package/dist/tools/grep.d.ts +0 -6
  384. package/dist/tools/grep.js.map +0 -1
  385. package/dist/tools/screenshot.d.ts +0 -15
  386. package/dist/tools/screenshot.js.map +0 -1
  387. package/dist/tools/shell.d.ts +0 -55
  388. package/dist/tools/shell.js.map +0 -1
  389. package/dist/tools/task.d.ts +0 -35
  390. package/dist/tools/task.js +0 -89
  391. package/dist/tools/task.js.map +0 -1
  392. package/dist/tools/todo.d.ts +0 -10
  393. package/dist/tools/todo.js.map +0 -1
  394. package/dist/tools/web.d.ts +0 -23
  395. package/dist/tools/web.js +0 -426
  396. package/dist/tools/web.js.map +0 -1
  397. package/dist/ui/configure.d.ts +0 -20
  398. package/dist/ui/configure.js +0 -378
  399. package/dist/ui/configure.js.map +0 -1
  400. package/dist/ui/diff.d.ts +0 -20
  401. package/dist/ui/diff.js.map +0 -1
  402. package/dist/ui/editor.d.ts +0 -33
  403. package/dist/ui/editor.js.map +0 -1
  404. package/dist/ui/markdown.d.ts +0 -17
  405. package/dist/ui/markdown.js.map +0 -1
  406. package/dist/ui/render.d.ts +0 -15
  407. package/dist/ui/render.js +0 -94
  408. package/dist/ui/render.js.map +0 -1
  409. package/dist/ui/screen.d.ts +0 -98
  410. package/dist/ui/screen.js +0 -108
  411. package/dist/ui/screen.js.map +0 -1
  412. package/dist/ui/transcript.d.ts +0 -33
  413. package/dist/ui/transcript.js.map +0 -1
  414. package/dist/ui/tui.d.ts +0 -45
  415. package/dist/ui/tui.js.map +0 -1
  416. package/src/commands.ts +0 -120
  417. package/src/context.ts +0 -64
  418. package/src/distro.ts +0 -400
  419. package/src/mentions.ts +0 -135
  420. package/src/plugin-cli.ts +0 -239
  421. package/src/plugins/budget.ts +0 -37
  422. package/src/plugins/builtins.ts +0 -31
  423. package/src/plugins/core.ts +0 -217
  424. package/src/plugins/install.ts +0 -429
  425. package/src/plugins/loader.ts +0 -386
  426. package/src/plugins/prompts.ts +0 -234
  427. package/src/plugins/repeats.ts +0 -96
  428. package/src/plugins/review.ts +0 -109
  429. package/src/sessions.ts +0 -61
  430. package/src/tools/task.ts +0 -109
  431. package/src/tools/web.ts +0 -451
  432. package/src/ui/configure.ts +0 -408
  433. package/src/ui/render.ts +0 -83
  434. package/src/ui/screen.ts +0 -169
  435. /package/{src/plugins → plugins/approval}/schema.ts +0 -0
  436. /package/{src → plugins/tui}/history.ts +0 -0
package/src/rescue.ts ADDED
@@ -0,0 +1,217 @@
1
+ // 救援 CLI:jade plugins list|add|update|remove|enable|disable。
2
+ // 只读写 plugins.json、faults.json、安装记录、信任存储和插件目录,不执行任何插件代码(5.4)。
3
+
4
+ import path from "node:path";
5
+ import type { TrustStore } from "uncarved";
6
+ import { readPluginManifest } from "./fetch.ts";
7
+ import { planPlugins, type HostOptions } from "./host.ts";
8
+ import { addPlugin, forgetPluginState, installDir, readRecords, removePlugin, updatePlugins, type InstallRecord, type UpdateResult } from "./install.ts";
9
+ import { forgetFaults, readFaults, readPluginsConfig, writeFaults, writePluginsConfig } from "./state.ts";
10
+
11
+ const USAGE = `usage: jade plugins <command>
12
+
13
+ list every plugin's state, services, and where it was installed from
14
+ add <source> [options] install a plugin
15
+ <source>: a local directory, an npm package (name, name@version, @scope/name,
16
+ npm:<spec>, a .tgz), or a git repository (https://…, git@…,
17
+ github:user/repo, user/repo; add #branch, #tag or #commit at the end)
18
+ --project install into <cwd>/.jade/plugins instead of $JADE_HOME/plugins
19
+ --path <dir> use this subdirectory of the source
20
+ --link local directory: link it instead of copying (for plugin development)
21
+ --force replace a plugin with the same id
22
+ update [id…] [--project] [--force] fetch again what "jade plugins add" installed
23
+ (all of them when no id is given); --force replaces local edits
24
+ remove <id> [--project] delete an installed plugin
25
+ disable <id> stop loading a plugin
26
+ enable <id> undo disable
27
+
28
+ Installing never runs the plugin's code; dependencies are installed with --ignore-scripts.`;
29
+
30
+ export type PluginsCommandOptions = Pick<HostOptions, "roots" | "home" | "flags" | "safe"> & {
31
+ /** 项目层插件的信任记录;--project 安装时用它记下内容哈希 */
32
+ trust?: TrustStore;
33
+ /** 下载进度,写到 stderr */
34
+ log?: (text: string) => void;
35
+ };
36
+
37
+ interface ParsedArgs {
38
+ positionals: string[];
39
+ project: boolean;
40
+ link: boolean;
41
+ force: boolean;
42
+ path?: string;
43
+ help: boolean;
44
+ }
45
+
46
+ /** 执行一条 plugins 子命令,返回要打印的文字;用法错误时抛错 */
47
+ export async function pluginsCommand(args: readonly string[], opts: PluginsCommandOptions): Promise<string> {
48
+ if (args[0] === "-h" || args[0] === "--help") return USAGE;
49
+ const [sub = "list", ...tail] = args;
50
+ const parsed = parseArgs(tail);
51
+ if (parsed.help) return USAGE;
52
+
53
+ switch (sub) {
54
+ case "list":
55
+ case "ls":
56
+ if (parsed.positionals.length > 0 || parsed.project || parsed.link || parsed.force || parsed.path) throw new Error(USAGE);
57
+ return list(opts);
58
+ case "add":
59
+ case "install": {
60
+ if (parsed.positionals.length !== 1) throw new Error(USAGE);
61
+ const installed = await addPlugin(parsed.positionals[0]!, {
62
+ root: installRoot(opts, parsed),
63
+ cwd: process.cwd(),
64
+ ...(parsed.path ? { subdir: parsed.path } : {}),
65
+ ...(parsed.link ? { link: true } : {}),
66
+ ...(parsed.force ? { force: true } : {}),
67
+ project: parsed.project,
68
+ ...(opts.trust ? { trust: opts.trust } : {}),
69
+ ...(opts.log ? { log: opts.log } : {}),
70
+ });
71
+ const wasDisabled = await forgetPluginState(opts.home, installed.id);
72
+ let text = `installed ${installed.id}@${installed.version} into ${installed.dir}`;
73
+ if (installed.record.kind !== "local") text += ` (${origin(installed.record)})`;
74
+ if (wasDisabled) text += `\n${installed.id} was disabled; installing it enabled it again.`;
75
+ if (parsed.project) text += `\nproject plugin: it will run with your permissions in this repository.`;
76
+ return text;
77
+ }
78
+ case "update":
79
+ case "upgrade": {
80
+ if (parsed.link || parsed.path) throw new Error(USAGE);
81
+ const results = await updatePlugins(parsed.positionals, {
82
+ root: installRoot(opts, parsed),
83
+ cwd: process.cwd(),
84
+ ...(parsed.force ? { force: true } : {}),
85
+ project: parsed.project,
86
+ ...(opts.trust ? { trust: opts.trust } : {}),
87
+ ...(opts.log ? { log: opts.log } : {}),
88
+ });
89
+ // 更新之后清掉连续崩溃记录;用户显式停用的仍然保持停用
90
+ for (const r of results) if (r.status === "updated") await forgetFaults(opts.home, r.id);
91
+ const lines = results.map(describe);
92
+ if (results.some((r) => r.status === "updated")) lines.push("restart jade to load the new versions.");
93
+ return lines.length > 0 ? lines.join("\n") : 'no plugins were installed with "jade plugins add"';
94
+ }
95
+ case "remove":
96
+ case "rm":
97
+ case "uninstall": {
98
+ if (parsed.positionals.length !== 1 || parsed.link || parsed.force || parsed.path) throw new Error(USAGE);
99
+ const id = parsed.positionals[0]!;
100
+ const root = installRoot(opts, parsed);
101
+ // 停用记录按插件 id;给的是目录名时先读清单换成 id
102
+ const manifest = await readPluginManifest(installDir(root, id)).catch(() => undefined);
103
+ const dir = await removePlugin(id, { root });
104
+ await forgetPluginState(opts.home, manifest?.id ?? id);
105
+ return `removed ${id} (${dir})`;
106
+ }
107
+ case "disable":
108
+ case "enable": {
109
+ if (parsed.positionals.length !== 1 || parsed.project || parsed.link || parsed.force || parsed.path) throw new Error(USAGE);
110
+ return enableOrDisable(sub, parsed.positionals[0]!, opts);
111
+ }
112
+ default:
113
+ throw new Error(USAGE);
114
+ }
115
+ }
116
+
117
+ async function enableOrDisable(sub: "enable" | "disable", id: string, opts: PluginsCommandOptions): Promise<string> {
118
+ const { plan } = await planPlugins(opts);
119
+ const known = plan.entries.some((e) => e.source.manifest.id === id);
120
+ const config = await readPluginsConfig(opts.home);
121
+ if (sub === "disable") {
122
+ if (!config.disabled.includes(id)) config.disabled.push(id);
123
+ await writePluginsConfig(opts.home, config);
124
+ return known ? `disabled ${id}` : `disabled ${id} (no installed plugin has this id)`;
125
+ }
126
+ config.disabled = config.disabled.filter((d) => d !== id);
127
+ await writePluginsConfig(opts.home, config);
128
+ // 同时清掉连续崩溃的记录,否则下次启动又被自动停用
129
+ const faults = await readFaults(opts.home);
130
+ faults.autoDisabled = faults.autoDisabled.filter((d) => d !== id);
131
+ delete faults.streaks[id];
132
+ await writeFaults(opts.home, faults);
133
+ return known ? `enabled ${id}` : `enabled ${id} (no installed plugin has this id)`;
134
+ }
135
+
136
+ /** 用户层插件的目录(`jade plugins add` 默认装到这里) */
137
+ const userRoot = (opts: Pick<HostOptions, "roots">): string =>
138
+ opts.roots.find((r) => r.layer === "user")?.root ?? path.join(process.env.JADE_HOME ?? "", "plugins");
139
+
140
+ const projectRoot = (opts: Pick<HostOptions, "roots">): string =>
141
+ opts.roots.find((r) => r.layer === "project")?.root ?? path.join(process.cwd(), ".jade", "plugins");
142
+
143
+ const installRoot = (opts: Pick<HostOptions, "roots">, parsed: ParsedArgs): string => (parsed.project ? projectRoot(opts) : userRoot(opts));
144
+
145
+ function parseArgs(tail: readonly string[]): ParsedArgs {
146
+ const out: ParsedArgs = { positionals: [], project: false, link: false, force: false, help: false };
147
+ for (let i = 0; i < tail.length; i++) {
148
+ const a = tail[i]!;
149
+ const value = (name: string) => {
150
+ const v = tail[++i];
151
+ if (v === undefined) throw new Error(`${name} needs a value\n${USAGE}`);
152
+ return v;
153
+ };
154
+ if (a === "--project") out.project = true;
155
+ else if (a === "--link") out.link = true;
156
+ else if (a === "--force" || a === "-f") out.force = true;
157
+ else if (a === "--path") out.path = value(a);
158
+ else if (a.startsWith("--path=")) out.path = a.slice("--path=".length);
159
+ else if (a === "-h" || a === "--help") out.help = true;
160
+ else if (a.startsWith("-")) throw new Error(`unknown option ${a}\n${USAGE}`);
161
+ else out.positionals.push(a);
162
+ }
163
+ return out;
164
+ }
165
+
166
+ function describe(r: UpdateResult): string {
167
+ switch (r.status) {
168
+ case "updated": {
169
+ if (r.from && r.to && r.from !== r.to) return `updated ${r.id} ${r.from} → ${r.to}`;
170
+ return `updated ${r.id}${r.to ? ` (${r.to})` : ""}`;
171
+ }
172
+ case "current":
173
+ return `current ${r.id}${r.to ? ` (${r.to})` : ""}`;
174
+ case "linked":
175
+ return `linked ${r.id} (local directory; nothing to fetch)`;
176
+ case "unmanaged":
177
+ case "modified":
178
+ case "failed":
179
+ return `${r.id}: ${r.error}`;
180
+ }
181
+ }
182
+
183
+ /** 按清单和状态文件推算出的状态:不激活插件,所以看不到激活阶段的失败(那些记在连续崩溃次数里) */
184
+ async function list(opts: PluginsCommandOptions): Promise<string> {
185
+ const { plan, broken, faults } = await planPlugins(opts);
186
+ const records = new Map<string, InstallRecord>();
187
+ for (const { root } of opts.roots) {
188
+ for (const rec of Object.values(await readRecords(root))) records.set(rec.id, rec);
189
+ }
190
+
191
+ const lines: string[] = [];
192
+ for (const e of plan.entries) {
193
+ const m = e.source.manifest;
194
+ const streak = faults.streaks[m.id];
195
+ const note = e.reason ?? (streak ? `faulted in the last ${streak.count} launch(es): ${streak.last}` : "");
196
+ const rec = records.get(m.id);
197
+ lines.push(
198
+ `${m.id}@${m.version} ${e.source.layer} ${e.state}${note ? ` ${note}` : ""}${rec ? ` from ${origin(rec)}` : ""}`,
199
+ );
200
+ }
201
+ for (const b of broken) lines.push(`${b.dir} ${b.layer} broken ${b.error}`);
202
+ for (const w of plan.warnings) lines.push(`warning: ${w}`);
203
+ if (plan.providers.size > 0) {
204
+ lines.push("", "services:");
205
+ for (const [service, id] of [...plan.providers].sort()) lines.push(` ${service} ${id}`);
206
+ }
207
+ if (faults.unattributed.length > 0) lines.push("", `${faults.unattributed.length} recent error(s) not attributable to any plugin, see state/faults.json`);
208
+ return lines.length > 0 ? lines.join("\n") : "no plugins installed";
209
+ }
210
+
211
+ function origin(rec: InstallRecord): string {
212
+ if (rec.kind === "link") return `link ${rec.source}`;
213
+ const at = rec.commit ? `@${rec.commit.slice(0, 7)}` : "";
214
+ if (rec.kind === "npm") return `${rec.source.startsWith("npm:") ? rec.source : `npm ${rec.source}`}${at}`;
215
+ if (rec.kind === "git") return `${rec.source.startsWith("git+") ? rec.source : `git ${rec.source}`}${at}`;
216
+ return `${rec.source}${at}`;
217
+ }
package/src/resolve.ts ADDED
@@ -0,0 +1,199 @@
1
+ // 由清单算出激活计划:哪些插件激活、按什么顺序、每个服务由谁提供(3.3、3.4)。
2
+ // 纯函数,不执行插件代码;运行期间计划不变(原则 4)。
3
+
4
+ import { LAYERS, type PluginSource } from "./api.ts";
5
+ import { satisfiesCaret } from "./manifest.ts";
6
+
7
+ /** 计划阶段的状态。激活之后宿主还会把状态改成 failed 或 quarantined */
8
+ export type PlanState = "active" | "disabled" | "duplicate" | "incompatible" | "replaced" | "conflict" | "skipped";
9
+
10
+ export interface PlanEntry {
11
+ source: PluginSource;
12
+ state: PlanState;
13
+ reason?: string;
14
+ /** 意料之中的跳过:没选中的前端,以及只因为它而缺依赖的插件。启动时不提示 */
15
+ expected?: boolean;
16
+ }
17
+
18
+ export interface Plan {
19
+ /** 发现顺序,包括没有激活的 */
20
+ entries: PlanEntry[];
21
+ /** 激活顺序:依赖在前 */
22
+ order: PluginSource[];
23
+ /** 服务名 → 提供者 id */
24
+ providers: Map<string, string>;
25
+ /** 选中的前端插件 id */
26
+ frontend?: string;
27
+ /** 不影响激活、但用户应该知道的事 */
28
+ warnings: string[];
29
+ }
30
+
31
+ export interface ResolveOptions {
32
+ apiVersion: string;
33
+ /** 按 id 停用的插件 */
34
+ disabled?: ReadonlySet<string>;
35
+ /** 安全模式:只加载 bundled(5.4) */
36
+ safe?: boolean;
37
+ /** 命令行开关,用来选前端 */
38
+ flags?: readonly string[];
39
+ /** 核心自己提供的服务(jade@1):插件可以在 requires 里写,别人的 provides 不能占用这个名字 */
40
+ coreServices?: readonly string[];
41
+ }
42
+
43
+ const rank = (e: PlanEntry) => LAYERS.indexOf(e.source.layer);
44
+
45
+ export function resolve(sources: readonly PluginSource[], opts: ResolveOptions): Plan {
46
+ const warnings: string[] = [];
47
+ const entries: PlanEntry[] = [];
48
+ const byId = new Map<string, PlanEntry>();
49
+ const core = new Set(opts.coreServices ?? []);
50
+ const out = (e: PlanEntry, state: PlanState, reason: string) => {
51
+ e.state = state;
52
+ e.reason = reason;
53
+ };
54
+ const live = () => entries.filter((e) => e.state === "active");
55
+
56
+ // 1. 身份、停用、兼容性
57
+ for (const source of sources) {
58
+ const { id, api } = source.manifest;
59
+ const e: PlanEntry = { source, state: "active" };
60
+ entries.push(e);
61
+ const first = byId.get(id);
62
+ if (first) out(e, "duplicate", `id ${id} is already used by ${first.source.dir}`);
63
+ else byId.set(id, e);
64
+ if (e.state !== "active") continue;
65
+ // 核心自己提供的服务不能被插件占用(host 会拒绝 provide,这里提前说明)
66
+ const taken = (source.manifest.provides ?? []).filter((s) => core.has(s));
67
+ if (opts.safe && source.layer !== "bundled") out(e, "disabled", "safe mode");
68
+ else if (opts.disabled?.has(id)) out(e, "disabled", "disabled in plugins.json");
69
+ else if (taken.length > 0) out(e, "conflict", `${taken.join(", ")} is provided by jade itself`);
70
+ else if (!satisfiesCaret(api, opts.apiVersion)) out(e, "incompatible", `requires plugin API ${api}, running ${opts.apiVersion}`);
71
+ }
72
+
73
+ // 2. 显式代替:项目层不能代替用户层或 bundled(第 7 节)
74
+ for (const e of live()) {
75
+ for (const target of e.source.manifest.replaces ?? []) {
76
+ const t = byId.get(target);
77
+ if (!t || t === e) {
78
+ warnings.push(`${e.source.manifest.id}: replaces unknown plugin ${target}`);
79
+ } else if (e.source.layer === "project" && t.source.layer !== "project") {
80
+ warnings.push(`${e.source.manifest.id}: a project plugin cannot replace ${t.source.layer} plugin ${target}; ignored`);
81
+ } else if (t.state === "active") {
82
+ out(t, "replaced", `replaced by ${e.source.manifest.id}`);
83
+ }
84
+ }
85
+ }
86
+
87
+ // 3. 选前端:有命令行开关匹配的选它,否则选 default;没选中的前端不激活
88
+ const fronts = live().filter((e) => e.source.manifest.frontend);
89
+ const flagged = fronts.filter((e) => opts.flags?.includes(e.source.manifest.frontend!.flag ?? "\0"));
90
+ const chosen = new Set(flagged.length > 0 ? flagged : fronts.filter((e) => e.source.manifest.frontend!.default));
91
+ for (const e of fronts) {
92
+ if (chosen.has(e)) continue;
93
+ out(e, "skipped", `frontend ${e.source.manifest.frontend!.name} is not selected`);
94
+ e.expected = true;
95
+ }
96
+
97
+ // 4. 服务裁决。先按层级排除低层(到不动点),再处理同层冲突
98
+ const providersOf = (service: string) => live().filter((e) => e.source.manifest.provides?.includes(service));
99
+ const services = () => [...new Set(live().flatMap((e) => e.source.manifest.provides ?? []))];
100
+ for (let changed = true; changed; ) {
101
+ changed = false;
102
+ for (const service of services()) {
103
+ const ps = providersOf(service);
104
+ if (ps.length < 2) continue;
105
+ const nonProject = ps.filter((e) => e.source.layer !== "project");
106
+ // 有用户层或 bundled 提供者时,项目层的提供者出局
107
+ const pool = nonProject.length > 0 ? nonProject : ps;
108
+ for (const e of ps) {
109
+ if (!pool.includes(e)) {
110
+ out(e, "conflict", `a project plugin cannot override the ${nonProject[0]!.source.layer} provider of ${service} (${nonProject[0]!.source.manifest.id})`);
111
+ changed = true;
112
+ }
113
+ }
114
+ const top = Math.max(...pool.map(rank));
115
+ for (const e of pool) {
116
+ if (rank(e) < top) {
117
+ const winner = pool.find((p) => rank(p) === top)!;
118
+ out(e, "replaced", `${service} is provided by ${winner.source.manifest.id} (${winner.source.layer})`);
119
+ changed = true;
120
+ }
121
+ }
122
+ }
123
+ }
124
+ for (const service of services()) {
125
+ const ps = providersOf(service);
126
+ if (ps.length < 2) continue;
127
+ const ids = ps.map((e) => e.source.manifest.id).join(", ");
128
+ for (const e of ps) out(e, "conflict", `${service} is provided by several ${e.source.layer} plugins (${ids}); disable all but one`);
129
+ }
130
+
131
+ // 5. 依赖与顺序。缺依赖的跳过;成环的跳过;直到不动点
132
+ for (;;) {
133
+ const providers = new Map<string, PlanEntry>();
134
+ for (const e of live()) for (const s of e.source.manifest.provides ?? []) providers.set(s, e);
135
+ let changed = false;
136
+ for (const e of live()) {
137
+ for (const need of e.source.manifest.requires ?? []) {
138
+ if (providers.has(need) || core.has(need)) continue;
139
+ const why = entries.find((x) => x.source.manifest.provides?.includes(need));
140
+ out(e, "skipped", why ? `requires ${need}: its provider ${why.source.manifest.id} is ${why.state}` : `requires ${need}, which no plugin provides`);
141
+ if (why?.expected) e.expected = true;
142
+ changed = true;
143
+ break;
144
+ }
145
+ }
146
+ if (changed) continue;
147
+
148
+ const order = topo(live(), providers);
149
+ if (order.cycle.length > 0) {
150
+ const ids = order.cycle.map((e) => e.source.manifest.id).join(", ");
151
+ for (const e of order.cycle) out(e, "skipped", `dependency cycle: ${ids}`);
152
+ continue;
153
+ }
154
+ const map = new Map([...providers].map(([s, e]) => [s, e.source.manifest.id]));
155
+ // 核心自己提供的服务也列出来,`jade plugins list` 才看得全
156
+ for (const s of core) map.set(s, "jade");
157
+ const frontend = live().find((e) => e.source.manifest.frontend)?.source.manifest.id;
158
+ return { entries, order: order.sorted.map((e) => e.source), providers: map, warnings, ...(frontend ? { frontend } : {}) };
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Kahn 算法,同等条件下保持发现顺序。
164
+ * optional 的依赖是软的:排不下去时,挡住它的只剩 optional 依赖的插件先激活(按发现顺序取第一个),
165
+ * 它在 process() 里取那些服务时得到 undefined,session() 和之后的调用里能拿到。只有 requires 组成的环才算成环
166
+ */
167
+ function topo(nodes: PlanEntry[], providers: Map<string, PlanEntry>): { sorted: PlanEntry[]; cycle: PlanEntry[] } {
168
+ const edges = (e: PlanEntry, list: readonly string[] | undefined) => {
169
+ const ds = new Set<PlanEntry>();
170
+ for (const s of list ?? []) {
171
+ const p = providers.get(s);
172
+ if (p && p !== e) ds.add(p);
173
+ }
174
+ return ds;
175
+ };
176
+ const hard = new Map(nodes.map((e) => [e, edges(e, e.source.manifest.requires)]));
177
+ const soft = new Map(nodes.map((e) => [e, edges(e, e.source.manifest.optional)]));
178
+ const sorted: PlanEntry[] = [];
179
+ const left = new Set(nodes);
180
+ const waiting = (e: PlanEntry, map: Map<PlanEntry, Set<PlanEntry>>) => [...map.get(e)!].some((d) => left.has(d));
181
+ const take = (e: PlanEntry) => {
182
+ sorted.push(e);
183
+ left.delete(e);
184
+ };
185
+ while (left.size > 0) {
186
+ let progress = false;
187
+ for (const e of nodes) {
188
+ if (!left.has(e) || waiting(e, hard) || waiting(e, soft)) continue;
189
+ take(e);
190
+ progress = true;
191
+ }
192
+ if (progress) continue;
193
+ const relaxed = nodes.find((e) => left.has(e) && !waiting(e, hard));
194
+ if (!relaxed) break;
195
+ take(relaxed);
196
+ }
197
+ // 剩下的插件里,只有自己在 requires 环上或依赖环上插件的才算;这里一并跳过
198
+ return { sorted, cycle: [...left] };
199
+ }
package/src/rpc.ts ADDED
@@ -0,0 +1,144 @@
1
+ // JSON-RPC 2.0,一行一条(第 6 节)。按 LF 切分,不用 readline:它会在 U+2028/2029 处切开。
2
+ // 双向:两边都可以发请求。传输(子进程的管道)由调用方接上。
3
+
4
+ export interface RpcError {
5
+ code: number;
6
+ message: string;
7
+ data?: unknown;
8
+ }
9
+
10
+ /** 收到的请求或通知的处理函数。signal 在对方发来 $/cancel 或连接关闭时中止 */
11
+ export type RpcHandler = (method: string, params: unknown, signal: AbortSignal) => unknown;
12
+
13
+ interface Pending {
14
+ resolve(v: unknown): void;
15
+ reject(e: unknown): void;
16
+ }
17
+
18
+ export class Rpc {
19
+ readonly #write: (line: string) => void;
20
+ readonly #handle: RpcHandler;
21
+ readonly #pending = new Map<number, Pending>();
22
+ readonly #incoming = new Map<number | string, AbortController>();
23
+ #next = 1;
24
+ #buf = "";
25
+ #closed: Error | undefined;
26
+ /** 对方发来的不是协议消息的行 */
27
+ onGarbage: ((line: string) => void) | undefined;
28
+
29
+ constructor(write: (line: string) => void, handle: RpcHandler) {
30
+ this.#write = write;
31
+ this.#handle = handle;
32
+ }
33
+
34
+ /** 喂进对方发来的文本(已按 UTF-8 解码) */
35
+ feed(chunk: string): void {
36
+ this.#buf += chunk;
37
+ for (let i = this.#buf.indexOf("\n"); i !== -1; i = this.#buf.indexOf("\n")) {
38
+ const line = this.#buf.slice(0, i).replace(/\r$/, "");
39
+ this.#buf = this.#buf.slice(i + 1);
40
+ if (line.trim()) this.#receive(line);
41
+ }
42
+ }
43
+
44
+ /** 发请求;signal 中止时发 $/cancel,并以 signal.reason 拒绝 */
45
+ request(method: string, params: unknown, signal?: AbortSignal): Promise<unknown> {
46
+ if (this.#closed) return Promise.reject(this.#closed);
47
+ if (signal?.aborted) return Promise.reject(signal.reason);
48
+ const id = this.#next++;
49
+ return new Promise((resolve, reject) => {
50
+ const onAbort = () => {
51
+ if (!this.#pending.delete(id)) return;
52
+ this.#send({ jsonrpc: "2.0", method: "$/cancel", params: { id } });
53
+ reject(signal!.reason);
54
+ };
55
+ signal?.addEventListener("abort", onAbort, { once: true });
56
+ const done = () => signal?.removeEventListener("abort", onAbort);
57
+ this.#pending.set(id, {
58
+ resolve: (v) => {
59
+ done();
60
+ resolve(v);
61
+ },
62
+ reject: (e) => {
63
+ done();
64
+ reject(e);
65
+ },
66
+ });
67
+ this.#send({ jsonrpc: "2.0", id, method, params });
68
+ });
69
+ }
70
+
71
+ notify(method: string, params: unknown): void {
72
+ if (!this.#closed) this.#send({ jsonrpc: "2.0", method, params });
73
+ }
74
+
75
+ /** 连接断了:在途的请求全部以 reason 拒绝,对方的请求全部中止 */
76
+ close(reason: Error): void {
77
+ if (this.#closed) return;
78
+ this.#closed = reason;
79
+ for (const p of this.#pending.values()) p.reject(reason);
80
+ this.#pending.clear();
81
+ for (const c of this.#incoming.values()) c.abort(reason);
82
+ this.#incoming.clear();
83
+ }
84
+
85
+ #send(msg: object): void {
86
+ if (this.#closed) return;
87
+ try {
88
+ this.#write(`${JSON.stringify(msg)}\n`);
89
+ } catch (e) {
90
+ this.close(e instanceof Error ? e : new Error(String(e)));
91
+ }
92
+ }
93
+
94
+ #receive(line: string): void {
95
+ let msg: { id?: number | string | null; method?: unknown; params?: unknown; result?: unknown; error?: RpcError };
96
+ try {
97
+ msg = JSON.parse(line);
98
+ } catch {
99
+ this.onGarbage?.(line);
100
+ return;
101
+ }
102
+ if (typeof msg !== "object" || msg === null) return this.onGarbage?.(line);
103
+ if (typeof msg.method === "string") {
104
+ if (msg.method === "$/cancel") {
105
+ const id = (msg.params as { id?: number | string } | undefined)?.id;
106
+ if (id !== undefined) this.#incoming.get(id)?.abort(new Error("cancelled by the plugin"));
107
+ return;
108
+ }
109
+ void this.#serve(msg.id ?? undefined, msg.method, msg.params);
110
+ return;
111
+ }
112
+ if (typeof msg.id !== "number") return this.onGarbage?.(line);
113
+ const p = this.#pending.get(msg.id);
114
+ if (!p) return;
115
+ this.#pending.delete(msg.id);
116
+ if (msg.error) p.reject(new RemoteError(msg.error));
117
+ else p.resolve(msg.result ?? null);
118
+ }
119
+
120
+ async #serve(id: number | string | undefined, method: string, params: unknown): Promise<void> {
121
+ const ctrl = new AbortController();
122
+ if (id !== undefined) this.#incoming.set(id, ctrl);
123
+ try {
124
+ const result = await this.#handle(method, params, ctrl.signal);
125
+ if (id !== undefined) this.#send({ jsonrpc: "2.0", id, result: result ?? null });
126
+ } catch (e) {
127
+ if (id !== undefined) this.#send({ jsonrpc: "2.0", id, error: { code: -32000, message: e instanceof Error ? e.message : String(e) } });
128
+ } finally {
129
+ if (id !== undefined) this.#incoming.delete(id);
130
+ }
131
+ }
132
+ }
133
+
134
+ /** 对方返回的错误 */
135
+ export class RemoteError extends Error {
136
+ readonly code: number;
137
+ readonly data: unknown;
138
+ constructor(e: RpcError) {
139
+ super(typeof e?.message === "string" ? e.message : "remote error");
140
+ this.name = "RemoteError";
141
+ this.code = typeof e?.code === "number" ? e.code : -32000;
142
+ this.data = e?.data;
143
+ }
144
+ }
package/src/secrets.ts ADDED
@@ -0,0 +1,122 @@
1
+ // 插件密钥(第 8 节):按插件 id 分开存在 $JADE_HOME/state/secrets/<id>.json。
2
+ //
3
+ // 只有插件自己的 ctx.secrets 能读写这一份;核心不把密钥放进配置,也不放进给进程外插件的环境变量。
4
+ // 文件写 0600(POSIX 上有效;Windows 上 chmod 只管理只读位),写入先落临时文件再改名。
5
+
6
+ import { randomBytes } from "node:crypto";
7
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { StaleContext, type Secrets } from "./api.ts";
10
+
11
+ /** 一个密钥名最多这么长;值是字符串,最多 1 MB */
12
+ const KEY_MAX = 256;
13
+ const VALUE_MAX = 1024 * 1024;
14
+
15
+ /** 每个插件的密钥存储;同一个 id 始终拿到同一个实例,写入才能串行 */
16
+ export class SecretsStore {
17
+ readonly #root: string;
18
+ readonly #plugins = new Map<string, Secrets>();
19
+
20
+ constructor(home: string) {
21
+ this.#root = path.join(home, "state", "secrets");
22
+ }
23
+
24
+ for(plugin: string): Secrets {
25
+ if (!plugin) throw new Error("secrets: plugin id is empty");
26
+ let secrets = this.#plugins.get(plugin);
27
+ if (!secrets) {
28
+ secrets = new PluginSecrets(this.#root, plugin);
29
+ this.#plugins.set(plugin, secrets);
30
+ }
31
+ return secrets;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 一个作用域里的 ctx.secrets:作用域关闭后再用旧 ctx 读写,抛 StaleContext,
37
+ * 和从旧 ctx 里拿到的服务一样(4.1)
38
+ */
39
+ export function scopedSecrets(base: Secrets, closed: () => boolean, plugin: string): Secrets {
40
+ return {
41
+ async get(key) {
42
+ if (closed()) throw new StaleContext(plugin);
43
+ return base.get(key);
44
+ },
45
+ async set(key, value) {
46
+ if (closed()) throw new StaleContext(plugin);
47
+ return base.set(key, value);
48
+ },
49
+ };
50
+ }
51
+
52
+ class PluginSecrets implements Secrets {
53
+ readonly #root: string;
54
+ readonly #plugin: string;
55
+ readonly #file: string;
56
+ /** 同一个插件的写入串行,避免两次 set 交错覆盖 */
57
+ #writing: Promise<void> = Promise.resolve();
58
+
59
+ constructor(root: string, plugin: string) {
60
+ this.#root = root;
61
+ this.#plugin = plugin;
62
+ this.#file = path.join(root, `${encodeURIComponent(plugin)}.json`);
63
+ }
64
+
65
+ async get(key: string): Promise<string | undefined> {
66
+ checkKey(key);
67
+ return (await this.#load())[key];
68
+ }
69
+
70
+ async set(key: string, value: string | undefined): Promise<void> {
71
+ checkKey(key);
72
+ if (value !== undefined) {
73
+ if (typeof value !== "string") throw new Error("secrets: value must be a string");
74
+ if (value.length > VALUE_MAX) throw new Error(`secrets: value is longer than ${VALUE_MAX} characters`);
75
+ }
76
+ // 读、改、写排在上一次写入之后:两次 set 不会互相覆盖。每次都从文件读,另一个 jade 进程写的不会丢
77
+ const run = this.#writing.then(async () => {
78
+ const data = await this.#load();
79
+ if (value === undefined) delete data[key];
80
+ else data[key] = value;
81
+ await this.#save(data);
82
+ });
83
+ this.#writing = run.catch(() => {});
84
+ await run;
85
+ }
86
+
87
+ async #load(): Promise<Record<string, string>> {
88
+ let raw: unknown;
89
+ try {
90
+ raw = JSON.parse(await readFile(this.#file, "utf8"));
91
+ } catch (e) {
92
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return Object.create(null) as Record<string, string>;
93
+ throw new Error(`secrets for ${this.#plugin} at ${this.#file}: ${e instanceof Error ? e.message : String(e)}`);
94
+ }
95
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
96
+ throw new Error(`secrets for ${this.#plugin} at ${this.#file}: expected a JSON object`);
97
+ }
98
+ // 用无原型对象:密钥名写成 __proto__ 也不会碰到原型
99
+ const data = Object.create(null) as Record<string, string>;
100
+ for (const [key, value] of Object.entries(raw)) if (typeof value === "string") data[key] = value;
101
+ return data;
102
+ }
103
+
104
+ async #save(data: Record<string, string>): Promise<void> {
105
+ await mkdir(this.#root, { recursive: true, mode: 0o700 });
106
+ await chmod(this.#root, 0o700).catch(() => {});
107
+ const tmp = `${this.#file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
108
+ try {
109
+ await writeFile(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
110
+ await rename(tmp, this.#file);
111
+ await chmod(this.#file, 0o600).catch(() => {});
112
+ } finally {
113
+ await rm(tmp, { force: true }).catch(() => {});
114
+ }
115
+ }
116
+ }
117
+
118
+ function checkKey(key: string): void {
119
+ if (typeof key !== "string" || key.length === 0) throw new Error("secrets: key must be a non-empty string");
120
+ if (key.length > KEY_MAX) throw new Error(`secrets: key is longer than ${KEY_MAX} characters`);
121
+ if (key.includes("\0")) throw new Error("secrets: key must not contain NUL");
122
+ }