pi-web-ui 0.109.0 → 0.111.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 (96) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +21 -1
  3. package/README.zh-CN.md +21 -1
  4. package/README.zh-TW.md +201 -677
  5. package/bin/frp-manager.mjs +85 -7
  6. package/dist/server/agent-formatters.js +10 -6
  7. package/dist/server/agent-service-daemon.js +29 -11
  8. package/dist/server/agent-service.js +160 -54
  9. package/dist/server/attachments.js +140 -37
  10. package/dist/server/canvas/canvas-agent-tool.js +587 -0
  11. package/dist/server/canvas/canvas-cards.js +144 -0
  12. package/dist/server/canvas/canvas-dispatch.js +155 -0
  13. package/dist/server/canvas/canvas-orchestrator.js +1027 -0
  14. package/dist/server/canvas/canvas-store.js +260 -0
  15. package/dist/server/client-id-utils.js +2 -2
  16. package/dist/server/client-state.js +24 -0
  17. package/dist/server/context-budget.js +6 -3
  18. package/dist/server/dispatch-domain-handlers.js +2 -0
  19. package/dist/server/dispatch-plugin-handlers.js +1 -0
  20. package/dist/server/dsh/dsh-agent-service.js +115 -9
  21. package/dist/server/dsh/dsh-client.js +10 -1
  22. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  23. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  24. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  25. package/dist/server/durable/durable-agent-service.js +3 -0
  26. package/dist/server/durable/durable-driver.js +1 -1
  27. package/dist/server/durable/durable-tools.js +4 -1
  28. package/dist/server/file-transfer-routes.js +8 -2
  29. package/dist/server/files-service.js +33 -6
  30. package/dist/server/goal-service.js +12 -3
  31. package/dist/server/index.js +175 -13
  32. package/dist/server/locales.js +33 -0
  33. package/dist/server/marker-service.js +10 -14
  34. package/dist/server/markers/builtins/action.js +5 -6
  35. package/dist/server/markers/builtins/notify.js +2 -2
  36. package/dist/server/markers/builtins/rename.js +2 -2
  37. package/dist/server/markers/marker.js +45 -4
  38. package/dist/server/markers/registry.js +36 -1
  39. package/dist/server/message-window.js +193 -0
  40. package/dist/server/model-admin.js +0 -4
  41. package/dist/server/office-parse.js +394 -7
  42. package/dist/server/plugin-api-catalog.js +6 -0
  43. package/dist/server/plugin-catalog-sync.js +10 -2
  44. package/dist/server/plugin-catalog.js +63 -10
  45. package/dist/server/plugins.js +144 -26
  46. package/dist/server/preset-fields.js +35 -1
  47. package/dist/server/preset-share.js +5 -3
  48. package/dist/server/process-utils.js +58 -24
  49. package/dist/server/prompt-assembler.js +7 -1
  50. package/dist/server/prompt-composer.js +66 -36
  51. package/dist/server/protocol-version.js +1 -1
  52. package/dist/server/remote-ssh-service.js +16 -4
  53. package/dist/server/settings-service.js +24 -3
  54. package/dist/server/slash-commands.js +16 -4
  55. package/dist/server/text-sniff.js +10 -7
  56. package/dist/server/themes.js +36 -1
  57. package/dist/server/tool-manager.js +30 -0
  58. package/dist/server/univer-service.js +448 -0
  59. package/dist/server/universal/drivers/claude-code.js +19 -2
  60. package/dist/server/universal/drivers/dsh-driver.js +1 -1
  61. package/dist/server/universal/universal-attachments.js +5 -0
  62. package/dist/server/universal/universal-service.js +5 -0
  63. package/dist/server/universal/universal-session.js +38 -15
  64. package/dist/server/update-check.js +90 -5
  65. package/dist/server/workspace-snapshot.js +33 -2
  66. package/dist/server/worktree-service.js +1 -1
  67. package/docs/dsh-engine.md +497 -0
  68. package/package.json +11 -5
  69. package/plugin-sdk/index.d.ts +37 -0
  70. package/plugin-sdk/index.mjs +19 -0
  71. package/plugins/catalog.json +44 -2
  72. package/themes/aetheris.css +263 -118
  73. package/themes/bases/flow-base.css +1363 -0
  74. package/themes/bases/obsidian-base.css +895 -0
  75. package/themes/bases/zhujian-base.css +687 -0
  76. package/themes/bases/zhupi-base.css +659 -0
  77. package/themes/flow-light.css +2 -925
  78. package/themes/flow.css +1 -936
  79. package/themes/md-preview.css +113 -0
  80. package/themes/wallpaper-flow.css +251 -1029
  81. package/themes/wallpaper-obsidian.css +1 -673
  82. package/themes/zhujian-dark.css +1 -605
  83. package/themes/zhujian.css +1 -654
  84. package/themes/zhupi-dark.css +1 -576
  85. package/themes/zhupi.css +1 -626
  86. package/web/dist/assets/{TerminalPanel-BD3a9o-a.js → TerminalPanel-BiUNySMA.js} +2 -2
  87. package/web/dist/assets/index-B0ajS__T.js +697 -0
  88. package/web/dist/assets/index-BHik5WGG.css +1 -0
  89. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  90. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  91. package/web/dist/index.html +4 -4
  92. package/web/dist/sw.js +1 -1
  93. package/web/dist/assets/es-DIDZppIF.js +0 -2
  94. package/web/dist/assets/index-AccytlpP.css +0 -1
  95. package/web/dist/assets/index-B3dar1BK.js +0 -690
  96. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -1,25 +1,8 @@
