@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
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
// web_fetch 拒绝 localhost 和内网地址:网页里的提示注入不能借它去访问本机的服务。
|
|
9
9
|
// 主机名要先解析,解析出的地址也要检查,否则 127.0.0.1.nip.io 这类域名就能绕过。
|
|
10
10
|
// 检查和 fetch 各自解析一次,DNS 重绑定仍有很小的窗口;要彻底杜绝需要按解析出的 IP 连接。
|
|
11
|
-
// web_search
|
|
11
|
+
// web_search 只在配置了搜索服务时发给模型(见 index.ts),否则模型每次调用都会失败。
|
|
12
|
+
//
|
|
13
|
+
// 从旧 jade 的 tools/web.ts 移植。服务的 key 每次调用时取(search()),/search 改了 key 当前会话立即用上,不用重开会话。
|
|
12
14
|
import { lookup as dnsLookup } from "node:dns/promises";
|
|
13
15
|
import { isIP } from "node:net";
|
|
14
|
-
import { Parser } from "htmlparser2";
|
|
15
16
|
/** 一次返回的最多字符数,更长的用 offset 分页 */
|
|
16
17
|
const MAX_CHARS = 30_000;
|
|
17
18
|
/** 下载的最大字节数 */
|
|
@@ -28,13 +29,13 @@ const MAX_RESULTS = 20;
|
|
|
28
29
|
const USER_AGENT = "Mozilla/5.0 (compatible; jade/0.1; +https://github.com/MochiNek0/uncarved)";
|
|
29
30
|
const defaultLookup = async (hostname) => (await dnsLookup(hostname, { all: true })).map((a) => a.address);
|
|
30
31
|
export function webTools(opts = {}) {
|
|
31
|
-
const env = opts.env ?? process.env;
|
|
32
|
+
const env = typeof opts.env === "function" ? opts.env : () => opts.env ?? process.env;
|
|
32
33
|
const fetchImpl = opts.fetch ?? fetch;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
return { tools };
|
|
34
|
+
if (opts.order)
|
|
35
|
+
checkOrder(opts.order);
|
|
36
|
+
const services = () => backends(env(), opts.order, fetchImpl);
|
|
37
|
+
const tools = [webFetchTool(fetchImpl, opts.lookup ?? defaultLookup, () => services().filter((s) => s.read)), webSearchTool(services, opts.results ?? DEFAULT_RESULTS)];
|
|
38
|
+
return { tools, search: () => services().map((s) => s.name) };
|
|
38
39
|
}
|
|
39
40
|
/** 网页正文少于这么多字符时算 thin */
|
|
40
41
|
const THIN_CHARS = 200;
|
|
@@ -89,7 +90,7 @@ function webFetchTool(fetchImpl, lookup, readers) {
|
|
|
89
90
|
// 直接下载被拦、出错或只拿到 JS 外壳时,交给能读网页的服务;404 这类明确的结果直接返回
|
|
90
91
|
const failures = [];
|
|
91
92
|
if ("content" in direct ? direct.retry : direct.thin) {
|
|
92
|
-
for (const r of readers) {
|
|
93
|
+
for (const r of readers()) {
|
|
93
94
|
try {
|
|
94
95
|
page = { at: Date.now(), url: target.href, via: r.name, text: await r.read(target.href, signal) };
|
|
95
96
|
break;
|
|
@@ -195,7 +196,7 @@ async function download(fetchImpl, lookup, target, signal) {
|
|
|
195
196
|
if (!res.ok) {
|
|
196
197
|
const body = await res.text().catch(() => "");
|
|
197
198
|
return {
|
|
198
|
-
content: `HTTP ${res.status} ${res.statusText} from ${url.href}${body ? `\n${clip(htmlToMarkdown(body).text || body, 1000)}` : ""}`,
|
|
199
|
+
content: `HTTP ${res.status} ${res.statusText} from ${url.href}${body ? `\n${clip((await htmlToMarkdown(body)).text || body, 1000)}` : ""}`,
|
|
199
200
|
isError: true,
|
|
200
201
|
retry: res.status === 403 || res.status === 429 || res.status >= 500,
|
|
201
202
|
};
|
|
@@ -217,7 +218,7 @@ async function download(fetchImpl, lookup, target, signal) {
|
|
|
217
218
|
const charset = /charset=([^;]+)/i.exec(res.headers.get("content-type") ?? "")?.[1]?.trim();
|
|
218
219
|
const raw = decode(buf, charset);
|
|
219
220
|
if (type === "text/html" || type === "application/xhtml+xml" || (!type && /^\s*<(!doctype|html)/i.test(raw))) {
|
|
220
|
-
const { title, text } = htmlToMarkdown(raw, url.href);
|
|
221
|
+
const { title, text } = await htmlToMarkdown(raw, url.href);
|
|
221
222
|
return { at: Date.now(), url: url.href, title, text, thin: text.length < THIN_CHARS };
|
|
222
223
|
}
|
|
223
224
|
if (type.startsWith("text/") || /json|xml|javascript|yaml|toml/.test(type) || !type) {
|
|
@@ -268,9 +269,11 @@ const SKIP = new Set(["script", "style", "noscript", "template", "svg", "canvas"
|
|
|
268
269
|
const BLOCKS = new Set(["p", "div", "section", "article", "main", "header", "ul", "ol", "table", "tr", "blockquote", "figure", "figcaption", "dl", "dt", "dd", "hr"]);
|
|
269
270
|
/**
|
|
270
271
|
* 用 htmlparser2 把网页转成 markdown 风格的文本:标题、段落、列表、链接、代码块,去掉脚本、样式和导航。
|
|
271
|
-
* 不追求还原排版,只要模型能读。Node 和 Bun 都能用(Bun 的 HTMLRewriter 在 Node
|
|
272
|
+
* 不追求还原排版,只要模型能读。Node 和 Bun 都能用(Bun 的 HTMLRewriter 在 Node 里没有)。
|
|
273
|
+
* htmlparser2 第一次用到时才加载:导入要几十毫秒,每次启动都付不值得
|
|
272
274
|
*/
|
|
273
|
-
export function htmlToMarkdown(html, base) {
|
|
275
|
+
export async function htmlToMarkdown(html, base) {
|
|
276
|
+
const { Parser } = await import("htmlparser2");
|
|
274
277
|
const out = [];
|
|
275
278
|
let skip = 0;
|
|
276
279
|
let pre = 0;
|
|
@@ -550,29 +553,51 @@ export const SEARCH_PROVIDERS = [
|
|
|
550
553
|
},
|
|
551
554
|
];
|
|
552
555
|
/**
|
|
553
|
-
* 配置了 key 的服务,按调用顺序。
|
|
554
|
-
*
|
|
556
|
+
* 配置了 key 的服务,按调用顺序。order 是服务名,决定顺序和范围(没 key 的跳过);
|
|
557
|
+
* 不给时用所有配了 key 的服务,按 SEARCH_PROVIDERS 的顺序
|
|
558
|
+
*/
|
|
559
|
+
function backends(env, order, fetchImpl) {
|
|
560
|
+
const list = order?.length ? order.map((n) => SEARCH_PROVIDERS.find((p) => p.name === n)) : SEARCH_PROVIDERS;
|
|
561
|
+
return list.flatMap((p) => (env[p.env] ? [p.make(env[p.env], fetchImpl)] : []));
|
|
562
|
+
}
|
|
563
|
+
function checkOrder(order) {
|
|
564
|
+
const unknown = order.filter((n) => !SEARCH_PROVIDERS.some((p) => p.name === n));
|
|
565
|
+
if (unknown.length)
|
|
566
|
+
throw new Error(`unknown search service ${unknown.join(", ")}; choose from ${SEARCH_PROVIDERS.map((p) => p.name).join(", ")}`);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* 配置项 search(或旧 jade 的 JADE_SEARCH):逗号分隔的服务名或服务名的数组。不设时返回 undefined;
|
|
570
|
+
* 不认识的服务名抛错,错误信息里带来源 label
|
|
555
571
|
*/
|
|
556
|
-
function
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
572
|
+
export function parseOrder(value, label) {
|
|
573
|
+
if (value === undefined || value === null || value === "")
|
|
574
|
+
return undefined;
|
|
575
|
+
const list = typeof value === "string" ? value.split(",") : Array.isArray(value) && value.every((v) => typeof v === "string") ? value : undefined;
|
|
576
|
+
if (!list)
|
|
577
|
+
throw new Error(`${label} must be a comma-separated list of search services, got ${JSON.stringify(value)}`);
|
|
578
|
+
const named = list.map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
579
|
+
try {
|
|
580
|
+
checkOrder(named);
|
|
581
|
+
}
|
|
582
|
+
catch (e) {
|
|
583
|
+
throw new Error(`${label}: ${e.message}`);
|
|
584
|
+
}
|
|
585
|
+
return named.length ? named : undefined;
|
|
563
586
|
}
|
|
564
|
-
/** JADE_SEARCH_RESULTS
|
|
565
|
-
function
|
|
566
|
-
const raw =
|
|
567
|
-
if (
|
|
587
|
+
/** 配置项 results(或旧 jade 的 JADE_SEARCH_RESULTS):每次搜索返回的条数,1 到 MAX_RESULTS */
|
|
588
|
+
export function parseResults(value, label) {
|
|
589
|
+
const raw = typeof value === "string" ? value.trim() : value;
|
|
590
|
+
if (raw === undefined || raw === null || raw === "")
|
|
568
591
|
return DEFAULT_RESULTS;
|
|
569
592
|
const n = Number(raw);
|
|
570
593
|
if (!Number.isInteger(n) || n < 1 || n > MAX_RESULTS)
|
|
571
|
-
throw new Error(
|
|
594
|
+
throw new Error(`${label} must be an integer from 1 to ${MAX_RESULTS}, got ${JSON.stringify(value)}`);
|
|
572
595
|
return n;
|
|
573
596
|
}
|
|
574
597
|
// ---------- web_search ----------
|
|
575
|
-
|
|
598
|
+
/** 没有配置搜索服务时调用 web_search 的结果(正常情况下这时 web_search 不发给模型) */
|
|
599
|
+
export const SEARCH_OFF = "Web search is not set up. The user can turn it on with the /search command.";
|
|
600
|
+
function webSearchTool(live, count) {
|
|
576
601
|
return {
|
|
577
602
|
name: "web_search",
|
|
578
603
|
description: `Search the web and return the top ${count} results with title, URL and a snippet. ` +
|
|
@@ -590,6 +615,9 @@ function webSearchTool(services, count) {
|
|
|
590
615
|
const { query } = input;
|
|
591
616
|
if (!query.trim())
|
|
592
617
|
return { content: "query must not be empty", isError: true };
|
|
618
|
+
const services = live();
|
|
619
|
+
if (!services.length)
|
|
620
|
+
return { content: SEARCH_OFF, isError: true };
|
|
593
621
|
// 按顺序试,出错或没有结果时换下一个
|
|
594
622
|
const failures = [];
|
|
595
623
|
let failed = false;
|
|
@@ -631,4 +659,3 @@ function errorText(err) {
|
|
|
631
659
|
return `${err.message} (${detail})`;
|
|
632
660
|
}
|
|
633
661
|
const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
|
|
634
|
-
//# sourceMappingURL=web.js.map
|
|
Binary file
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""jade 进程外插件的 Python SDK(设计见 docs/design/jade.md 第 6 节)。单文件,只用标准库。
|
|
2
|
+
|
|
3
|
+
jade 启动插件进程时把这个文件所在的目录加进 PYTHONPATH,插件直接 ``import jade_plugin``。
|
|
4
|
+
|
|
5
|
+
from jade_plugin import Plugin
|
|
6
|
+
|
|
7
|
+
plugin = Plugin()
|
|
8
|
+
|
|
9
|
+
@plugin.process
|
|
10
|
+
def process(ctx):
|
|
11
|
+
ctx.provide("greeter@1", Greeter()) # 公开方法都能被其他插件调用
|
|
12
|
+
ctx.service("commands@1").register({"name": "hello", "run": hello})
|
|
13
|
+
ctx.secrets.set("API_TOKEN", "...") # 只有这个插件自己的密钥(第 8 节)
|
|
14
|
+
|
|
15
|
+
@plugin.session
|
|
16
|
+
def session(ctx):
|
|
17
|
+
ctx.tool("shout", "Upper-cases text", {"type": "object"}, effect="read", execute=shout)
|
|
18
|
+
|
|
19
|
+
plugin.run()
|
|
20
|
+
|
|
21
|
+
stdout 只用来传协议消息,日志写到 stderr(jade 会转告用户)。每个请求在自己的线程里处理,
|
|
22
|
+
插件的处理函数可能同时被调用;处理函数里可以调用宿主(ctx.service(...).method(...)),调用会阻塞到宿主回复。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import traceback
|
|
31
|
+
from typing import Any, Callable
|
|
32
|
+
|
|
33
|
+
__all__ = ["Plugin", "Context", "Caller", "JadeError", "cancelled"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class JadeError(Exception):
|
|
37
|
+
"""宿主返回的错误"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_local = threading.local()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cancelled() -> bool:
|
|
44
|
+
"""当前处理的请求是否已被宿主取消(例如用户中止了正在执行的工具)"""
|
|
45
|
+
ev = getattr(_local, "cancel", None)
|
|
46
|
+
return bool(ev and ev.is_set())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Plugin:
|
|
50
|
+
def __init__(self, id: str | None = None):
|
|
51
|
+
self.id = id
|
|
52
|
+
self._process: Callable[[Context], Any] | None = None
|
|
53
|
+
self._session: Callable[[Context], Any] | None = None
|
|
54
|
+
|
|
55
|
+
def process(self, fn: Callable[["Context"], Any]):
|
|
56
|
+
"""进程级:提供服务、向其他插件的注册服务注册东西"""
|
|
57
|
+
self._process = fn
|
|
58
|
+
return fn
|
|
59
|
+
|
|
60
|
+
def session(self, fn: Callable[["Context"], Any]):
|
|
61
|
+
"""会话级:每个会话调用一次,注册工具和 hook"""
|
|
62
|
+
self._session = fn
|
|
63
|
+
return fn
|
|
64
|
+
|
|
65
|
+
def run(self) -> None:
|
|
66
|
+
_Connection(self).serve()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Caller:
|
|
70
|
+
"""按调用方创建的服务实例拿到的调用方信息"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, id: str, plugin: str, layer: str):
|
|
73
|
+
self.id = id
|
|
74
|
+
self.plugin = plugin
|
|
75
|
+
self.layer = layer
|
|
76
|
+
self._disposers: list[Callable[[], Any]] = []
|
|
77
|
+
|
|
78
|
+
def on_dispose(self, fn: Callable[[], Any]) -> None:
|
|
79
|
+
"""调用方关闭时执行:注册表在这里撤销调用方注册的东西"""
|
|
80
|
+
self._disposers.append(fn)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _Secrets:
|
|
84
|
+
"""一个作用域里的 ctx.secrets:按插件 id 隔离,value 为 None 时删除"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, conn: "_Connection", scope: str):
|
|
87
|
+
self._conn = conn
|
|
88
|
+
self._scope = scope
|
|
89
|
+
|
|
90
|
+
def get(self, key: str) -> str | None:
|
|
91
|
+
return self._conn.request("secrets/get", {"scope": self._scope, "key": key})
|
|
92
|
+
|
|
93
|
+
def set(self, key: str, value: str | None) -> None:
|
|
94
|
+
self._conn.request("secrets/set", {"scope": self._scope, "key": key, "value": value})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _Service:
|
|
98
|
+
"""宿主那边一个服务的代理:任何属性都是方法,调用时发给宿主"""
|
|
99
|
+
|
|
100
|
+
def __init__(self, conn: "_Connection", scope: str, name: str):
|
|
101
|
+
self._conn = conn
|
|
102
|
+
self._scope = scope
|
|
103
|
+
self._name = name
|
|
104
|
+
|
|
105
|
+
def __getattr__(self, method: str):
|
|
106
|
+
if method.startswith("__"):
|
|
107
|
+
raise AttributeError(method)
|
|
108
|
+
return lambda *args: self._conn.call(self._scope, self._name, method, list(args))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _RemoteFunction:
|
|
112
|
+
"""宿主交给插件的函数"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, conn: "_Connection", scope: str, fn: str):
|
|
115
|
+
self._conn = conn
|
|
116
|
+
self._scope = scope
|
|
117
|
+
self._fn = fn
|
|
118
|
+
|
|
119
|
+
def __call__(self, *args):
|
|
120
|
+
return self._conn.call(self._scope, {"$fn": self._fn}, None, list(args))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class Context:
|
|
124
|
+
"""一个作用域(进程级或某个会话)的 ctx"""
|
|
125
|
+
|
|
126
|
+
def __init__(self, conn: "_Connection", scope: str, params: dict):
|
|
127
|
+
self._conn = conn
|
|
128
|
+
self.scope = scope
|
|
129
|
+
self.kind: str = params["kind"]
|
|
130
|
+
self.cwd: str = params.get("cwd", "")
|
|
131
|
+
self.home: str = params.get("home", "")
|
|
132
|
+
self.config: dict = params.get("config") or {}
|
|
133
|
+
self.secrets = _Secrets(conn, scope)
|
|
134
|
+
self.session_id: str | None = (params.get("session") or {}).get("id")
|
|
135
|
+
self._on_close: list[Callable[[], Any]] = []
|
|
136
|
+
|
|
137
|
+
def service(self, name: str) -> Any:
|
|
138
|
+
"""取一个声明在 plugin.json 的 requires 或 optional 里的服务"""
|
|
139
|
+
return _Service(self._conn, self.scope, name)
|
|
140
|
+
|
|
141
|
+
require = service
|
|
142
|
+
|
|
143
|
+
def provide(self, name: str, impl: Any = None, *, factory: Callable[[Caller], Any] | None = None, methods: list[str] | None = None) -> None:
|
|
144
|
+
"""
|
|
145
|
+
提供一个声明在 provides 里的服务,只能在 process 里调用。
|
|
146
|
+
impl:所有调用方共用的对象,公开方法都可以被调用。
|
|
147
|
+
factory:每个调用方调用一次,返回这个调用方专用的实例;factory 不是类时用 methods 列出方法名
|
|
148
|
+
"""
|
|
149
|
+
if (impl is None) == (factory is None):
|
|
150
|
+
raise ValueError("provide needs exactly one of impl and factory")
|
|
151
|
+
source = impl if impl is not None else factory
|
|
152
|
+
if methods is None:
|
|
153
|
+
if factory is not None and not isinstance(factory, type):
|
|
154
|
+
raise ValueError("provide(factory=...) needs methods=[...] unless the factory is a class")
|
|
155
|
+
methods = [n for n in dir(source) if not n.startswith("_") and callable(getattr(source, n))]
|
|
156
|
+
if factory is not None:
|
|
157
|
+
self._conn.factories[name] = factory
|
|
158
|
+
else:
|
|
159
|
+
self._conn.services[name] = impl
|
|
160
|
+
self._conn.request("provide", {"scope": self.scope, "service": name, "methods": methods, "perCaller": factory is not None})
|
|
161
|
+
|
|
162
|
+
def tool(self, name: str, description: str, input_schema: dict, *, effect: str, execute: Callable[[Any, dict], Any], concurrency: str = "exclusive", idempotent: bool = False) -> None:
|
|
163
|
+
"""
|
|
164
|
+
注册一个工具,只能在 session 里调用。effect:"read"、"write" 或 "external"。
|
|
165
|
+
execute(input, ctx) 返回文字,或 {"content": 文字或 block 列表, "isError": bool}
|
|
166
|
+
"""
|
|
167
|
+
tool = {"name": name, "description": description, "inputSchema": input_schema, "effect": effect, "concurrency": concurrency, "idempotent": idempotent}
|
|
168
|
+
self._conn.request("kernel/tool", {"scope": self.scope, "tool": tool, "execute": self._conn.handle(execute, self.scope)})
|
|
169
|
+
|
|
170
|
+
def hook(self, kind: str, point: str, fn: Callable[[dict], Any], *, reads: list[str], writes: list[str] | None = None, timeout_ms: int = 30_000, order: int | None = None) -> None:
|
|
171
|
+
"""
|
|
172
|
+
注册一个内核 hook,只能在 session 里调用。fn 只收到 reads 列出的字段;
|
|
173
|
+
transform 返回要改的字段(只能是 writes 里的),gate 返回 {"decision": ..., "reason": ...}
|
|
174
|
+
"""
|
|
175
|
+
hook = {"kind": kind, "point": point, "reads": reads, "writes": writes or [], "timeoutMs": timeout_ms}
|
|
176
|
+
if order is not None:
|
|
177
|
+
hook["order"] = order
|
|
178
|
+
self._conn.request("kernel/hook", {"scope": self.scope, "hook": hook, "fn": self._conn.handle(fn, self.scope)})
|
|
179
|
+
|
|
180
|
+
def send(self, input: dict) -> None:
|
|
181
|
+
"""发起一轮(会话级)。不要在工具或 hook 里调用:它要等当前这一轮结束"""
|
|
182
|
+
self._conn.call(self.scope, "$session", "send", [input])
|
|
183
|
+
|
|
184
|
+
def abort(self, reason: str | None = None) -> None:
|
|
185
|
+
"""中止正在跑的这一轮(会话级);空闲时什么都不做"""
|
|
186
|
+
self._conn.call(self.scope, "$session", "abort", [reason])
|
|
187
|
+
|
|
188
|
+
def after_turn(self, fn: Callable[[], Any]) -> None:
|
|
189
|
+
"""本轮完全结束后执行一次(会话级)"""
|
|
190
|
+
self._conn.call(self.scope, "$session", "afterTurn", [fn])
|
|
191
|
+
|
|
192
|
+
def on_close(self, fn: Callable[[], Any]) -> None:
|
|
193
|
+
"""作用域关闭时执行,逆序"""
|
|
194
|
+
self._on_close.append(fn)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _Connection:
|
|
198
|
+
def __init__(self, plugin: Plugin):
|
|
199
|
+
self.plugin = plugin
|
|
200
|
+
self.services: dict[str, Any] = {}
|
|
201
|
+
self.factories: dict[str, Callable[[Caller], Any]] = {}
|
|
202
|
+
self.callers: dict[str, tuple[Caller, Any]] = {}
|
|
203
|
+
self.scopes: dict[str, Context] = {}
|
|
204
|
+
self._fns: dict[str, Callable] = {}
|
|
205
|
+
self._buckets: dict[str, set[str]] = {}
|
|
206
|
+
self._pending: dict[int, list] = {}
|
|
207
|
+
self._incoming: dict[Any, threading.Event] = {}
|
|
208
|
+
self._lock = threading.Lock()
|
|
209
|
+
self._next = 0
|
|
210
|
+
self._out = sys.stdout.buffer
|
|
211
|
+
self._in = sys.stdin.buffer
|
|
212
|
+
# 插件代码误用 print 时不要弄坏协议:stdout 改指向 stderr
|
|
213
|
+
sys.stdout = sys.stderr
|
|
214
|
+
|
|
215
|
+
# ---------- 值 ----------
|
|
216
|
+
|
|
217
|
+
def handle(self, fn: Callable, scope: str) -> dict:
|
|
218
|
+
with self._lock:
|
|
219
|
+
self._next += 1
|
|
220
|
+
h = f"p{self._next}"
|
|
221
|
+
self._fns[h] = fn
|
|
222
|
+
self._buckets.setdefault(scope, set()).add(h)
|
|
223
|
+
return {"$fn": h}
|
|
224
|
+
|
|
225
|
+
def encode(self, v: Any, scope: str) -> Any:
|
|
226
|
+
if callable(v) and not isinstance(v, (type, _Service)):
|
|
227
|
+
return self.handle(v, scope)
|
|
228
|
+
if isinstance(v, (list, tuple)):
|
|
229
|
+
return [self.encode(x, scope) for x in v]
|
|
230
|
+
if isinstance(v, dict):
|
|
231
|
+
return {k: self.encode(x, scope) for k, x in v.items()}
|
|
232
|
+
return v
|
|
233
|
+
|
|
234
|
+
def decode(self, v: Any, scope: str) -> Any:
|
|
235
|
+
if isinstance(v, dict):
|
|
236
|
+
if len(v) == 1 and isinstance(v.get("$fn"), str):
|
|
237
|
+
return _RemoteFunction(self, scope, v["$fn"])
|
|
238
|
+
return {k: self.decode(x, scope) for k, x in v.items()}
|
|
239
|
+
if isinstance(v, list):
|
|
240
|
+
return [self.decode(x, scope) for x in v]
|
|
241
|
+
return v
|
|
242
|
+
|
|
243
|
+
# ---------- 传输 ----------
|
|
244
|
+
|
|
245
|
+
def _write(self, msg: dict) -> None:
|
|
246
|
+
data = json.dumps(msg).encode("utf-8") + b"\n"
|
|
247
|
+
with self._lock:
|
|
248
|
+
self._out.write(data)
|
|
249
|
+
self._out.flush()
|
|
250
|
+
|
|
251
|
+
def request(self, method: str, params: dict) -> Any:
|
|
252
|
+
with self._lock:
|
|
253
|
+
self._next += 1
|
|
254
|
+
id = self._next
|
|
255
|
+
slot = [threading.Event(), None, None]
|
|
256
|
+
self._pending[id] = slot
|
|
257
|
+
self._write({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
|
|
258
|
+
slot[0].wait()
|
|
259
|
+
if slot[2] is not None:
|
|
260
|
+
raise JadeError(slot[2].get("message", "error"))
|
|
261
|
+
return slot[1]
|
|
262
|
+
|
|
263
|
+
def call(self, scope: str, target: Any, method: str | None, args: list) -> Any:
|
|
264
|
+
params = {"scope": scope, "target": target, "args": self.encode(args, scope)}
|
|
265
|
+
if method is not None:
|
|
266
|
+
params["method"] = method
|
|
267
|
+
return self.decode(self.request("call", params), scope)
|
|
268
|
+
|
|
269
|
+
def serve(self) -> None:
|
|
270
|
+
while True:
|
|
271
|
+
line = self._in.readline()
|
|
272
|
+
if not line:
|
|
273
|
+
break
|
|
274
|
+
line = line.strip()
|
|
275
|
+
if not line:
|
|
276
|
+
continue
|
|
277
|
+
try:
|
|
278
|
+
msg = json.loads(line)
|
|
279
|
+
except ValueError:
|
|
280
|
+
print(f"jade_plugin: ignored a malformed line: {line[:200]!r}", file=sys.stderr)
|
|
281
|
+
continue
|
|
282
|
+
method = msg.get("method")
|
|
283
|
+
if method is None:
|
|
284
|
+
slot = self._pending.pop(msg.get("id"), None)
|
|
285
|
+
if slot is not None:
|
|
286
|
+
slot[1] = msg.get("result")
|
|
287
|
+
slot[2] = msg.get("error")
|
|
288
|
+
slot[0].set()
|
|
289
|
+
elif method == "$/cancel":
|
|
290
|
+
ev = self._incoming.get((msg.get("params") or {}).get("id"))
|
|
291
|
+
if ev is not None:
|
|
292
|
+
ev.set()
|
|
293
|
+
else:
|
|
294
|
+
id = msg.get("id")
|
|
295
|
+
cancel = threading.Event()
|
|
296
|
+
if id is not None:
|
|
297
|
+
self._incoming[id] = cancel
|
|
298
|
+
threading.Thread(target=self._serve_one, args=(id, method, msg.get("params") or {}, cancel), daemon=True).start()
|
|
299
|
+
# 宿主关闭了管道:清理全部作用域后退出
|
|
300
|
+
for scope in list(self.scopes):
|
|
301
|
+
self._close(scope)
|
|
302
|
+
|
|
303
|
+
def _serve_one(self, id: Any, method: str, params: dict, cancel: threading.Event) -> None:
|
|
304
|
+
_local.cancel = cancel
|
|
305
|
+
try:
|
|
306
|
+
result = self._dispatch(method, params)
|
|
307
|
+
if id is not None:
|
|
308
|
+
self._write({"jsonrpc": "2.0", "id": id, "result": result})
|
|
309
|
+
except Exception as e:
|
|
310
|
+
if not isinstance(e, JadeError):
|
|
311
|
+
traceback.print_exc(file=sys.stderr)
|
|
312
|
+
if id is not None:
|
|
313
|
+
self._write({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": str(e) or type(e).__name__}})
|
|
314
|
+
finally:
|
|
315
|
+
self._incoming.pop(id, None)
|
|
316
|
+
|
|
317
|
+
# ---------- 宿主发来的请求 ----------
|
|
318
|
+
|
|
319
|
+
def _dispatch(self, method: str, p: dict) -> Any:
|
|
320
|
+
if method == "initialize":
|
|
321
|
+
return {**({"id": self.plugin.id} if self.plugin.id else {}), "session": self.plugin._session is not None}
|
|
322
|
+
if method == "scope/open":
|
|
323
|
+
ctx = Context(self, p["scope"], p)
|
|
324
|
+
self.scopes[ctx.scope] = ctx
|
|
325
|
+
fn = self.plugin._process if ctx.kind == "process" else self.plugin._session
|
|
326
|
+
if fn is not None:
|
|
327
|
+
fn(ctx)
|
|
328
|
+
return None
|
|
329
|
+
if method == "scope/close":
|
|
330
|
+
self._close(p["scope"])
|
|
331
|
+
return None
|
|
332
|
+
if method == "caller/open":
|
|
333
|
+
c = p["caller"]
|
|
334
|
+
caller = Caller(c["id"], c["plugin"], c["layer"])
|
|
335
|
+
self.callers[caller.id] = (caller, self.factories[p["service"]](caller))
|
|
336
|
+
return None
|
|
337
|
+
if method == "caller/close":
|
|
338
|
+
entry = self.callers.pop(p["caller"], None)
|
|
339
|
+
if entry:
|
|
340
|
+
for d in reversed(entry[0]._disposers):
|
|
341
|
+
_quietly(d)
|
|
342
|
+
return None
|
|
343
|
+
if method == "call":
|
|
344
|
+
scope = p.get("scope", "process")
|
|
345
|
+
args = self.decode(p.get("args") or [], scope)
|
|
346
|
+
target = p.get("target")
|
|
347
|
+
if isinstance(target, dict):
|
|
348
|
+
fn = self._fns.get(target.get("$fn"))
|
|
349
|
+
if fn is None:
|
|
350
|
+
raise JadeError(f"function {target.get('$fn')} is no longer valid")
|
|
351
|
+
result = fn(*args)
|
|
352
|
+
else:
|
|
353
|
+
if "caller" in p:
|
|
354
|
+
entry = self.callers.get(p["caller"])
|
|
355
|
+
if entry is None:
|
|
356
|
+
raise JadeError(f"caller {p['caller']} is closed")
|
|
357
|
+
impl = entry[1]
|
|
358
|
+
else:
|
|
359
|
+
impl = self.services.get(target)
|
|
360
|
+
if impl is None:
|
|
361
|
+
raise JadeError(f"service {target} is not provided by this plugin")
|
|
362
|
+
result = getattr(impl, p["method"])(*args)
|
|
363
|
+
return self.encode(result, scope)
|
|
364
|
+
raise JadeError(f"unknown method {method}")
|
|
365
|
+
|
|
366
|
+
def _close(self, scope: str) -> None:
|
|
367
|
+
ctx = self.scopes.pop(scope, None)
|
|
368
|
+
if ctx is not None:
|
|
369
|
+
for fn in reversed(ctx._on_close):
|
|
370
|
+
_quietly(fn)
|
|
371
|
+
with self._lock:
|
|
372
|
+
for h in self._buckets.pop(scope, set()):
|
|
373
|
+
self._fns.pop(h, None)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _quietly(fn: Callable[[], Any]) -> None:
|
|
377
|
+
try:
|
|
378
|
+
fn()
|
|
379
|
+
except Exception:
|
|
380
|
+
traceback.print_exc(file=sys.stderr)
|