@uncarved/jade 0.1.3 → 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 (450) hide show
  1. package/bin/jade.js +5 -27
  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 -30
  18. package/dist/index.js +11 -30
  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 +159 -1362
  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 +2 -0
  57. package/dist/update.js +6 -3
  58. package/dist/update.js.map +1 -1
  59. package/package.json +10 -8
  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 -100
  63. package/{src/plugins → plugins/approval}/review.ts +62 -16
  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 +48 -38
  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 +73 -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 +2 -2
  81. package/{src/tools → plugins/fs}/fs.ts +19 -42
  82. package/{src/tools → plugins/fs}/grep.ts +1 -1
  83. package/plugins/fs/index.ts +34 -0
  84. package/plugins/fs/plugin.json +7 -0
  85. package/{src/ui → plugins/fs}/renderers.ts +25 -70
  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 +16 -119
  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 +31 -20
  141. package/{src → plugins/shell}/sys.ts +2 -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 +3 -0
  155. package/plugins/tui/frontend.ts +596 -0
  156. package/plugins/tui/index.ts +37 -0
  157. package/plugins/tui/mentions.ts +113 -0
  158. package/plugins/tui/plugin.json +10 -0
  159. package/{src/ui → plugins/tui}/render.ts +8 -2
  160. package/{src/ui → plugins/tui}/screen.ts +8 -3
  161. package/{src/ui → plugins/tui}/transcript.ts +74 -99
  162. package/{src/ui/tui.tsx → plugins/tui/tui.ts} +358 -387
  163. package/{src/tools → plugins/undo}/checkpoint.ts +21 -60
  164. package/plugins/undo/index.ts +139 -0
  165. package/plugins/undo/notes.ts +43 -0
  166. package/plugins/undo/plugin.json +7 -0
  167. package/plugins/undo/style.ts +17 -0
  168. package/plugins/update/index.ts +40 -0
  169. package/plugins/update/plugin.json +13 -0
  170. package/plugins/web/env.ts +78 -0
  171. package/plugins/web/index.ts +133 -0
  172. package/plugins/web/plugin.json +15 -0
  173. package/plugins/web/renderers.ts +11 -0
  174. package/{src/tools → plugins/web}/web.ts +58 -26
  175. package/plugins-dist/approval/index.js +271 -0
  176. package/plugins-dist/approval/plugin.json +24 -0
  177. package/{dist/plugins → plugins-dist/approval}/policy.js +15 -81
  178. package/{dist/plugins → plugins-dist/approval}/review.js +56 -10
  179. package/{dist/plugins → plugins-dist/approval}/schema.js +0 -1
  180. package/plugins-dist/ask/index.js +145 -0
  181. package/plugins-dist/ask/plugin.json +12 -0
  182. package/plugins-dist/budget/index.js +37 -0
  183. package/plugins-dist/budget/plugin.json +15 -0
  184. package/{dist/plugins → plugins-dist/checks}/checks.js +46 -35
  185. package/plugins-dist/checks/index.js +150 -0
  186. package/plugins-dist/checks/plugin.json +21 -0
  187. package/plugins-dist/checks/project.js +76 -0
  188. package/plugins-dist/commands/index.js +33 -0
  189. package/plugins-dist/commands/plugin.json +9 -0
  190. package/{dist/plugins → plugins-dist/compact}/compact.js +51 -33
  191. package/plugins-dist/compact/index.js +100 -0
  192. package/plugins-dist/compact/plugin.json +25 -0
  193. package/plugins-dist/compact/style.js +14 -0
  194. package/plugins-dist/continue/index.js +57 -0
  195. package/plugins-dist/continue/plugin.json +15 -0
  196. package/{dist/ui → plugins-dist/fs}/diff.js +2 -3
  197. package/{dist/tools → plugins-dist/fs}/fs.js +17 -42
  198. package/{dist/tools → plugins-dist/fs}/grep.js +1 -2
  199. package/plugins-dist/fs/index.js +36 -0
  200. package/plugins-dist/fs/plugin.json +10 -0
  201. package/{dist/ui → plugins-dist/fs}/renderers.js +24 -61
  202. package/plugins-dist/fs/style.js +15 -0
  203. package/plugins-dist/fs/sys.js +54 -0
  204. package/plugins-dist/keys/index.js +36 -0
  205. package/plugins-dist/keys/plugin.json +9 -0
  206. package/plugins-dist/mcp/index.js +187 -0
  207. package/{dist → plugins-dist/mcp}/mcp.js +34 -30
  208. package/plugins-dist/mcp/plugin.json +12 -0
  209. package/plugins-dist/mcp/project.js +90 -0
  210. package/plugins-dist/memory/index.js +94 -0
  211. package/{dist → plugins-dist/memory}/memory.js +21 -3
  212. package/plugins-dist/memory/notes.js +36 -0
  213. package/plugins-dist/memory/plugin.json +11 -0
  214. package/plugins-dist/memory/style.js +14 -0
  215. package/plugins-dist/mentions/attach.js +120 -0
  216. package/plugins-dist/mentions/index.js +69 -0
  217. package/plugins-dist/mentions/plugin.json +9 -0
  218. package/plugins-dist/mentions/style.js +14 -0
  219. package/plugins-dist/models/config.js +53 -0
  220. package/plugins-dist/models/configure.js +415 -0
  221. package/plugins-dist/models/context.js +27 -0
  222. package/plugins-dist/models/index.js +167 -0
  223. package/plugins-dist/models/plugin.json +14 -0
  224. package/{dist → plugins-dist/models}/provider.js +18 -81
  225. package/plugins-dist/models/saved.js +80 -0
  226. package/plugins-dist/modes/index.js +190 -0
  227. package/plugins-dist/modes/plugin.json +18 -0
  228. package/plugins-dist/plugins/index.js +37 -0
  229. package/plugins-dist/plugins/plugin.json +10 -0
  230. package/plugins-dist/print/index.js +153 -0
  231. package/plugins-dist/print/plugin.json +14 -0
  232. package/plugins-dist/prompts/index.js +57 -0
  233. package/plugins-dist/prompts/plugin.json +13 -0
  234. package/plugins-dist/prompts/prompts.js +227 -0
  235. package/plugins-dist/prompts/sys.js +46 -0
  236. package/plugins-dist/renderers/index.js +36 -0
  237. package/plugins-dist/renderers/plugin.json +9 -0
  238. package/plugins-dist/repeats/index.js +165 -0
  239. package/plugins-dist/repeats/plugin.json +6 -0
  240. package/plugins-dist/schedule/cron.js +67 -0
  241. package/plugins-dist/schedule/index.js +281 -0
  242. package/plugins-dist/schedule/plugin.json +16 -0
  243. package/plugins-dist/schedule/store.js +125 -0
  244. package/plugins-dist/scratch/index.js +26 -0
  245. package/plugins-dist/scratch/plugin.json +10 -0
  246. package/plugins-dist/screenshot/index.js +35 -0
  247. package/plugins-dist/screenshot/plugin.json +11 -0
  248. package/plugins-dist/screenshot/sys.js +76 -0
  249. package/{dist/tools/screenshot.js → plugins-dist/screenshot/tool.js} +5 -4
  250. package/plugins-dist/sessions/index.js +136 -0
  251. package/plugins-dist/sessions/plugin.json +12 -0
  252. package/plugins-dist/shell/index.js +33 -0
  253. package/plugins-dist/shell/plugin.json +19 -0
  254. package/plugins-dist/shell/renderers.js +40 -0
  255. package/plugins-dist/shell/service.js +29 -0
  256. package/{dist/tools → plugins-dist/shell}/shell.js +31 -22
  257. package/{dist → plugins-dist/shell}/sys.js +2 -43
  258. package/plugins-dist/skills/index.js +90 -0
  259. package/plugins-dist/skills/plugin.json +12 -0
  260. package/plugins-dist/skills/project.js +47 -0
  261. package/{dist → plugins-dist/skills}/skills.js +3 -7
  262. package/plugins-dist/suggest/index.js +282 -0
  263. package/plugins-dist/suggest/plugin.json +23 -0
  264. package/plugins-dist/task/index.js +151 -0
  265. package/plugins-dist/task/plugin.json +23 -0
  266. package/plugins-dist/task/style.js +14 -0
  267. package/plugins-dist/task/subagent.js +208 -0
  268. package/{dist/tools/todo.js → plugins-dist/todo/index.js} +29 -7
  269. package/plugins-dist/todo/plugin.json +9 -0
  270. package/{dist/ui → plugins-dist/tui}/editor.js +3 -1
  271. package/plugins-dist/tui/frontend.js +586 -0
  272. package/{dist → plugins-dist/tui}/history.js +0 -1
  273. package/plugins-dist/tui/index.js +21 -0
  274. package/{dist/ui → plugins-dist/tui}/markdown.js +0 -1
  275. package/plugins-dist/tui/mentions.js +115 -0
  276. package/plugins-dist/tui/plugin.json +25 -0
  277. package/{dist/ui → plugins-dist/tui}/render.js +7 -3
  278. package/{dist/ui → plugins-dist/tui}/screen.js +6 -2
  279. package/{dist/ui → plugins-dist/tui}/transcript.js +76 -98
  280. package/{dist/ui → plugins-dist/tui}/tui.js +185 -53
  281. package/{dist/tools → plugins-dist/undo}/checkpoint.js +21 -55
  282. package/plugins-dist/undo/index.js +140 -0
  283. package/plugins-dist/undo/notes.js +36 -0
  284. package/plugins-dist/undo/plugin.json +9 -0
  285. package/plugins-dist/undo/style.js +14 -0
  286. package/plugins-dist/update/index.js +34 -0
  287. package/plugins-dist/update/plugin.json +15 -0
  288. package/plugins-dist/web/env.js +80 -0
  289. package/plugins-dist/web/index.js +124 -0
  290. package/plugins-dist/web/plugin.json +21 -0
  291. package/plugins-dist/web/renderers.js +7 -0
  292. package/{dist/tools → plugins-dist/web}/web.js +50 -24
  293. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  294. package/sdk/python/jade_plugin.py +380 -0
  295. package/src/api.ts +298 -0
  296. package/src/config.ts +32 -134
  297. package/src/fetch.ts +216 -0
  298. package/src/hash.ts +39 -0
  299. package/src/host.ts +429 -0
  300. package/src/index.ts +23 -30
  301. package/src/install.ts +355 -0
  302. package/src/main.ts +155 -1387
  303. package/src/manifest.ts +160 -0
  304. package/src/membrane.ts +142 -0
  305. package/src/remote.ts +288 -0
  306. package/src/rescue.ts +217 -0
  307. package/src/resolve.ts +199 -0
  308. package/src/rpc.ts +144 -0
  309. package/src/secrets.ts +122 -0
  310. package/src/session.ts +458 -0
  311. package/src/source.ts +83 -0
  312. package/src/state.ts +120 -0
  313. package/src/update.ts +265 -262
  314. package/LICENSE +0 -21
  315. package/README.md +0 -204
  316. package/dist/commands.d.ts +0 -50
  317. package/dist/commands.js +0 -126
  318. package/dist/commands.js.map +0 -1
  319. package/dist/context.d.ts +0 -17
  320. package/dist/context.js +0 -53
  321. package/dist/context.js.map +0 -1
  322. package/dist/distro.d.ts +0 -141
  323. package/dist/distro.js +0 -462
  324. package/dist/distro.js.map +0 -1
  325. package/dist/history.d.ts +0 -10
  326. package/dist/history.js.map +0 -1
  327. package/dist/mcp.d.ts +0 -114
  328. package/dist/mcp.js.map +0 -1
  329. package/dist/memory.d.ts +0 -19
  330. package/dist/memory.js.map +0 -1
  331. package/dist/mentions.d.ts +0 -35
  332. package/dist/mentions.js +0 -130
  333. package/dist/mentions.js.map +0 -1
  334. package/dist/plugin-cli.d.ts +0 -16
  335. package/dist/plugin-cli.js +0 -294
  336. package/dist/plugin-cli.js.map +0 -1
  337. package/dist/plugins/budget.d.ts +0 -9
  338. package/dist/plugins/budget.js +0 -30
  339. package/dist/plugins/budget.js.map +0 -1
  340. package/dist/plugins/builtins.d.ts +0 -10
  341. package/dist/plugins/builtins.js +0 -25
  342. package/dist/plugins/builtins.js.map +0 -1
  343. package/dist/plugins/checks.d.ts +0 -71
  344. package/dist/plugins/checks.js.map +0 -1
  345. package/dist/plugins/compact.d.ts +0 -26
  346. package/dist/plugins/compact.js.map +0 -1
  347. package/dist/plugins/core.d.ts +0 -47
  348. package/dist/plugins/core.js +0 -229
  349. package/dist/plugins/core.js.map +0 -1
  350. package/dist/plugins/host.d.ts +0 -52
  351. package/dist/plugins/host.js +0 -115
  352. package/dist/plugins/host.js.map +0 -1
  353. package/dist/plugins/install.d.ts +0 -68
  354. package/dist/plugins/install.js +0 -377
  355. package/dist/plugins/install.js.map +0 -1
  356. package/dist/plugins/loader.d.ts +0 -410
  357. package/dist/plugins/loader.js +0 -407
  358. package/dist/plugins/loader.js.map +0 -1
  359. package/dist/plugins/policy.d.ts +0 -98
  360. package/dist/plugins/policy.js.map +0 -1
  361. package/dist/plugins/prompts.d.ts +0 -43
  362. package/dist/plugins/prompts.js +0 -284
  363. package/dist/plugins/prompts.js.map +0 -1
  364. package/dist/plugins/repeats.d.ts +0 -16
  365. package/dist/plugins/repeats.js +0 -151
  366. package/dist/plugins/repeats.js.map +0 -1
  367. package/dist/plugins/review.d.ts +0 -18
  368. package/dist/plugins/review.js.map +0 -1
  369. package/dist/plugins/schema.d.ts +0 -2
  370. package/dist/plugins/schema.js.map +0 -1
  371. package/dist/plugins/sessions.d.ts +0 -7
  372. package/dist/plugins/sessions.js +0 -110
  373. package/dist/plugins/sessions.js.map +0 -1
  374. package/dist/provider.d.ts +0 -165
  375. package/dist/provider.js.map +0 -1
  376. package/dist/session-lifecycle.d.ts +0 -61
  377. package/dist/session-lifecycle.js +0 -167
  378. package/dist/session-lifecycle.js.map +0 -1
  379. package/dist/session-scope.d.ts +0 -53
  380. package/dist/session-scope.js +0 -116
  381. package/dist/session-scope.js.map +0 -1
  382. package/dist/sessions.d.ts +0 -28
  383. package/dist/sessions.js +0 -73
  384. package/dist/sessions.js.map +0 -1
  385. package/dist/skills.d.ts +0 -37
  386. package/dist/skills.js.map +0 -1
  387. package/dist/sys.d.ts +0 -51
  388. package/dist/sys.js.map +0 -1
  389. package/dist/tools/ask.d.ts +0 -11
  390. package/dist/tools/ask.js +0 -62
  391. package/dist/tools/ask.js.map +0 -1
  392. package/dist/tools/checkpoint.d.ts +0 -43
  393. package/dist/tools/checkpoint.js.map +0 -1
  394. package/dist/tools/fs.d.ts +0 -39
  395. package/dist/tools/fs.js.map +0 -1
  396. package/dist/tools/grep.d.ts +0 -6
  397. package/dist/tools/grep.js.map +0 -1
  398. package/dist/tools/screenshot.d.ts +0 -15
  399. package/dist/tools/screenshot.js.map +0 -1
  400. package/dist/tools/shell.d.ts +0 -55
  401. package/dist/tools/shell.js.map +0 -1
  402. package/dist/tools/task.d.ts +0 -39
  403. package/dist/tools/task.js +0 -117
  404. package/dist/tools/task.js.map +0 -1
  405. package/dist/tools/todo.d.ts +0 -10
  406. package/dist/tools/todo.js.map +0 -1
  407. package/dist/tools/web.d.ts +0 -53
  408. package/dist/tools/web.js.map +0 -1
  409. package/dist/ui/configure.d.ts +0 -20
  410. package/dist/ui/configure.js +0 -447
  411. package/dist/ui/configure.js.map +0 -1
  412. package/dist/ui/diff.d.ts +0 -20
  413. package/dist/ui/diff.js.map +0 -1
  414. package/dist/ui/editor.d.ts +0 -41
  415. package/dist/ui/editor.js.map +0 -1
  416. package/dist/ui/markdown.d.ts +0 -22
  417. package/dist/ui/markdown.js.map +0 -1
  418. package/dist/ui/render.d.ts +0 -14
  419. package/dist/ui/render.js.map +0 -1
  420. package/dist/ui/renderers.d.ts +0 -8
  421. package/dist/ui/renderers.js.map +0 -1
  422. package/dist/ui/screen.d.ts +0 -118
  423. package/dist/ui/screen.js.map +0 -1
  424. package/dist/ui/transcript.d.ts +0 -46
  425. package/dist/ui/transcript.js.map +0 -1
  426. package/dist/ui/tui.d.ts +0 -47
  427. package/dist/ui/tui.js.map +0 -1
  428. package/src/commands.ts +0 -144
  429. package/src/context.ts +0 -64
  430. package/src/distro.ts +0 -577
  431. package/src/mentions.ts +0 -135
  432. package/src/plugin-cli.ts +0 -278
  433. package/src/plugins/budget.ts +0 -37
  434. package/src/plugins/builtins.ts +0 -34
  435. package/src/plugins/core.ts +0 -257
  436. package/src/plugins/host.ts +0 -146
  437. package/src/plugins/install.ts +0 -429
  438. package/src/plugins/loader.ts +0 -742
  439. package/src/plugins/prompts.ts +0 -327
  440. package/src/plugins/repeats.ts +0 -157
  441. package/src/plugins/sessions.ts +0 -109
  442. package/src/session-lifecycle.ts +0 -194
  443. package/src/session-scope.ts +0 -135
  444. package/src/sessions.ts +0 -78
  445. package/src/tools/ask.ts +0 -72
  446. package/src/tools/task.ts +0 -149
  447. package/src/ui/configure.ts +0 -471
  448. /package/{src/plugins → plugins/approval}/schema.ts +0 -0
  449. /package/{src → plugins/tui}/history.ts +0 -0
  450. /package/{src/ui → plugins/tui}/markdown.ts +0 -0