1
- /**
2
- * pi-web-ui 插件管理器 —— 可选界面组件的加载与桥接。
3
- *
4
- * 一个插件 = <dataDir>/plugins/<id>/ 目录:
5
- * manifest.json 元数据 { id?, name, version?, description? }(id 缺省取目录名)
6
- * index.mjs 服务端入口(可选):export default { activate(host) → deactivate? }
7
- * client/ 前端资源(可选),经 /plugins/<id>/client/* 以静态文件暴露;
8
- * entry.mjs 视图入口:export default { mount(el, ctx) → cleanup? }
9
- *
10
- * 设计要点:
11
- * - 不装即不存在:目录不在就没有任何协议/UI 痕迹;每次客户端 attach 时重扫目录,
12
- * 新丢进来的插件无需重启服务即可出现在顶栏(import 只做一次并缓存)。
13
- * - id 必须匹配 ID_RE,防路径穿越;client 静态服务同样逐段校验。
14
- * - host 窄接口:broadcast(pluginId, payload) 广播 plugin_data、onMessage 注册
15
- * 客户端上行处理、dataDir/cwd/log 环境。发送通道由 index.ts 注入(每个 socket
16
- * 的 send 函数),插件本身不接触 ws。
17
- * - activate 抛错只标记 error 字段并记日志,绝不影响主进程。
18
- */
1
+ import { registerMarker, unregisterMarker, isBuiltinMarker } from "./markers/index.js";
19
2
  import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
20
- import { cpSync, existsSync, readFileSync, readdirSync, renameSync, watch as fsWatch, writeFileSync } from "node:fs";
3
+ import { cpSync, existsSync, lstatSync, readFileSync, readdirSync, renameSync, watch as fsWatch, writeFileSync, } from "node:fs";
21
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
22
- import { pathToFileURL, fileURLToPath } from "node:url";
5
+ import { pathToFileURL } from "node:url";
23
6
  import {} from "./protocol.js";
24
7
  import { UI_SLOTS } from "./plugin-ui-slots.js";
25
8
  import { LeftPanelRunningStore } from "./left-panel-running.js";
