@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/manifest.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// 发现插件、读取并校验 plugin.json:不执行插件代码(原则 4)。
|
|
2
|
+
|
|
3
|
+
import { readdir, readFile, readlink, stat } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type { ConfigKey, Manifest, PluginLayer, PluginSource } from "./api.ts";
|
|
6
|
+
|
|
7
|
+
export interface LayerRoot {
|
|
8
|
+
layer: PluginLayer;
|
|
9
|
+
/** 这个目录下的每个子目录是一个插件 */
|
|
10
|
+
root: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 读不出清单的插件目录 */
|
|
14
|
+
export interface BrokenSource {
|
|
15
|
+
dir: string;
|
|
16
|
+
layer: PluginLayer;
|
|
17
|
+
error: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const SERVICE = /^[a-z0-9][\w.\-/]*@\d+$/i;
|
|
21
|
+
/** 核心自己的身份(调用方 id、交给内核的插件 id),插件不能用 */
|
|
22
|
+
const RESERVED_IDS: ReadonlySet<string> = new Set(["jade", "jade/core"]);
|
|
23
|
+
const ID = /^[a-z0-9][\w.\-]*(\/[a-z0-9][\w.\-]*)*$/i;
|
|
24
|
+
|
|
25
|
+
/** 插件 id 的形状;救援 CLI 用它拒绝带路径分隔符或 .. 的 id */
|
|
26
|
+
export function isPluginId(value: string): boolean {
|
|
27
|
+
return ID.test(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* --link 装的插件,链接指向的目录被删了(例如源码仓库里挪走了):说清楚是链接坏了,并给出删掉它的命令。
|
|
32
|
+
* 不是这种情况时返回 undefined
|
|
33
|
+
*/
|
|
34
|
+
async function danglingLink(dir: string, name: string, layer: PluginLayer, err: Error): Promise<string | undefined> {
|
|
35
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
|
|
36
|
+
const target = await readlink(dir).catch(() => undefined);
|
|
37
|
+
if (target === undefined) return undefined;
|
|
38
|
+
// Windows 的 junction 读出来带 \\?\ 前缀和结尾的分隔符
|
|
39
|
+
const shown = path.resolve(path.dirname(dir), target.replace(/^\\\\\?\\/, ""));
|
|
40
|
+
// 目录名是 id 里的 / 换成 __(install.ts 的 installDir)
|
|
41
|
+
const id = name.replaceAll("__", "/");
|
|
42
|
+
return `a link to ${shown}, which no longer exists; run "jade plugins remove ${id}${layer === "project" ? " --project" : ""}"`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 按层级顺序发现插件;层级内按目录名排序,结果稳定 */
|
|
46
|
+
export async function discover(roots: LayerRoot[]): Promise<{ sources: PluginSource[]; broken: BrokenSource[] }> {
|
|
47
|
+
const sources: PluginSource[] = [];
|
|
48
|
+
const broken: BrokenSource[] = [];
|
|
49
|
+
for (const { layer, root } of roots) {
|
|
50
|
+
let names: string[];
|
|
51
|
+
try {
|
|
52
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
53
|
+
// . 开头的是安装时的临时目录(.staging-*、.old-*),不是插件。
|
|
54
|
+
// --link 装的是符号链接/junction,Dirent 里不算目录,用 stat 跟过去再判断。
|
|
55
|
+
names = entries.filter((e) => !e.name.startsWith(".") && (e.isDirectory() || e.isSymbolicLink())).map((e) => e.name).sort();
|
|
56
|
+
} catch {
|
|
57
|
+
continue; // 层级目录不存在:没有插件
|
|
58
|
+
}
|
|
59
|
+
for (const name of names) {
|
|
60
|
+
const dir = path.resolve(root, name);
|
|
61
|
+
const info = await stat(dir).catch((e: unknown) => e as Error);
|
|
62
|
+
if (info instanceof Error) {
|
|
63
|
+
broken.push({ dir, layer, error: (await danglingLink(dir, name, layer, info)) ?? `not a readable directory: ${info.message}` });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!info.isDirectory()) continue;
|
|
67
|
+
try {
|
|
68
|
+
const raw: unknown = JSON.parse(await readFile(path.join(dir, "plugin.json"), "utf8"));
|
|
69
|
+
sources.push({ manifest: parseManifest(raw), dir, layer });
|
|
70
|
+
} catch (e) {
|
|
71
|
+
broken.push({ dir, layer, error: e instanceof Error ? e.message : String(e) });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { sources, broken };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 校验清单的形状,出错时抛出说明哪个字段不对的错误 */
|
|
79
|
+
export function parseManifest(raw: unknown): Manifest {
|
|
80
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("plugin.json: expected an object");
|
|
81
|
+
const m = raw as Record<string, unknown>;
|
|
82
|
+
const str = (k: string) => {
|
|
83
|
+
if (typeof m[k] !== "string" || m[k] === "") throw new Error(`plugin.json: "${k}" must be a non-empty string`);
|
|
84
|
+
return m[k] as string;
|
|
85
|
+
};
|
|
86
|
+
const services = (k: string) => {
|
|
87
|
+
const v = m[k];
|
|
88
|
+
if (v === undefined) return undefined;
|
|
89
|
+
if (!Array.isArray(v) || v.some((s) => typeof s !== "string" || !SERVICE.test(s))) {
|
|
90
|
+
throw new Error(`plugin.json: "${k}" must be a list of services like "commands@1"`);
|
|
91
|
+
}
|
|
92
|
+
return v as string[];
|
|
93
|
+
};
|
|
94
|
+
const id = str("id");
|
|
95
|
+
if (!ID.test(id)) throw new Error(`plugin.json: invalid id "${id}"`);
|
|
96
|
+
if (RESERVED_IDS.has(id)) throw new Error(`plugin.json: id "${id}" is reserved for the core`);
|
|
97
|
+
const manifest: Manifest = { id, version: str("version"), api: str("api") };
|
|
98
|
+
if (parseCaret(manifest.api) === undefined) throw new Error(`plugin.json: "api" must be a ^ range like "^1", got "${manifest.api}"`);
|
|
99
|
+
|
|
100
|
+
if ((m.entry === undefined) === (m.runtime === undefined)) throw new Error(`plugin.json: exactly one of "entry" and "runtime" is required`);
|
|
101
|
+
if (m.entry !== undefined) manifest.entry = str("entry");
|
|
102
|
+
if (m.runtime !== undefined) {
|
|
103
|
+
const r = m.runtime as Record<string, unknown> | null;
|
|
104
|
+
if (typeof r !== "object" || r === null || typeof r.command !== "string" || (r.args !== undefined && !(Array.isArray(r.args) && r.args.every((a) => typeof a === "string")))) {
|
|
105
|
+
throw new Error(`plugin.json: "runtime" must be { command: string, args?: string[] }`);
|
|
106
|
+
}
|
|
107
|
+
manifest.runtime = { command: r.command, ...(r.args ? { args: r.args as string[] } : {}) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for (const k of ["provides", "requires", "optional"] as const) {
|
|
111
|
+
const v = services(k);
|
|
112
|
+
if (v) manifest[k] = v;
|
|
113
|
+
}
|
|
114
|
+
if (m.replaces !== undefined) {
|
|
115
|
+
if (!Array.isArray(m.replaces) || m.replaces.some((s) => typeof s !== "string")) throw new Error(`plugin.json: "replaces" must be a list of plugin ids`);
|
|
116
|
+
manifest.replaces = m.replaces as string[];
|
|
117
|
+
}
|
|
118
|
+
if (m.frontend !== undefined) {
|
|
119
|
+
const f = m.frontend as Record<string, unknown> | null;
|
|
120
|
+
if (typeof f !== "object" || f === null || typeof f.name !== "string" || (f.default !== undefined && typeof f.default !== "boolean") || (f.flag !== undefined && typeof f.flag !== "string")) {
|
|
121
|
+
throw new Error(`plugin.json: "frontend" must be { name: string, default?: boolean, flag?: string }`);
|
|
122
|
+
}
|
|
123
|
+
manifest.frontend = { name: f.name, ...(f.default !== undefined ? { default: f.default as boolean } : {}), ...(f.flag !== undefined ? { flag: f.flag as string } : {}) };
|
|
124
|
+
}
|
|
125
|
+
if (m.config !== undefined) {
|
|
126
|
+
const c = m.config as Record<string, unknown> | null;
|
|
127
|
+
const bad = (k: string) => new Error(`plugin.json: "config.${k}" must be { default?, description?: string, project?: boolean }`);
|
|
128
|
+
if (typeof c !== "object" || c === null || Array.isArray(c)) throw new Error(`plugin.json: "config" must be an object of keys`);
|
|
129
|
+
manifest.config = {};
|
|
130
|
+
for (const [k, raw] of Object.entries(c)) {
|
|
131
|
+
const v = raw as Record<string, unknown> | null;
|
|
132
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) throw bad(k);
|
|
133
|
+
if ((v.description !== undefined && typeof v.description !== "string") || (v.project !== undefined && typeof v.project !== "boolean")) throw bad(k);
|
|
134
|
+
manifest.config[k] = { ...v } as ConfigKey;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return manifest;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** "^1"、"^1.2"、"^0.3.1" → 数字列表;格式不对返回 undefined */
|
|
141
|
+
function parseCaret(range: string): number[] | undefined {
|
|
142
|
+
const m = /^\^(\d+)(?:\.(\d+)(?:\.(\d+))?)?$/.exec(range);
|
|
143
|
+
return m ? m.slice(1).filter((x) => x !== undefined).map(Number) : undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** semver 的 ^ 规则,和内核的 satisfiesCaret 一致:第一个非零位(未写出的位不算)不变,且不低于范围本身 */
|
|
147
|
+
export function satisfiesCaret(range: string, version: string): boolean {
|
|
148
|
+
const want = parseCaret(range);
|
|
149
|
+
if (!want) return false;
|
|
150
|
+
const have = version.split(".").map(Number);
|
|
151
|
+
const fixed = want.findIndex((x) => x !== 0);
|
|
152
|
+
const last = fixed === -1 ? want.length - 1 : fixed;
|
|
153
|
+
for (let i = 0; i <= last; i++) if (have[i] !== want[i]) return false;
|
|
154
|
+
for (let i = last + 1; i < 3; i++) {
|
|
155
|
+
const h = have[i] ?? 0;
|
|
156
|
+
const w = want[i] ?? 0;
|
|
157
|
+
if (h !== w) return h > w;
|
|
158
|
+
}
|
|
159
|
+
return true;
|
|
160
|
+
}
|
package/src/membrane.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// 膜:所有跨插件的调用都经过这里(5.2)。负责归属、过期检查、错误包装。
|
|
2
|
+
// 作用域:所有注册都挂在作用域上,关闭时逆序撤销(4.1)。
|
|
3
|
+
|
|
4
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
+
import { PluginError, ServiceUnavailable, StaleContext, type Disposer } from "./api.ts";
|
|
6
|
+
|
|
7
|
+
export const DISPOSE_TIMEOUT_MS = 5000;
|
|
8
|
+
|
|
9
|
+
export class Scope {
|
|
10
|
+
readonly plugin: string;
|
|
11
|
+
#ctrl = new AbortController();
|
|
12
|
+
/** owner:以谁的身份执行(提供者挂在调用方作用域上的清理函数属于提供者) */
|
|
13
|
+
#disposers: { d: Disposer; owner?: Owner }[] = [];
|
|
14
|
+
#closed = false;
|
|
15
|
+
|
|
16
|
+
constructor(plugin: string) {
|
|
17
|
+
this.plugin = plugin;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get signal(): AbortSignal {
|
|
21
|
+
return this.#ctrl.signal;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get closed(): boolean {
|
|
25
|
+
return this.#closed;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 登记清理函数,默认以本作用域的插件身份执行。作用域已关闭时抛 StaleContext */
|
|
29
|
+
add(d: Disposer, owner?: Owner): void {
|
|
30
|
+
if (this.#closed) throw new StaleContext(this.plugin);
|
|
31
|
+
this.#disposers.push(owner ? { d, owner } : { d });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 中止 signal,逆序执行清理函数;每个最多等 DISPOSE_TIMEOUT_MS。返回清理时的错误,不抛出 */
|
|
35
|
+
async close(timeoutMs = DISPOSE_TIMEOUT_MS): Promise<unknown[]> {
|
|
36
|
+
if (this.#closed) return [];
|
|
37
|
+
this.#closed = true;
|
|
38
|
+
this.#ctrl.abort(new StaleContext(this.plugin));
|
|
39
|
+
const errors: unknown[] = [];
|
|
40
|
+
const self: Owner = { plugin: this.plugin, scope: this };
|
|
41
|
+
for (const { d, owner = self } of this.#disposers.reverse()) {
|
|
42
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
43
|
+
try {
|
|
44
|
+
const done = ambient.run(owner, d);
|
|
45
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
46
|
+
timer = setTimeout(() => reject(new Error(`dispose timed out after ${timeoutMs} ms`)), timeoutMs);
|
|
47
|
+
});
|
|
48
|
+
await Promise.race([done, timeout]);
|
|
49
|
+
} catch (e) {
|
|
50
|
+
errors.push(new PluginError(owner.plugin, "dispose", e));
|
|
51
|
+
} finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
this.#disposers = [];
|
|
56
|
+
return errors;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 一段代码属于哪个插件的哪个作用域 */
|
|
61
|
+
export interface Owner {
|
|
62
|
+
plugin: string;
|
|
63
|
+
scope: Scope;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 当前正在执行的插件代码的归属;定时器、Promise 回调会继承它(node 下可靠,bun 下只有定时器可靠,见 5.3) */
|
|
67
|
+
export const ambient = new AsyncLocalStorage<Owner>();
|
|
68
|
+
|
|
69
|
+
const PASS_THROUGH = (e: unknown) => e instanceof PluginError || e instanceof StaleContext || e instanceof ServiceUnavailable;
|
|
70
|
+
|
|
71
|
+
/** 以 owner 的身份执行 fn:过期检查、归属、把错误包成 PluginError。结果里的函数和普通对象也归 owner */
|
|
72
|
+
export function invoke<T>(owner: Owner, where: string, fn: () => T): T {
|
|
73
|
+
if (owner.scope.closed) throw new StaleContext(owner.plugin);
|
|
74
|
+
const fail = (e: unknown) => {
|
|
75
|
+
throw PASS_THROUGH(e) ? e : new PluginError(owner.plugin, where, e);
|
|
76
|
+
};
|
|
77
|
+
let result: T;
|
|
78
|
+
try {
|
|
79
|
+
result = ambient.run(owner, fn);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
return fail(e);
|
|
82
|
+
}
|
|
83
|
+
if (result instanceof Promise) return result.then((v) => wrap(v, owner), fail) as T;
|
|
84
|
+
return wrap(result, owner);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const MAX_DEPTH = 4;
|
|
88
|
+
const wrapped = new WeakSet<object>();
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 把值里的函数包成"属于 owner 的函数":被别人调用时以 owner 身份执行,出错归 owner,owner 关闭后失效。
|
|
92
|
+
* 只深入普通对象和数组;class 实例、Promise 等原样返回(对象的身份会变,见 5.2)
|
|
93
|
+
*/
|
|
94
|
+
export function wrap<T>(value: T, owner: Owner, depth = 0): T {
|
|
95
|
+
if (typeof value === "function") {
|
|
96
|
+
if (wrapped.has(value)) return value;
|
|
97
|
+
const fn = value as unknown as (...args: unknown[]) => unknown;
|
|
98
|
+
const out = function (this: unknown, ...args: unknown[]) {
|
|
99
|
+
// 参数里的回调属于调用方
|
|
100
|
+
const caller = ambient.getStore();
|
|
101
|
+
const a = caller ? args.map((x) => wrap(x, caller)) : args;
|
|
102
|
+
return invoke(owner, fn.name || "callback", () => fn.apply(this, a));
|
|
103
|
+
};
|
|
104
|
+
wrapped.add(out);
|
|
105
|
+
return out as T;
|
|
106
|
+
}
|
|
107
|
+
if (depth >= MAX_DEPTH || value === null || typeof value !== "object" || wrapped.has(value)) return value;
|
|
108
|
+
if (Array.isArray(value)) return value.map((x) => wrap(x, owner, depth + 1)) as T;
|
|
109
|
+
const proto = Object.getPrototypeOf(value);
|
|
110
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
111
|
+
const out: Record<string, unknown> = {};
|
|
112
|
+
for (const [k, x] of Object.entries(value)) out[k] = wrap(x, owner, depth + 1);
|
|
113
|
+
return out as T;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 调用方 caller 手里的服务句柄。每次访问检查:调用方没有过期、提供者仍然有效。
|
|
118
|
+
* 方法以提供者身份执行,参数里的回调归调用方
|
|
119
|
+
*/
|
|
120
|
+
export function serviceHandle<T extends object>(service: string, impl: object, provider: Owner, caller: Owner, isLive: () => boolean): T {
|
|
121
|
+
return new Proxy(Object.create(null) as T, {
|
|
122
|
+
get(_, prop) {
|
|
123
|
+
if (caller.scope.closed) throw new StaleContext(caller.plugin);
|
|
124
|
+
if (!isLive()) throw new ServiceUnavailable(service, provider.plugin);
|
|
125
|
+
const v = (impl as Record<string | symbol, unknown>)[prop];
|
|
126
|
+
if (typeof v !== "function") return wrap(v, provider);
|
|
127
|
+
const method = v as (...args: unknown[]) => unknown;
|
|
128
|
+
return (...args: unknown[]) => {
|
|
129
|
+
if (caller.scope.closed) throw new StaleContext(caller.plugin);
|
|
130
|
+
if (!isLive()) throw new ServiceUnavailable(service, provider.plugin);
|
|
131
|
+
const a = args.map((x) => wrap(x, caller));
|
|
132
|
+
return invoke(provider, `${service}.${String(prop)}`, () => method.apply(impl, a));
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
has(_, prop) {
|
|
136
|
+
return prop in impl;
|
|
137
|
+
},
|
|
138
|
+
set() {
|
|
139
|
+
throw new TypeError(`service ${service} is read-only`);
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
}
|
package/src/remote.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// 进程外插件的桥(第 6 节):启动插件进程,把它包成一个普通的 PluginModule。
|
|
2
|
+
// 核心的其余部分不知道插件在进程外:服务、注册、作用域、膜、隔离都和进程内插件一样。
|
|
3
|
+
//
|
|
4
|
+
// 协议方法和具体服务无关:
|
|
5
|
+
// 宿主 → 插件:initialize、scope/open、scope/close、call,通知 caller/open、caller/close、$/cancel
|
|
6
|
+
// 插件 → 宿主:provide、kernel/tool、kernel/hook、secrets/get、secrets/set、call(target 是服务名、"$session" 或函数句柄)
|
|
7
|
+
// 值里的函数表示成句柄 { "$fn": id },对方用 call 调用它。句柄属于一个作用域,作用域关闭后失效。
|
|
8
|
+
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import type { HookContext, RemoteHookSpec, ToolResult } from "uncarved";
|
|
13
|
+
import { API_VERSION, type Caller, type PluginModule, type PluginSource, type ProcessContext, type ScopeContext, type SessionContext } from "./api.ts";
|
|
14
|
+
import { ambient, type Owner } from "./membrane.ts";
|
|
15
|
+
import { Rpc } from "./rpc.ts";
|
|
16
|
+
|
|
17
|
+
/** 插件进程启动后多久内要回复 initialize */
|
|
18
|
+
export const INIT_TIMEOUT_MS = 10_000;
|
|
19
|
+
/** 关闭时等插件进程自己退出的时间,之后强制结束 */
|
|
20
|
+
const EXIT_GRACE_MS = 2000;
|
|
21
|
+
/** Python SDK(单文件 jade_plugin.py)所在目录,加进插件进程的 PYTHONPATH */
|
|
22
|
+
const PYTHON_SDK = fileURLToPath(new URL("../sdk/python", import.meta.url));
|
|
23
|
+
/** 插件进程退出时附在原因后面的 stderr 行数 */
|
|
24
|
+
const STDERR_TAIL = 5;
|
|
25
|
+
|
|
26
|
+
export interface RemoteOptions {
|
|
27
|
+
report(message: string): void;
|
|
28
|
+
/** 插件进程意外退出(不是宿主关闭它) */
|
|
29
|
+
exited(reason: string): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Fn = (...args: unknown[]) => unknown;
|
|
33
|
+
type Handle = { $fn: string };
|
|
34
|
+
/** 参数里的 AbortSignal 不能序列化:发给插件时换成 null,中止时给插件发 $/cancel */
|
|
35
|
+
const signalIn = (args: unknown[]) => args.find((x): x is AbortSignal => x instanceof AbortSignal);
|
|
36
|
+
const withoutSignals = (args: unknown[]) => args.map((x) => (x instanceof AbortSignal ? null : x));
|
|
37
|
+
const isHandle = (v: unknown): v is Handle =>
|
|
38
|
+
typeof v === "object" && v !== null && !Array.isArray(v) && typeof (v as Handle).$fn === "string" && Object.keys(v).length === 1;
|
|
39
|
+
|
|
40
|
+
/** 插件在 initialize 里的回复 */
|
|
41
|
+
interface InitReply {
|
|
42
|
+
id?: string;
|
|
43
|
+
/** 插件有会话级部分;没有就不为它打开会话作用域 */
|
|
44
|
+
session?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function startRemote(source: PluginSource, owner: Owner, opts: RemoteOptions): Promise<PluginModule> {
|
|
48
|
+
const { manifest, dir } = source;
|
|
49
|
+
const id = manifest.id;
|
|
50
|
+
const { command, args = [] } = manifest.runtime!;
|
|
51
|
+
const env = { ...process.env, PYTHONPATH: [PYTHON_SDK, process.env.PYTHONPATH].filter(Boolean).join(path.delimiter), PYTHONUNBUFFERED: "1", PYTHONIOENCODING: "utf-8" };
|
|
52
|
+
// 插件进程的工作目录是插件目录,所以清单里可以写 "args": ["main.py"];jade 的工作目录在 scope/open 里给
|
|
53
|
+
const child = spawn(/^\.\.?[\\/]/.test(command) ? path.resolve(dir, command) : command, args, { cwd: dir, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
54
|
+
|
|
55
|
+
/** 打开的作用域:id → ctx。进程级的 id 是 "process" */
|
|
56
|
+
const scopes = new Map<string, ScopeContext>();
|
|
57
|
+
/** 交给插件的宿主函数:句柄 → 函数;按作用域分组,作用域关闭时释放 */
|
|
58
|
+
const local = new Map<string, Fn>();
|
|
59
|
+
const buckets = new Map<string, Set<string>>();
|
|
60
|
+
let next = 1;
|
|
61
|
+
let closing = false;
|
|
62
|
+
const stderr: string[] = [];
|
|
63
|
+
|
|
64
|
+
const encode = (v: unknown, scope: string, depth = 0): unknown => {
|
|
65
|
+
if (typeof v === "function") {
|
|
66
|
+
const h = `h${next++}`;
|
|
67
|
+
local.set(h, v as Fn);
|
|
68
|
+
buckets.get(scope)?.add(h);
|
|
69
|
+
return { $fn: h };
|
|
70
|
+
}
|
|
71
|
+
if (depth > 32 || typeof v !== "object" || v === null) return v;
|
|
72
|
+
if (Array.isArray(v)) return v.map((x) => encode(x, scope, depth + 1));
|
|
73
|
+
const proto = Object.getPrototypeOf(v);
|
|
74
|
+
if (proto !== Object.prototype && proto !== null) return v; // class 实例按 JSON 序列化
|
|
75
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, encode(x, scope, depth + 1)]));
|
|
76
|
+
};
|
|
77
|
+
const decode = (v: unknown, scope: string): unknown => {
|
|
78
|
+
if (isHandle(v)) return remoteFn(v.$fn, scope);
|
|
79
|
+
if (typeof v !== "object" || v === null) return v;
|
|
80
|
+
if (Array.isArray(v)) return v.map((x) => decode(x, scope));
|
|
81
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decode(x, scope)]));
|
|
82
|
+
};
|
|
83
|
+
/** 插件的函数:调用时经 call 发给插件 */
|
|
84
|
+
const remoteFn = (fn: string, scope: string): Fn => {
|
|
85
|
+
return (...a: unknown[]) => {
|
|
86
|
+
if (!scopes.has(scope)) throw new Error(`a function of plugin ${id} was called after its scope closed`);
|
|
87
|
+
return rpc.request("call", { scope, target: { $fn: fn }, args: encode(withoutSignals(a), scope) }, signalIn(a)).then((r) => decode(r, scope));
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const rpc = new Rpc(
|
|
92
|
+
(line) => child.stdin.write(line),
|
|
93
|
+
(method, params, signal) => ambient.run(owner, () => serve(method, (params ?? {}) as Record<string, unknown>, signal)),
|
|
94
|
+
);
|
|
95
|
+
rpc.onGarbage = (line) => opts.report(`plugin ${id}: ignored a line on stdout that is not a protocol message (write logs to stderr): ${line.slice(0, 200)}`);
|
|
96
|
+
child.stdout.setEncoding("utf8");
|
|
97
|
+
child.stdout.on("data", (d: string) => rpc.feed(d));
|
|
98
|
+
child.stdin.on("error", () => {}); // 进程已退出时写入失败,由 exit 处理
|
|
99
|
+
let errBuf = "";
|
|
100
|
+
child.stderr.setEncoding("utf8");
|
|
101
|
+
child.stderr.on("data", (d: string) => {
|
|
102
|
+
errBuf += d;
|
|
103
|
+
for (let i = errBuf.indexOf("\n"); i !== -1; i = errBuf.indexOf("\n")) {
|
|
104
|
+
const line = errBuf.slice(0, i).replace(/\r$/, "");
|
|
105
|
+
errBuf = errBuf.slice(i + 1);
|
|
106
|
+
if (!line.trim()) continue;
|
|
107
|
+
stderr.push(line);
|
|
108
|
+
if (stderr.length > STDERR_TAIL) stderr.shift();
|
|
109
|
+
opts.report(`plugin ${id}: ${line}`);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
const exited = new Promise<void>((resolve) => {
|
|
113
|
+
child.on("error", (e) => {
|
|
114
|
+
rpc.close(new Error(`cannot start "${command}": ${e.message}`));
|
|
115
|
+
resolve();
|
|
116
|
+
});
|
|
117
|
+
child.on("exit", (code, signal) => {
|
|
118
|
+
const reason = `its process exited (${signal ?? `code ${code}`})`;
|
|
119
|
+
rpc.close(new Error(stderr.length > 0 ? `${reason}; stderr: ${stderr.join(" | ")}` : reason));
|
|
120
|
+
if (!closing) opts.exited(reason);
|
|
121
|
+
resolve();
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// 宿主关闭插件(退出、隔离、激活失败)时结束进程。最先登记,所以在进程级作用域里最后执行
|
|
126
|
+
owner.scope.add(async () => {
|
|
127
|
+
closing = true;
|
|
128
|
+
await closeScope("process");
|
|
129
|
+
child.stdin.end();
|
|
130
|
+
const timer = setTimeout(() => child.kill(), EXIT_GRACE_MS);
|
|
131
|
+
await exited;
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
async function openScope(scope: string, kind: "process" | "session", ctx: ScopeContext, extra: object): Promise<void> {
|
|
136
|
+
scopes.set(scope, ctx);
|
|
137
|
+
buckets.set(scope, new Set());
|
|
138
|
+
await rpc.request("scope/open", { scope, kind, cwd: ctx.cwd, home: ctx.home, config: ctx.config, ...extra });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function closeScope(scope: string): Promise<void> {
|
|
142
|
+
if (!scopes.delete(scope)) return;
|
|
143
|
+
for (const h of buckets.get(scope) ?? []) local.delete(h);
|
|
144
|
+
buckets.delete(scope);
|
|
145
|
+
try {
|
|
146
|
+
await rpc.request("scope/close", { scope });
|
|
147
|
+
} catch {
|
|
148
|
+
// 进程已经退出,或者插件清理时出错:作用域在宿主这边已经关了
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 插件发来的请求 */
|
|
153
|
+
async function serve(method: string, p: Record<string, unknown>, signal: AbortSignal): Promise<unknown> {
|
|
154
|
+
const scope = String(p.scope);
|
|
155
|
+
const ctx = scopes.get(scope);
|
|
156
|
+
if (!ctx) throw new Error(`scope ${scope} is not open`);
|
|
157
|
+
switch (method) {
|
|
158
|
+
case "provide": {
|
|
159
|
+
if (scope !== "process") throw new Error("services can only be provided in the process scope");
|
|
160
|
+
const service = String(p.service);
|
|
161
|
+
const methods = p.methods;
|
|
162
|
+
if (!Array.isArray(methods) || methods.some((m) => typeof m !== "string" || m === "then")) throw new Error("provide: methods must be a list of method names");
|
|
163
|
+
const build = (caller?: string) =>
|
|
164
|
+
Object.fromEntries(
|
|
165
|
+
(methods as string[]).map((m) => [
|
|
166
|
+
m,
|
|
167
|
+
(...a: unknown[]) =>
|
|
168
|
+
rpc.request("call", { scope, target: service, method: m, args: encode(withoutSignals(a), scope), ...(caller ? { caller } : {}) }, signalIn(a)).then((r) => decode(r, scope)),
|
|
169
|
+
]),
|
|
170
|
+
);
|
|
171
|
+
// 按调用方创建实例:插件那边收到 caller/open 时用工厂创建,caller/close 时撤销这个调用方的注册
|
|
172
|
+
const perCaller = (caller: Caller) => {
|
|
173
|
+
const c = `c${next++}`;
|
|
174
|
+
rpc.notify("caller/open", { service, caller: { id: c, plugin: caller.plugin, layer: caller.layer } });
|
|
175
|
+
caller.onDispose(() => rpc.notify("caller/close", { caller: c }));
|
|
176
|
+
return build(c);
|
|
177
|
+
};
|
|
178
|
+
(ctx as ProcessContext).provide(service, p.perCaller === true ? perCaller : build());
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
case "kernel/tool": {
|
|
182
|
+
if (scope === "process") throw new Error("kernel/tool is only available in a session scope");
|
|
183
|
+
const t = (p.tool ?? {}) as Record<string, unknown>;
|
|
184
|
+
if (!isHandle(p.execute)) throw new Error("kernel/tool: execute must be a function handle");
|
|
185
|
+
if (t.effect !== "read" && t.effect !== "write" && t.effect !== "external") throw new Error(`kernel/tool ${String(t.name)}: effect must be "read", "write" or "external"`);
|
|
186
|
+
const fn = p.execute.$fn;
|
|
187
|
+
(ctx as SessionContext).kernel.tool({
|
|
188
|
+
name: String(t.name),
|
|
189
|
+
description: String(t.description ?? ""),
|
|
190
|
+
inputSchema: (t.inputSchema as Record<string, unknown>) ?? { type: "object" },
|
|
191
|
+
effect: t.effect,
|
|
192
|
+
concurrency: t.concurrency === "safe" ? "safe" : "exclusive",
|
|
193
|
+
idempotent: t.idempotent === true,
|
|
194
|
+
execute: async (input, tctx) => {
|
|
195
|
+
const r = await rpc.request("call", { scope, target: { $fn: fn }, args: [input, { sessionId: tctx.sessionId, toolUseId: tctx.toolUseId }] }, tctx.signal);
|
|
196
|
+
return (typeof r === "string" ? { content: r } : r) as ToolResult;
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
case "kernel/hook": {
|
|
202
|
+
if (scope === "process") throw new Error("kernel/hook is only available in a session scope");
|
|
203
|
+
const h = (p.hook ?? {}) as Record<string, unknown>;
|
|
204
|
+
if (!isHandle(p.fn)) throw new Error("kernel/hook: fn must be a function handle");
|
|
205
|
+
const fn = p.fn.$fn;
|
|
206
|
+
// 字段裁剪、回复检查、超时由内核保证(RemoteHookSpec)
|
|
207
|
+
const spec = {
|
|
208
|
+
kind: h.kind,
|
|
209
|
+
point: h.point,
|
|
210
|
+
remote: true,
|
|
211
|
+
reads: h.reads,
|
|
212
|
+
writes: h.writes ?? [],
|
|
213
|
+
timeoutMs: h.timeoutMs,
|
|
214
|
+
...(typeof h.order === "number" ? { order: h.order } : {}),
|
|
215
|
+
call: (payload: Record<string, unknown>, hctx: HookContext) => rpc.request("call", { scope, target: { $fn: fn }, args: [payload] }, hctx.signal),
|
|
216
|
+
} as RemoteHookSpec;
|
|
217
|
+
(ctx as SessionContext).kernel.hook(spec);
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
case "secrets/get": {
|
|
221
|
+
if (typeof p.key !== "string") throw new Error("secrets/get: key must be a string");
|
|
222
|
+
return (await ctx.secrets.get(p.key)) ?? null;
|
|
223
|
+
}
|
|
224
|
+
case "secrets/set": {
|
|
225
|
+
if (typeof p.key !== "string") throw new Error("secrets/set: key must be a string");
|
|
226
|
+
if (p.value !== null && typeof p.value !== "string") throw new Error("secrets/set: value must be a string or null");
|
|
227
|
+
await ctx.secrets.set(p.key, p.value === null ? undefined : p.value);
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
case "call": {
|
|
231
|
+
const a = decode(p.args ?? [], scope);
|
|
232
|
+
if (!Array.isArray(a)) throw new Error("call: args must be a list");
|
|
233
|
+
const target = p.target;
|
|
234
|
+
let result: unknown;
|
|
235
|
+
if (isHandle(target)) {
|
|
236
|
+
const f = local.get(target.$fn);
|
|
237
|
+
if (!f) throw new Error(`function ${target.$fn} is no longer valid`);
|
|
238
|
+
result = await f(...a);
|
|
239
|
+
} else if (target === "$session") {
|
|
240
|
+
const session = (ctx as SessionContext).session;
|
|
241
|
+
if (!session) throw new Error("$session is only available in a session scope");
|
|
242
|
+
if (p.method === "send") result = await session.send(a[0] as Parameters<typeof session.send>[0]);
|
|
243
|
+
else if (p.method === "afterTurn") session.afterTurn(a[0] as () => void);
|
|
244
|
+
else if (p.method === "abort") session.abort(a[0] === undefined || a[0] === null ? undefined : String(a[0]));
|
|
245
|
+
else throw new Error(`$session has no method ${String(p.method)}`);
|
|
246
|
+
} else if (typeof target === "string") {
|
|
247
|
+
const service = ctx.service<Record<string, unknown>>(target);
|
|
248
|
+
if (!service) throw new Error(`service ${target} is not available`);
|
|
249
|
+
const m = service[String(p.method)];
|
|
250
|
+
if (typeof m !== "function") throw new Error(`service ${target} has no method ${String(p.method)}`);
|
|
251
|
+
result = await (m as Fn)(...a);
|
|
252
|
+
} else {
|
|
253
|
+
throw new Error("call: target must be a service name, \"$session\" or a function handle");
|
|
254
|
+
}
|
|
255
|
+
if (signal.aborted) throw signal.reason;
|
|
256
|
+
return encode(result, scope);
|
|
257
|
+
}
|
|
258
|
+
default:
|
|
259
|
+
throw new Error(`unknown method ${method}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
let init: InitReply;
|
|
264
|
+
try {
|
|
265
|
+
init = ((await rpc.request("initialize", { plugin: id, version: manifest.version, api: API_VERSION }, AbortSignal.timeout(INIT_TIMEOUT_MS))) ?? {}) as InitReply;
|
|
266
|
+
} catch (e) {
|
|
267
|
+
if (e instanceof Error && e.name === "TimeoutError") throw new Error(`"${command}" did not answer initialize within ${INIT_TIMEOUT_MS / 1000} s`);
|
|
268
|
+
throw e;
|
|
269
|
+
}
|
|
270
|
+
if (init.id !== undefined && init.id !== id) throw new Error(`the process says it is plugin ${init.id}, but plugin.json says ${id}`);
|
|
271
|
+
|
|
272
|
+
let sessions = 0;
|
|
273
|
+
return {
|
|
274
|
+
async process(ctx) {
|
|
275
|
+
await openScope("process", "process", ctx, {});
|
|
276
|
+
},
|
|
277
|
+
...(init.session
|
|
278
|
+
? {
|
|
279
|
+
async session(ctx: SessionContext) {
|
|
280
|
+
const scope = `s${++sessions}`;
|
|
281
|
+
// 先登记关闭:插件在 scope/open 里出错时,宿主撤销这个作用域,插件那边也要清理
|
|
282
|
+
await ctx.effect(() => () => closeScope(scope));
|
|
283
|
+
await openScope(scope, "session", ctx, { session: { id: ctx.session.id } });
|
|
284
|
+
},
|
|
285
|
+
}
|
|
286
|
+
: {}),
|
|
287
|
+
};
|
|
288
|
+
}
|