package/src/main.ts CHANGED
@@ -1,1426 +1,194 @@
1
- #!/usr/bin/env -S bun --no-env-file
2
- // jade:基于 uncarved 内核的编程 Agent 命令行宿主。
3
- //
4
- // 宿主负责内核不管的事:配置目录、会话索引、项目层插件的确认、审批界面、渲染、中断。
5
- // 不读当前目录的 .env(见 config.ts):模型配置放在 $JADE_HOME/.env。
6
- // 交互运行时用终端界面(ui/tui.tsx),-p 和非交互运行时逐行输出(ui/screen.ts)。
1
+ // jade 命令行入口:解析核心自己的参数,启动插件宿主,把控制权交给前端插件(3.4)。
2
+ // 核心自己只处理 jade plugins …、jade update、--safe、--version(以及把 jade remove x 这类漏了 plugins 的写法挡下来);其余参数原样交给前端。
7
3
 
8
- import { mkdtemp, readdir, stat } from "node:fs/promises";
4
+ import { existsSync, readFileSync } from "node:fs";
9
5
  import os from "node:os";
10
6
  import path from "node:path";
11
- import { createHash } from "node:crypto";
12
- import { stripVTControlCharacters } from "node:util";
13
- import { JsonlLogStore, JsonlTrustStore } from "@uncarved/store-jsonl";
14
- import {
15
- readAll,
16
- Runtime,
17
- RuntimeBusy,
18
- type Block,
19
- type Plugin,
20
- type Provider,
21
- type UserInput,
22
- } from "uncarved";
23
- import { realpathSync } from "node:fs";
24
- import { expandCommand, loadCommands, pluginMenu } from "./commands.ts";
25
- import { type PluginBundle, type SessionControl } from "./plugins/loader.ts";
26
- import { openPluginHost } from "./plugins/host.ts";
27
- import { readPluginSettings } from "./plugins/install.ts";
28
- import { PLUGIN_HELP, pluginCli, UsageError } from "./plugin-cli.ts";
29
- import { describeServer, loadMcpConfig, McpClient, mcpTrustHash } from "./mcp.ts";
30
- import { loadSkills } from "./skills.ts";
31
- import { hasProvider, loadEnvFile, parseTokens, updateEnvFile } from "./config.ts";
32
- import { createJade, type Jade } from "./distro.ts";
33
- import { SessionScope } from "./session-scope.ts";
34
- import { SessionLifecycle, type Current } from "./session-lifecycle.ts";
35
- import { describeRule, MODES, POLICY_KEY, type AllowRule, type Mode, type PolicySettings } from "./plugins/policy.ts";
36
- import { compactThreshold, contextWindowFromEnv, contextWindowInfo, isContextOverflow } from "./context.ts";
37
- import { InputHistory } from "./history.ts";
38
- import { attachMentions, mentionCandidates } from "./mentions.ts";
39
- import { repoRoot } from "./plugins/prompts.ts";
40
- import { isBuiltinKind, isRateLimit, pluginProvider, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, switchable, withRetry } from "./provider.ts";
41
- import { ago, discardIfEmpty, matchSession, SessionIndex } from "./sessions.ts";
42
- import { display } from "./tools/fs.ts";
43
- import type { ApproveSubagent, SubagentApproval } from "./tools/task.ts";
44
- import type { Question } from "./tools/ask.ts";
45
- import type { Check } from "./plugins/checks.ts";
46
- import { bold, dim, green, plainScreen, red, safeScreen, yellow, type CommandInfo, type Screen } from "./ui/screen.ts";
47
- import { configurator } from "./ui/configure.ts";
48
- import { reviewer } from "./plugins/review.ts";
49
- import { clip, shortPath } from "./ui/render.ts";
50
- import { transcript } from "./ui/transcript.ts";
51
- import { run, VERSION } from "./sys.ts";
52
- import { autoUpdate, autoUpdateEnabled, detectInstall, newerVersion, updateCli } from "./update.ts";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import type { TrustOptions } from "uncarved";
10
+ import type { Frontend, UI } from "./api.ts";
11
+ import { PluginHost, type HostOptions } from "./host.ts";
12
+ import type { LayerRoot } from "./manifest.ts";
13
+ import { pluginsCommand } from "./rescue.ts";
14
+ import { FileTrustStore } from "./state.ts";
15
+ import { updateCli } from "./update.ts";
53
16
 
54
- const HELP = `Usage: jade [options] [prompt]
55
- jade plugin <list|add|update|remove|enable|disable> (jade plugin --help)
56
- jade update [--check] upgrade jade to the latest version on npm
17
+ /** 连续两次 Ctrl+C 间隔不超过它时,核心直接退出(第 7 节) */
18
+ const DOUBLE_SIGINT_MS = 2000;
57
19
 
58
- -p, --print <prompt> run one prompt and exit
59
- -c, --continue continue the most recent session in this directory
60
- -r, --resume [id] resume a session by id, or pick one from a list
61
- -m, --mode <mode> permission mode for this run: ${MODES.join(" | ")} (default: the last mode you switched to, or ask)
62
- --cwd <dir> working directory (default: current directory)
63
- -v, --version
64
- -h, --help
20
+ const USAGE = `usage: jade [--safe] [frontend options…]
21
+ jade plugins [list | add <source> | update [id…] | remove <id> | enable <id> | disable <id>] [options]
22
+ jade update [--check] upgrade jade itself to the latest version on npm
65
23
 
66
- Type / in the session for commands; /model configures the model.
67
- Model settings are read from $JADE_HOME/.env, and data lives in $JADE_HOME (default ~/.jade).
68
- Instructions are read from AGENTS.md (or CLAUDE.md) in $JADE_HOME and from the repository root down to the working directory.`;
24
+ --safe load only the plugins that come with jade
25
+ -v, --version print the version
69
26
 
70
- /** 会话里的命令:/help、输入 / 时的菜单都从这里取 */
71
- const COMMANDS: CommandInfo[] = [
72
- { name: "help", about: "list the commands and keys" },
73
- { name: "model", args: "[name]", about: "switch between saved models, or add one and configure its provider, API key and output limit" },
74
- { name: "mode", args: `[${MODES.join("|")}]`, about: "show or change the permission mode" },
75
- { name: "plugins", about: "built-in and installed plugins: their tools, hooks and commands, and the hook execution order" },
76
- { name: "exit", about: "quit (the session stays resumable)" },
77
- ];
78
- /** 运行中也立即执行的命令(不碰运行时,或者只读;/mode 运行中先记在 pendingMode) */
79
- const INSTANT = new Set(["help", "model", "mode", "plugins", "exit"]);
80
- /** 内置插件提供的命令(/memory 在 jade/memory 里,等等):名字保留给它们,自定义命令不能占用 */
81
- const BUILTIN_PLUGIN_COMMANDS = ["memory", "checks", "mcp", "skills", "compact", "clear", "resume", "retry", "undo", "search"];
27
+ Run "jade plugins --help" for the install and update options.
28
+ Everything else is passed to the frontend plugin; see its own --help.`;
82
29
 
