pi-web-ui 0.87.2 → 0.88.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.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,29 @@
8
8
  每个版本的内容按"实际合入该版本发布的提交"归档(以 `package.json` 的 version 变更提交为准),
9
9
  而不是按提交日期聚类——连续快速发布的 patch 版本以此为准最准确。
10
10
 
11
+ ## [Unreleased]
12
+
13
+ ## [0.88.0] — 2026-09-16
14
+
15
+ ### Added
16
+
17
+ - **底栏主机资源指标**(#174)—— 底栏实时显示主机处理器与内存使用率,悬浮看明细;`bottombar` 对齐方式改为数据驱动,随布局偏好走。
18
+ - **布局槽位全量接线** —— `chat.header` / `chat.empty` / `file.preview.toolbar` 接上渲染(无贡献时 DOM 与原来一致);设置布局页从 9 槽补到 21 槽,新增搜索过滤、align 对齐、改名、`uiLayoutMovedFrom` 移自显示。
19
+ - **输入框新增前置槽位 `composer.leading`** —— 第三方插件终于可以把图标放到文件上传按钮左侧了(以前 `composer.actions` 只能排在上传右侧)。写法与其它槽位一致(`"ui": { "composer.leading": [...] }`,必须写完整名、没有简写别名),排序/隐藏/布局页偏好全套生效。
20
+ - **插件宿主能力扩展 + `plugin-sdk` 起手包** —— 新增 `host.llm`(模型调用)、`host.schedule`(定时任务)、`host.permissions`(权限声明)、`composerProviders`(输入框内容源);`plugin-sdk/` 开箱即用的类型 + 运行时 + README,可直接抄起手。
21
+ - **插件诊断输出 + `create` 脚手架 + `host.log` 日志面板** —— manifest / UI 贡献被丢弃时给出原因(设置面板可展开查看,不再是静默消失);`plugin create` 一键搭架子(minimal / ui-slot / agent-tool / renderer 四模板,`--with-test` 附带单测);运行时日志分级落盘(内存环形缓冲 + 面板级别过滤/清空);另附 `createMockHost` 本地单测 harness + `plugin upgrade-sdk`。
22
+
23
+ ### Changed
24
+
25
+ - `slot-toolbar` 抽成独立模块,`TerminalPanel` 恢复 lazy / xterm 拆包(首屏包体积回落)。
26
+
27
+ <!-- auto-i18n:start -->
28
+ ### i18n
29
+
30
+ - 前端新增 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`
31
+ - 服务端新增 key(1):`plugins.settings.too.long`
32
+ <!-- auto-i18n:end -->
33
+
11
34
  ## [0.87.2] — 2026-09-16
12
35
 
13
36
  ### Fixed
@@ -920,7 +943,8 @@ when?, children?}`,也收 `topbar` / `settings` 这类简写别名);宿主
920
943
  - 0.35.1(2026-08-27):编辑重问保留附件(#18)+ 全窗口拖放(#19)。
921
944
  - 0.29.0(2026-08-23):全局搜索弹窗(Ctrl+K)+ 消息列表惰性窗口化。
922
945
 
923
- [Unreleased]: https://github.com/xing-shuyin/pi-web-ui/compare/v0.87.1...main
946
+ [Unreleased]: https://github.com/xing-shuyin/pi-web-ui/compare/v0.88.0...main
947
+ [0.88.0]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.88.0
924
948
  [0.87.2]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.87.2
925
949
  [0.87.1]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.87.1
926
950
  [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
  }
@@ -2228,6 +2228,40 @@ export class ClientSession {
2228
2228
  return { ok: false, error: err.message };
2229
2229
  }
2230
2230
  }
2231
+ /** 插件扩展点(供 llmProvider):孤立补全的环境(cwd/agentDir/回落模型)。
2232
+ * 取最近活跃的主对话(跳过子代理);model 读不到就只给 cwd(调用方再回落默认模型)。
2233
+ * 纯数据组装,不 emit、不改状态。 */
2234
+ llmEnvForPlugins() {
2235
+ let target = null;
2236
+ try {
2237
+ for (const c of this.convs.values()) {
2238
+ if (c.isSubagent)
2239
+ continue;
2240
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2241
+ target = c;
2242
+ }
2243
+ if (!target) {
2244
+ for (const c of this.convs.values()) {
2245
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2246
+ target = c;
2247
+ }
2248
+ }
2249
+ }
2250
+ catch {
2251
+ target = null;
2252
+ }
2253
+ const cwd = target?.cwd ?? this.cwd;
2254
+ let fallbackModel;
2255
+ try {
2256
+ const m = target?.session?.model;
2257
+ if (m?.provider && m.id)
2258
+ fallbackModel = { provider: m.provider, id: m.id };
2259
+ }
2260
+ catch {
2261
+ /* model 读不到就回落默认 */
2262
+ }
2263
+ return { cwd, agentDir: this.agentDir, ...(fallbackModel ? { fallbackModel } : {}) };
2264
+ }
2231
2265
  /** 插件扩展点 v2(供 modelLister):复用 listModels 的模型列表映射 {id,provider,vision}。
2232
2266
  * 与 listModels 唯一差别:不做网络 refresh(插件列表走缓存目录,15s 超时也不等),只读不 emit。 */
2233
2267
  async listModelsForPlugins() {
@@ -6418,6 +6452,33 @@ export class AgentService {
6418
6452
  void cs.prompt(text);
6419
6453
  return { conversationId: before, clientId };
6420
6454
  }
6455
+ /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
6456
+ * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
6457
+ * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
6458
+ async completeForPlugins(pluginId, req) {
6459
+ try {
6460
+ if (this.quiesced)
6461
+ return { ok: false, error: "插件 LLM 调用被拒绝,请等服务器恢复后重试" };
6462
+ let env;
6463
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
6464
+ try {
6465
+ const cs = this.pluginClient();
6466
+ env = cs?.llmEnvForPlugins() ?? { cwd: this.cwd, agentDir };
6467
+ }
6468
+ catch {
6469
+ env = { cwd: this.cwd, agentDir };
6470
+ }
6471
+ const mod = await import("./plugin-llm.js");
6472
+ const r = await mod.completeWithIsolatedSession(env, { ...req, prompt: String(req?.prompt ?? "") });
6473
+ if (!r.ok)
6474
+ return r;
6475
+ console.log(`[plugin:${pluginId}] llm.complete ok(模型 ${r.model},输出 ${r.text.length} 字)`);
6476
+ return r;
6477
+ }
6478
+ catch (err) {
6479
+ return { ok: false, error: err.message };
6480
+ }
6481
+ }
6421
6482
  /** index.ts calls this when a browser socket opens/closes. */
6422
6483
  noteSocketOpen() {
6423
6484
  this.socketCount += 1;