@@ -996,6 +979,10 @@ export class PluginManager {
996
979
  pluginBgTasks = new Map();
997
980
  /** 任务集合变化回调(index.ts 接到 AgentService,重推 bg_servers)。 */
998
981
  onBgTasksChanged = undefined;
982
+ /** 插件注册的内联标记:pluginId → (name → 定义)。 */
983
+ pluginMarkers = new Map();
984
+ /** 标记工具集合变化回调(index.ts 接到 AgentService,刷新各客户端 markers)。 */
985
+ onMarkersChanged = undefined;
999
986
  /** P3:左栏插件运行条目(见 left-panel-running.ts)。 */
1000
987
  panelRunning = new LeftPanelRunningStore();
1001
988
  panelPushTimer = null;
@@ -1174,9 +1161,15 @@ export class PluginManager {
1174
1161
  get customCatalogPath() {
1175
1162
  return join(this.dataDir, "plugin-catalog.json");
1176
1163
  }
1177
- /** 合并后的插件市场列表(builtin + 用户自定义,同 id 用户覆盖)。 */
1164
+ /** 官方社区生态插件清单文件(<dataDir>/community-catalog.json)。 */
1165
+ get communityCatalogPath() {
1166
+ return join(this.dataDir, "community-catalog.json");
1167
+ }
1168
+ /** 合并后的插件市场列表(builtin + community + 用户自定义,同 id 用户覆盖)。 */
1178
1169
  catalog() {
1179
- return this.builtinCatalogPath ? readCatalog(this.builtinCatalogPath, this.customCatalogPath) : [];
1170
+ return this.builtinCatalogPath
1171
+ ? readCatalog(this.builtinCatalogPath, this.customCatalogPath, this.communityCatalogPath)
1172
+ : [];
1180
1173
  }
1181
1174
  /** 插件市场列表纪元(随 plugin_catalog 消息下发)。 */
1182
1175
  get catalogEpochValue() {
@@ -1203,14 +1196,14 @@ export class PluginManager {
1203
1196
  return { error: err.message };
1204
1197
  }
1205
1198
  }
1206
- /** 移除一条用户自定义条目(builtin 不可经此删除);返回错误信息或 null。 */
1199
+ /** 移除一条用户自定义条目(builtin / 社区条目不可经此删除);返回错误信息或 null。 */
1207
1200
  removeCatalogEntry(id, lang) {
1208
1201
  const l = lang?.() ?? "en";
1209
1202
  try {
1210
1203
  const ok = removeCustomEntry(this.customCatalogPath, id);
1211
1204
  if (!ok)
1212
1205
  return {
1213
- error: pick(l, "未找到该条目,或它是内置条目(不可移除)", "Entry not found, or it is a built-in entry (cannot be removed)", "plugins.catalog.entry.cannot.remove"),
1206
+ error: pick(l, "未找到该条目,或它是内置/社区条目(不可移除)", "Entry not found, or it is a built-in/community entry (cannot be removed)", "plugins.catalog.entry.cannot.remove"),
1214
1207
  };
1215
1208
  this.catalogEpoch += 1;
1216
1209
  void this.pushCatalog();
@@ -1846,6 +1839,82 @@ export class PluginManager {
1846
1839
  }
1847
1840
  };
1848
1841
  }
1842
+ /** 注册内联标记(Inline Marker):跨插件重名拒绝,系统内置标记冲突拒绝。 */
1843
+ registerMarker(pluginId, marker) {
1844
+ if (!marker || typeof marker !== "object") {
1845
+ console.error(`[plugin:${pluginId}] registerMarker: 缺少 marker 参数,忽略`);
1846
+ this.pushRuntimeDiag(pluginId, "registerMarker: missing marker parameter, ignored");
1847
+ return () => { };
1848
+ }
1849
+ const name = String(marker.name ?? "").trim();
1850
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(name)) {
1851
+ console.error(`[plugin:${pluginId}] registerMarker: 非法名称「${marker.name}」(需英文字母开头,只允许字母数字_-),忽略`);
1852
+ this.pushRuntimeDiag(pluginId, `registerMarker: invalid name "${String(marker.name ?? "").slice(0, 32)}", ignored`);
1853
+ return () => { };
1854
+ }
1855
+ if (isBuiltinMarker(name)) {
1856
+ console.error(`[plugin:${pluginId}] registerMarker: 名称「${name}」为系统内置标记保留名称,忽略冲突注册`);
1857
+ this.pushRuntimeDiag(pluginId, `registerMarker: "${name}" conflicts with built-in marker, ignored`);
1858
+ return () => { };
1859
+ }
1860
+ if (typeof marker.apply !== "function") {
1861
+ console.error(`[plugin:${pluginId}] registerMarker: ${name} 缺少 apply 函数,忽略`);
1862
+ this.pushRuntimeDiag(pluginId, `marker "${name}": missing apply function, ignored`);
1863
+ return () => { };
1864
+ }
1865
+ if (!Array.isArray(marker.guidance) || marker.guidance.length === 0) {
1866
+ console.error(`[plugin:${pluginId}] registerMarker: ${name} 缺少 guidance 引导说明,忽略`);
1867
+ this.pushRuntimeDiag(pluginId, `marker "${name}": missing guidance, ignored`);
1868
+ return () => { };
1869
+ }
1870
+ for (const [pid, other] of this.pluginMarkers) {
1871
+ if (pid !== pluginId && other.has(name)) {
1872
+ console.error(`[plugin:${pluginId}] 标记 "${name}" 已被插件 ${pid} 注册,忽略重复`);
1873
+ this.pushRuntimeDiag(pluginId, `marker "${name}": already registered by plugin ${pid}, ignored`);
1874
+ return () => { };
1875
+ }
1876
+ }
1877
+ let table = this.pluginMarkers.get(pluginId);
1878
+ if (!table)
1879
+ this.pluginMarkers.set(pluginId, (table = new Map()));
1880
+ if (table.has(name)) {
1881
+ console.error(`[plugin:${pluginId}] 标记 "${name}" 重复注册,忽略`);
1882
+ this.pushRuntimeDiag(pluginId, `marker "${name}": duplicate registration, ignored`);
1883
+ return () => { };
1884
+ }
1885
+ const markerTool = {
1886
+ name,
1887
+ label: marker.label ? String(marker.label).slice(0, 80) : undefined,
1888
+ pluginId,
1889
+ guidance: [...marker.guidance],
1890
+ getGuidance: marker.getGuidance,
1891
+ apply: marker.apply,
1892
+ overlay: marker.overlay,
1893
+ init: marker.init,
1894
+ };
1895
+ table.set(name, markerTool);
1896
+ registerMarker(markerTool);
1897
+ console.log(`[plugin:${pluginId}] registered inline marker: ${name}`);
1898
+ try {
1899
+ this.onMarkersChanged?.();
1900
+ }
1901
+ catch (err) {
1902
+ console.error("[plugins] onMarkersChanged failed:", err);
1903
+ }
1904
+ return () => {
1905
+ if (table.delete(name)) {
1906
+ if (table.size === 0)
1907
+ this.pluginMarkers.delete(pluginId);
1908
+ unregisterMarker(name);
1909
+ try {
1910
+ this.onMarkersChanged?.();
1911
+ }
1912
+ catch {
1913
+ /* shutting down */
1914
+ }
1915
+ }
1916
+ };
1917
+ }
1849
1918
  /** 注册斜杠命令:跨插件重名拒绝(先注册者胜出),onCommandsChanged 通知目录刷新。 */
1850
1919
  registerCommand(pluginId, cmd) {
1851
1920
  const name = String(cmd?.name ?? "").replace(/^\/+/, ""); // 容忍误带的前导 /
@@ -2188,6 +2257,20 @@ export class PluginManager {
2188
2257
  if (pluginIds.has(this.proxyRoutes.get(prefix).pluginId))
2189
2258
  this.proxyRoutes.delete(prefix);
2190
2259
  }
2260
+ if (this.panelPushTimer) {
2261
+ clearTimeout(this.panelPushTimer);
2262
+ this.panelPushTimer = null;
2263
+ }
2264
+ if (this.panelSweepTimer) {
2265
+ clearInterval(this.panelSweepTimer);
2266
+ this.panelSweepTimer = null;
2267
+ }
2268
+ this.agentTools.clear();
2269
+ this.pluginMarkers.clear();
2270
+ this.pluginCommands.clear();
2271
+ this.uiRuntime.clear();
2272
+ this.uiBase.clear();
2273
+ this.proxyRoutes.clear();
2191
2274
  this.pluginBgTasks.clear();
2192
2275
  this.loaded.clear();
2193
2276
  this.messageHandlers.clear();
@@ -2227,6 +2310,15 @@ export class PluginManager {
2227
2310
  continue;
2228
2311
  const targetDir = join(this.pluginsDir, name);
2229
2312
  const sourceDir = join(builtinDir, name);
2313
+ try {
2314
+ if (lstatSync(targetDir).isSymbolicLink()) {
2315
+ // 处于源码开发软链接模式(如 npm run plugins:link),直接使用源码,跳过随包文件覆盖
2316
+ continue;
2317
+ }
2318
+ }
2319
+ catch {
2320
+ /* lstat 失败走普通流程 */
2321
+ }
2230
2322
  const targetManifest = join(targetDir, "manifest.json");
2231
2323
  const sourceManifest = join(sourceDir, "manifest.json");
2232
2324
  if (!existsSync(sourceDir) || !existsSync(sourceManifest) || !existsSync(targetManifest)) {
@@ -2268,8 +2360,15 @@ export class PluginManager {
2268
2360
  continue;
2269
2361
  const dir = join(this.pluginsDir, name);
2270
2362
  try {
2271
- if (!(await stat(dir)).isDirectory())
2363
+ const st = await stat(dir);
2364
+ if (!st.isDirectory())
2272
2365
  continue;
2366
+ }
2367
+ catch {
2368
+ // 目录不存在(如失效的软链接)或非目录/不可访问,跳过
2369
+ continue;
2370
+ }
2371
+ try {
2273
2372
  const raw = await readFile(join(dir, "manifest.json"), "utf8");
2274
2373
  // wantsDom 快照供静态门禁用(manifest 坏了 → JSON.parse 抛 → catch 跳过,旧快照残留无害:门禁只拦「快照里要且没授权」的)。
2275
2374
  const m = JSON.parse(raw);
@@ -3182,6 +3281,19 @@ export class PluginManager {
3182
3281
  const off = this.registerCommand(info.id, cmd);
3183
3282
  return effects.add(`command:/${String(cmd?.name ?? "?").replace(/^\/+/, "")}`, off);
3184
3283
  },
3284
+ execCommand: async (name, args, context) => {
3285
+ const hit = this.findCommand(name);
3286
+ if (!hit)
3287
+ return { ok: false, error: `未找到命令 /${name}` };
3288
+ try {
3289
+ const res = await hit.def.run(args, context ?? { clientId: `plugin:${info.id}` });
3290
+ return { ok: true, result: typeof res === "string" ? res : "" };
3291
+ }
3292
+ catch (err) {
3293
+ return { ok: false, error: err.message };
3294
+ }
3295
+ },
3296
+ getPluginCommands: () => this.listCommands(),
3185
3297
  storage,
3186
3298
  secrets,
3187
3299
  ensureDeps: (specs, opts) => ensurePluginDeps(dir, specs ?? [], opts?.onProgress),
@@ -3189,7 +3301,7 @@ export class PluginManager {
3189
3301
  if (!can("http"))
3190
3302
  return () => { };
3191
3303
  const m = String(method ?? "GET").toUpperCase();
3192
- if (!["GET", "POST", "PUT", "DELETE"].includes(m) ||
3304
+ if (!["GET", "POST", "PUT", "DELETE", "OPTIONS"].includes(m) ||
3193
3305
  typeof path !== "string" ||
3194
3306
  !path.startsWith("/") ||
3195
3307
  typeof handler !== "function") {
@@ -3221,6 +3333,12 @@ export class PluginManager {
3221
3333
  const off = this.registerAgentTool(info.id, tool);
3222
3334
  return effects.add(`agentTool:${String(tool?.name ?? "?")}`, off);
3223
3335
  },
3336
+ registerMarker: (marker) => {
3337
+ if (!can("tools"))
3338
+ return () => { };
3339
+ const off = this.registerMarker(info.id, marker);
3340
+ return effects.add(`marker:${String(marker?.name ?? "?")}`, off);
3341
+ },
3224
3342
  registerTool: (tool) => {
3225
3343
  if (!can("tools"))
3226
3344
  return () => { };
@@ -51,7 +51,14 @@ export const PRESET_FIELD_GROUPS = {
51
51
  // 终端接管
52
52
  terminal: ["terminalBash", "terminalBashIdleMs", "terminalBashMaxForegroundMs"],
53
53
  // 技能与扩展
54
- skills: ["disabledSkills", "disabledExtensions", "skillsFullText"],
54
+ skills: [
55
+ "disabledSkills",
56
+ "disabledExtensions",
57
+ "skillsFullText",
58
+ "skillsCatalogMaxDesc",
59
+ "skillsCatalogShowLocation",
60
+ "skillsCatalogBudget",
61
+ ],
55
62
  // 模型侧行为与各专用提示词
56
63
  ai: [
57
64
  "retryMaxAttempts",
@@ -283,6 +290,24 @@ export const PRESET_FIELD_META = {
283
290
  hintZh: "将指定技能的完整正文直接注入上下文,跳过 skill 工具按需载入",
284
291
  hintEn: "Inject full text of selected skills directly into context",
285
292
  },
293
+ skillsCatalogMaxDesc: {
294
+ labelZh: "技能描述截断字符数",
295
+ labelEn: "Skill Description Cap",
296
+ hintZh: "名录中单条技能描述最大字符数(默认 250,0 为不截断)",
297
+ hintEn: "Max characters per skill description in catalog (default 250, 0 to disable)",
298
+ },
299
+ skillsCatalogShowLocation: {
300
+ labelZh: "名录显示物理路径",
301
+ labelEn: "Show Skill Location",
302
+ hintZh: "是否在技能名录中输出 location 文件绝对路径(默认关,避免浪费 token 和泄露路径)",
303
+ hintEn: "Whether to output file path in skill catalog (default off to save tokens and prevent path leak)",
304
+ },
305
+ skillsCatalogBudget: {
306
+ labelZh: "技能名录总字符预算",
307
+ labelEn: "Skill Catalog Budget",
308
+ hintZh: "技能名录字符上限(默认 20000),超限自动降级为紧凑名称索引",
309
+ hintEn: "Total catalog character limit (default 20000), falls back to compact name index when exceeded",
310
+ },
286
311
  // ai
287
312
  retryMaxAttempts: {
288
313
  labelZh: "网络重试上限",
@@ -602,6 +627,15 @@ export function formatPresetFieldValue(field, value, lang = "zh") {
602
627
  detail: list.map((item) => `- ${item}`).join("\n"),
603
628
  };
604
629
  }
630
+ if (field === "skillsCatalogMaxDesc" || field === "skillsCatalogBudget") {
631
+ const n = Number(value);
632
+ const zeroText = isZh ? "不限" : "No limit";
633
+ const valText = n === 0 ? zeroText : isZh ? `${n} 字符` : `${n} chars`;
634
+ return { summary: valText };
635
+ }
636
+ if (field === "skillsCatalogShowLocation") {
637
+ return { summary: value ? (isZh ? "开启" : "Enabled") : isZh ? "关闭" : "Disabled" };
638
+ }
605
639
  // 6. 提示词文本
606
640
  if (field === "customSystemPrompt" ||
607
641
  field === "promptTemplate" ||
@@ -21,10 +21,9 @@
21
21
  * 与副作用(createPresetIssue / fetchPresetCatalog)分开,便于单测。
22
22
  */
23
23
  import { execFile } from "node:child_process";
24
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
24
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
25
25
  import { tmpdir } from "node:os";
26
- import { dirname, join } from "node:path";
27
- import { fileURLToPath } from "node:url";
26
+ import { join } from "node:path";
28
27
  import { promisify } from "node:util";
29
28
  import { getAppVersion } from "./pkg-info.js";
30
29
  import { normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeSkillList, normalizeUiLayout, } from "./client-state.js";
@@ -251,6 +250,9 @@ const PRESET_FIELD_KINDS = {
251
250
  disabledSkills: "list",
252
251
  disabledExtensions: "list",
253
252
  skillsFullText: "list",
253
+ skillsCatalogMaxDesc: "number",
254
+ skillsCatalogShowLocation: "bool",
255
+ skillsCatalogBudget: "number",
254
256
  // -- ai --------------------------------------------------------------
255
257
  retryMaxAttempts: "retry",
256
258
  softCapTokens: "softCap",
@@ -4,6 +4,61 @@ import { resolve } from "node:path";
4
4
  * 后台任务面板(bgServers)用它们检测/停止 agent 在后台拉起的服务。
5
5
  * 从 agent-service.ts 抽出,行为保持不变。全平台 best-effort:失败静默。
6
6
  */
7
+ /**
8
+ * 解析 Windows `netstat -ano -p tcp` 输出 → 端口→pid。纯函数,单测覆盖。
9
+ * 行形状:`TCP 0.0.0.0:5173 0.0.0.0:0 LISTENING 12345`。
10
+ */
11
+ export function parseNetstatListening(stdout) {
12
+ const m = new Map();
13
+ for (const line of stdout.split(/\r?\n/)) {
14
+ const p = line.trim().split(/\s+/);
15
+ if (p.length >= 5 && p[0] === "TCP" && p[3] === "LISTENING") {
16
+ // 本地地址可能是 0.0.0.0:5173 / [::1]:5173 —— 取最后一段就是端口。
17
+ const port = Number(p[1].split(":").pop());
18
+ const pid = Number(p[4]);
19
+ if (Number.isFinite(port) && Number.isFinite(pid))
20
+ m.set(port, pid);
21
+ }
22
+ }
23
+ return m;
24
+ }
25
+ /**
26
+ * 解析 POSIX `lsof -iTCP -sTCP:LISTEN -P -n` 输出 → 端口→pid。纯函数,单测覆盖。
27
+ *
28
+ * NAME 列形如 `*:5173` / `127.0.0.1:5173` / `[::1]:5173`。监听态 `(LISTEN)`
29
+ * 在不同发行版上**要么贴在 NAME 里、要么自成最后一列**,所以“取最后一列”的
30
+ * 写法(旧实现)在后者上拿到的是 `(LISTEN)` 而不是地址 —— 整条 posix 端口探测
31
+ * 静默失效(后台任务面板就看不到 AI 拉起的服务)。这里改成扫列:第一个
32
+ * “以冒号+数字收尾”的列就是地址(FD/TYPE/DEVICE/SIZE-OFF/NODE 都不带这种形状)。
33
+ */
34
+ export function parseLsofListening(stdout) {
35
+ const m = new Map();
36
+ for (const line of stdout.split(/\r?\n/)) {
37
+ const p = line.trim().split(/\s+/);
38
+ if (p.length < 5)
39
+ continue;
40
+ const pid = Number(p[1]);
41
+ if (!Number.isFinite(pid) || pid <= 0)
42
+ continue; // 表头 / 脏行
43
+ const port = findListenPort(p.slice(3));
44
+ if (port === null)
45
+ continue;
46
+ m.set(port, pid);
47
+ }
48
+ return m;
49
+ }
50
+ /** 从 lsof 行尾列里找出监听端口(第一个 `:数字` 收尾的列)。 */
51
+ function findListenPort(cols) {
52
+ for (const col of cols) {
53
+ const mm = col.match(/:(\d{1,5})$/);
54
+ if (!mm)
55
+ continue;
56
+ const port = Number(mm[1]);
57
+ if (port > 0 && port <= 65535)
58
+ return port;
59
+ }
60
+ return null;
61
+ }
7
62
  /**
8
63
  * Snapshot currently LISTENING TCP ports → owning pid. Windows: netstat;
9
64
  * POSIX: lsof. Used to detect servers the agent started in the background
@@ -15,31 +70,10 @@ export async function snapshotListeningPorts() {
15
70
  const { execFile } = await import("node:child_process");
16
71
  if (process.platform === "win32") {
17
72
  const out = await new Promise((resolve, reject) => execFile("netstat", ["-ano", "-p", "tcp"], { windowsHide: true, timeout: 8000 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
18
- for (const line of out.split(/\r?\n/)) {
19
- const p = line.trim().split(/\s+/);
20
- // TCP 0.0.0.0:5173 0.0.0.0:0 LISTENING 12345
21
- if (p.length >= 5 && p[0] === "TCP" && p[3] === "LISTENING") {
22
- const port = Number(p[1].split(":").pop());
23
- const pid = Number(p[4]);
24
- if (Number.isFinite(port) && Number.isFinite(pid))
25
- m.set(port, pid);
26
- }
27
- }
28
- }
29
- else {
30
- const out = await new Promise((resolve, reject) => execFile("lsof", ["-iTCP", "-sTCP:LISTEN", "-P", "-n"], { timeout: 8000 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
31
- for (const line of out.split(/\r?\n/).slice(1)) {
32
- const p = line.trim().split(/\s+/);
33
- if (p.length >= 9) {
34
- // NAME column tail: "*:5173 (LISTEN)" or "[::1]:5173 (LISTEN)"
35
- const mm = (p[p.length - 1] ?? "").match(/(\d+)\)?\s*$/);
36
- const port = mm ? Number(mm[1]) : NaN;
37
- const pid = Number(p[1]);
38
- if (Number.isFinite(port) && Number.isFinite(pid))
39
- m.set(port, pid);
40
- }
41
- }
73
+ return parseNetstatListening(out);
42
74
  }
75
+ const out = await new Promise((resolve, reject) => execFile("lsof", ["-iTCP", "-sTCP:LISTEN", "-P", "-n"], { timeout: 8000 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
76
+ return parseLsofListening(out);
43
77
  }
44
78
  catch {
45
79
  // best effort — snapshot failure just means no tracking this round
@@ -64,7 +64,13 @@ export function shouldRenderMainCompose(opts) {
64
64
  const ovs = opts.promptOverrides ?? {};
65
65
  const hasOverride = Object.values(ovs).some((v) => typeof v === "string" && v.trim());
66
66
  const preset = opts.preset ?? "standard";
67
- return !!tpl || hasOverride || preset !== "standard" || opts.disabledToolCount > 0 || opts.isLazy === true;
67
+ return (!!tpl ||
68
+ hasOverride ||
69
+ preset !== "standard" ||
70
+ opts.disabledToolCount > 0 ||
71
+ opts.isLazy === true ||
72
+ opts.hasSkills === true ||
73
+ opts.hasSkillsFullText === true);
68
74
  }
69
75
  /**
70
76
  * 渲染组合模板。非定制状态返回 undefined 让 SDK 内部装配。
@@ -129,46 +129,72 @@ function buildGuidelinesText(inputs) {
129
129
  add(pick(lang, "处理文件时清楚地给出文件路径", "Show file paths clearly when working with files", "prompt.guidelines.show.paths"));
130
130
  return `${pick(lang, "指导原则:", "Guidelines:", "prompt.guidelines.title")}\n${lines.map((l) => `- ${l}`).join("\n")}`;
131
131
  }
132
- function escapeXml(s) {
133
- return s
134
- .replace(/&/g, "&amp;")
135
- .replace(/</g, "&lt;")
136
- .replace(/>/g, "&gt;")
137
- .replace(/"/g, "&quot;")
138
- .replace(/'/g, "&apos;");
139
- }
140
- /** 技能段文本(不含前导空行)。与 SDK formatSkillsForPrompt 一致。
132
+ /** 技能段文本(不含前导空行)。
141
133
  * fullText = true 全员全文注入(oh-my-pi 式:标题 + 引用描述 + body 全文);
142
- * 传技能名数组 = 只注入名单里的;content 缺失的条目回落列表行,不中断渲染。 */
143
- export function buildSkillsText(skills, lang = "en", fullText = false) {
144
- const visible = skills.filter((s) => !s.disableModelInvocation);
134
+ * 传技能名数组 = 只注入名单里的;content 缺失的条目回落列表行,不中断渲染。
135
+ * 默认名录采用紧凑单行格式(- name: desc),抛弃多层 XML 标签通胀与多行冗余,
136
+ * 默认不输出宿主 location 物理路径以节约 token 且避免路径泄露。 */
137
+ export function buildSkillsText(skills, lang = "en", fullText = false, options) {
138
+ const visible = skills
139
+ .filter((s) => !s.disableModelInvocation)
140
+ .slice()
141
+ .sort((a, b) => a.name.localeCompare(b.name));
145
142
  if (visible.length === 0)
146
143
  return "";
147
- const lines = [
148
- pick(lang, "以下技能为特定任务提供专门的指令。", "The following skills provide specialized instructions for specific tasks.", "prompt.skills.intro.specialized"),
149
- pick(lang, "当任务与某技能的描述相符时,用 skill 工具按名称加载该技能全文。", "Use the skill tool to load a skill's full text by name when the task matches its description.", "prompt.skills.intro.use.skill"),
150
- pick(lang, "当技能文件引用相对路径时,以技能目录(SKILL.md 的父目录 / 该路径的 dirname)为基准解析,并在工具命令中使用解析后的绝对路径。", "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.", "prompt.skills.intro.resolve.path"),
151
- "",
152
- "<available_skills>",
153
- ];
154
- for (const skill of visible) {
155
- // 全文模式且有内容:oh-my-pi 注入格式(### Skill: 名 / > 描述 / 全文)。
156
- const inject = fullText === true || (Array.isArray(fullText) && fullText.includes(skill.name));
157
- if (inject && skill.content?.trim()) {
158
- lines.push(`### Skill: ${skill.name}`);
159
- if (skill.description.trim())
160
- lines.push(`> ${skill.description.trim()}`);
161
- lines.push("", skill.content.trim(), "");
162
- continue;
144
+ const maxDesc = options?.maxDesc !== undefined ? options.maxDesc : 250;
145
+ const showLocation = options?.showLocation ?? false;
146
+ const budget = options?.budget !== undefined ? options.budget : 20000;
147
+ // 单行化并截断描述文本
148
+ const formatDesc = (desc) => {
149
+ const singleLine = desc.replace(/[\r\n]+/g, " ").trim();
150
+ if (maxDesc > 0 && singleLine.length > maxDesc) {
151
+ return singleLine.length > 3 ? `${singleLine.slice(0, maxDesc - 3)}...` : singleLine.slice(0, maxDesc);
152
+ }
153
+ return singleLine;
154
+ };
155
+ const renderCatalog = (compact) => {
156
+ const lines = [
157
+ pick(lang, "以下技能为特定任务提供专门的指令。", "The following skills provide specialized instructions for specific tasks.", "prompt.skills.intro.specialized"),
158
+ pick(lang, "当任务与某技能的描述相符时,用 skill 工具按名称加载该技能全文。", "Use the skill tool to load a skill's full text by name when the task matches its description.", "prompt.skills.intro.use.skill"),
159
+ pick(lang, "当技能文件引用相对路径时,以技能目录(SKILL.md 的父目录 / 该路径的 dirname)为基准解析,并在工具命令中使用解析后的绝对路径。", "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.", "prompt.skills.intro.resolve.path"),
160
+ ];
161
+ if (compact) {
162
+ lines.push(pick(lang, "(技能名录庞大已启用紧凑索引,仅显示名称。请使用 skill 工具按名称载入或查询)", "(Skill catalog is large; compact name index enabled. Use the skill tool to inspect or load by name.)", "prompt.skills.catalog.compact"));
163
+ }
164
+ lines.push("", "<available_skills>");
165
+ for (const skill of visible) {
166
+ // 全文模式且有内容:oh-my-pi 注入格式(### Skill: 名 / > 描述 / 全文)。
167
+ const inject = fullText === true || (Array.isArray(fullText) && fullText.includes(skill.name));
168
+ if (inject && skill.content?.trim()) {
169
+ lines.push(`### Skill: ${skill.name}`);
170
+ if (skill.description.trim())
171
+ lines.push(`> ${skill.description.trim()}`);
172
+ lines.push("", skill.content.trim(), "");
173
+ continue;
174
+ }
175
+ if (compact) {
176
+ lines.push(`- ${skill.name}`);
177
+ }
178
+ else {
179
+ const d = formatDesc(skill.description);
180
+ let line = `- ${skill.name}`;
181
+ if (d)
182
+ line += `: ${d}`;
183
+ if (showLocation && skill.filePath) {
184
+ line += ` (location: ${skill.filePath})`;
185
+ }
186
+ lines.push(line);
187
+ }
163
188
  }
164
- lines.push(" <skill>");
165
- lines.push(` <name>${escapeXml(skill.name)}</name>`);
166
- lines.push(` <description>${escapeXml(skill.description)}</description>`);
167
- lines.push(` <location>${escapeXml(skill.filePath)}</location>`);
168
- lines.push(" </skill>");
189
+ lines.push("</available_skills>");
190
+ return lines;
191
+ };
192
+ const standardLines = renderCatalog(false);
193
+ const standardText = standardLines.join("\n");
194
+ if (budget > 0 && standardText.length > budget) {
195
+ return renderCatalog(true).join("\n");
169
196
  }
170
- lines.push("</available_skills>");
171
- return lines.join("\n");
197
+ return standardText;
172
198
  }
173
199
  /** 项目上下文块(不含前导空行)。 */
174
200
  function buildContextText(files, lang = "en") {
@@ -242,7 +268,11 @@ export function resolveSectionTexts(inputs) {
242
268
  terminal: inputs.terminalGuidance,
243
269
  markers: inputs.markersGuidance,
244
270
  context: buildContextText(inputs.contextFiles, lang),
245
- skills: buildSkillsText(inputs.skills, lang, inputs.skillsFullText ?? false),
271
+ skills: buildSkillsText(inputs.skills, lang, inputs.skillsFullText ?? false, {
272
+ maxDesc: inputs.skillsCatalogMaxDesc,
273
+ showLocation: inputs.skillsCatalogShowLocation,
274
+ budget: inputs.skillsCatalogBudget,
275
+ }),
246
276
  cwd: `Current working directory: ${cwd}`,
247
277
  };
248
278
  }
@@ -8,4 +8,4 @@
8
8
  * its own copy in web/src/protocol-version.ts; scripts/check-protocol-sync.mjs
9
9
  * verifies the two never drift.
10
10
  */
11
- export const PROTOCOL_VERSION = 33;
11
+ export const PROTOCOL_VERSION = 36;
@@ -70,7 +70,13 @@ export function formatRemoteWorkspaceUri(username, host, port, remotePath) {
70
70
  */
71
71
  export function resolveRemoteWorkspacePath(remoteRoot, rawPath) {
72
72
  const root = path.posix.normalize(remoteRoot.replace(/\\/g, "/")).replace(/\/+$/, "") || "/";
73
- const cleaned = (rawPath || "").replace(/\\/g, "/").trim();
73
+ let cleaned = (rawPath || "").replace(/\\/g, "/").trim();
74
+ if (isRemoteWorkspaceUri(cleaned)) {
75
+ const parsed = parseRemoteWorkspaceUri(cleaned);
76
+ if (parsed) {
77
+ cleaned = parsed.remotePath;
78
+ }
79
+ }
74
80
  if (!cleaned || cleaned === ".") {
75
81
  return { abs: root, rel: "" };
76
82
  }
@@ -1183,9 +1189,15 @@ fi
1183
1189
  if (typeof sftp.createReadStream === "function") {
1184
1190
  return sftp.createReadStream(remoteAbsPath, opts);
1185
1191
  }
1186
- const { data } = await this.sftpReadFile(uri, remoteAbsPath);
1187
- const slice = opts?.start !== undefined || opts?.end !== undefined
1188
- ? data.subarray(opts?.start ?? 0, opts?.end !== undefined ? opts.end + 1 : undefined)
1192
+ // 回退路径:整文件读进内存再切片。必须设上限——不支持 createReadStream 的
1193
+ // 实现(基本只有测试 mock)遇到 GB 级文件会直接打爆内存(OOM)。
1194
+ const MAX_FALLBACK_BYTES = 512 * 1024 * 1024;
1195
+ const capEnd = opts?.end !== undefined ? Math.min(opts.end, MAX_FALLBACK_BYTES - 1) : MAX_FALLBACK_BYTES - 1;
1196
+ const { data } = await this.sftpReadFile(uri, remoteAbsPath, MAX_FALLBACK_BYTES);
1197
+ const sliceStart = opts?.start ?? 0;
1198
+ const sliceEnd = capEnd;
1199
+ const slice = sliceStart > 0 || sliceEnd < MAX_FALLBACK_BYTES - 1 || data.length === MAX_FALLBACK_BYTES
1200
+ ? data.subarray(sliceStart, sliceEnd + 1)
1189
1201
  : data;
1190
1202
  return Readable.from(slice);
1191
1203
  }