83
- const KEYS = `Keys: enter send · \\ or alt+enter new line · ↑↓ history · @ reference a file · esc interrupt (twice to also clear queued messages) · shift+tab cycle ask/auto/plan · ctrl+c twice to exit
84
- mouse wheel or PgUp/PgDn scroll the conversation · ctrl+home/ctrl+end jump to the top/bottom · click ▸ expands an item (ctrl+o the latest one) · click in the input moves the cursor · shift+drag selects text
85
- While jade is working you can keep typing: messages are queued and sent when the current turn ends.`;
86
-
87
- /** 终端界面启动时最多等 MCP 服务连接这么久,没连上的在后台接着连 */
88
- const MCP_STARTUP_WAIT_MS = 5000;
89
-
90
- /** 回复被输出上限截断后,自动让模型接着做的次数(每条用户消息) */
91
- const MAX_CONTINUES = 3;
92
- const CONTINUE_NOTE =
93
- "Your previous reply was cut off because it reached the output token limit. Continue from where you stopped. " +
94
- "If you were writing a large file or edit, split it into several smaller write_file/edit_file calls.";
95
-
96
- // ---------- 参数 ----------
97
-
98
- const argv = process.argv.slice(2);
99
- if (argv[0] === "plugin" || argv[0] === "plugins") {
100
- const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
101
- const here = process.cwd();
102
- try {
103
- const root = realPath(await repoRoot(here));
104
- process.exit(await pluginCli(argv.slice(1), { home, cwd: here, root, trust: new JsonlTrustStore(path.join(home, "trust.jsonl")) }));
105
- } catch (err) {
106
- console.error(`jade plugin: ${err instanceof Error ? err.message : String(err)}${err instanceof UsageError ? `\n\n${PLUGIN_HELP}` : ""}`);
107
- process.exit(err instanceof UsageError ? 2 : 1);
108
- }
109
- }
110
- if (argv[0] === "update") process.exit(await updateCli(argv.slice(1)));
111
- const opts: { print?: string; cont?: boolean; resume?: string; mode?: Mode; cwd?: string; prompt: string[] } = { prompt: [] };
112
- for (let i = 0; i < argv.length; i++) {
113
- const a = argv[i]!;
114
- const value = () => {
115
- const v = argv[++i];
116
- if (v === undefined) fail(`${a} needs a value`);
117
- return v;
118
- };
119
- if (a === "-h" || a === "--help") {
120
- console.log(HELP);
121
- process.exit(0);
122
- } else if (a === "-v" || a === "--version") {
123
- console.log(VERSION);
124
- process.exit(0);
125
- } else if (a === "-p" || a === "--print") opts.print = value();
126
- else if (a === "-c" || a === "--continue") opts.cont = true;
127
- // 不带 id 时从列表里选
128
- else if (a === "-r" || a === "--resume") opts.resume = argv[i + 1] === undefined || argv[i + 1]!.startsWith("-") ? "" : argv[++i]!;
129
- else if (a === "-m" || a === "--mode") {
130
- const m = value();
131
- if (!(MODES as readonly string[]).includes(m)) fail(`unknown mode ${m}`);
132
- opts.mode = m as Mode;
133
- } else if (a === "--cwd") opts.cwd = value();
134
- else if (a.startsWith("-")) fail(`unknown option ${a}`);
135
- else opts.prompt.push(a);
136
- }
137
-
138
- function fail(msg: string): never {
139
- console.error(`jade: ${msg}\n\n${HELP}`);
140
- process.exit(2);
141
- }
142
-
143
- /** 解析符号链接和 Windows 短文件名,和 git 给出的仓库根目录可以比较 */
144
- function realPath(p: string): string {
145
- try {
146
- return realpathSync.native(p);
147
- } catch {
148
- return path.resolve(p);
149
- }
150
- }
151
-
152
- const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
153
-
154
- async function gitBranch(dir: string): Promise<string | undefined> {
155
- try {
156
- const { code, stdout } = await run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd: dir });
157
- return code === 0 ? stdout.trim() : undefined;
158
- } catch {
159
- return undefined;
160
- }
161
- }
162
-
163
- // ---------- 配置与界面 ----------
164
-
165
- const cwd = path.resolve(opts.cwd ?? process.cwd());
166
- if (!(await stat(cwd).catch(() => undefined))?.isDirectory()) fail(`${cwd} is not a directory`);
167
- const home = process.env.JADE_HOME ?? path.join(os.homedir(), ".jade");
168
- const envFile = path.join(home, ".env");
169
- await loadEnvFile(envFile);
170
-
171
- /** 新会话的权限模式:-m 只管这一次;没给时用上次在会话里切换到的模式(JADE_MODE,见 rememberMode),都没有时是 ask */
172
- const savedMode = process.env.JADE_MODE?.trim();
173
- const badSavedMode = savedMode && !(MODES as readonly string[]).includes(savedMode) ? savedMode : undefined;
174
- if (savedMode && !badSavedMode) opts.mode ??= savedMode as Mode;
175
-
176
- const tui = Boolean(process.stdin.isTTY && process.stdout.isTTY) && opts.print === undefined;
177
- // 终端界面依赖 ink 和 react,加载要几百毫秒,只在真的用到时才导入;现在就开始加载,和下面读配置、跑 git 同时进行
178
- const tuiModule = tui ? import("./ui/tui.tsx") : undefined;
179
- const branchFound = tui ? gitBranch(cwd) : undefined;
180
- // provider 要动态导入 SDK(一百多毫秒),和终端界面一起加载;出错时在下面创建界面之后再报。
181
- // JADE_PROVIDER 选的是插件提供的服务时,等插件加载完再创建(pluginProviderPending)
182
- const pluginProviderPending = hasProvider() && !isBuiltinKind(providerKind());
183
- const providerEarly = hasProvider() && !pluginProviderPending ? providerFromEnv() : undefined;
184
- providerEarly?.catch(() => {});
185
- if (!hasProvider() && !tui) {
186
- console.error(
187
- `jade: no model is configured.\n\n` +
188
- `Run jade in a terminal and use /model, or put one of these in ${envFile} (or set them in the shell):\n` +
189
- ` OPENAI_COMPAT_BASE_URL=… OPENAI_COMPAT_API_KEY=… OPENAI_COMPAT_MODEL=… (any /chat/completions service)\n` +
190
- ` OPENAI_API_KEY=… [OPENAI_BASE_URL=… OPENAI_MODEL=…] (OpenAI Responses API)\n` +
191
- ` ANTHROPIC_API_KEY=… [ANTHROPIC_MODEL=…] (Claude)\n` +
192
- ` JADE_PROVIDER=<kind> plus the settings that plugin documents (a model service from a plugin)`,
193
- );
194
- process.exit(2);
195
- }
196
-
197
- // 写错时直接报错:NaN 会让"是否超过阈值"永远为假,每次请求都压缩
198
- let compactTokens: number | undefined;
199
- try {
200
- compactTokens = process.env.JADE_COMPACT_TOKENS ? parseTokens("JADE_COMPACT_TOKENS", process.env.JADE_COMPACT_TOKENS) : undefined;
201
- } catch (err) {
202
- fail(errorText(err));
203
- }
204
- /** 模型的上下文窗口:JADE_CONTEXT_WINDOW,/model 改配置后更新 */
205
- let contextWindow = 0;
206
- try {
207
- contextWindow = contextWindowFromEnv();
208
- } catch (err) {
209
- fail(errorText(err));
210
- }
211
- /** 压缩阈值:JADE_COMPACT_TOKENS,否则由上下文窗口推出 */
212
- const compactAt = () => compactTokens ?? compactThreshold(contextWindow);
213
-
214
- const modelLabel = () => (hasProvider() ? providerInfo().model || "(no model)" : "(no model)");
215
-
216
- // 界面在启动过程中就已经可以输入;启动完成前提交的内容先存着,完成后再处理
217
- let ready = false;
218
- const early: string[] = [];
219
-
220
- const inputs = new InputHistory(path.join(home, "history.jsonl"), cwd);
221
-
222
- /** $JADE_HOME/plugins.json 里停用的插件和内置插件(id) */
223
- const disabledPlugins = new Set((await readPluginSettings(home)).disabled);
224
- const repo = realPath(await repoRoot(cwd));
225
- const trust = new JsonlTrustStore(path.join(home, "trust.jsonl"));
226
- /**
227
- * 第三方插件(进程级,见 plugins/host.ts):这里只读清单,不执行代码,停用的不加载,也不读它们带的内容。
228
- * 加载(项目层的要确认)在界面起来之后
229
- */
230
- const plugins = await openPluginHost({
231
- home,
232
- root: repo,
233
- cwd: realPath(cwd),
234
- disabled: disabledPlugins,
235
- trust,
236
- confirm: async ({ path: p, hash, files, command }) =>
237
- (await screen.select(
238
- `Project plugin ${display(cwd, p)} is new or changed. Load and run it?`,
239
- [
240
- { label: "No", value: false },
241
- { label: "Yes, load it", value: true },
242
- ],
243
- {
244
- body: dim(`${command ? `runs: ${command}\n` : ""}sha256 ${hash.slice(0, 12)}, ${files.length} files:\n${files.map((f) => ` ${f}`).join("\n")}`),
245
- },
246
- )) ?? false,
247
- report: (kind, text) => screen.log(kind === "note" ? dim(`[note] ${text}`) : yellow(`[${kind}] ${text}`)),
248
- display: (dir) => display(cwd, dir),
249
- untrustedHint: tui ? undefined : "(run jade interactively in this directory once to confirm it)",
250
- });
251
- const bundled = plugins.bundled;
252
-
253
- /** 自定义命令($JADE_HOME/commands、.jade/commands、插件带的 commands/);和内置命令同名的不生效 */
254
- const builtinNames = new Set([...COMMANDS.map((c) => c.name), ...BUILTIN_PLUGIN_COMMANDS]);
255
- /** 宿主自己处理的命令(/help、/model 等):插件的同名命令永远不生效 */
256
- const hostNames = new Set(COMMANDS.map((c) => c.name));
257
- const customLoaded = await loadCommands({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.commands) });
258
- const shadowed = customLoaded.filter((c) => builtinNames.has(c.name));
259
- const customs = new Map(customLoaded.filter((c) => !builtinNames.has(c.name)).map((c) => [c.name, c]));
260
- const ALL_COMMANDS: CommandInfo[] = [
261
- ...COMMANDS,
262
- ...[...customs.values()].map((c) => ({ name: c.name, args: c.args, about: `${c.description} (${c.plugin ? `plugin ${c.plugin}` : c.layer})` })),
263
- ];
264
-
265
- // 插件、工具输出和模型的文字都经过这里显示:只留颜色,去掉能搅乱终端的控制序列
266
- const screen: Screen = safeScreen(tuiModule
267
- ? (await tuiModule).tuiScreen({
268
- status: { cwd: shortPath(cwd), branch: await branchFound, model: modelLabel(), mode: opts.mode ?? "ask" },
269
- version: VERSION,
270
- commands: ALL_COMMANDS,
271
- history: await inputs.load(),
272
- handlers: {
273
- submit: (text) => {
274
- inputs.add(text).catch(() => {});
275
- if (ready) onSubmit(text);
276
- else early.push(text);
277
- },
278
- interrupt: () => ready && interrupt(),
279
- exit: () => (ready ? void quit() : process.exit(130)),
280
- files: () => mentionCandidates(cwd),
281
- cycleMode: () => ready && cycleMode(),
282
- key: (spec) => ready && pluginKey(spec),
283
- },
284
- })
285
- : plainScreen({ interactive: Boolean(process.stdin.isTTY) }));
286
-
287
- /** 压缩、子 Agent 和主循环共用;/model 改配置后换掉里面的实现 */
288
- const provider = switchable({
289
- id: "unconfigured",
290
- complete: () => Promise.reject(new Error("no model is configured; use /model")),
291
- });
292
-
293
- /** /model 的交互:改配置后换掉 provider、更新上下文窗口和状态栏 */
294
- const configure = configurator({
295
- screen,
296
- envFile,
297
- modelsFile: path.join(home, "models.json"),
298
- apply: async () => {
299
- provider.set(retrying(await providerFromEnv()));
300
- contextWindow = contextWindowFromEnv();
301
- },
302
- contextWindow: () => contextWindow,
303
- onApplied: () => screen.status({ model: modelLabel() }),
304
- });
305
-
306
- // 还没配置模型时,等插件加载完再问(见下面 registerProviders 之后):插件提供的服务也要列出来
307
- if (providerEarly) {
308
- try {
309
- provider.set(retrying(await providerEarly));
310
- } catch (err) {
311
- await screen.close();
312
- fail(errorText(err));
313
- }
314
- }
315
-
316
- /**
317
- * 外面包一层重试和限速。限速对这个服务的所有请求(主 Agent、子 Agent、压缩)共用:
318
- * JADE_RPM 设了上限时把请求平均分布在一分钟里;被限流时所有请求一起等,而不是各自去撞
319
- */
320
- function retrying(inner: Provider) {
321
- /** 状态行正显示着排队或等待重试:请求发出后换回来 */
322
- let waiting = false;
323
- const gate = new RateGate({
324
- rpm: rpmFromEnv(),
325
- onWait: (ms) => {
326
- if (ms < 1000) return;
327
- waiting = true;
328
- screen.busy(`Pacing requests (${gate.rpm ? `${+gate.rpm.toFixed(1)}/min` : "rate limited"}, ${seconds(ms)})`);
329
- },
330
- onLearn: (rpm) =>
331
- screen.log(dim(`[rate limited: spacing requests to ${rpm} per minute from now on; set the exact limit with /model → requests per minute]`)),
332
- });
333
- return withRetry(inner, {
334
- gate,
335
- onRequest: () => {
336
- if (waiting && running) screen.busy("Waiting for the model");
337
- waiting = false;
338
- },
339
- onRetry: ({ attempt, retries, delayMs, error }) => {
340
- const why = isRateLimit(error) ? "rate limited" : clip(error.message.replace(/\s+/g, " "), tui ? 60 : 160);
341
- // 终端界面只在状态行显示,不在对话里每次重试刷一行;重试用完仍然失败时照常报错
342
- if (!tui) screen.log(yellow(`[${why} · retry ${attempt}/${retries} in ${seconds(delayMs)}]`));
343
- waiting = true;
344
- screen.busy(`Waiting to retry (${why} · ${attempt}/${retries}, ${seconds(delayMs)})`);
345
- },
346
- });
347
- }
348
-
349
- const seconds = (ms: number) => (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000) ? `${Math.round((ms % 60_000) / 1000)}s` : ""}` : `${Math.max(1, Math.round(ms / 1000))}s`);
350
-
351
- const store = new JsonlLogStore(path.join(home, "sessions"));
352
- const index = new SessionIndex(path.join(home, "index.jsonl"));
353
-
354
- /** 正在退出:这时 MCP 服务断开是预期的,不提示 */
355
- let pluginsClosing = false;
356
- // 插件、skill、MCP 服务同时加载:MCP 服务启动可能要好几秒。确认对话框一个接一个:MCP 的排在插件的后面。
357
- // 插件加载完就注册了它们导出的模型服务(不用创建插件实例),所以下面先配置好模型,再创建插件,工厂函数里也能用 ctx.complete
358
- const pluginsLoading = plugins.load();
359
- const mcpConnecting = connectMcp(pluginsLoading);
360
- const skillsLoading = loadSkills({ home, root: repo, cwd: realPath(cwd), plugins: bundled((b) => b.skills) });
361
- const pluginSources = await pluginsLoading;
362
- const skillsLoaded = await skillsLoading;
363
- for (const w of skillsLoaded.warnings) screen.log(yellow(`[warning] ${w}`));
364
- const skills = skillsLoaded.skills;
365
- const mcpClients = await mcpConnecting;
366
30
  /**
367
- * 运行中切换的权限模式:这一轮正占着日志,写不进去。关卡先按它判断(下一个工具调用就生效),
368
- * 这一轮结束后再记进日志(flushPendingMode)
31
+ * jade plugins 的子命令(含别名):单独写在 jade 后面时多半是漏了 plugins。
32
+ * update、upgrade 不在里面:jade update 升级 jade 本身,jade upgrade 多半也是想升级 jade
369
33
  */
370
- let pendingMode: Mode | undefined;
371
- /** 当前配置的模型和服务,写进系统提示词,用户问起时模型照这个回答;/model 改了配置后下一次请求就是新的 */
372
- function currentModel(): { name: string; via: string } | undefined {
373
- if (!hasProvider()) return undefined;
374
- const info = providerInfo();
375
- let host: string | undefined;
376
- try {
377
- host = info.baseURL ? new URL(info.baseURL).host : undefined;
378
- } catch {}
379
- if (!isBuiltinKind(info.kind)) {
380
- let via = `the ${info.kind} provider`;
381
- try {
382
- via = pluginProvider(info.kind)?.def.via?.(process.env) || via;
383
- } catch {}
384
- return { name: info.model, via };
385
- }
386
- const api = { anthropic: "the Anthropic API", openai: "the OpenAI Responses API", "openai-compat": "an OpenAI-compatible API" }[info.kind];
387
- return { name: info.model, via: host ? `${api} at ${host}` : api };
388
- }
34
+ const PLUGIN_SUBCOMMANDS: ReadonlySet<string> = new Set(["list", "ls", "add", "install", "remove", "rm", "uninstall", "enable", "disable"]);
389
35
 
390
- // 模型放临时脚本、测试数据的目录,整个进程共用一个(换会话时提示词不变,不影响缓存)。
391
- // 写成正斜杠:Windows 上 Git Bash、Python、Node 都认 C:/Users/...,而 /tmp 在它们之间不是同一个地方
392
- const scratch = realpathSync.native(await mkdtemp(path.join(os.tmpdir(), "jade-"))).replaceAll("\\", "/");
36
+ const pkgDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
393
37
 
394
- /**
395
- * 每个会话用一套新的插件实例(SessionScope):插件里有按会话记的状态(例如压缩、重复调用的计数)。
396
- * 新的一套先在 preparing 里创建(工厂函数这时运行),换会话成功了才 activate;失败了直接 dispose,当前的一套不受影响。
397
- * 插件的 ctx.status、ctx.input、ctx.send 只在 active 时生效,见 session-scope.ts
398
- */
399
- async function prepareScope(mode?: Mode): Promise<SessionScope> {
400
- const next = new SessionScope({
401
- showStatus: (plugins) => screen.status({ plugins }),
402
- input: screen.draft && { text: () => screen.draft!.text(), insert: (t) => screen.draft!.insert(t), set: (t) => screen.draft!.set(t) },
403
- send: screen.draft && pluginSend,
404
- warn: (w) => warn([w]),
405
- tidy: (t) => clip(stripVTControlCharacters(t).replace(/\s+/g, " ").trim(), 40),
406
- });
407
- next.attach(await createJade({
408
- cwd,
409
- home,
410
- store,
411
- provider,
412
- mode,
413
- model: currentModel,
414
- extensions: pluginSources,
415
- disabled: disabledPlugins,
416
- mcp: mcpClients,
417
- skills,
418
- compactTokens: compactAt,
419
- scratch,
420
- approveSubagent,
421
- // 不能交互时(-p)没有人回答,不提供这个工具
422
- askUser: screen.interactive ? askUser : undefined,
423
- sharedRules: (): AllowRule[] => [...settings().rules, ...pendingRules],
424
- pendingMode: () => pendingMode,
425
- // auto 模式的审查用当前的模型;rt 换会话时跟着换,所以每次取
426
- review: reviewer({ provider, cwd, scratch, messages: () => rt.state.messages }),
427
- approveCheck: process.env.JADE_CHECKS === "off" ? undefined : approveCheck,
428
- checkConfirmed: (c) => trust.has(checkHash(c)),
429
- checksUnavailable: process.env.JADE_CHECKS === "off" ? "Edit-time checks are turned off by JADE_CHECKS=off." : undefined,
430
- ...next.hooks,
431
- }));
432
- return next;
38
+ function version(): string {
39
+ return JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8")).version;
433
40
  }
434
41
 
435
- const warn = (list: string[]) => {
436
- for (const w of list) screen.log(yellow(`[warning] ${w}`));
437
- };
438
- if (!hasProvider()) {
439
- // 第一次运行:插件已经加载,/model 的服务列表里也有插件提供的
440
- screen.log(bold("Welcome to jade.") + " No model is configured yet; let's set one up.");
441
- if (!(await configure.provider())) {
442
- await closePlugins();
443
- await screen.close();
444
- process.exit(2);
42
+ export async function main(argv: readonly string[]): Promise<number> {
43
+ if (argv[0] === "-v" || argv[0] === "--version") {
44
+ console.log(version());
45
+ return 0;
445
46
  }
446
- } else if (pluginProviderPending) {
447
- try {
448
- provider.set(retrying(await providerFromEnv()));
449
- contextWindow = contextWindowFromEnv();
450
- } catch (err) {
451
- // 例如提供这个服务的插件被删掉、停用或者没加载成功:原因在上面插件的警告里
452
- await providerUnavailable(errorText(err));
453
- }
454
- screen.status({ model: modelLabel() });
455
- }
456
- /** 会话的开始、离开、换会话、重新加载,见 session-lifecycle.ts */
457
- const sessions = await SessionLifecycle.prepare<Mode>(
458
- {
459
- prepare: prepareScope,
460
- open: (plugins, id) => (id ? Runtime.resume({ store, provider, plugins, sessionId: id }) : Runtime.create({ store, provider, plugins })),
461
- discard: (id) => discardIfEmpty(store, id),
462
- warn,
463
- error: (err) => screen.log(red(`[error] ${errorText(err)}`)),
464
- },
465
- opts.mode,
466
- );
467
- /** 当前会话的插件作用域、插件实例、运行时和 id;换会话之后由 adopt 一起换 */
468
- let scope = sessions.scope;
469
- let jade: Jade = sessions.jade;
470
- warn(jade.warnings);
47
+ const cwd = process.cwd();
48
+ const home = process.env.JADE_HOME || path.join(os.homedir(), ".jade");
49
+ const roots: LayerRoot[] = [
50
+ // 编译好的宿主(dist/*.js)用编译好的插件:Node 不给 node_modules 里的 .ts 去类型
51
+ { layer: "bundled", root: path.join(pkgDir, import.meta.url.endsWith(".js") ? "plugins-dist" : "plugins") },
52
+ { layer: "user", root: path.join(home, "plugins") },
53
+ { layer: "project", root: path.join(cwd, ".jade", "plugins") },
54
+ ];
55
+ const safe = argv.includes("--safe");
56
+ const rest = argv.filter((a) => a !== "--safe");
57
+ const flags = rest.filter((a) => a.startsWith("-"));
471
58
 
472
- /** 选的模型服务用不了:终端界面里直接进 /model 换一个服务,不然用户只能手改 .env;不能交互时报错退出 */
473
- async function providerUnavailable(message: string): Promise<void> {
474
- if (tui) {
475
- screen.log(red(`[error] ${message}`));
476
- screen.log("Choose another model with /model.");
477
- if (await configure.provider()) return;
478
- await closePlugins();
479
- await screen.close();
480
- process.exit(2);
481
- }
482
- await closePlugins();
483
- await screen.close();
484
- fail(message);
485
- }
486
- if (badSavedMode) screen.log(yellow(`[warning] JADE_MODE=${badSavedMode} is not a mode (${MODES.join(", ")}); starting in ${opts.mode ?? "ask"}`));
487
- for (const c of shadowed) screen.log(yellow(`[warning] custom command ${display(cwd, c.file)} is ignored: /${c.name} is a built-in command`));
488
- // 插件的命令加进菜单(名字在各个会话的实例之间不变)。内置命令和 .jade/commands 里的同名命令优先
489
- // skill 也可以当命令用:/<skill 名> [要做的事]。内置命令和自定义命令优先
490
- const skillCommands = new Map<string, (typeof skills)[number]>();
491
- for (const sk of skills) {
492
- const name = sk.name.toLowerCase();
493
- if (builtinNames.has(name) || customs.has(name)) continue;
494
- skillCommands.set(name, sk);
495
- ALL_COMMANDS.push({ name: sk.name, args: "[task]", about: `${clip(sk.description.replace(/\s+/g, " "), 80)} (skill)` });
496
- }
497
- // 内置插件的命令排在宿主命令后面;第三方插件的命令排在最后。同名时谁生效见 pluginMenu
498
- const menu = pluginMenu(jade.commands, { host: hostNames, custom: customs, skill: skillCommands });
499
- warn(menu.warnings);
500
- ALL_COMMANDS.push(...menu.plugins);
501
- ALL_COMMANDS.splice(COMMANDS.length, 0, ...menu.builtin);
502
-
503
- /** 结束进程外插件的进程和 MCP 服务 */
504
- async function closePlugins() {
505
- pluginsClosing = true;
506
- await Promise.all([plugins.close(), ...mcpClients.map((c) => c.close().catch(() => {}))]);
507
- }
508
-
509
- /**
510
- * 连接 mcp.json 里配置的 MCP 服务。项目层(随仓库分发)的服务第一次启动前要用户确认,按配置内容记在 trust.jsonl;
511
- * 连不上的跳过并提示,不影响启动。所有服务并发连接,不用确认的立即开始连。
512
- * 启动时最多等 MCP_STARTUP_WAIT_MS:还没连上的在后台接着连,它们的工具从下一个会话(/clear)开始提供
513
- * (一个会话里的工具列表不变,否则提示缓存失效)。
514
- * dialogsAfter:在它完成之后才弹确认框,不和插件的确认框同时出现
515
- */
516
- async function connectMcp(dialogsAfter: Promise<unknown>): Promise<McpClient[]> {
517
- const carried = plugins.plugins.flatMap((f) => {
518
- const mcp = f.info.bundle.mcp;
519
- return mcp ? [{ plugin: f.id, dir: f.dir, layer: f.layer, file: mcp.file, servers: mcp.servers }] : [];
520
- });
521
- const { servers, warnings } = await loadMcpConfig({ home, root: repo, cwd: realPath(cwd), plugins: carried });
522
- for (const w of warnings) screen.log(yellow(`[warning] ${w}`));
523
- const clients: McpClient[] = [];
524
- const connecting: Promise<unknown>[] = [];
525
- for (const entry of servers) {
526
- if (entry.config.disabled) continue;
527
- if (entry.layer === "project") {
528
- const hash = mcpTrustHash(repo, entry);
529
- if (!(await trust.has(hash))) {
530
- if (tui) await dialogsAfter.catch(() => {});
531
- const ok = tui
532
- ? ((await screen.select(
533
- `MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`,
534
- [
535
- { label: "No", value: false },
536
- { label: "Yes, start it", value: true },
537
- ],
538
- { body: dim(`${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`) },
539
- )) ?? false)
540
- : false;
541
- if (!ok) {
542
- screen.log(yellow(`[skipped] MCP server ${entry.name}: not confirmed${tui ? "" : " (run jade interactively in this directory once to confirm it)"}`));
543
- continue;
544
- }
545
- await trust.add({ hash, path: entry.file, at: new Date().toISOString() });
546
- }
547
- }
548
- const client = new McpClient(entry, {
549
- cwd,
550
- onDisconnect: (c, why) => {
551
- if (!pluginsClosing) screen.log(yellow(`[warning] MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`));
552
- },
553
- });
554
- clients.push(client);
555
- connecting.push(client.connect().catch((err) => screen.log(yellow(`[warning] MCP server ${client.name} is unavailable: ${errorText(err)}`))));
556
- }
557
- if (clients.length === 0) return clients;
558
- screen.busy(`Connecting to ${clients.length} MCP server${clients.length > 1 ? "s" : ""}`);
559
- const all = Promise.all(connecting);
560
- // 不能交互时(-p)只运行这一次,没有"下一个会话",照常等到每个服务连上或超时
561
- let timer: ReturnType<typeof setTimeout> | undefined;
562
- if (tui) await Promise.race([all, new Promise<void>((resolve) => (timer = setTimeout(resolve, MCP_STARTUP_WAIT_MS)))]);
563
- else await all;
564
- clearTimeout(timer);
565
- screen.busy(undefined);
566
- for (const c of clients.filter((x) => x.status === "connecting")) {
567
- screen.log(dim(`[MCP server ${c.name} is still starting; its tools are available from the next session (/clear) once it is connected]`));
568
- void c.connect().then(
569
- () => screen.log(dim(`[MCP server ${c.name} connected; its tools are available from the next session (/clear)]`)),
570
- () => {},
571
- );
572
- }
573
- return clients;
574
- }
575
-
576
- let resumeId = opts.resume;
577
- if (resumeId === "") {
578
- if (!tui) {
579
- await screen.close();
580
- fail("--resume without an id needs a terminal to pick from; pass the id");
581
- }
582
- resumeId = await pickSession();
583
- } else if (resumeId) resumeId = matchSession(await index.list(cwd), resumeId);
584
- if (opts.cont) {
585
- resumeId = (await index.list(cwd))[0]?.id;
586
- if (!resumeId) {
587
- await screen.close();
588
- fail(`no session to continue in ${cwd}`);
589
- }
590
- }
591
-
592
- // /clear 换成新的运行时和会话
593
- let rt!: Runtime;
594
- let sessionId!: string;
595
- function adopt(c: Current) {
596
- scope = c.scope;
597
- jade = c.jade;
598
- rt = c.rt;
599
- sessionId = c.sessionId;
600
- }
601
- adopt(await sessions.begin(resumeId));
602
-
603
- // 权限设置记在日志里(derived),关卡从那里读,恢复会话后仍然有效
604
- // 主会话不会是 readonly(只给子 Agent 用;旧会话里记的 readonly 由关卡换成 plan)
605
- // 只取这一项:rt.state 每次都拷贝整段历史,而这里调用得很频繁(子 Agent 的每次关卡判断都会调用)
606
- const settings = () => jade.policy.settings({ [POLICY_KEY]: rt.derived(POLICY_KEY) }) as PolicySettings & { mode: Mode };
607
- const saveSettings = async (next: PolicySettings) => {
608
- await rt.record(POLICY_KEY, next);
609
- pendingMode = undefined;
610
- screen.status({ mode: next.mode });
611
- };
612
-
613
- /**
614
- * 用户切换的模式记进 $JADE_HOME/.env 的 JADE_MODE,之后新开的会话默认用它(恢复的会话仍用它自己记下的模式)。
615
- * yolo 不记:免得以后一打开就什么都不问;要默认 yolo 可以手动写 JADE_MODE=yolo 或用 -m yolo
616
- */
617
- async function rememberMode(mode: Mode) {
618
- if (mode === "yolo" || process.env.JADE_MODE === mode) return;
619
- await updateEnvFile(envFile, { JADE_MODE: mode }).catch((err) =>
620
- screen.log(yellow(`[warning] could not remember the mode in ${envFile}: ${errorText(err)}`)),
621
- );
622
- }
623
-
624
- /** 换权限模式;运行时正在执行这一轮时先记在 pendingMode,关卡立即按它判断,这一轮结束后再写进日志 */
625
- async function setMode(mode: Mode) {
626
- await rememberMode(mode);
627
- try {
628
- await saveSettings({ ...settings(), mode });
629
- } catch (err) {
630
- if (!(err instanceof RuntimeBusy)) throw err;
631
- pendingMode = mode;
632
- screen.status({ mode });
633
- }
634
- }
635
-
636
- /** 把运行中切换的模式写进日志 */
637
- async function flushPendingMode() {
638
- if (pendingMode === undefined) return;
639
- try {
640
- await saveSettings(settings());
641
- } catch (err) {
642
- if (!(err instanceof RuntimeBusy)) screen.log(red(`[error] ${errorText(err)}`));
643
- }
644
- }
645
-
646
- // ---------- 渲染 ----------
647
-
648
- const view = transcript({ screen, cwd, store, contextWindow: () => contextWindow, compactAt: () => compactAt(), canRetry: () => canRetry(), renderer: (tool) => jade.renderers.get(tool) });
649
- rt.subscribe(view.onNotice);
650
-
651
- // ---------- 审批 ----------
652
-
653
- type Call = { toolUseId: string; name: string; input: unknown; reason?: string };
654
-
655
- /**
656
- * 问用户是否允许一个调用;选了"总是允许"时交给 remember 记下规则。
657
- * signal 中止时(例如中断了子 Agent)关掉对话框并抛出
658
- */
659
- async function ask(c: Call, who: string, remember: (rule: AllowRule) => Promise<void> | void, signal?: AbortSignal): Promise<SubagentApproval> {
660
- const head = `${c.name}(${view.summary(c.name, c.input)})`;
661
- if (!screen.interactive) {
662
- screen.log(red(`✗ ${who}${head} denied: not running interactively`));
663
- return { approved: false, reason: "The user is not available to approve this action." };
664
- }
665
- const rule = jade.policy.ruleFor(c);
666
- const always = rule.command !== undefined ? "this exact command" : describeRule(rule);
667
- // 关卡给了理由的(例如 auto 模式下审查转给用户的),说明为什么要问
668
- const body = (c.reason ? `${yellow(c.reason)}\n\n` : "") + (await view.preview(c));
669
- const answer = await screen.select(
670
- `Allow ${who}${head}?`,
671
- [
672
- { label: "Yes", value: "yes" as const },
673
- { label: `Yes, and always allow ${always} in this session`, value: "always" as const },
674
- { label: "No, and tell jade what to do instead", value: "no" as const },
675
- ],
676
- { body, signal },
677
- );
678
- signal?.throwIfAborted();
679
- if (answer === "always") await remember(rule);
680
- const approved = answer === "yes" || answer === "always";
681
- const said = answer === "no" ? (await screen.input("What should jade do instead? (optional)", { signal }))?.trim() : undefined;
682
- signal?.throwIfAborted();
683
- // 带上"用户拒绝了"这层前提,否则模型可能把用户的话当成命令的输出
684
- const reason = approved ? undefined : said ? `The user rejected this action and said: ${said}` : "The user rejected this action.";
685
- // 主 Agent 的调用的结果之后接在这一行后面
686
- screen.log((approved ? green(`✓ ${who}${head}`) : red(`✗ ${who}${head}`)) + dim(reason ? ` — ${clip(reason, 200)}` : ""), {
687
- id: c.toolUseId,
688
- details: view.details(c.name, c.input),
689
- });
690
- return { approved, reason };
691
- }
692
-
693
- async function approvePending() {
694
- while (rt.state.phase === "awaiting") {
695
- for (const c of rt.state.batch.filter((x) => x.decision === "ask")) {
696
- const answer = await ask(c, "", async (rule) => {
697
- const s = settings();
698
- await saveSettings({ ...s, rules: [...s.rules, rule] });
699
- });
700
- await rt.send({ kind: "approval", toolUseId: c.toolUseId, ...answer });
701
- }
702
- }
703
- }
704
-
705
- /**
706
- * 子 Agent 审批时选了"总是允许"的规则:主会话这时正在执行 task 工具,日志写不进去,
707
- * 先在这里生效(sharedRules),这一轮结束后再记进日志
708
- */
709
- const pendingRules: AllowRule[] = [];
710
- /** 并行的子 Agent 一次只问一个 */
711
- let subagentAsking: Promise<unknown> = Promise.resolve();
712
-
713
- function approveSubagent(...[c, signal]: Parameters<ApproveSubagent>): Promise<SubagentApproval> {
714
- const turn = subagentAsking.then(() => {
715
- signal.throwIfAborted();
716
- // 中断时不再等用户回答,对话框和插件那边的请求一起关掉
717
- return ask(c, "sub-agent ", (rule) => void pendingRules.push(rule), signal);
718
- });
719
- subagentAsking = turn.catch(() => {});
720
- return turn;
721
- }
722
-
723
- /** ask_user:逐个问题让用户选一项,或者选"其他"自己输入;任何一个问题取消就算没有回答。signal 中止时关掉对话框并抛出 */
724
- async function askUser(questions: Question[], signal: AbortSignal): Promise<string[] | undefined> {
725
- if (!screen.interactive) return undefined;
726
- const OTHER = -1;
727
- // 和子 Agent 的审批轮流问,不同时弹两个对话框
728
- const run = subagentAsking.then(async () => {
729
- const answers: string[] = [];
730
- for (const [i, q] of questions.entries()) {
731
- const title = questions.length > 1 ? `${q.question} (${i + 1}/${questions.length})` : q.question;
732
- const choice = await screen.select(
733
- title,
734
- [...q.options.map((o, k) => ({ label: o.label, value: k, hint: o.description })), { label: "Other (type your answer)", value: OTHER }],
735
- { signal },
59
+ if (rest[0] === "plugins") {
60
+ try {
61
+ console.log(
62
+ await pluginsCommand(rest.slice(1), {
63
+ roots,
64
+ home,
65
+ flags,
66
+ safe,
67
+ trust: new FileTrustStore(path.join(home, "state", "trust.json")),
68
+ log: (message) => console.error(`jade: ${message}`),
69
+ }),
736
70
  );
737
- const answer = choice === undefined ? undefined : choice === OTHER ? (await screen.input(q.question, { signal }))?.trim() : q.options[choice]!.label;
738
- signal.throwIfAborted();
739
- if (!answer) return undefined;
740
- answers.push(answer);
741
- screen.log(dim(` ${q.question} → `) + answer);
71
+ return 0;
72
+ } catch (e) {
73
+ console.error(e instanceof Error ? e.message : String(e));
74
+ return 2;
742
75
  }
743
- return answers;
744
- });
745
- subagentAsking = run.catch(() => {});
746
- return run;
747
- }
748
-
749
- /** 编辑后检查的确认记录:同一个目录里的同一条命令只问一次,记在 trust.jsonl */
750
- const checkHash = (c: Check) => createHash("sha256").update(`jade-check\0${c.cwd}\0${c.command}`).digest("hex");
751
- const confirmedChecks = new Set<string>();
752
-
753
- /**
754
- * 编辑后检查的命令第一次运行前问用户:它会执行仓库里的代码(node_modules 里的 tsc、配置里的命令)。
755
- * yolo 模式不问;不能交互时不运行
756
- */
757
- async function approveCheck(c: Check, signal: AbortSignal): Promise<boolean> {
758
- const hash = checkHash(c);
759
- // 每批修改都会问一次:确认过的记在内存里,不用每次重读、解析整份 trust.jsonl
760
- if (confirmedChecks.has(hash)) return true;
761
- if (await trust.has(hash)) {
762
- confirmedChecks.add(hash);
763
- return true;
764
- }
765
- if (settings().mode === "yolo") return true;
766
- if (!screen.interactive) return false;
767
- const run = subagentAsking.then(() => {
768
- signal.throwIfAborted();
769
- return abortable(
770
- screen.select(
771
- `Run ${c.name} after the agent edits files, and show it the problems found?`,
772
- [
773
- { label: "Yes, in this project from now on", value: true },
774
- { label: "No, not in this session", value: false },
775
- ],
776
- { body: `${c.command}\n${dim(`in ${display(cwd, c.cwd) || "."}${c.source === "config" ? " (from checks.json)" : " (detected)"}`)}` },
777
- ),
778
- signal,
779
- );
780
- });
781
- subagentAsking = run.catch(() => {});
782
- const ok = (await run) ?? false;
783
- if (ok) {
784
- await trust.add({ hash, path: c.cwd, at: new Date().toISOString() });
785
- confirmedChecks.add(hash);
786
- } else screen.log(dim(`[${c.name} will not run in this session; /checks on to ask again]`));
787
- return ok;
788
- }
789
-
790
- /** /checks:开关本会话的编辑后检查;不带参数时列出对本会话改过的文件会运行的检查 */
791
- /** /<skill> 发给模型的消息:让它先加载这个 skill */
792
- function skillMessage(name: string, args: string): string {
793
- return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
794
- }
795
-
796
- /** 正在执行的插件命令;esc 中断它们。instant 的命令可以在另一个命令的模型回合里执行,所以可能同时有几个 */
797
- const commandAborts = new Set<AbortController>();
798
- /** 插件命令经 session 发起的换会话、重试:命令被 esc 中断后也要等它收尾,再处理下一条输入 */
799
- let sessionWork: Promise<unknown> | undefined;
800
-
801
- /** 执行插件的斜杠命令,返回要发给模型的提示词(没有就是 undefined) */
802
- async function pluginCommand(name: string, args: string): Promise<string | undefined> {
803
- const found = jade.commands.get(name.toLowerCase());
804
- if (!found) {
805
- screen.log(red(`unknown command /${name}; type / to see the commands`));
806
- return undefined;
807
76
  }
808
- const ac = new AbortController();
809
- commandAborts.add(ac);
810
- try {
811
- const result = await abortable(
812
- Promise.resolve(
813
- found.command.run(args, {
814
- sessionId,
815
- cwd,
816
- signal: ac.signal,
817
- derived: structuredClone(rt.state.derived),
818
- ui: {
819
- interactive: screen.interactive,
820
- log: (text) => screen.log(text),
821
- select: (title, choices, o) => screen.select(title, choices, o),
822
- input: (title, o) => screen.input(title, o),
823
- },
824
- note: (text) => void notes.push(text),
825
- // instant 的命令在模型工作时执行,不能换会话、写日志
826
- session: found.command.instant ? undefined : sessionControl(found.plugin),
827
- }),
828
- ),
829
- ac.signal,
830
- );
831
- if (typeof result === "string") {
832
- if (result) screen.log(result);
833
- return undefined;
834
- }
835
- if (result && typeof result === "object" && typeof result.prompt === "string") {
836
- // instant 的命令在模型工作时也会执行,不能再发一条消息
837
- if (found.command.instant) {
838
- screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}) is instant, so it cannot send a prompt`));
839
- return undefined;
840
- }
841
- return result.prompt.trim() ? result.prompt : undefined;
842
- }
843
- return undefined;
844
- } catch (err) {
845
- // 用户按 esc 中断的不算出错
846
- if (!ac.signal.aborted) screen.log(red(`[error] /${found.command.name} (plugin ${found.plugin}): ${errorText(err)}`));
847
- return undefined;
848
- } finally {
849
- // instant 的命令没有 session,不会发起 sessionWork;运行中的是别的命令发起的,不能替它等、替它清掉
850
- if (!found.command.instant) {
851
- await sessionWork?.catch(() => {});
852
- sessionWork = undefined;
77
+ // 不启动插件宿主:插件坏了也能升级 jade
78
+ if (rest[0] === "update") return updateCli(rest.slice(1));
79
+ if (rest[0] === "upgrade") {
80
+ console.error(`jade: "upgrade" is not a jade command; did you mean "jade update"?\nTo send it to the model instead, type it inside jade.`);
81
+ return 2;
82
+ }
83
+ if (rest[0] === "help") {
84
+ console.log(USAGE);
85
+ return 0;
86
+ }
87
+ // jade remove plugins x、jade add foo:前端会把它当成第一条消息发给模型(auto 模式下模型可能真去删东西)。
88
+ // 带引号的消息(jade "add a test")是一整个参数,不会和子命令名完全相同
89
+ if (rest[0] !== undefined && PLUGIN_SUBCOMMANDS.has(rest[0])) {
90
+ const args = rest.slice(1).filter((a) => a !== "plugins" && a !== "plugin");
91
+ // 只有一个词时加引号还是同一个参数,只能进 jade 再输入
92
+ const instead = rest.length > 1 ? `quote the whole message (jade "${rest.join(" ")}") or type it inside jade` : "type it inside jade";
93
+ console.error(`jade: "${rest[0]}" is not a jade command; did you mean "${["jade plugins", rest[0], ...args].join(" ")}"?\nTo send it to the model instead, ${instead}.`);
94
+ return 2;
95
+ }
96
+
97
+ // 前端起来之前,消息打到 stderr;之后交给 ui@1
98
+ let host: PluginHost | undefined;
99
+ const report = (message: string) => {
100
+ try {
101
+ const ui = host?.service<UI>("ui@1");
102
+ if (ui) return ui.notify(message, "warning");
103
+ } catch {
104
+ // ui@1 的提供者坏了:退回 stderr
853
105
  }
854
- commandAborts.delete(ac);
855
- }
856
- }
857
-
858
- /** 插件命令操作会话的接口;换会话后指向新的会话(rt、sessionId 每次现取) */
859
- function sessionControl(plugin: string): SessionControl {
860
- const track = <T>(p: Promise<T>): Promise<T> => ((sessionWork = p), p);
861
- return {
862
- messages: () => structuredClone(rt.state.messages),
863
- record: async (key, value) => {
864
- if (key !== plugin && !key.startsWith(`${plugin}/`)) throw new Error(`plugin ${plugin} can only record keys "${plugin}" or "${plugin}/…", not ${JSON.stringify(key)}`);
865
- await rt.record(key, value);
866
- },
867
- list: async () => (await index.list(cwd)).map(({ id, title, at }) => ({ id, title, at })),
868
- clear: () => track(switchSession()),
869
- reload: () => track(reloadSession()),
870
- resume: (id) => track(switchSession(id)),
871
- retry: async () => {
872
- if (!canRetry()) return false;
873
- await track(drive({ kind: "retry" }));
874
- return true;
875
- },
106
+ console.error(`jade: ${message}`);
107
+ };
108
+ const opts: HostOptions = {
109
+ roots,
110
+ home,
111
+ cwd,
112
+ flags,
113
+ safe,
114
+ config: { project: path.join(cwd, ".jade", "config.json") },
115
+ report,
116
+ ...(await trustOptions(home, roots)),
876
117
  };
877
- }
878
-
879
- /** /plugins:内置插件的状态,每个第三方插件的来源、工具、hook、命令和带的内容;跳过的插件在启动时已经提示过 */
880
- function showPlugins() {
881
- const width = Math.max(...jade.builtins.map((b) => b.id.length)) + 2;
882
- const lines: string[] = [bold("Built-in") + dim(" (jade plugin disable <id> turns one off)")];
883
- for (const b of jade.builtins) {
884
- const state = b.state === "replaced" ? yellow(` replaced by ${b.by}`) : b.state === "disabled" ? yellow(" disabled") : "";
885
- lines.push(` ${b.id.padEnd(width)}${dim(b.about)}${state}`);
886
- }
887
- const contentOnly = pluginSources.filter((p) => p.kind === "content");
888
- lines.push("", bold("Installed") + dim(" (jade plugin add <git URL | npm package | directory>)"));
889
- if (jade.extensions.length === 0 && contentOnly.length === 0) {
890
- lines.push(dim(` (none) put plugins in ${display(cwd, path.join(home, "plugins"))}/<name>/ or .jade/plugins/<name>/`));
891
- }
892
- const carried = (b: PluginBundle) =>
893
- [b.skills.length ? "skills" : "", b.commands.length ? "commands" : "", b.mcp ? "MCP servers" : ""].filter(Boolean).join(", ");
894
- for (const { source, plugin, commands, keys } of jade.extensions) {
895
- const exit = source.process?.exited;
896
- const state = source.kind === "process" ? (exit ? red(` exited (${exit.signal ?? `code ${exit.code}`})`) : green(" running")) : "";
897
- lines.push(`${bold(plugin.id)} ${plugin.version} ${dim(`${source.layer} · ${display(cwd, source.dir)} · ${source.kind === "process" ? `runs ${source.entry}` : source.entry}`)}${state}`);
898
- const tools = (plugin.tools ?? []).map((t) => `${t.name} (${t.effect})`);
899
- const hooks = [...new Set((plugin.hooks ?? []).map((h) => `${h.kind}:${h.point}`))];
900
- const cmds = commands.map((c) => `/${c.name}`);
901
- if (tools.length) lines.push(` tools ${tools.join(", ")}`);
902
- if (hooks.length) lines.push(` hooks ${hooks.join(", ")}`);
903
- if (cmds.length) lines.push(` commands ${cmds.join(", ")}`);
904
- if (keys.length) lines.push(` keys ${keys.map((k) => k.key).join(", ")}`);
905
- if (source.info.replaces?.length) lines.push(` replaces ${source.info.replaces.join(", ")}`);
906
- if (carried(source.info.bundle)) lines.push(` carries ${carried(source.info.bundle)}`);
907
- if (exit && source.process!.stderr.length) lines.push(dim(source.process!.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
908
- }
909
- for (const p of contentOnly) {
910
- lines.push(`${bold(p.id)}${p.info.version ? ` ${p.info.version}` : ""} ${dim(`${p.layer} · ${display(cwd, p.dir)}`)}`);
911
- lines.push(` carries ${carried(p.info.bundle)}`);
912
- }
913
- lines.push("", bold("Hook execution order"));
914
- for (const p of ["context.project", "context.build", "model.before", "model.after", "tool.before", "tool.gate", "tool.after", "turn.continue", "event", "session.start", "session.end"]) {
915
- lines.push(` ${p.padEnd(16)} ${rt.hookOrder(p).join(" → ") || dim("(none)")}`);
916
- }
917
- screen.log(lines.join("\n"));
918
- }
919
-
920
- async function savePendingRules() {
921
- if (pendingRules.length === 0) return;
922
- const s = settings();
923
- await saveSettings({ ...s, rules: [...s.rules, ...pendingRules.splice(0)] });
924
- }
925
-
926
- /** p 和 signal 谁先结束用谁:signal 中止时以它的 reason 拒绝 */
927
- function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
928
- return new Promise((resolve, reject) => {
929
- const stop = () => reject(signal.reason);
930
- if (signal.aborted) return stop();
931
- signal.addEventListener("abort", stop, { once: true });
932
- p.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
933
- });
934
- }
935
-
936
- // ---------- 运行 ----------
937
-
938
- /** 正在执行一轮对话(或一个需要独占运行时的命令) */
939
- let running = false;
940
- /** running 期间那段工作;退出时等它收尾 */
941
- let work: Promise<void> | undefined;
942
-
943
- /** 独占运行时执行 fn;同一时间只有一个 */
944
- async function occupy(fn: () => Promise<void>) {
945
- running = true;
946
- work = fn();
947
- try {
948
- await work;
949
- } finally {
950
- running = false;
951
- work = undefined;
952
- interruptPending = false;
953
- screen.busy(undefined);
954
- await flushPendingMode();
955
- }
956
- }
957
-
958
- /**
959
- * 上一次打断的时间;正在收尾的这一轮结束、开始下一条排队的输入之前一直算"刚打断过"(interruptPending)。
960
- * 刚打断过时再按一次 esc,连排队的消息一起清掉
961
- */
962
- let interruptedAt = 0;
963
- let interruptPending = false;
964
- /** 第二次 esc 算作"再按一次"的时间窗口(从打断的那一轮结束、开始下一条排队的输入算起) */
965
- const SECOND_ESC_MS = 3000;
966
-
967
- function interrupt() {
968
- if (!running) return;
969
- const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
970
- interruptedAt = Date.now();
971
- interruptPending = true;
972
- for (const ac of commandAborts) ac.abort(new Error("interrupted by user"));
973
- rt.abort("interrupted by user");
974
- screen.busy("Interrupting");
975
- if (queue.length === 0) return;
976
- if (again) {
977
- const n = queue.splice(0).length;
978
- screen.queued(queue);
979
- screen.log(dim(`[cleared ${n} queued message${n > 1 ? "s" : ""}]`));
980
- } else {
981
- screen.log(dim(`[${queue.length} queued message${queue.length > 1 ? "s" : ""} will still be sent; press esc again to clear ${queue.length > 1 ? "them" : "it"}]`));
982
- }
983
- }
984
-
985
- /**
986
- * 离开会话但保留它:写入 session.detached,插件的收尾写入完成后再退出(4.2)。
987
- * 没收到过输入的会话没什么可恢复的,删掉它的日志;返回会话是否保留了下来
988
- */
989
- function leave(): Promise<boolean> {
990
- return sessions.leave();
991
- }
992
-
993
- /** 关掉界面后再提示怎么恢复:终端界面退出备用屏幕后,里面的内容就看不到了 */
994
- async function closeScreen() {
995
- await screen.close();
996
- if (rt.state.messages.length > 0) console.log(dim(`Resume with: jade --resume ${sessionId}`));
997
- }
998
-
999
- let quitting = false;
1000
- async function quit(code = 0) {
1001
- if (quitting) return;
1002
- quitting = true;
1003
- if (running) rt.abort("exiting");
1004
- // 中断后等这一轮收尾,再写 session.detached;pump 看到 quitting 就不再取排队的输入
1005
- await work?.catch(() => {});
1006
- await leave();
1007
- await sessions.settled();
1008
- await closePlugins();
1009
- await closeScreen();
1010
- process.exit(code);
1011
- }
1012
-
1013
- /**
1014
- * 换成另一个会话:/clear 开始新会话,/resume 恢复 id 指定的会话。当前会话保持可恢复;
1015
- * 新会话用一套新的插件和运行时,权限模式沿用(恢复的会话用它日志里的设置)。
1016
- * 恢复失败时留在当前会话
1017
- */
1018
- async function switchSession(id?: string) {
1019
- await flushPendingMode();
1020
- let switched: { previous: string; kept: boolean };
1021
- try {
1022
- switched = await sessions.switchTo(id, settings().mode);
1023
- } catch (err) {
1024
- // 已经回滚:留在当前会话
1025
- return screen.log(red(`[error] ${id ? `could not resume ${id}` : "could not start a new session"}: ${errorText(err)}`));
1026
- }
1027
- const { previous: old, kept } = switched;
1028
- adopt(sessions.current);
1029
- rt.subscribe(view.onNotice);
1030
- view.reset();
1031
- notes.length = 0;
1032
- announcedMode = undefined;
1033
- pendingRules.length = 0;
1034
- screen.clear();
1035
- screen.status({ session: sessionId, mode: settings().mode, context: undefined, cache: undefined, spent: undefined, speed: undefined });
1036
- if (!id) return screen.log(dim(kept ? `Started a new session. The previous one can be resumed with /resume or: jade --resume ${old}` : "Started a new session."));
1037
- if (!(await resumeSession())) {
1038
- screen.log(dim("Starting a new session instead."));
1039
- await switchSession();
1040
- }
1041
- }
1042
-
1043
- /**
1044
- * 用新的插件实例继续当前会话:工具和系统提示词按现在的配置重新生成(例如 /search 改了搜索服务),对话内容不变。
1045
- * 只在空闲时调用:插件命令的 session.reload(instant 命令没有 session)
1046
- */
1047
- async function reloadSession() {
1048
- await flushPendingMode();
1049
- let error: unknown;
1050
118
  try {
1051
- ({ error } = await sessions.reload(settings().mode));
1052
- } catch (err) {
1053
- // 没换成新的插件实例时(prepare 失败)当前会话照常;已经离开当前会话、新会话也开不了时,只能等用户再试
1054
- if (!sessions.left) throw err;
1055
- screen.log(red(`[error] could not reload the session or start a new one: ${errorText(err)}`));
1056
- screen.log("Use /clear or /resume to continue.");
1057
- return;
119
+ host = await PluginHost.start(opts);
120
+ } catch (e) {
121
+ // 例如手改坏了的 plugins.json:说清楚是哪个文件,不打一整段堆栈
122
+ console.error(`jade: ${e instanceof Error ? e.message : String(e)}`);
123
+ return 1;
1058
124
  }
1059
- adopt(sessions.current);
1060
- if (error !== undefined) {
1061
- screen.log(red(`[error] could not reload the session: ${errorText(error)}; starting a new one`));
1062
- view.reset();
1063
- screen.status({ session: sessionId });
1064
- }
1065
- rt.subscribe(view.onNotice);
1066
- await guarded(() => rt.recover());
1067
- }
125
+ const uninstall = host.installProcessHandlers();
1068
126
 
1069
- /** 从这个目录最近的会话里选一个(-r 不带 id 时);取消或没有时返回 undefined */
1070
- async function pickSession(): Promise<string | undefined> {
1071
- const all = (await index.list(cwd)).slice(0, 50);
1072
- if (all.length === 0) {
1073
- screen.log(dim(`No other sessions in ${shortPath(cwd)}.`));
1074
- return undefined;
1075
- }
1076
- return screen.select(
1077
- "Resume which session?",
1078
- all.map((s) => ({ label: s.title || "(untitled)", value: s.id, hint: `${ago(s.at)} · ${s.id}` })),
1079
- );
1080
- }
1081
-
1082
- process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
1083
-
1084
- /** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
1085
- let lastThrown: string | undefined;
127
+ const ac = new AbortController();
128
+ let lastSigint = 0;
129
+ const onSigint = () => {
130
+ const now = Date.now();
131
+ if (now - lastSigint <= DOUBLE_SIGINT_MS) {
132
+ // 不经过任何插件:插件出问题时用户一定能停下来
133
+ host?.sessions.current?.abort(new Error("interrupted"));
134
+ process.stderr.write("\njade: interrupted\n");
135
+ process.exit(130);
136
+ }
137
+ lastSigint = now;
138
+ };
139
+ process.on("SIGINT", onSigint);
1086
140
 
1087
- async function guarded(fn: () => Promise<void>) {
1088
- view.turnFailed = false;
1089
- view.lastError = undefined;
1090
- lastThrown = undefined;
141
+ let code = 1;
1091
142
  try {
1092
- await fn();
1093
- await approvePending();
1094
- } catch (err) {
1095
- lastThrown = errorText(err);
1096
- if (!view.turnFailed) screen.log(red(`[error] ${errorText(err)}`));
143
+ const frontend = host.service<Frontend>("frontend@1");
144
+ if (!frontend) {
145
+ console.error(noFrontend(host, safe));
146
+ } else {
147
+ code = (await frontend.run({ argv: rest, sessions: host.sessions, signal: ac.signal })) ?? 0;
148
+ }
149
+ } catch (e) {
150
+ console.error(`jade: ${e instanceof Error ? e.message : String(e)}`);
1097
151
  } finally {
1098
- screen.endStream();
152
+ ac.abort();
153
+ process.off("SIGINT", onSigint);
154
+ await host.close();
155
+ uninstall();
1099
156
  }
157
+ return code;
1100
158
  }
1101
159
 
1102
- /** 宿主替用户告诉模型的事(例如 /undo),随下一条消息发出 */
1103
- const notes: string[] = [];
1104
-
1105
- /** 最近一次告诉模型的权限模式;进入、离开计划模式时要随下一条消息告诉它 */
1106
- let announcedMode: Mode | undefined;
1107
- const PLAN_ON =
1108
- "The session is now in plan mode. Investigate with read-only tools (and the task tool for broad searches); do not try to modify files " +
1109
- "or run commands that change anything, such calls are denied. When you understand the task, reply with a concise, concrete plan: " +
1110
- "the files to change and how, in order, any open questions, and how you will verify the result. Then stop and wait for the user's approval.";
1111
- const PLAN_OFF = "The session has left plan mode; you can now change files and run commands (subject to the user's approval settings).";
1112
-
1113
- function announceMode() {
1114
- const mode = settings().mode;
1115
- if (mode === "plan" && announcedMode !== "plan") notes.push(PLAN_ON);
1116
- else if (mode !== "plan" && announcedMode === "plan") notes.push(PLAN_OFF);
1117
- announcedMode = mode;
1118
- }
1119
-
1120
- /** Shift+Tab:ask → auto → plan → ask;yolo 也回到 ask。运行中也能切换,从下一个工具调用起生效 */
1121
- const CYCLE: Mode[] = ["ask", "auto", "plan"];
1122
- function cycleMode() {
1123
- const i = CYCLE.indexOf(settings().mode as Mode);
1124
- setMode(CYCLE[(i + 1) % CYCLE.length]!).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1125
- }
1126
-
1127
- /**
1128
- * 计划模式下模型给出计划、这一轮正常结束后,问用户是否按计划执行。
1129
- * 用户已经排了别的输入、或者不能交互时不问
1130
- */
1131
- async function offerPlan() {
1132
- // 这一轮中途才切到计划模式的,模型并不知道要给计划,不问
1133
- if (settings().mode !== "plan" || announcedMode !== "plan" || view.lastEnd !== "end" || !screen.interactive || queue.length > 0) return;
1134
- const last = rt.state.messages.at(-1);
1135
- if (last?.role !== "assistant" || !last.content.some((b) => b.kind === "text" && b.text.trim())) return;
1136
- const choice = await screen.select("Execute this plan?", [
1137
- { label: "Yes, in auto mode", value: "auto" as const, hint: "edits and safe commands run without asking" },
1138
- { label: "Yes, and ask before each edit", value: "ask" as const, hint: "mode ask" },
1139
- { label: "No, keep planning", value: "plan" as const, hint: "type what to change" },
1140
- ]);
1141
- if (!choice || choice === "plan") return;
1142
- await rememberMode(choice);
1143
- await saveSettings({ ...settings(), mode: choice });
1144
- screen.log(dim(`mode: ${choice}`));
1145
- await say("The plan is approved. Implement it now.");
1146
- }
1147
- const hostNote = (text: string): Block => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "host" }, trust: "trusted" });
1148
-
1149
- /** 本进程里已经记进会话索引的会话:每个会话每次运行只记一次,索引不随消息数增长 */
1150
- const indexed = new Set<string>();
1151
-
1152
- async function say(text: string) {
1153
- if (!indexed.has(sessionId)) {
1154
- indexed.add(sessionId);
1155
- await index.add({ id: sessionId, cwd, title: clip(text.replace(/\s+/g, " "), 80), at: new Date().toISOString() });
160
+ /** 没有前端时核心没有任何界面:打印出问题的插件,提示救援办法(3.2) */
161
+ function noFrontend(host: PluginHost, safe: boolean): string {
162
+ const lines = ["jade: no frontend plugin could start."];
163
+ for (const p of host.status()) {
164
+ if (p.state === "active" || p.state === "disabled" || p.reason?.startsWith("frontend ")) continue;
165
+ lines.push(` ${p.id ?? p.dir} (${p.layer}): ${p.state}${p.reason ? `: ${p.reason}` : ""}`);
1156
166
  }
1157
- announceMode();
1158
- const content: Block[] = notes.splice(0).map(hostNote);
1159
- content.push({ kind: "text", text, origin: { by: "user" }, trust: "trusted" });
1160
- // @ 引用的文件和目录:内容随消息发出,模型不用再读一遍
1161
- const refs = await attachMentions(text, { cwd, tools: jade.tools, sessionId, signal: AbortSignal.timeout(30_000) });
1162
- for (const f of refs.failed) screen.log(yellow(`[@${f.path} not attached: ${clip(f.reason, 200)}]`));
1163
- if (refs.attached.length) screen.log(dim(`[attached ${refs.attached.map((p) => `@${p}`).join(", ")}]`));
1164
- content.push(...refs.blocks);
1165
- await drive({ kind: "message", content });
1166
- await offerPlan();
167
+ lines.push(safe ? "Run `jade plugins list` to see every plugin's state." : "Try `jade --safe`, or `jade plugins disable <id>` for the plugin that fails.");
168
+ return lines.join("\n");
1167
169
  }
1168
170
 
1169
171
  /**
1170
- * 插件的快捷键:找到了就在后台执行,返回 true。同一个键可以同时执行几次(例如按一下开始录音、再按一下结束);
1171
- * signal 是当前作用域的,换会话、重新加载、退出时全部中止,卡住的插件积压的请求也就到此为止
172
+ * 项目层插件的确认(第 7 节):有带代码的项目层插件、且能在终端里问时才提供。
173
+ * 确认记录存在 $JADE_HOME/state/trust.json,按插件目录内容的哈希,内容变了要重新确认
1172
174
  */
1173
- function pluginKey(spec: string): boolean {
1174
- const found = jade.keys.get(spec);
1175
- if (!found) return false;
1176
- const signal = scope.signal;
1177
- Promise.resolve()
1178
- .then(() => found.key.run({ key: spec, sessionId, signal }))
1179
- .catch((err) => {
1180
- if (!signal.aborted) screen.log(yellow(`[warning] plugin ${found.plugin}: ${spec} failed: ${errorText(err)}`));
1181
- });
1182
- return true;
1183
- }
1184
-
1185
- /** 插件的 ctx.send:和用户在输入框里提交一样,先注明是哪个插件发的 */
1186
- function pluginSend(plugin: string, text: string) {
1187
- if (typeof text !== "string" || !text.trim()) return;
1188
- screen.log(dim(`[plugin ${plugin} sent this for you]`));
1189
- if (ready) onSubmit(text);
1190
- else early.push(text);
1191
- }
1192
-
1193
- /** 上一轮在模型回复之前就失败了:最后一条消息还没有回复 */
1194
- const canRetry = () => rt.phase === "idle" && rt.state.messages.at(-1)?.role === "user";
1195
-
1196
- async function drive(input: UserInput) {
1197
- // 重新加载失败后没有可用的会话(见 reloadSession)
1198
- if (sessions.left) return screen.log(red("[error] there is no open session. Use /clear or /resume to continue."));
1199
- // 计时从这次输入开始,不接着上一条排队消息的
1200
- screen.busy(undefined);
1201
- screen.busy("Working");
1202
- view.lastEnd = undefined;
1203
- await guarded(() => rt.send(input));
1204
- // 请求超出了上下文窗口(窗口估大了,或者一次读进来太多):压缩后重试一次
1205
- if (isContextOverflow(view.lastError ?? lastThrown) && canRetry()) {
1206
- screen.log(
1207
- yellow("[the request exceeded the model's context window; compacting the history and retrying]") +
1208
- (contextWindowInfo().source === "env" ? "" : dim(`\n[jade assumed a ${contextWindow}-token window; set the real one with /model → context window]`)),
1209
- );
1210
- jade.compact?.request();
1211
- await guarded(() => rt.send({ kind: "retry" }));
1212
- }
1213
- // 回复被输出上限截断:让模型接着做,而不是把半截任务丢给用户
1214
- for (let i = 0; i < MAX_CONTINUES && view.lastEnd === "max_tokens"; i++) {
1215
- screen.log(dim(`[asking the model to continue (${i + 1}/${MAX_CONTINUES})]`));
1216
- view.lastEnd = undefined;
1217
- await guarded(() => rt.send({ kind: "message", content: [hostNote(CONTINUE_NOTE)] }));
1218
- }
1219
- await savePendingRules().catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1220
- }
1221
-
1222
- /** 恢复的会话里已有的内容:终端界面里重新显示对话,逐行输出时只统计用量 */
1223
- async function replayHistory() {
1224
- await view.replay(await readAll(store, sessionId), tui);
1225
- }
1226
-
1227
- /** 恢复会话:先显示之前的对话,处理插件变化(4.6),再继续日志里没做完的工作。插件变化后不能继续时返回 false */
1228
- async function resumeSession(): Promise<boolean> {
1229
- await replayHistory();
1230
- const held = rt.state.held;
1231
- if (held) {
1232
- screen.log(yellow(`Plugins changed since this session was last used: ${held.plugins.map((p) => `${p.id}@${p.version}`).join(", ")}`));
1233
- if (held.resolution === "abort") {
1234
- screen.log(red("A plugin requires this session to stop. Restore the previous plugins to continue."));
1235
- return false;
1236
- }
1237
- const ok =
1238
- (await screen.select("Continue with the new plugins? Pending tool calls will be re-checked.", [
1239
- { label: "Yes, continue", value: true },
1240
- { label: "No", value: false },
1241
- ])) ?? false;
1242
- await guarded(() => rt.send({ kind: "plugins", approved: ok }));
1243
- if (!ok) return false;
1244
- }
1245
- await guarded(() => rt.recover());
1246
- // 命令行明确给了 --mode 时覆盖日志里的设置
1247
- if (opts.mode && opts.mode !== settings().mode) await saveSettings({ ...settings(), mode: opts.mode });
1248
- screen.log(dim(`Resumed ${sessionId} (${rt.state.messages.length} messages, mode ${settings().mode})`));
1249
- return true;
1250
- }
1251
-
1252
- // ---------- 命令 ----------
1253
-
1254
-
1255
- const commandWidth = () => Math.max(...ALL_COMMANDS.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
1256
-
1257
- /** 执行命令;返回 false 表示退出 */
1258
- async function command(input: string): Promise<boolean> {
1259
- const [cmd, ...rest] = input.slice(1).split(/\s+/);
1260
- switch (cmd) {
1261
- case "help":
1262
- screen.log(ALL_COMMANDS.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(commandWidth())}${dim(c.about)}`).join("\n"));
1263
- screen.log(dim(KEYS));
1264
- if (jade.keys.size)
1265
- screen.log(dim(`Plugin keys: ${[...jade.keys].map(([k, { plugin, key }]) => `${k} ${key.description ?? ""} (${plugin})`.replace(" ", " ")).join(" · ")}`));
1266
- break;
1267
- case "model":
1268
- await configure.model(rest[0]);
1269
- break;
1270
- case "mode": {
1271
- let m = rest[0];
1272
- if (!m) {
1273
- m = await screen.select(
1274
- "Permission mode",
1275
- MODES.map((x) => ({ label: x, value: x, hint: x === settings().mode ? "current" : MODE_HINTS[x] })),
1276
- );
1277
- if (!m) break;
1278
- }
1279
- if (!(MODES as readonly string[]).includes(m)) screen.log(red(`unknown mode ${m}`));
1280
- else await setMode(m as Mode);
1281
- screen.log(`mode: ${settings().mode}${pendingMode ? dim(" (from the next tool call)") : ""}`);
1282
- if (settings().rules.length) screen.log(dim(`always allowed in this session:\n${settings().rules.map((r) => ` ${describeRule(r)}`).join("\n")}`));
1283
- break;
1284
- }
1285
- case "plugins":
1286
- showPlugins();
1287
- break;
1288
- case "exit":
1289
- return false;
1290
- default: {
1291
- const custom = customs.get(cmd!.toLowerCase());
1292
- const skill = skillCommands.get(cmd!.toLowerCase());
1293
- if (!custom && skill) {
1294
- await say(skillMessage(skill.name, input.slice(1).replace(/^\S+\s*/, "")));
1295
- break;
1296
- }
1297
- if (!custom) {
1298
- const text = await pluginCommand(cmd!, input.slice(1).replace(/^\S+\s*/, ""));
1299
- if (text !== undefined) await say(text);
1300
- break;
1301
- }
1302
- const text = expandCommand(custom, input.slice(1).replace(/^\S+\s*/, ""));
1303
- if (!text.trim()) {
1304
- screen.log(red(`/${custom.name} is empty (${display(cwd, custom.file)})`));
1305
- break;
1306
- }
1307
- await say(text);
1308
- }
1309
- }
1310
- return true;
1311
- }
1312
-
1313
- const MODE_HINTS: Record<string, string> = {
1314
- ask: "ask before edits and commands",
1315
- auto: "edits in this directory run without asking; other commands are reviewed by the model, risky ones still ask",
1316
- plan: "research read-only and propose a plan; edits start after you approve it",
1317
- yolo: "never ask",
1318
- };
1319
-
1320
- // ---------- 输入 ----------
1321
-
1322
- /** 等待执行的输入:运行中提交的消息和需要独占运行时的命令排在这里,按顺序执行 */
1323
- const queue: string[] = [];
1324
-
1325
- const echo = view.echo;
1326
-
1327
- function onSubmit(text: string) {
1328
- const name = text.startsWith("/") ? text.slice(1).split(/\s+/)[0]! : undefined;
1329
- if (name !== undefined && (INSTANT.has(name) || instantPlugin(name))) {
1330
- // 只读命令和 /model 不碰运行时状态,运行中也直接执行
1331
- echo(text);
1332
- if (name === "exit" || name === "quit") return void quit();
1333
- return void command(text).catch((err) => screen.log(red(`[error] ${errorText(err)}`)));
1334
- }
1335
- queue.push(text);
1336
- if (running) screen.queued(queue);
1337
- void pump();
1338
- }
1339
-
1340
- /** 解析到的是插件命令(不是同名的自定义命令或 skill),而且它声明了 instant */
1341
- function instantPlugin(name: string): boolean {
1342
- const n = name.toLowerCase();
1343
- const found = jade.commands.get(n);
1344
- if (!found?.command.instant) return false;
1345
- if (found.builtin) return true;
1346
- return !hostNames.has(n) && !customs.has(n) && !skillCommands.has(n);
1347
- }
1348
-
1349
- async function pump() {
1350
- if (running) return;
1351
- let exit = false;
1352
- await occupy(async () => {
1353
- while (queue.length > 0 && !quitting) {
1354
- // 打断的那一轮已经结束:从现在起再给 SECOND_ESC_MS 的时间按第二次 esc
1355
- if (interruptPending) interruptedAt = Date.now();
1356
- interruptPending = false;
1357
- const text = queue.shift()!;
1358
- screen.queued(queue);
1359
- echo(text);
1360
- if (text.startsWith("/")) {
1361
- try {
1362
- if (!(await command(text))) {
1363
- exit = true;
1364
- return;
1365
- }
1366
- } catch (err) {
1367
- screen.log(red(`[error] ${errorText(err)}`));
1368
- }
1369
- } else await say(text);
175
+ async function trustOptions(home: string, roots: LayerRoot[]): Promise<{ trust?: TrustOptions }> {
176
+ const project = roots.find((r) => r.layer === "project")!;
177
+ if (!existsSync(project.root) || !process.stdin.isTTY || !process.stderr.isTTY) return {};
178
+ const confirm: TrustOptions["confirm"] = async ({ path: dir, files }) => {
179
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
180
+ try {
181
+ const shown = files.slice(0, 10).map((f) => ` ${f}`).join("\n") + (files.length > 10 ? `\n … ${files.length - 10} more` : "");
182
+ const answer = await rl.question(`jade: this project has a plugin at ${dir}:\n${shown}\nIt runs with your permissions. Load it? [y/N] `);
183
+ return /^y(es)?$/i.test(answer.trim());
184
+ } finally {
185
+ rl.close();
1370
186
  }
1371
- });
1372
- if (exit) await quit();
1373
- }
1374
-
1375
- /**
1376
- * 有新版本时在后台升级,下次启动生效;JADE_AUTO_UPDATE=off 时只提示。
1377
- * 每天最多查一次 npm;仓库里的开发版和 npm link 既不提示也不升级
1378
- */
1379
- async function checkForUpdate() {
1380
- const install = detectInstall();
1381
- if (install.kind === "dev") return;
1382
- const latest = await newerVersion(home).catch(() => undefined);
1383
- if (!latest) return;
1384
- const manual = () => screen.log(dim(`[jade ${latest} is available (you have ${VERSION}); run jade update]`));
1385
- if (!autoUpdateEnabled()) return manual();
1386
- const result = await autoUpdate(home, latest, { install }).catch(() => undefined);
1387
- if (result?.status === "installed") screen.log(dim(`[jade ${latest} was installed in the background; restart jade to use it]`));
1388
- else if (result?.status === "failed") screen.log(yellow(`[automatic update to jade ${latest} failed (see ${display(cwd, result.log)}); run jade update]`));
1389
- else if (result?.why !== "busy") manual();
1390
- }
1391
-
1392
- // ---------- 开始 ----------
1393
-
1394
- if (resumeId) {
1395
- let ok = false;
1396
- await occupy(async () => void (ok = await resumeSession()));
1397
- if (!ok) {
1398
- await screen.close();
1399
- process.exit(1);
1400
- }
187
+ };
188
+ return { trust: { trust: new FileTrustStore(path.join(home, "state", "trust.json")), confirm } };
1401
189
  }
1402
- else if (tui) screen.log(dim("Type / for commands, /model to configure the model, esc to interrupt."));
1403
- else screen.log(dim(`jade · ${shortPath(cwd)} · ${modelLabel()} · mode ${settings().mode} · session ${sessionId}`));
1404
- screen.status({ mode: settings().mode, session: sessionId });
1405
190
 
1406
- const first = opts.print ?? (opts.prompt.length > 0 ? opts.prompt.join(" ") : undefined);
1407
- if (tui) {
1408
- // 之后由输入框驱动:onSubmit → pump
1409
- ready = true;
1410
- for (const text of [...(first ? [first] : []), ...early.splice(0)]) onSubmit(text);
1411
- void checkForUpdate();
1412
- } else {
1413
- // -p 也能用自定义命令和插件的命令(内置命令需要交互,不在这里处理)
1414
- const name = first?.startsWith("/") ? first.slice(1).split(/\s+/)[0]!.toLowerCase() : undefined;
1415
- const args = first?.slice(1).replace(/^\S+\s*/, "") ?? "";
1416
- const custom = name !== undefined ? customs.get(name) : undefined;
1417
- await occupy(async () => {
1418
- const skill = name !== undefined && !custom ? skillCommands.get(name) : undefined;
1419
- const text = custom ? expandCommand(custom, args) : skill ? skillMessage(skill.name, args) : name !== undefined && !hostNames.has(name) && jade.commands.has(name) && !jade.commands.get(name)!.builtin ? await pluginCommand(name, args) : first;
1420
- if (text) await say(text);
1421
- });
1422
- await leave();
1423
- await sessions.settled();
1424
- await closePlugins();
1425
- await closeScreen();
191
+ // 直接运行(bun src/main.ts)时;bin/jade.js 导入后自己调用 main
192
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
193
+ process.exit(await main(process.argv.slice(2)));
1426
194
  }