pi-web-ui 0.87.2 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/bin/pi-web-ui.mjs +463 -0
  3. package/dist/server/agent-service.js +419 -45
  4. package/dist/server/attachments.js +39 -0
  5. package/dist/server/client-state.js +22 -0
  6. package/dist/server/conversation-read-tool.js +325 -0
  7. package/dist/server/dsh/dsh-agent-service.js +32 -3
  8. package/dist/server/files-service.js +103 -0
  9. package/dist/server/host-metrics.js +59 -0
  10. package/dist/server/index.js +381 -8
  11. package/dist/server/model-admin.js +285 -36
  12. package/dist/server/plugin-facilities.js +115 -2
  13. package/dist/server/plugin-llm.js +129 -0
  14. package/dist/server/plugin-permissions.js +176 -0
  15. package/dist/server/plugin-schedule.js +211 -0
  16. package/dist/server/plugins.js +1005 -68
  17. package/dist/server/scheduler-tasks.js +405 -0
  18. package/dist/server/settings-service.js +8 -1
  19. package/dist/server/terminals.js +14 -1
  20. package/dist/server/tool-manager.js +6 -1
  21. package/dist/server/update-check.js +249 -19
  22. package/extensions/webui.ts +9 -2
  23. package/package.json +4 -2
  24. package/plugin-sdk/README.md +127 -0
  25. package/plugin-sdk/index.d.ts +454 -0
  26. package/plugin-sdk/index.mjs +545 -0
  27. package/plugin-sdk/package.json +9 -0
  28. package/plugins/catalog.json +11 -2
  29. package/web/dist/assets/TerminalPanel-BOUmN3uu.js +6 -0
  30. package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
  31. package/web/dist/assets/index-3XU67qMh.js +376 -0
  32. package/web/dist/assets/index-B-gdvWtW.css +10 -0
  33. package/web/dist/index.html +2 -3
  34. package/web/dist/assets/index-CYuoen3I.js +0 -374
  35. package/web/dist/assets/index-F86qWlJy.css +0 -41
package/CHANGELOG.md CHANGED
@@ -8,6 +8,68 @@
8
8
  每个版本的内容按"实际合入该版本发布的提交"归档(以 `package.json` 的 version 变更提交为准),
9
9
  而不是按提交日期聚类——连续快速发布的 patch 版本以此为准最准确。
10
10
 
