@uncarved/jade 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +161 -150
- package/bin/jade.js +14 -25
- package/dist/api.d.ts +266 -0
- package/dist/api.js +38 -0
- package/dist/api.js.map +1 -0
- package/dist/config.d.ts +13 -32
- package/dist/config.js +39 -121
- package/dist/config.js.map +1 -1
- package/dist/fetch.d.ts +20 -0
- package/dist/fetch.js +190 -0
- package/dist/fetch.js.map +1 -0
- package/dist/hash.d.ts +2 -0
- package/dist/hash.js +42 -0
- package/dist/hash.js.map +1 -0
- package/dist/host.d.ts +71 -0
- package/dist/host.js +400 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +11 -30
- package/dist/index.js +11 -30
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +78 -0
- package/dist/install.js +292 -0
- package/dist/install.js.map +1 -0
- package/dist/main.d.ts +1 -2
- package/dist/main.js +160 -1362
- package/dist/main.js.map +1 -1
- package/dist/manifest.d.ts +23 -0
- package/dist/manifest.js +159 -0
- package/dist/manifest.js.map +1 -0
- package/dist/membrane.d.ts +33 -0
- package/dist/membrane.js +140 -0
- package/dist/membrane.js.map +1 -0
- package/dist/remote.d.ts +10 -0
- package/dist/remote.js +292 -0
- package/dist/remote.js.map +1 -0
- package/dist/rescue.d.ts +10 -0
- package/dist/rescue.js +216 -0
- package/dist/rescue.js.map +1 -0
- package/dist/resolve.d.ts +34 -0
- package/dist/resolve.js +178 -0
- package/dist/resolve.js.map +1 -0
- package/dist/rpc.d.ts +26 -0
- package/dist/rpc.js +144 -0
- package/dist/rpc.js.map +1 -0
- package/dist/secrets.d.ts +12 -0
- package/dist/secrets.js +125 -0
- package/dist/secrets.js.map +1 -0
- package/dist/session.d.ts +45 -0
- package/dist/session.js +401 -0
- package/dist/session.js.map +1 -0
- package/dist/source.d.ts +12 -0
- package/dist/source.js +72 -0
- package/dist/source.js.map +1 -0
- package/dist/state.d.ts +37 -0
- package/dist/state.js +93 -0
- package/dist/state.js.map +1 -0
- package/dist/update.d.ts +2 -0
- package/dist/update.js +6 -3
- package/dist/update.js.map +1 -1
- package/package.json +10 -8
- package/plugins/approval/index.ts +311 -0
- package/plugins/approval/plugin.json +22 -0
- package/{src/plugins → plugins/approval}/policy.ts +45 -104
- package/{src/plugins → plugins/approval}/review.ts +62 -16
- package/plugins/ask/index.ts +159 -0
- package/plugins/ask/plugin.json +8 -0
- package/plugins/budget/index.ts +38 -0
- package/plugins/budget/plugin.json +13 -0
- package/{src/plugins → plugins/checks}/checks.ts +48 -38
- package/plugins/checks/index.ts +158 -0
- package/plugins/checks/plugin.json +14 -0
- package/plugins/checks/project.ts +81 -0
- package/plugins/commands/index.ts +76 -0
- package/plugins/commands/plugin.json +7 -0
- package/{src/plugins → plugins/compact}/compact.ts +80 -39
- package/plugins/compact/index.ts +115 -0
- package/plugins/compact/plugin.json +17 -0
- package/plugins/compact/style.ts +17 -0
- package/plugins/continue/index.ts +58 -0
- package/plugins/continue/plugin.json +13 -0
- package/{src/ui → plugins/fs}/diff.ts +2 -2
- package/{src/tools → plugins/fs}/fs.ts +89 -46
- package/{src/tools → plugins/fs}/grep.ts +36 -8
- package/plugins/fs/index.ts +37 -0
- package/plugins/fs/plugin.json +7 -0
- package/{src/ui → plugins/fs}/renderers.ts +25 -70
- package/plugins/fs/style.ts +18 -0
- package/plugins/fs/sys.ts +81 -0
- package/plugins/keys/index.ts +53 -0
- package/plugins/keys/plugin.json +7 -0
- package/plugins/mcp/index.ts +192 -0
- package/{src → plugins/mcp}/mcp.ts +32 -32
- package/plugins/mcp/plugin.json +7 -0
- package/plugins/mcp/project.ts +93 -0
- package/plugins/memory/index.ts +105 -0
- package/{src → plugins/memory}/memory.ts +20 -2
- package/plugins/memory/notes.ts +43 -0
- package/plugins/memory/plugin.json +7 -0
- package/plugins/memory/style.ts +17 -0
- package/plugins/mentions/attach.ts +127 -0
- package/plugins/mentions/index.ts +99 -0
- package/plugins/mentions/plugin.json +7 -0
- package/plugins/mentions/style.ts +17 -0
- package/plugins/models/config.ts +53 -0
- package/plugins/models/configure.ts +455 -0
- package/plugins/models/context.ts +32 -0
- package/plugins/models/index.ts +213 -0
- package/plugins/models/plugin.json +8 -0
- package/{src → plugins/models}/provider.ts +16 -119
- package/plugins/models/saved.ts +94 -0
- package/plugins/modes/index.ts +222 -0
- package/plugins/modes/plugin.json +9 -0
- package/plugins/plugins/index.ts +38 -0
- package/plugins/plugins/plugin.json +7 -0
- package/plugins/print/index.ts +160 -0
- package/plugins/print/plugin.json +8 -0
- package/plugins/prompts/index.ts +111 -0
- package/plugins/prompts/plugin.json +8 -0
- package/plugins/prompts/prompts.ts +258 -0
- package/plugins/prompts/results.ts +63 -0
- package/plugins/prompts/sys.ts +84 -0
- package/plugins/renderers/index.ts +78 -0
- package/plugins/renderers/plugin.json +7 -0
- package/plugins/repeats/index.ts +165 -0
- package/plugins/repeats/plugin.json +6 -0
- package/plugins/schedule/cron.ts +74 -0
- package/plugins/schedule/index.ts +292 -0
- package/plugins/schedule/plugin.json +13 -0
- package/plugins/schedule/store.ts +149 -0
- package/plugins/scratch/index.ts +31 -0
- package/plugins/scratch/plugin.json +7 -0
- package/plugins/screenshot/index.ts +40 -0
- package/plugins/screenshot/plugin.json +7 -0
- package/plugins/screenshot/sys.ts +84 -0
- package/{src/tools/screenshot.ts → plugins/screenshot/tool.ts} +6 -6
- package/plugins/sessions/index.ts +148 -0
- package/plugins/sessions/plugin.json +8 -0
- package/plugins/shell/index.ts +33 -0
- package/plugins/shell/plugin.json +17 -0
- package/plugins/shell/renderers.ts +45 -0
- package/plugins/shell/service.ts +44 -0
- package/{src/tools → plugins/shell}/shell.ts +31 -20
- package/{src → plugins/shell}/sys.ts +2 -43
- package/plugins/skills/index.ts +96 -0
- package/plugins/skills/plugin.json +7 -0
- package/plugins/skills/project.ts +49 -0
- package/{src → plugins/skills}/skills.ts +4 -11
- package/plugins/suggest/index.ts +286 -0
- package/plugins/suggest/plugin.json +18 -0
- package/plugins/task/index.ts +168 -0
- package/plugins/task/plugin.json +15 -0
- package/plugins/task/style.ts +17 -0
- package/plugins/task/subagent.ts +343 -0
- package/plugins/todo/index.ts +93 -0
- package/plugins/todo/plugin.json +7 -0
- package/{src/ui → plugins/tui}/editor.ts +3 -0
- package/plugins/tui/frontend.ts +619 -0
- package/plugins/tui/index.ts +37 -0
- package/plugins/tui/mentions.ts +153 -0
- package/plugins/tui/plugin.json +10 -0
- package/{src/ui → plugins/tui}/render.ts +8 -2
- package/{src/ui → plugins/tui}/screen.ts +8 -3
- package/{src/ui → plugins/tui}/transcript.ts +79 -100
- package/{src/ui/tui.tsx → plugins/tui/tui.ts} +360 -392
- package/plugins/tui/vendor.ts +16 -0
- package/{src/tools → plugins/undo}/checkpoint.ts +45 -60
- package/plugins/undo/index.ts +143 -0
- package/plugins/undo/notes.ts +43 -0
- package/plugins/undo/plugin.json +7 -0
- package/plugins/undo/style.ts +17 -0
- package/plugins/update/index.ts +40 -0
- package/plugins/update/plugin.json +13 -0
- package/plugins/web/env.ts +78 -0
- package/plugins/web/index.ts +133 -0
- package/plugins/web/plugin.json +15 -0
- package/plugins/web/renderers.ts +11 -0
- package/{src/tools → plugins/web}/web.ts +64 -31
- package/plugins-dist/approval/index.js +287 -0
- package/plugins-dist/approval/plugin.json +28 -0
- package/{dist/plugins → plugins-dist/approval}/policy.js +41 -85
- package/{dist/plugins → plugins-dist/approval}/review.js +56 -10
- package/{dist/plugins → plugins-dist/approval}/schema.js +0 -1
- package/plugins-dist/ask/index.js +145 -0
- package/plugins-dist/ask/plugin.json +12 -0
- package/plugins-dist/budget/index.js +37 -0
- package/plugins-dist/budget/plugin.json +15 -0
- package/{dist/plugins → plugins-dist/checks}/checks.js +46 -35
- package/plugins-dist/checks/index.js +150 -0
- package/plugins-dist/checks/plugin.json +21 -0
- package/plugins-dist/checks/project.js +76 -0
- package/plugins-dist/commands/index.js +33 -0
- package/plugins-dist/commands/plugin.json +9 -0
- package/{dist/plugins → plugins-dist/compact}/compact.js +58 -34
- package/plugins-dist/compact/index.js +100 -0
- package/plugins-dist/compact/plugin.json +25 -0
- package/plugins-dist/compact/style.js +14 -0
- package/plugins-dist/continue/index.js +57 -0
- package/plugins-dist/continue/plugin.json +15 -0
- package/{dist/ui → plugins-dist/fs}/diff.js +2 -3
- package/{dist/tools → plugins-dist/fs}/fs.js +82 -46
- package/{dist/tools → plugins-dist/fs}/grep.js +36 -11
- package/plugins-dist/fs/index.js +39 -0
- package/plugins-dist/fs/plugin.json +10 -0
- package/{dist/ui → plugins-dist/fs}/renderers.js +24 -61
- package/plugins-dist/fs/style.js +15 -0
- package/plugins-dist/fs/sys.js +54 -0
- package/plugins-dist/keys/index.js +36 -0
- package/plugins-dist/keys/plugin.json +9 -0
- package/plugins-dist/mcp/index.js +187 -0
- package/{dist → plugins-dist/mcp}/mcp.js +34 -30
- package/plugins-dist/mcp/plugin.json +12 -0
- package/plugins-dist/mcp/project.js +90 -0
- package/plugins-dist/memory/index.js +94 -0
- package/{dist → plugins-dist/memory}/memory.js +21 -3
- package/plugins-dist/memory/notes.js +36 -0
- package/plugins-dist/memory/plugin.json +11 -0
- package/plugins-dist/memory/style.js +14 -0
- package/plugins-dist/mentions/attach.js +120 -0
- package/plugins-dist/mentions/index.js +87 -0
- package/plugins-dist/mentions/plugin.json +9 -0
- package/plugins-dist/mentions/style.js +14 -0
- package/plugins-dist/models/config.js +53 -0
- package/plugins-dist/models/configure.js +415 -0
- package/plugins-dist/models/context.js +27 -0
- package/plugins-dist/models/index.js +181 -0
- package/plugins-dist/models/plugin.json +14 -0
- package/{dist → plugins-dist/models}/provider.js +18 -81
- package/plugins-dist/models/saved.js +80 -0
- package/plugins-dist/modes/index.js +190 -0
- package/plugins-dist/modes/plugin.json +18 -0
- package/plugins-dist/plugins/index.js +37 -0
- package/plugins-dist/plugins/plugin.json +10 -0
- package/plugins-dist/print/index.js +172 -0
- package/plugins-dist/print/plugin.json +14 -0
- package/plugins-dist/prompts/index.js +85 -0
- package/plugins-dist/prompts/plugin.json +13 -0
- package/plugins-dist/prompts/prompts.js +231 -0
- package/plugins-dist/prompts/results.js +60 -0
- package/plugins-dist/prompts/sys.js +58 -0
- package/plugins-dist/renderers/index.js +36 -0
- package/plugins-dist/renderers/plugin.json +9 -0
- package/plugins-dist/repeats/index.js +165 -0
- package/plugins-dist/repeats/plugin.json +6 -0
- package/plugins-dist/schedule/cron.js +67 -0
- package/plugins-dist/schedule/index.js +281 -0
- package/plugins-dist/schedule/plugin.json +16 -0
- package/plugins-dist/schedule/store.js +125 -0
- package/plugins-dist/scratch/index.js +26 -0
- package/plugins-dist/scratch/plugin.json +10 -0
- package/plugins-dist/screenshot/index.js +35 -0
- package/plugins-dist/screenshot/plugin.json +11 -0
- package/plugins-dist/screenshot/sys.js +76 -0
- package/{dist/tools/screenshot.js → plugins-dist/screenshot/tool.js} +5 -4
- package/plugins-dist/sessions/index.js +136 -0
- package/plugins-dist/sessions/plugin.json +12 -0
- package/plugins-dist/shell/index.js +33 -0
- package/plugins-dist/shell/plugin.json +19 -0
- package/plugins-dist/shell/renderers.js +40 -0
- package/plugins-dist/shell/service.js +29 -0
- package/{dist/tools → plugins-dist/shell}/shell.js +31 -22
- package/{dist → plugins-dist/shell}/sys.js +2 -43
- package/plugins-dist/skills/index.js +90 -0
- package/plugins-dist/skills/plugin.json +12 -0
- package/plugins-dist/skills/project.js +47 -0
- package/{dist → plugins-dist/skills}/skills.js +3 -7
- package/plugins-dist/suggest/index.js +282 -0
- package/plugins-dist/suggest/plugin.json +23 -0
- package/plugins-dist/task/index.js +152 -0
- package/plugins-dist/task/plugin.json +23 -0
- package/plugins-dist/task/style.js +14 -0
- package/plugins-dist/task/subagent.js +284 -0
- package/{dist/tools/todo.js → plugins-dist/todo/index.js} +31 -9
- package/plugins-dist/todo/plugin.json +9 -0
- package/{dist/ui → plugins-dist/tui}/editor.js +3 -1
- package/plugins-dist/tui/frontend.js +609 -0
- package/{dist → plugins-dist/tui}/history.js +0 -1
- package/plugins-dist/tui/index.js +21 -0
- package/{dist/ui → plugins-dist/tui}/markdown.js +0 -1
- package/plugins-dist/tui/mentions.js +153 -0
- package/plugins-dist/tui/plugin.json +25 -0
- package/{dist/ui → plugins-dist/tui}/render.js +7 -3
- package/{dist/ui → plugins-dist/tui}/screen.js +6 -2
- package/{dist/ui → plugins-dist/tui}/transcript.js +79 -99
- package/{dist/ui → plugins-dist/tui}/tui.js +185 -54
- package/plugins-dist/tui/vendor.js +13822 -0
- package/{dist/tools → plugins-dist/undo}/checkpoint.js +48 -55
- package/plugins-dist/undo/index.js +143 -0
- package/plugins-dist/undo/notes.js +36 -0
- package/plugins-dist/undo/plugin.json +9 -0
- package/plugins-dist/undo/style.js +14 -0
- package/plugins-dist/update/index.js +34 -0
- package/plugins-dist/update/plugin.json +15 -0
- package/plugins-dist/web/env.js +80 -0
- package/plugins-dist/web/index.js +124 -0
- package/plugins-dist/web/plugin.json +21 -0
- package/plugins-dist/web/renderers.js +7 -0
- package/{dist/tools → plugins-dist/web}/web.js +56 -29
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +380 -0
- package/src/api.ts +298 -0
- package/src/config.ts +32 -134
- package/src/fetch.ts +216 -0
- package/src/hash.ts +39 -0
- package/src/host.ts +429 -0
- package/src/index.ts +23 -30
- package/src/install.ts +355 -0
- package/src/main.ts +156 -1387
- package/src/manifest.ts +160 -0
- package/src/membrane.ts +142 -0
- package/src/remote.ts +288 -0
- package/src/rescue.ts +217 -0
- package/src/resolve.ts +199 -0
- package/src/rpc.ts +144 -0
- package/src/secrets.ts +122 -0
- package/src/session.ts +458 -0
- package/src/source.ts +83 -0
- package/src/state.ts +120 -0
- package/src/update.ts +265 -262
- package/LICENSE +0 -21
- package/dist/commands.d.ts +0 -50
- package/dist/commands.js +0 -126
- package/dist/commands.js.map +0 -1
- package/dist/context.d.ts +0 -17
- package/dist/context.js +0 -53
- package/dist/context.js.map +0 -1
- package/dist/distro.d.ts +0 -141
- package/dist/distro.js +0 -462
- package/dist/distro.js.map +0 -1
- package/dist/history.d.ts +0 -10
- package/dist/history.js.map +0 -1
- package/dist/mcp.d.ts +0 -114
- package/dist/mcp.js.map +0 -1
- package/dist/memory.d.ts +0 -19
- package/dist/memory.js.map +0 -1
- package/dist/mentions.d.ts +0 -35
- package/dist/mentions.js +0 -130
- package/dist/mentions.js.map +0 -1
- package/dist/plugin-cli.d.ts +0 -16
- package/dist/plugin-cli.js +0 -294
- package/dist/plugin-cli.js.map +0 -1
- package/dist/plugins/budget.d.ts +0 -9
- package/dist/plugins/budget.js +0 -30
- package/dist/plugins/budget.js.map +0 -1
- package/dist/plugins/builtins.d.ts +0 -10
- package/dist/plugins/builtins.js +0 -25
- package/dist/plugins/builtins.js.map +0 -1
- package/dist/plugins/checks.d.ts +0 -71
- package/dist/plugins/checks.js.map +0 -1
- package/dist/plugins/compact.d.ts +0 -26
- package/dist/plugins/compact.js.map +0 -1
- package/dist/plugins/core.d.ts +0 -47
- package/dist/plugins/core.js +0 -229
- package/dist/plugins/core.js.map +0 -1
- package/dist/plugins/host.d.ts +0 -52
- package/dist/plugins/host.js +0 -115
- package/dist/plugins/host.js.map +0 -1
- package/dist/plugins/install.d.ts +0 -68
- package/dist/plugins/install.js +0 -377
- package/dist/plugins/install.js.map +0 -1
- package/dist/plugins/loader.d.ts +0 -410
- package/dist/plugins/loader.js +0 -407
- package/dist/plugins/loader.js.map +0 -1
- package/dist/plugins/policy.d.ts +0 -98
- package/dist/plugins/policy.js.map +0 -1
- package/dist/plugins/prompts.d.ts +0 -43
- package/dist/plugins/prompts.js +0 -284
- package/dist/plugins/prompts.js.map +0 -1
- package/dist/plugins/repeats.d.ts +0 -16
- package/dist/plugins/repeats.js +0 -151
- package/dist/plugins/repeats.js.map +0 -1
- package/dist/plugins/review.d.ts +0 -18
- package/dist/plugins/review.js.map +0 -1
- package/dist/plugins/schema.d.ts +0 -2
- package/dist/plugins/schema.js.map +0 -1
- package/dist/plugins/sessions.d.ts +0 -7
- package/dist/plugins/sessions.js +0 -110
- package/dist/plugins/sessions.js.map +0 -1
- package/dist/provider.d.ts +0 -165
- package/dist/provider.js.map +0 -1
- package/dist/session-lifecycle.d.ts +0 -61
- package/dist/session-lifecycle.js +0 -167
- package/dist/session-lifecycle.js.map +0 -1
- package/dist/session-scope.d.ts +0 -53
- package/dist/session-scope.js +0 -116
- package/dist/session-scope.js.map +0 -1
- package/dist/sessions.d.ts +0 -28
- package/dist/sessions.js +0 -73
- package/dist/sessions.js.map +0 -1
- package/dist/skills.d.ts +0 -37
- package/dist/skills.js.map +0 -1
- package/dist/sys.d.ts +0 -51
- package/dist/sys.js.map +0 -1
- package/dist/tools/ask.d.ts +0 -11
- package/dist/tools/ask.js +0 -62
- package/dist/tools/ask.js.map +0 -1
- package/dist/tools/checkpoint.d.ts +0 -43
- package/dist/tools/checkpoint.js.map +0 -1
- package/dist/tools/fs.d.ts +0 -39
- package/dist/tools/fs.js.map +0 -1
- package/dist/tools/grep.d.ts +0 -6
- package/dist/tools/grep.js.map +0 -1
- package/dist/tools/screenshot.d.ts +0 -15
- package/dist/tools/screenshot.js.map +0 -1
- package/dist/tools/shell.d.ts +0 -55
- package/dist/tools/shell.js.map +0 -1
- package/dist/tools/task.d.ts +0 -39
- package/dist/tools/task.js +0 -117
- package/dist/tools/task.js.map +0 -1
- package/dist/tools/todo.d.ts +0 -10
- package/dist/tools/todo.js.map +0 -1
- package/dist/tools/web.d.ts +0 -53
- package/dist/tools/web.js.map +0 -1
- package/dist/ui/configure.d.ts +0 -20
- package/dist/ui/configure.js +0 -447
- package/dist/ui/configure.js.map +0 -1
- package/dist/ui/diff.d.ts +0 -20
- package/dist/ui/diff.js.map +0 -1
- package/dist/ui/editor.d.ts +0 -41
- package/dist/ui/editor.js.map +0 -1
- package/dist/ui/markdown.d.ts +0 -22
- package/dist/ui/markdown.js.map +0 -1
- package/dist/ui/render.d.ts +0 -14
- package/dist/ui/render.js.map +0 -1
- package/dist/ui/renderers.d.ts +0 -8
- package/dist/ui/renderers.js.map +0 -1
- package/dist/ui/screen.d.ts +0 -118
- package/dist/ui/screen.js.map +0 -1
- package/dist/ui/transcript.d.ts +0 -46
- package/dist/ui/transcript.js.map +0 -1
- package/dist/ui/tui.d.ts +0 -47
- package/dist/ui/tui.js.map +0 -1
- package/src/commands.ts +0 -144
- package/src/context.ts +0 -64
- package/src/distro.ts +0 -577
- package/src/mentions.ts +0 -135
- package/src/plugin-cli.ts +0 -278
- package/src/plugins/budget.ts +0 -37
- package/src/plugins/builtins.ts +0 -34
- package/src/plugins/core.ts +0 -257
- package/src/plugins/host.ts +0 -146
- package/src/plugins/install.ts +0 -429
- package/src/plugins/loader.ts +0 -742
- package/src/plugins/prompts.ts +0 -327
- package/src/plugins/repeats.ts +0 -157
- package/src/plugins/sessions.ts +0 -109
- package/src/session-lifecycle.ts +0 -194
- package/src/session-scope.ts +0 -135
- package/src/sessions.ts +0 -78
- package/src/tools/ask.ts +0 -72
- package/src/tools/task.ts +0 -149
- package/src/tools/todo.ts +0 -67
- package/src/ui/configure.ts +0 -471
- /package/{src/plugins → plugins/approval}/schema.ts +0 -0
- /package/{src → plugins/tui}/history.ts +0 -0
- /package/{src/ui → plugins/tui}/markdown.ts +0 -0
package/src/main.ts
CHANGED
|
@@ -1,1426 +1,195 @@
|
|
|
1
|
-
|
|
2
|
-
// jade
|
|
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 {
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
5
|
import os from "node:os";
|
|
10
6
|
import path from "node:path";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
-
|
|
67
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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: "jade --help" shows the terminal interface's options,
|
|
29
|
+
"jade -p --help" the options for running one prompt.`;
|
|
82
30
|
|
|
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
31
|
/**
|
|
367
|
-
*
|
|
368
|
-
*
|
|
32
|
+
* jade plugins 的子命令(含别名):单独写在 jade 后面时多半是漏了 plugins。
|
|
33
|
+
* update、upgrade 不在里面:jade update 升级 jade 本身,jade upgrade 多半也是想升级 jade
|
|
369
34
|
*/
|
|
370
|
-
|
|
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
|
-
}
|
|
35
|
+
const PLUGIN_SUBCOMMANDS: ReadonlySet<string> = new Set(["list", "ls", "add", "install", "remove", "rm", "uninstall", "enable", "disable"]);
|
|
389
36
|
|
|
390
|
-
|
|
391
|
-
// 写成正斜杠:Windows 上 Git Bash、Python、Node 都认 C:/Users/...,而 /tmp 在它们之间不是同一个地方
|
|
392
|
-
const scratch = realpathSync.native(await mkdtemp(path.join(os.tmpdir(), "jade-"))).replaceAll("\\", "/");
|
|
37
|
+
const pkgDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
393
38
|
|
|
394
|
-
|
|
395
|
-
|
|
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;
|
|
39
|
+
function version(): string {
|
|
40
|
+
return JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8")).version;
|
|
433
41
|
}
|
|
434
42
|
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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);
|
|
43
|
+
export async function main(argv: readonly string[]): Promise<number> {
|
|
44
|
+
if (argv[0] === "-v" || argv[0] === "--version") {
|
|
45
|
+
console.log(version());
|
|
46
|
+
return 0;
|
|
445
47
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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);
|
|
48
|
+
const cwd = process.cwd();
|
|
49
|
+
const home = process.env.JADE_HOME || path.join(os.homedir(), ".jade");
|
|
50
|
+
const roots: LayerRoot[] = [
|
|
51
|
+
// 编译好的宿主(dist/*.js)用编译好的插件:Node 不给 node_modules 里的 .ts 去类型
|
|
52
|
+
{ layer: "bundled", root: path.join(pkgDir, import.meta.url.endsWith(".js") ? "plugins-dist" : "plugins") },
|
|
53
|
+
{ layer: "user", root: path.join(home, "plugins") },
|
|
54
|
+
{ layer: "project", root: path.join(cwd, ".jade", "plugins") },
|
|
55
|
+
];
|
|
56
|
+
const safe = argv.includes("--safe");
|
|
57
|
+
const rest = argv.filter((a) => a !== "--safe");
|
|
58
|
+
const flags = rest.filter((a) => a.startsWith("-"));
|
|
471
59
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
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 },
|
|
60
|
+
if (rest[0] === "plugins") {
|
|
61
|
+
try {
|
|
62
|
+
console.log(
|
|
63
|
+
await pluginsCommand(rest.slice(1), {
|
|
64
|
+
roots,
|
|
65
|
+
home,
|
|
66
|
+
flags,
|
|
67
|
+
safe,
|
|
68
|
+
trust: new FileTrustStore(path.join(home, "state", "trust.json")),
|
|
69
|
+
log: (message) => console.error(`jade: ${message}`),
|
|
70
|
+
}),
|
|
736
71
|
);
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
screen.log(dim(` ${q.question} → `) + answer);
|
|
72
|
+
return 0;
|
|
73
|
+
} catch (e) {
|
|
74
|
+
console.error(e instanceof Error ? e.message : String(e));
|
|
75
|
+
return 2;
|
|
742
76
|
}
|
|
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
77
|
}
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
return
|
|
834
|
-
}
|
|
835
|
-
|
|
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;
|
|
78
|
+
// 不启动插件宿主:插件坏了也能升级 jade
|
|
79
|
+
if (rest[0] === "update") return updateCli(rest.slice(1));
|
|
80
|
+
if (rest[0] === "upgrade") {
|
|
81
|
+
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.`);
|
|
82
|
+
return 2;
|
|
83
|
+
}
|
|
84
|
+
if (rest[0] === "help") {
|
|
85
|
+
console.log(USAGE);
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
// jade remove plugins x、jade add foo:前端会把它当成第一条消息发给模型(auto 模式下模型可能真去删东西)。
|
|
89
|
+
// 带引号的消息(jade "add a test")是一整个参数,不会和子命令名完全相同
|
|
90
|
+
if (rest[0] !== undefined && PLUGIN_SUBCOMMANDS.has(rest[0])) {
|
|
91
|
+
const args = rest.slice(1).filter((a) => a !== "plugins" && a !== "plugin");
|
|
92
|
+
// 只有一个词时加引号还是同一个参数,只能进 jade 再输入
|
|
93
|
+
const instead = rest.length > 1 ? `quote the whole message (jade "${rest.join(" ")}") or type it inside jade` : "type it inside jade";
|
|
94
|
+
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}.`);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 前端起来之前,消息打到 stderr;之后交给 ui@1
|
|
99
|
+
let host: PluginHost | undefined;
|
|
100
|
+
const report = (message: string) => {
|
|
101
|
+
try {
|
|
102
|
+
const ui = host?.service<UI>("ui@1");
|
|
103
|
+
if (ui) return ui.notify(message, "warning");
|
|
104
|
+
} catch {
|
|
105
|
+
// ui@1 的提供者坏了:退回 stderr
|
|
853
106
|
}
|
|
854
|
-
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
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
|
-
},
|
|
107
|
+
console.error(`jade: ${message}`);
|
|
108
|
+
};
|
|
109
|
+
const opts: HostOptions = {
|
|
110
|
+
roots,
|
|
111
|
+
home,
|
|
112
|
+
cwd,
|
|
113
|
+
flags,
|
|
114
|
+
safe,
|
|
115
|
+
config: { project: path.join(cwd, ".jade", "config.json") },
|
|
116
|
+
report,
|
|
117
|
+
...(await trustOptions(home, roots)),
|
|
876
118
|
};
|
|
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
119
|
try {
|
|
1051
|
-
|
|
1052
|
-
} catch (
|
|
1053
|
-
//
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
screen.log("Use /clear or /resume to continue.");
|
|
1057
|
-
return;
|
|
120
|
+
host = await PluginHost.start(opts);
|
|
121
|
+
} catch (e) {
|
|
122
|
+
// 例如手改坏了的 plugins.json:说清楚是哪个文件,不打一整段堆栈
|
|
123
|
+
console.error(`jade: ${e instanceof Error ? e.message : String(e)}`);
|
|
124
|
+
return 1;
|
|
1058
125
|
}
|
|
1059
|
-
|
|
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
|
-
}
|
|
126
|
+
const uninstall = host.installProcessHandlers();
|
|
1068
127
|
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
const
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
process.on("SIGINT", () => (running ? interrupt() : void quit(130)));
|
|
1083
|
-
|
|
1084
|
-
/** guarded 里最近一次抛出的错误;每次 guarded 开始时清掉 */
|
|
1085
|
-
let lastThrown: string | undefined;
|
|
128
|
+
const ac = new AbortController();
|
|
129
|
+
let lastSigint = 0;
|
|
130
|
+
const onSigint = () => {
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
if (now - lastSigint <= DOUBLE_SIGINT_MS) {
|
|
133
|
+
// 不经过任何插件:插件出问题时用户一定能停下来
|
|
134
|
+
host?.sessions.current?.abort(new Error("interrupted"));
|
|
135
|
+
process.stderr.write("\njade: interrupted\n");
|
|
136
|
+
process.exit(130);
|
|
137
|
+
}
|
|
138
|
+
lastSigint = now;
|
|
139
|
+
};
|
|
140
|
+
process.on("SIGINT", onSigint);
|
|
1086
141
|
|
|
1087
|
-
|
|
1088
|
-
view.turnFailed = false;
|
|
1089
|
-
view.lastError = undefined;
|
|
1090
|
-
lastThrown = undefined;
|
|
142
|
+
let code = 1;
|
|
1091
143
|
try {
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
144
|
+
const frontend = host.service<Frontend>("frontend@1");
|
|
145
|
+
if (!frontend) {
|
|
146
|
+
console.error(noFrontend(host, safe));
|
|
147
|
+
} else {
|
|
148
|
+
code = (await frontend.run({ argv: rest, sessions: host.sessions, signal: ac.signal })) ?? 0;
|
|
149
|
+
}
|
|
150
|
+
} catch (e) {
|
|
151
|
+
console.error(`jade: ${e instanceof Error ? e.message : String(e)}`);
|
|
1097
152
|
} finally {
|
|
1098
|
-
|
|
153
|
+
ac.abort();
|
|
154
|
+
process.off("SIGINT", onSigint);
|
|
155
|
+
await host.close();
|
|
156
|
+
uninstall();
|
|
1099
157
|
}
|
|
158
|
+
return code;
|
|
1100
159
|
}
|
|
1101
160
|
|
|
1102
|
-
/**
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
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() });
|
|
161
|
+
/** 没有前端时核心没有任何界面:打印出问题的插件,提示救援办法(3.2) */
|
|
162
|
+
function noFrontend(host: PluginHost, safe: boolean): string {
|
|
163
|
+
const lines = ["jade: no frontend plugin could start."];
|
|
164
|
+
for (const p of host.status()) {
|
|
165
|
+
if (p.state === "active" || p.state === "disabled" || p.reason?.startsWith("frontend ")) continue;
|
|
166
|
+
lines.push(` ${p.id ?? p.dir} (${p.layer}): ${p.state}${p.reason ? `: ${p.reason}` : ""}`);
|
|
1156
167
|
}
|
|
1157
|
-
|
|
1158
|
-
|
|
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();
|
|
168
|
+
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.");
|
|
169
|
+
return lines.join("\n");
|
|
1167
170
|
}
|
|
1168
171
|
|
|
1169
172
|
/**
|
|
1170
|
-
*
|
|
1171
|
-
*
|
|
173
|
+
* 项目层插件的确认(第 7 节):有带代码的项目层插件、且能在终端里问时才提供。
|
|
174
|
+
* 确认记录存在 $JADE_HOME/state/trust.json,按插件目录内容的哈希,内容变了要重新确认
|
|
1172
175
|
*/
|
|
1173
|
-
function
|
|
1174
|
-
const
|
|
1175
|
-
if (!
|
|
1176
|
-
const
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
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);
|
|
176
|
+
async function trustOptions(home: string, roots: LayerRoot[]): Promise<{ trust?: TrustOptions }> {
|
|
177
|
+
const project = roots.find((r) => r.layer === "project")!;
|
|
178
|
+
if (!existsSync(project.root) || !process.stdin.isTTY || !process.stderr.isTTY) return {};
|
|
179
|
+
const confirm: TrustOptions["confirm"] = async ({ path: dir, files }) => {
|
|
180
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
181
|
+
try {
|
|
182
|
+
const shown = files.slice(0, 10).map((f) => ` ${f}`).join("\n") + (files.length > 10 ? `\n … ${files.length - 10} more` : "");
|
|
183
|
+
const answer = await rl.question(`jade: this project has a plugin at ${dir}:\n${shown}\nIt runs with your permissions. Load it? [y/N] `);
|
|
184
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
185
|
+
} finally {
|
|
186
|
+
rl.close();
|
|
1370
187
|
}
|
|
1371
|
-
}
|
|
1372
|
-
|
|
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
|
-
}
|
|
188
|
+
};
|
|
189
|
+
return { trust: { trust: new FileTrustStore(path.join(home, "state", "trust.json")), confirm } };
|
|
1401
190
|
}
|
|
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
191
|
|
|
1406
|
-
|
|
1407
|
-
if (
|
|
1408
|
-
|
|
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();
|
|
192
|
+
// 直接运行(bun src/main.ts)时;bin/jade.js 导入后自己调用 main
|
|
193
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
194
|
+
process.exit(await main(process.argv.slice(2)));
|
|
1426
195
|
}
|