11
+ ## [0.89.0] — 2026-09-17
12
+
13
+ ### Added
14
+
15
+ - **文件树右键:在资源管理器中显示 / 用默认应用打开**(issue #187)—— 文件/目录右键新增「在资源管理器中显示」(Windows 选中文件、macOS 访达定位、Linux 打开所在目录)与「用默认应用打开」(仅文件,如 Excel 开 xlsx)。服务端 `spawn` 直调系统命令(detached,不占进程),远端/无桌面主机回 warning 提示。
16
+
17
+ - **插件宿主 API v11:模型目录 + 定模型开对话**(issue #188)—— 插件经 `models.list()` 拿到已配置的模型目录(canonical `provider/model`,与 `set_model` 同口径,给插件做真实的模型选择器用),`startChat` / `openSession` 新增 `model` 选项(须在目录里,非法直接拒绝、不建对话、不动旧对话的模型;newChat 时先建新对话再把**新对话**切到该模型)。
18
+
19
+ - **插件通用反向代理 + 实时预览插件(live-preview)** —— 插件经 `host.registerProxy(prefix, 127.0.0.1:port)` 把真服务(只绑回环地址,外部不可达也无妨)挂到同源前缀下对外暴露:去前缀原样透传(相对路径/Range/SSE/ws upgrade 全可用,目标锁死回环防 SSRF,鉴权继承主站口令);live-preview 用它实现 `/liveserver`(HTML 预览:目录默认 index.html、改文件 SSE 自动刷新)与 `/md`(Markdown 渲染),另带 `live_preview` AI 工具。
20
+
21
+ - **内置定时任务调度**(issue #184)—— 设置面板新增「定时任务」页:任务名称/说明、执行目标项目(cwd)、Cron 表达式(常用预设一键选 + 自定义 5 字段)或固定间隔、可选模型与思考强度、启用/停用;任务列表展示下次触发与上次状态(成功/失败/耗时/手动标记),支持手动立即运行与历史记录(近 20 次)。触发经无头伪客户端执行(每任务独立会话、无浏览器也能跑,最长等 10 分钟回填真实结果),跑完推送通知;配置落盘 `<dataDir>/scheduler-tasks.json`(全局共享,重启不丢,catchUp 可补跑一次)。标准 pi 引擎可用,DSH 下该页隐藏。
22
+
23
+ - **输入框可拖拽调高** —— 输入框顶部悬停出现抓手,上下拖动直接固定输入区高度(40–720px,内容少也撑大,localStorage 持久化),双击恢复自适应高度。
24
+
25
+ - **桌面版应用内更新**(issue #180)—— 桌面壳的服务随应用包发布,`npm i -g` 换的是别处:顶栏更新面板在桌面里改走 electron-updater(检查 → 下载 → 安装并重启,全程面板内完成,另有下载页直链兜底);太旧的桌面壳(无更新通道)只给下载页指引。mac 产物补 zip(增量更新通道只吃 zip),Windows 安装包文件名去空格(修更新 feed 里下载链接 404)。
26
+ - **「全部组件更新」覆盖 git 源扩展**(issue #178)—— `settings.json` 里 `git:` 源的扩展以前在更新面板里根本不出现。现在全局 + 项目两级 settings 的 git 条目各列一行(远端 `git ls-remote` 比对,`pi update <host>/<path>` 一键更新);`PI_WEB_GIT_EXTENSION_CHECK=0` 可关掉这一路(大仓库逃生口)。
27
+ - **设置面板:界面布局独立分组 + 插件市场子页签** —— 「界面布局」从界面插件页里搬出来自成一组;插件市场拆出「市场 / 插件列表」子页签,已安装插件另列一页,不再和市场列表挤在一起。
28
+ - **插件 AI 工具统一门控** —— 插件经 `registerAgentTool` 注册的 AI 工具在设置 → 工具里按插件列出,可逐个关闭(关闭即从会话移除、重开立即加回,无需 reload;禁用记录保留,重装仍保持关闭)。webmail 的「允许 AI 管理邮箱」插件内开关同步取消(改常驻,走统一门控关)。
29
+ - **数据库插件注册 AI 工具**(db-client)—— `db_connections` / `db_databases` / `db_tables` / `db_schema` / `db_rows` / `db_query` / `db_redis_keys` / `db_redis_get` / `db_redis_cmd` 常驻注册(开关走上面的统一门控),模型可按连接 id / 名称直接查库;AI 打开的连接不计入面板状态点。
30
+ - **编辑器插件 AI 自主操作(vscode-editor 0.4.0)** —— 注册 15 个 `vsc_sftp_*` / `vsc_ssh_*` / `vsc_remote_*` 工具:模型可自己读/存 SFTP 同步配置(`.vscode/sftp.json`,vscode-sftp 兼容)、测试连接、一键上传/下载代码,新建 SSH 主机、拨号、远端执行命令、远端文件列表/读写/复制/删除/搜索;与界面表单共用同一套后端校验(`upsertSyncCfg` / `upsertSshHost` / `buildSshOpts` 收敛,旧逻辑原样迁移)。
31
+ - **编辑器文件树与右栏文件列表对齐** —— 右键剪切/复制/粘贴(同 scope 内移动或复制)、创建副本(`_copy` 自动递增)、复制路径、两棵树工具栏 🔍 文件名搜索(结果复用 Ctrl+P 浮层,远端带 🌐 标记);远端删除改为递归(含非空目录)、远端写/建自动补父目录;新增 `copy` / `search` 服务端动作(本地 + 远端 SFTP 共用)。
32
+
33
+ ### Changed
34
+
35
+ - **切项目更快** —— 冷切换先回 ack,模型/key 恢复扔后台做(带代际 guard,半路又切走自动丢弃,做完补一次快照刷新模型栏);历史面板没打开过不扫盘;最近项目列表 15s 缓存 + 并发搭车,不再反复扫盘。
36
+
37
+ ### Fixed
38
+
39
+ - **顶栏「⋯」溢出菜单不再裁掉搬进来的语言/主题等下拉(issue #183,#162 的回归)** —— 溢出菜单 portal 化之后,菜单项的无作用域 `button` 规则盖掉了嵌套 Dropdown 触发器(`.chip`)与面板行(`.dd-item`)的 flex 布局,且 portal 自身的纵向滚动在横向上也裁掉了宽 340px 的嵌套面板(标题切成 `ANGUAGE`)。菜单项规则收紧为直子选择器;嵌套面板打开时 portal 经 `:has(.dd-menu)` 门控放行横向溢出(平时长列表照样内滚)。
40
+ - **残留 AI bash 不再把对话钉在列表里**(issue #181)—— 终端接管 bash 留下的 ai-bash 记录是 agent 的内部执行记录,随对话一起释放;以前它们被算成“存活终端”,移出/✕ 关对话时被拦截,会话永久赖在运行列表里。现在移出与关闭拦截只看用户亲手用过的终端,pi 与 DSH 双端同修。
41
+ - **Windows 下 `/webui` 启动不再闪一下控制台窗口**(#176,社区)—— spawn 补 `windowsHide`,`detached` 只在非 Windows 下设;POSIX 行为不变。
42
+
43
+ <!-- auto-i18n:start -->
44
+ ### i18n
45
+
46
+ - 前端新增 key(89):`composerResize`、`updateDesktopNote`、`updateDesktopCheck`、`updateDesktopChecking`、`updateDesktopAvailable`、`updateDesktopDownload`、`updateDesktopDownloading`、`updateDesktopDownloaded`、`updateDesktopInstall`、`updateDesktopManual`、`updateDesktopError`、`updateDesktopNoBridge`、`kindGitExtension`、`fileReveal`、`fileOpenDefault`、`refreshBuiltinCatalog`、`refreshBuiltinHint`、`refreshBuiltinBusy`、`refreshBuiltinOk`、`refreshBuiltinFail`、`appendModel`、`appendModelTitle`、`appendModelIdPh`、`appendModelNamePh`、`appendModelAdd`、`appendModelBusy`、`appendModelCancel`、`appendModelOk`、`appendModelFail`、`appendModelApiTitle`、`appendModelApiAuto`、`appendModelBaseUrlPh`、`toolsSectionPlugin`、`toolsPluginHint`、`pluginToolsSection`、`pluginToolsEmpty`、`pluginToolOffHint`、`pluginListTab`、`settingsScheduler`、`schedulerDesc`、`schedulerEmpty`、`schedulerNew`、`schedulerEdit`、`schedulerDelete`、`schedulerRunNow`、`schedulerRunning`、`schedulerEnable`、`schedulerDisable`、`schedulerEnabled`、`schedulerDisabled`、`schedulerNameLabel`、`schedulerNamePlaceholder`、`schedulerDescPlaceholder`、`schedulerCwdLabel`、`schedulerCwdPlaceholder`、`schedulerUseCurrentCwd`、`schedulerKindLabel`、`schedulerKindCron`、`schedulerKindInterval`、`schedulerCronPlaceholder`、`schedulerPresetDaily`、`schedulerPresetHourly`、`schedulerPresetHalfHour`、`schedulerPresetWorkday`、`schedulerPresetMonday`、`schedulerPresetCustom`、`schedulerIntervalMinutes`、`schedulerPromptLabel`、`schedulerPromptPlaceholder`、`schedulerModelLabel`、`schedulerThinkingLabel`、`schedulerCatchUp`、`schedulerCatchUpHint`、`schedulerNextFire`、`schedulerLastRun`、`schedulerNeverRun`、`schedulerHistory`、`schedulerManualBadge`、`schedulerRunOk`、`schedulerRunFail`、`schedulerConfirmDelete`、`schedulerSave`、`schedulerCancelEdit`、`copyConversationId`、`copyConversationPath`、`quoteConversation`、`quoteConversationShort`、`attachConversation`、`attachConversationShort`
47
+ - 服务端新增 key(6):`convread.list.bad.scope`、`convread.read.bad.args`、`convread.read.id.not.found`、`convread.read.path.not.found`、`convread.bad.action`、`dsh.provider.builtin.refresh.unsupported`
48
+ <!-- auto-i18n:end -->
49
+
50
+ ## [0.88.0] — 2026-09-16
51
+
52
+ ### Added
53
+
54
+ - **底栏主机资源指标**(#174)—— 底栏实时显示主机处理器与内存使用率,悬浮看明细;`bottombar` 对齐方式改为数据驱动,随布局偏好走。
55
+ - **布局槽位全量接线** —— `chat.header` / `chat.empty` / `file.preview.toolbar` 接上渲染(无贡献时 DOM 与原来一致);设置布局页从 9 槽补到 21 槽,新增搜索过滤、align 对齐、改名、`uiLayoutMovedFrom` 移自显示。
56
+ - **输入框新增前置槽位 `composer.leading`** —— 第三方插件终于可以把图标放到文件上传按钮左侧了(以前 `composer.actions` 只能排在上传右侧)。写法与其它槽位一致(`"ui": { "composer.leading": [...] }`,必须写完整名、没有简写别名),排序/隐藏/布局页偏好全套生效。
57
+ - **插件宿主能力扩展 + `plugin-sdk` 起手包** —— 新增 `host.llm`(模型调用)、`host.schedule`(定时任务)、`host.permissions`(权限声明)、`composerProviders`(输入框内容源);`plugin-sdk/` 开箱即用的类型 + 运行时 + README,可直接抄起手。
58
+ - **插件诊断输出 + `create` 脚手架 + `host.log` 日志面板** —— manifest / UI 贡献被丢弃时给出原因(设置面板可展开查看,不再是静默消失);`plugin create` 一键搭架子(minimal / ui-slot / agent-tool / renderer 四模板,`--with-test` 附带单测);运行时日志分级落盘(内存环形缓冲 + 面板级别过滤/清空);另附 `createMockHost` 本地单测 harness + `plugin upgrade-sdk`。
59
+
60
+ ### Changed
61
+
62
+ - `slot-toolbar` 抽成独立模块,`TerminalPanel` 恢复 lazy / xterm 拆包(首屏包体积回落)。
63
+
64
+ <!-- auto-i18n:start -->
65
+
66
+ ### i18n
67
+
68
+ - 前端新增 key(46):`hostResources`、`hostProcessor`、`hostMemory`、`hostResourcesTip`、`uiLayoutComposerLeading`、`uiLayoutModal`、`uiLayoutContextTopbar`、`uiLayoutContextMessage`、`uiLayoutContextSession`、`uiLayoutContextFile`、`uiLayoutLeftSessions`、`uiLayoutChatHeader`、`uiLayoutChatEmpty`、`uiLayoutFilePreview`、`uiLayoutTerminal`、`uiLayoutScm`、`uiLayoutGoalbar`、`uiLayoutNotice`、`uiLayoutSearch`、`uiLayoutMovedFrom`、`uiLayoutAlign`、`uiLayoutRename`、`pluginPermTitle`、`pluginPermBodyNet`、`pluginPermBodyLlm`、`pluginPermOnce`、`pluginPermAlways`、`pluginPermsTitle`、`pluginPermsHint`、`pluginPermsEmpty`、`pluginPermSession`、`pluginPermNet`、`pluginPermLlm`、`pluginPermUnscoped`、`pluginDiagTitle`、`pluginDiagShow`、`pluginDiagHide`、`pluginLogTitle`、`pluginLogShow`、`pluginLogHide`、`pluginLogLevel`、`pluginLogAll`、`pluginLogEmpty`、`pluginLogClear`、`pluginSecretSet`、`pluginSecretUnset`
69
+ - 服务端新增 key(1):`plugins.settings.too.long`
70
+
71
+ <!-- auto-i18n:end -->
72
+
11
73
  ## [0.87.2] — 2026-09-16
12
74
 
13
75
  ### Fixed
@@ -66,12 +128,14 @@
66
128
  - **顶栏「⋯」溢出菜单在 DOM 里但永远点不到**(issue #162)—— 菜单元件挂在 `.view-switch{overflow:hidden}`(桌面端圆角药丸容器的裁剪)/ `.topbar-actions` 横滑容器(窄屏 ≤768px)里面,往下展开的部分全被祖先裁掉,`z-index` 再高也出不来;藏进溢出菜单的条目实际不可达。现在菜单经 portal 到 `document.body` + `position: fixed`(与右键菜单同路),按触发按钮实测锚定、视口钳制(下方放不下翻到上方),并补上点外面 / Esc 关闭(滚动/缩放时重跟锚点,不关闭)。另修一个连带坑:关闭回调若是内联箭头,effect 每 render 解绑/重绑全套 document 监听,离散按键可能正好落在空窗里导致 Esc 丢键 —— 关闭走 ref,监听只装一次。回归:`tests/ui-layout-ui-test.mjs` 新增「真的可见可点」断言(`elementFromPoint` 落在菜单内)。
67
129
 
68
130
  <!-- auto-i18n:start -->
131
+
69
132
  ### i18n
70
133
 
71
134
  - 前端新增 key(61):`atMentions`、`atMenuHint`、`fileOpenPreview`、`fileEnterDir`、`fileNewFile`、`fileNewDir`、`fileRename`、`fileNamePlaceholder`、`fileDuplicate`、`fileCut`、`fileCopyEntry`、`filePaste`、`fileDelete`、`fileDeleteConfirm`、`fileCopyRelPath`、`fileRefresh`、`providerAuthHint`、`oauthLogin`、`oauthLogout`、`oauthConnected`、`oauthDeviceCode`、`oauthOpenVerification`、`oauthContinue`、`pluginCatalogSync`、`pluginCatalogSyncHint`、`pluginCatalogSyncSource`、`pluginCatalogSyncSubmit`、`pluginCatalogSyncInstall`、`pluginCatalogSyncReplace`、`pluginCatalogSyncRecent`、`pluginCatalogSyncOk`、`pluginCatalogSyncInstalled`、`dshPreset`、`dshPresetNewChat`、`dshPresetLocked`、`dshPresetBlankOnly`、`dshPresetBroken`、`dshPresetUser`、`dshPresetDefaultTag`、`dshPresetCurrent`、`dshPresetMinimalNote`、`dshDefaultPreset`、`dshDefaultPresetDesc`、`dshPresetUserNote`、`dshPerm`、`dshPermReadOnly`、`dshPermReadOnlyDesc`、`dshPermWorkspaceWrite`、`dshPermWorkspaceWriteDesc`、`dshPermFullAccess`、`dshPermFullAccessDesc`、`dshPermFullAccessTag`、`dshPermCustom`、`dshPermConfirmFull`、`dshPermDefault`、`dshPermDefaultDesc`、`pluginDomNeed`、`pluginDomDesc`、`pluginDomGrant`、`pluginDomRevoke`、`pluginDomGranted`
72
135
  - 前端中文变更(1):`pluginBuildHint`
73
136
  - 前端英文变更(1):`pluginBuildHint`
74
137
  - 服务端新增 key(2):`plugininstaller.build.conflict`、`plugins.host.engines.mismatch`
138
+
75
139
  <!-- auto-i18n:end -->
76
140
 
77
141
  ## [0.86.2] — 2026-09-15
@@ -920,7 +984,8 @@ when?, children?}`,也收 `topbar` / `settings` 这类简写别名);宿主
920
984
  - 0.35.1(2026-08-27):编辑重问保留附件(#18)+ 全窗口拖放(#19)。
921
985
  - 0.29.0(2026-08-23):全局搜索弹窗(Ctrl+K)+ 消息列表惰性窗口化。
922
986
 
923
- [Unreleased]: https://github.com/xing-shuyin/pi-web-ui/compare/v0.87.1...main
987
+ [Unreleased]: https://github.com/xing-shuyin/pi-web-ui/compare/v0.88.0...main
988
+ [0.88.0]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.88.0
924
989
  [0.87.2]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.87.2
925
990
  [0.87.1]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.87.1
926
991
  [0.87.0]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.87.0
package/bin/pi-web-ui.mjs CHANGED
@@ -107,6 +107,7 @@ server 选项:
107
107
  快捷方式: Windows → 桌面 .lnk · macOS → 桌面 .command 启动器 · Linux → 桌面 .desktop 图标
108
108
 
109
109
  界面插件(安装到 <data-dir>/plugins/,服务运行中刷新浏览器即生效):
110
+ pi-web-ui plugin create <id> 生成最小可跑的插件骨架
110
111
  pi-web-ui install <源> 从 GitHub 安装界面插件
111
112
  pi-web-ui uninstall <id> 卸载已安装的界面插件
112
113
  pi-web-ui plugins 列出已安装的界面插件
@@ -158,6 +159,7 @@ Platforms: macOS → launchd user agent · Linux → systemd · Windows → Logo
158
159
  Shortcuts: Windows → desktop .lnk · macOS → desktop .command · Linux → desktop .desktop
159
160
 
160
161
  UI plugins (installed into <data-dir>/plugins/; refresh browser to activate while running):
162
+ pi-web-ui plugin create <id> Scaffold a minimal runnable plugin
161
163
  pi-web-ui install <source> Install a UI plugin from GitHub
162
164
  pi-web-ui uninstall <id> Uninstall a UI plugin
163
165
  pi-web-ui plugins List installed UI plugins
@@ -233,6 +235,9 @@ function parseFlags(argv) {
233
235
  force: false,
234
236
  checkUpdates: false,
235
237
  rollback: undefined,
238
+ dir: undefined,
239
+ template: undefined,
240
+ withTest: false,
236
241
  help: false,
237
242
  };
238
243
  const positionals = [];
@@ -298,6 +303,15 @@ function parseFlags(argv) {
298
303
  case "--rollback":
299
304
  opts.rollback = take("--rollback");
300
305
  break;
306
+ case "--dir":
307
+ opts.dir = take("--dir");
308
+ break;
309
+ case "--template":
310
+ opts.template = take("--template");
311
+ break;
312
+ case "--with-test":
313
+ opts.withTest = true;
314
+ break;
301
315
  case "--help":
302
316
  case "-h":
303
317
  opts.help = true;
@@ -1459,8 +1473,11 @@ function controlService(action, opts) {
1459
1473
  const PLUGIN_ID_RE = /^[A-Za-z0-9_-]+$/;
1460
1474
 
1461
1475
  const PLUGIN_HELP = `用法:
1476
+ pi-web-ui plugin create <id> [选项] 生成最小可跑的插件骨架
1462
1477
  pi-web-ui install <源> [选项] 安装 GitHub 上的界面插件
1463
1478
  pi-web-ui install --catalog <目录> [选项] 同步插件市场目录并逐条安装
1479
+ pi-web-ui plugin create <id> [选项] 生成插件骨架(minimal|ui-slot|agent-tool|renderer)
1480
+ pi-web-ui plugin upgrade-sdk [id] [选项] 刷新已装插件的 SDK 拷贝(SDK_VERSION 对不上才拷)
1464
1481
  pi-web-ui uninstall <id> [选项] 卸载已安装的界面插件
1465
1482
  pi-web-ui plugins [选项] 列出已安装的界面插件
1466
1483
 
@@ -1485,6 +1502,16 @@ const PLUGIN_HELP = `用法:
1485
1502
  (已安装的条目默认跳过,加 --force 则更新;单条失败不中断整批)
1486
1503
  --replace 配合 --catalog:整体替换可安装列表(默认按 id 合并,保留旧条目)
1487
1504
 
1505
+ create 选项:
1506
+ --template <t> minimal(默认,零权限)| ui-slot | agent-tool | renderer
1507
+ --dir <dir> 插件父目录(默认 <data-dir>/plugins;也可用 --data-dir 指定数据目录)
1508
+ --force 目标目录已存在时覆盖
1509
+ --with-test 顺带生成 index.test.mjs(node --test + createMockHost 最小单测,需包内 SDK)
1510
+
1511
+ upgrade-sdk 选项:
1512
+ [id] 只刷新这一个插件(缺省刷新全部有 sdk 拷贝的插件)
1513
+ --dir <dir> 插件父目录(默认 <data-dir>/plugins;也可用 --data-dir 指定数据目录)
1514
+
1488
1515
  plugins 选项:
1489
1516
  --check-updates 逐个对比最近安装版本与远端 HEAD,列出可更新插件
1490
1517
  --rollback <id> 回滚到最近一份更新前备份(<dataDir>/plugin-backups/)
@@ -2000,6 +2027,434 @@ async function installCatalogCmd(opts) {
2000
2027
  if (failCount) process.exitCode = 1;
2001
2028
  }
2002
2029
 
2030
+ // ---------------------------------------------------------------------------
2031
+ // 插件脚手架(plugin create):生成最小可跑骨架
2032
+ // 形态 = <dataDir>/plugins/<id>/(manifest.json + index.mjs + client/entry.mjs),
2033
+ // 与 server/plugins.ts 的加载约定对齐;官方插件(plugins/demo-mailbox 等)可作参考。
2034
+ // ---------------------------------------------------------------------------
2035
+
2036
+ /** 脚手架模板:minimal(零权限)| ui-slot | agent-tool | renderer(view:false)。 */
2037
+ const PLUGIN_TEMPLATES = ["minimal", "ui-slot", "agent-tool", "renderer"];
2038
+
2039
+ /** 包内 plugin-sdk 入口(随包发布,见 package.json files;拷进骨架的 sdk/ 目录)。 */
2040
+ function pluginSdkSource() {
2041
+ const p = join(BIN_DIR, "..", "plugin-sdk", "index.mjs");
2042
+ return existsSync(p) ? p : undefined;
2043
+ }
2044
+
2045
+ /** 各模板的 manifest.description(一句话说明骨架来源)。 */
2046
+ function scaffoldDescription(template) {
2047
+ switch (template) {
2048
+ case "ui-slot":
2049
+ return "输入框动作按钮示例(pi-web-ui plugin create --template ui-slot 生成的骨架)";
2050
+ case "agent-tool":
2051
+ return "AI 工具扩展示例(pi-web-ui plugin create --template agent-tool 生成的骨架)";
2052
+ case "renderer":
2053
+ return "围栏代码渲染器示例(pi-web-ui plugin create --template renderer 生成的骨架)";
2054
+ default:
2055
+ return "最小可跑插件骨架(pi-web-ui plugin create 生成)";
2056
+ }
2057
+ }
2058
+
2059
+ /** 拼骨架文件:{ 相对路径: 内容 }。useSdk=false 时走无 SDK 导入的等价写法。
2060
+ * withTest=true(且 useSdk)时多带 index.test.mjs(node --test + createMockHost 最小单测)。 */
2061
+ function buildPluginScaffold(id, template, useSdk, withTest = false) {
2062
+ const sdkServer = useSdk ? `import { definePlugin } from "./sdk/index.mjs";\n\n` : "";
2063
+ const sdkClient = useSdk ? `import { defineView, onUiAction } from "../sdk/index.mjs";\n\n` : "";
2064
+ const wrapServer = (body) =>
2065
+ useSdk ? `${sdkServer}export default definePlugin({\n${body}\n});\n` : `export default {\n${body}\n};\n`;
2066
+ const wrapClient = (body) =>
2067
+ useSdk ? `${sdkClient}export default defineView({\n${body}\n});\n` : `export default {\n${body}\n};\n`;
2068
+ const toolName = `${id.replace(/[^A-Za-z0-9_]/g, "_")}_hello`;
2069
+ const action = `${id}:hello`;
2070
+ const lang = id.toLowerCase().replace(/[^a-z0-9]/g, "") || "hello";
2071
+
2072
+ const manifest = {
2073
+ id,
2074
+ name: id,
2075
+ version: "0.1.0",
2076
+ description: scaffoldDescription(template),
2077
+ apiVersion: 2,
2078
+ };
2079
+
2080
+ const minimalServer = wrapServer(
2081
+ `\tactivate(host) {\n` +
2082
+ `\t\thost.log("activated");\n` +
2083
+ `\t\tconst off = host.onMessage((payload) => {\n` +
2084
+ `\t\t\thost.log("message:", JSON.stringify(payload ?? {}));\n` +
2085
+ `\t\t});\n` +
2086
+ `\t\treturn () => {\n` +
2087
+ `\t\t\toff();\n` +
2088
+ `\t\t\thost.log("deactivated");\n` +
2089
+ `\t\t};\n` +
2090
+ `\t},`,
2091
+ );
2092
+ const minimalClient = wrapClient(
2093
+ `\tmount(container) {\n` +
2094
+ `\t\tconst el = document.createElement("div");\n` +
2095
+ `\t\tel.style.padding = "16px";\n` +
2096
+ `\t\tel.textContent = "Hello from ${id} —— 改 client/entry.mjs 后刷新浏览器即生效。";\n` +
2097
+ `\t\tcontainer.appendChild(el);\n` +
2098
+ `\t\treturn () => {\n` +
2099
+ `\t\t\tel.remove();\n` +
2100
+ `\t\t};\n` +
2101
+ `\t},`,
2102
+ );
2103
+
2104
+ let indexJs = minimalServer;
2105
+ let clientJs = minimalClient;
2106
+
2107
+ if (template === "ui-slot") {
2108
+ manifest.permissions = ["ui"];
2109
+ manifest.ui = {
2110
+ "composer.actions": [{ id: "hello", label: "打招呼", kind: "action", action }],
2111
+ };
2112
+ indexJs = wrapServer(
2113
+ `\tactivate(host) {\n` +
2114
+ `\t\thost.log("activated");\n` +
2115
+ `\t\t// manifest.ui["composer.actions"] 里声明的按钮点下后,客户端经 ctx.send 发到这里。\n` +
2116
+ `\t\tconst off = host.onMessage((payload) => {\n` +
2117
+ `\t\t\tif (payload?.action === "${action}") {\n` +
2118
+ `\t\t\t\thost.notify("info", "你好,来自插件 ${id} 👋");\n` +
2119
+ `\t\t\t}\n` +
2120
+ `\t\t});\n` +
2121
+ `\t\treturn () => {\n` +
2122
+ `\t\t\toff();\n` +
2123
+ `\t\t\thost.log("deactivated");\n` +
2124
+ `\t\t};\n` +
2125
+ `\t},`,
2126
+ );
2127
+ clientJs = useSdk
2128
+ ? `${sdkClient}export default defineView({\n` +
2129
+ `\tmount(container, ctx) {\n` +
2130
+ `\t\tconst el = document.createElement("div");\n` +
2131
+ `\t\tel.style.padding = "16px";\n` +
2132
+ `\t\tel.textContent = "点输入框旁的「打招呼」按钮试试 👆";\n` +
2133
+ `\t\tcontainer.appendChild(el);\n` +
2134
+ `\t\t// manifest.ui 里 action 为 "${action}" 的条目点下走这里,再经 ctx.send 落到服务端。\n` +
2135
+ `\t\tconst off = onUiAction("${action}", () => {\n` +
2136
+ `\t\t\tel.textContent = "已点击,服务端收到啦 ✅";\n` +
2137
+ `\t\t\tctx.send({ action: "${action}" });\n` +
2138
+ `\t\t});\n` +
2139
+ `\t\treturn () => {\n` +
2140
+ `\t\t\toff();\n` +
2141
+ `\t\t\tel.remove();\n` +
2142
+ `\t\t};\n` +
2143
+ `\t},\n});\n`
2144
+ : `export default {\n` +
2145
+ `\tmount(container, ctx) {\n` +
2146
+ `\t\tconst el = document.createElement("div");\n` +
2147
+ `\t\tel.style.padding = "16px";\n` +
2148
+ `\t\tel.textContent = "点输入框旁的「打招呼」按钮试试 👆";\n` +
2149
+ `\t\tcontainer.appendChild(el);\n` +
2150
+ `\t\tconst bridge = globalThis.window?.__piWebUiHost;\n` +
2151
+ `\t\tconst off = bridge?.onUiAction?.("${action}", () => {\n` +
2152
+ `\t\t\tel.textContent = "已点击,服务端收到啦 ✅";\n` +
2153
+ `\t\t\tctx.send({ action: "${action}" });\n` +
2154
+ `\t\t}) ?? (() => {});\n` +
2155
+ `\t\treturn () => {\n` +
2156
+ `\t\t\toff();\n` +
2157
+ `\t\t\tel.remove();\n` +
2158
+ `\t\t};\n` +
2159
+ `\t},\n};\n`;
2160
+ }
2161
+
2162
+ if (template === "agent-tool") {
2163
+ manifest.permissions = ["tools"];
2164
+ indexJs = wrapServer(
2165
+ `\tactivate(host) {\n` +
2166
+ `\t\thost.log("activated");\n` +
2167
+ `\t\t// 注册给 AI 用的工具(manifest.permissions 须含 "tools";name 全局唯一)。\n` +
2168
+ `\t\tconst offTool = host.registerAgentTool({\n` +
2169
+ `\t\t\tname: "${toolName}",\n` +
2170
+ `\t\t\tdescription: "打招呼示例工具:返回一句问候(plugin create 生成的骨架)。",\n` +
2171
+ `\t\t\tparameters: {\n` +
2172
+ `\t\t\t\ttype: "object",\n` +
2173
+ `\t\t\t\tproperties: { name: { type: "string", description: "要问候的名字" } },\n` +
2174
+ `\t\t\t},\n` +
2175
+ `\t\t\texecute: async (_toolCallId, params) => {\n` +
2176
+ `\t\t\t\tconst raw = params?.name;\n` +
2177
+ `\t\t\t\tconst who = typeof raw === "string" && raw.trim() ? raw.trim() : "world";\n` +
2178
+ `\t\t\t\treturn "Hello, " + who + "! 👋(来自插件 ${id})";\n` +
2179
+ `\t\t\t},\n` +
2180
+ `\t\t});\n` +
2181
+ `\t\treturn () => {\n` +
2182
+ `\t\t\toffTool();\n` +
2183
+ `\t\t\thost.log("deactivated");\n` +
2184
+ `\t\t};\n` +
2185
+ `\t},`,
2186
+ );
2187
+ }
2188
+
2189
+ if (template === "renderer") {
2190
+ manifest.view = false;
2191
+ manifest.renderers = [lang];
2192
+ indexJs = wrapServer(
2193
+ `\tactivate(host) {\n` +
2194
+ `\t\thost.log("activated");\n` +
2195
+ `\t\treturn () => {\n` +
2196
+ `\t\t\thost.log("deactivated");\n` +
2197
+ `\t\t};\n` +
2198
+ `\t},`,
2199
+ );
2200
+ // 渲染器走裸 ESM(命中围栏才懒加载):默认导出 { renderers },不用 defineView。
2201
+ clientJs =
2202
+ `/**\n` +
2203
+ ` * ${id} —— fenced-code 渲染器(pi-web-ui plugin create 生成)。\n` +
2204
+ ` * manifest 须写 "view": false + "renderers": ["${lang}"];命中 ${lang} 围栏才懒加载。\n` +
2205
+ ` */\n` +
2206
+ `export default {\n` +
2207
+ `\trenderers: {\n` +
2208
+ `\t\t"${lang}": (code) => {\n` +
2209
+ `\t\t\tconst pre = document.createElement("pre");\n` +
2210
+ `\t\t\tpre.style.padding = "12px 16px";\n` +
2211
+ `\t\t\tpre.textContent = String(code ?? "");\n` +
2212
+ `\t\t\treturn pre;\n` +
2213
+ `\t\t},\n` +
2214
+ `\t},\n` +
2215
+ `};\n`;
2216
+ }
2217
+
2218
+ const header = (file) =>
2219
+ `/**\n` +
2220
+ ` * ${id} —— ${file}(pi-web-ui plugin create --template ${template} 生成)。\n` +
2221
+ ` * 约定:服务端 ESM 默认导出 { activate(host) → cleanup? };\n` +
2222
+ ` * 客户端 ESM 默认导出 { mount(container, ctx) → cleanup? }。\n` +
2223
+ ` */\n`;
2224
+ const nextStep =
2225
+ template === "ui-slot"
2226
+ ? "在 manifest.ui 里加更多 composer.actions 条目,client 里用 onUiAction 接住 action。"
2227
+ : template === "agent-tool"
2228
+ ? `在 index.mjs 里追加 host.registerAgentTool(name 全局唯一,建议 ${id.replace(/[^A-Za-z0-9_]/g, "_")}_<动作> 前缀)。`
2229
+ : template === "renderer"
2230
+ ? "把 renderers 回调换成真正的渲染(如 mermaid 插件那样懒加载引擎),manifest.renderers 追加语言。"
2231
+ : "在 index.mjs 里接 host API(log/onMessage/broadcast/notify),视图改 client/entry.mjs。";
2232
+ const readme =
2233
+ `# ${id}\n` +
2234
+ `\n` +
2235
+ `${scaffoldDescription(template)}。\n` +
2236
+ `\n` +
2237
+ `## 目录\n` +
2238
+ `\n` +
2239
+ `- \`manifest.json\` —— 插件声明(id/name/version/description/apiVersion/permissions…)\n` +
2240
+ `- \`index.mjs\` —— 服务端入口(\`export default { activate(host) }\`)\n` +
2241
+ `- \`client/entry.mjs\` —— 客户端视图${template === "renderer" ? "(渲染器:\`{ renderers }\`)" : "(\`{ mount }\`)"}\n` +
2242
+ (useSdk ? `- \`sdk/index.mjs\` —— plugin-sdk 拷贝(definePlugin/defineView/onUiAction,零依赖)\n` : "") +
2243
+ (withTest && useSdk
2244
+ ? "- `index.test.mjs` —— 最小单测(`node --test index.test.mjs`,createMockHost harness)\n"
2245
+ : "") +
2246
+ `\n` +
2247
+ `## 下一步\n` +
2248
+ `\n` +
2249
+ `1. 改名改描述:编辑 manifest.json 的 name/description。\n` +
2250
+ `2. 写逻辑:${nextStep}\n` +
2251
+ `3. 生效:服务运行中刷新浏览器即可加载(或发 \`plugins_reload\`);未运行则下次启动生效。\n` +
2252
+ `4. 参考:官方插件 \`plugins/demo-mailbox\`(最小)、\`plugin-sdk/README.md\`(完整契约)。\n` +
2253
+ (withTest && useSdk
2254
+ ? `\n## 单测\n\n\`node --test index.test.mjs\`(createMockHost harness:activate 记录断言 + reset;改逻辑前保持它绿)。\n`
2255
+ : "");
2256
+
2257
+ const out = {
2258
+ "manifest.json": JSON.stringify(manifest, null, "\t") + "\n",
2259
+ "index.mjs": header("服务端入口") + (useSdk ? sdkServer : "") + indexJs.slice(indexJs.indexOf("export")),
2260
+ "client/entry.mjs":
2261
+ template === "renderer"
2262
+ ? `/**\n * ${id} —— 客户端渲染器(pi-web-ui plugin create --template renderer 生成)。\n */\n` +
2263
+ clientJs.slice(clientJs.indexOf("export"))
2264
+ : header("客户端视图") + (useSdk ? sdkClient : "") + clientJs.slice(clientJs.indexOf("export")),
2265
+ "README.md": readme,
2266
+ };
2267
+ if (withTest && useSdk) {
2268
+ // 最小单测:四个模板的 activate 都会 host.log("activated"),断言与模板无关。
2269
+ out["index.test.mjs"] =
2270
+ `/**\n` +
2271
+ ` * ${id} —— 最小单测(pi-web-ui plugin create --with-test 生成)。\n` +
2272
+ ` * 跑法(插件目录下):node --test index.test.mjs(零依赖,node 内置 runner + assert)。\n` +
2273
+ ` */\n` +
2274
+ `import { describe, it } from "node:test";\n` +
2275
+ `import assert from "node:assert/strict";\n` +
2276
+ `import plugin from "./index.mjs";\n` +
2277
+ `import { createMockHost } from "./sdk/index.mjs";\n` +
2278
+ `\n` +
2279
+ `describe("${id} activate", () => {\n` +
2280
+ `\tit("激活不抛错,且调了 host 方法", async () => {\n` +
2281
+ `\t\tconst host = createMockHost({ settings: {} });\n` +
2282
+ `\t\tconst cleanup = await plugin.activate(host);\n` +
2283
+ `\t\tassert.ok(host.calls.length > 0, "activate 应该至少调一次 host 方法(log 也算)");\n` +
2284
+ `\t\tassert.ok(\n` +
2285
+ `\t\t\thost.logs.some((l) => l.text.includes("activated")),\n` +
2286
+ `\t\t\t"骨架 activate 会 host.log('activated')",\n` +
2287
+ `\t\t);\n` +
2288
+ `\t\tif (typeof cleanup === "function") cleanup();\n` +
2289
+ `\t});\n` +
2290
+ `\n` +
2291
+ `\tit("reset() 清空调用记录与日志", async () => {\n` +
2292
+ `\t\tconst host = createMockHost();\n` +
2293
+ `\t\tawait plugin.activate(host);\n` +
2294
+ `\t\tassert.ok(host.calls.length > 0);\n` +
2295
+ `\t\thost.reset();\n` +
2296
+ `\t\tassert.equal(host.calls.length, 0);\n` +
2297
+ `\t\tassert.equal(host.logs.length, 0);\n` +
2298
+ `\t});\n` +
2299
+ `});\n`;
2300
+ }
2301
+ return out;
2302
+ }
2303
+
2304
+ /** 生成后的 manifest 基础校验(必填/口径);返回 warnings(无则空数组)。 */
2305
+ function validateScaffoldManifest(manifest, dirName) {
2306
+ const warnings = [];
2307
+ for (const k of ["id", "name", "version", "description"]) {
2308
+ if (typeof manifest[k] !== "string" || !manifest[k].trim()) warnings.push(`manifest 缺少必填字段 "${k}"`);
2309
+ }
2310
+ if (manifest.id && manifest.id !== dirName)
2311
+ warnings.push(`manifest.id "${manifest.id}" 与目录名 "${dirName}" 不一致(以目录名为准)`);
2312
+ if (manifest.version && !/^\d+\.\d+\.\d+/.test(manifest.version)) {
2313
+ warnings.push(`manifest.version "${manifest.version}" 不是 x.y.z 格式`);
2314
+ }
2315
+ const api = manifest.apiVersion ?? 1;
2316
+ if (typeof api !== "number" || api > 2) {
2317
+ warnings.push(`manifest.apiVersion=${JSON.stringify(api)} 高于宿主 v2,插件会被拒绝激活`);
2318
+ }
2319
+ if (manifest.permissions !== undefined) {
2320
+ const ok = Array.isArray(manifest.permissions) && manifest.permissions.every((p) => typeof p === "string" && p);
2321
+ if (!ok) warnings.push(`manifest.permissions 须是字符串数组(如 ["ui"])`);
2322
+ }
2323
+ if (manifest.view === false && !(Array.isArray(manifest.renderers) && manifest.renderers.length > 0)) {
2324
+ warnings.push(`view:false 但未声明 renderers —— 插件将没有任何界面`);
2325
+ }
2326
+ return warnings;
2327
+ }
2328
+
2329
+ /** 已装插件的 sdk/index.mjs 里解析 SDK_VERSION(老拷贝无此常量 → null,即未知旧版)。 */
2330
+ function installedSdkVersion(sdkFile) {
2331
+ try {
2332
+ const src = readFileSync(sdkFile, "utf8");
2333
+ const m = src.match(/SDK_VERSION\s*=\s*["']([^"']+)["']/);
2334
+ return m ? m[1] : null;
2335
+ } catch {
2336
+ return null;
2337
+ }
2338
+ }
2339
+
2340
+ /** 包内 SDK 版本(单源:plugin-sdk/index.mjs 的 `export const SDK_VERSION`)。 */
2341
+ function packageSdkVersion() {
2342
+ const sdkSrc = pluginSdkSource();
2343
+ if (!sdkSrc) fail(`包内无 plugin-sdk(找不到 plugin-sdk/index.mjs),无法刷新`);
2344
+ let src;
2345
+ try {
2346
+ src = readFileSync(sdkSrc, "utf8");
2347
+ } catch {
2348
+ fail(`包内 plugin-sdk/index.mjs 不可读,无法刷新`);
2349
+ }
2350
+ const m = src.match(/export const SDK_VERSION\s*=\s*["']([^"']+)["']/);
2351
+ if (!m) fail(`包内 plugin-sdk/index.mjs 无 SDK_VERSION 导出,无法刷新(请升级 pi-web-ui)`);
2352
+ return { version: m[1], file: sdkSrc };
2353
+ }
2354
+
2355
+ /** 刷新已装插件的 sdk/index.mjs 拷贝(版本号对不上才拷;无拷贝的插件跳过)。 */
2356
+ function pluginUpgradeSdkCmd(argv) {
2357
+ const { opts, positionals } = parseFlags(argv);
2358
+ if (opts.help || positionals.length > 1) {
2359
+ console.log(PLUGIN_HELP);
2360
+ if (!opts.help) process.exit(1);
2361
+ return;
2362
+ }
2363
+ const { version: latest, file: sdkSrc } = packageSdkVersion();
2364
+ const parentDir = opts.dir ? resolve(opts.dir) : join(pluginDataDir(opts), "plugins");
2365
+ const only = positionals.length === 1 ? positionals[0] : null;
2366
+ if (only && !PLUGIN_ID_RE.test(only)) fail(`非法插件 id "${only}"(仅限字母数字-_)`);
2367
+ if (only && !existsSync(join(parentDir, only))) fail(`未安装插件 "${only}"(pi-web-ui plugins 查看已装列表)`);
2368
+ let entries;
2369
+ try {
2370
+ entries = readdirSync(parentDir, { withFileTypes: true })
2371
+ .filter((e) => e.isDirectory() && PLUGIN_ID_RE.test(e.name))
2372
+ .map((e) => e.name);
2373
+ } catch {
2374
+ fail(`读插件目录失败: ${parentDir}`);
2375
+ }
2376
+ const targets = only ? [only] : entries;
2377
+ let upgraded = 0;
2378
+ let fresh = 0;
2379
+ let skipped = 0;
2380
+ const broken = [];
2381
+ for (const id of targets) {
2382
+ const sdkFile = join(parentDir, id, "sdk", "index.mjs");
2383
+ if (!existsSync(sdkFile)) {
2384
+ skipped++;
2385
+ console.log(`- ${id}:无 sdk/index.mjs 拷贝,跳过`);
2386
+ continue;
2387
+ }
2388
+ const cur = installedSdkVersion(sdkFile);
2389
+ if (cur === latest) {
2390
+ fresh++;
2391
+ console.log(`✔ ${id}:已是最新(SDK ${latest})`);
2392
+ continue;
2393
+ }
2394
+ copyFileSync(sdkSrc, sdkFile);
2395
+ const r = spawnSync(NODE, ["--check", sdkFile], { stdio: "ignore" });
2396
+ if (r.status !== 0) broken.push(`${sdkFile} 未通过 node --check(磁盘/权限异常?请手动检查)`);
2397
+ else {
2398
+ upgraded++;
2399
+ console.log(`✔ ${id}:SDK ${cur ?? "未知旧版"} → ${latest}`);
2400
+ }
2401
+ }
2402
+ for (const w of broken) console.log(`⚠ ${w}`);
2403
+ console.log(`共 ${targets.length} 个插件:刷新 ${upgraded} 个,已最新 ${fresh} 个,跳过 ${skipped} 个。`);
2404
+ console.log(` 生效: 服务运行中插件重载(或刷新浏览器)后新 SDK 生效;未运行则下次启动生效。`);
2405
+ }
2406
+
2407
+ function pluginCreateCmd(argv) {
2408
+ const { opts, positionals } = parseFlags(argv);
2409
+ if (opts.help || positionals.length !== 1) {
2410
+ console.log(PLUGIN_HELP);
2411
+ if (!opts.help) process.exit(1);
2412
+ return;
2413
+ }
2414
+ const id = positionals[0];
2415
+ if (!PLUGIN_ID_RE.test(id)) fail(`非法插件 id "${id}"(仅限字母数字-_)`);
2416
+ const template = opts.template ?? "minimal";
2417
+ if (!PLUGIN_TEMPLATES.includes(template)) fail(`未知模板 "${template}"(可选 ${PLUGIN_TEMPLATES.join("|")})`);
2418
+ const parentDir = opts.dir ? resolve(opts.dir) : join(pluginDataDir(opts), "plugins");
2419
+ const target = join(parentDir, id);
2420
+ if (existsSync(target) && opts.force !== true) fail(`目标已存在: ${target}(加 --force 覆盖)`);
2421
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true });
2422
+ mkdirSync(join(target, "client"), { recursive: true });
2423
+ const sdkSrc = pluginSdkSource();
2424
+ const useSdk = Boolean(sdkSrc);
2425
+ if (useSdk) {
2426
+ mkdirSync(join(target, "sdk"), { recursive: true });
2427
+ copyFileSync(sdkSrc, join(target, "sdk", "index.mjs"));
2428
+ }
2429
+ const wantTest = opts.withTest === true;
2430
+ const files = buildPluginScaffold(id, template, useSdk, wantTest && useSdk);
2431
+ for (const [rel, content] of Object.entries(files)) writeFileSync(join(target, rel), content);
2432
+ // 生成后校验:manifest 基础必填 + 生成文件的 node 语法检查。
2433
+ let manifest;
2434
+ try {
2435
+ manifest = JSON.parse(readFileSync(join(target, "manifest.json"), "utf8"));
2436
+ } catch {
2437
+ fail(`生成的 manifest.json 解析失败(请检查磁盘/权限)`);
2438
+ }
2439
+ const warnings = validateScaffoldManifest(manifest, id);
2440
+ if (wantTest && !useSdk)
2441
+ warnings.push(`已加 --with-test 但包内无 plugin-sdk,跳过 index.test.mjs(无 SDK 版没有 createMockHost 可用)`);
2442
+ const checkFiles = ["index.mjs", "client/entry.mjs"];
2443
+ if (wantTest && useSdk) checkFiles.push("index.test.mjs");
2444
+ for (const rel of checkFiles) {
2445
+ const r = spawnSync(NODE, ["--check", join(target, rel)], { stdio: "ignore" });
2446
+ if (r.status !== 0) warnings.push(`${rel} 未通过 node --check(请检查生成文件)`);
2447
+ }
2448
+ console.log(`✔ 已生成插件骨架 ${id}(模板 ${template})`);
2449
+ console.log(` 位置: ${target}`);
2450
+ if (wantTest && useSdk)
2451
+ console.log(` 单测: node --test ${join(target, "index.test.mjs")}(createMockHost harness)`);
2452
+ if (!useSdk) console.log(`⚠ 未找到包内 plugin-sdk,已生成无 SDK 依赖版本(逻辑等价,详见 plugin-sdk/README.md)`);
2453
+ for (const w of warnings) console.log(`⚠ ${w}`);
2454
+ console.log(` 生效: 服务运行中刷新浏览器即可加载(或发 plugins_reload);未运行则下次启动生效。`);
2455
+ console.log(` 下一步: 打开 ${join(target, "README.md")}(改名 → 写逻辑 → 刷新验证)`);
2456
+ }
2457
+
2003
2458
  async function pluginInstallCmd(argv) {
2004
2459
  const { opts, positionals } = parseFlags(argv);
2005
2460
  if (opts.help) {
@@ -2236,6 +2691,14 @@ async function main() {
2236
2691
  return;
2237
2692
  }
2238
2693
  if (first === "plugins" || first === "plugin") {
2694
+ if (argv[1] === "upgrade-sdk") {
2695
+ pluginUpgradeSdkCmd(argv.slice(2));
2696
+ return;
2697
+ }
2698
+ if (argv[1] === "create") {
2699
+ pluginCreateCmd(argv.slice(2));
2700
+ return;
2701
+ }
2239
2702
  pluginListCmd(argv.slice(1));
2240
2703
  return;
2241
2704
  }