pi-web-ui 0.105.1 → 0.107.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 (95) hide show
  1. package/CHANGELOG.md +84 -2
  2. package/README.md +193 -797
  3. package/README.zh-CN.md +186 -625
  4. package/README.zh-TW.md +781 -0
  5. package/bin/frp-manager.mjs +1488 -0
  6. package/bin/pi-web-ui.mjs +27 -0
  7. package/deploy/nginx-subpath.conf +16 -1
  8. package/dist/server/agent-service-daemon.js +34 -0
  9. package/dist/server/agent-service.js +259 -60
  10. package/dist/server/claim-files-tool.js +8 -1
  11. package/dist/server/client-state.js +136 -30
  12. package/dist/server/conversation-read-tool.js +12 -4
  13. package/dist/server/delegate-task.js +9 -1
  14. package/dist/server/dispatch-domain-handlers.js +15 -0
  15. package/dist/server/dsh/dsh-agent-service.js +848 -246
  16. package/dist/server/dsh/dsh-client.js +59 -18
  17. package/dist/server/dsh/dsh-market-service.js +233 -0
  18. package/dist/server/dsh/dsh-serialize.js +11 -3
  19. package/dist/server/dsh/dsh-sessions.js +64 -2
  20. package/dist/server/dsh/preset-clones.js +12 -1
  21. package/dist/server/dsh/runtime/goal-rpc.mjs +183 -45
  22. package/dist/server/durable/durable-agent-service.js +153 -0
  23. package/dist/server/durable/durable-capabilities.js +11 -0
  24. package/dist/server/durable/durable-driver.js +481 -0
  25. package/dist/server/durable/durable-loader.js +38 -0
  26. package/dist/server/durable/durable-models.js +283 -0
  27. package/dist/server/durable/durable-storage.js +42 -0
  28. package/dist/server/durable/durable-tools.js +45 -0
  29. package/dist/server/durable/index.js +8 -0
  30. package/dist/server/engine-capabilities.js +91 -0
  31. package/dist/server/engine-probe.js +391 -0
  32. package/dist/server/global-loader.js +335 -0
  33. package/dist/server/goal-service.js +23 -12
  34. package/dist/server/i18n.js +20 -1
  35. package/dist/server/index.js +286 -71
  36. package/dist/server/locales.js +1 -0
  37. package/dist/server/managed.js +2 -0
  38. package/dist/server/marker-service.js +5 -19
  39. package/dist/server/markers/index.js +1 -3
  40. package/dist/server/mcp-agent-tool.js +10 -7
  41. package/dist/server/mcp-bridge.js +428 -24
  42. package/dist/server/model-admin.js +172 -74
  43. package/dist/server/model-resolver.js +309 -0
  44. package/dist/server/plugin-installer.js +4 -2
  45. package/dist/server/plugins.js +89 -12
  46. package/dist/server/present-files-tool.js +10 -2
  47. package/dist/server/preset-fields.js +14 -0
  48. package/dist/server/preset-share.js +2 -0
  49. package/dist/server/protocol-version.js +1 -1
  50. package/dist/server/schedule-agent-tool.js +2 -1
  51. package/dist/server/scm-commitmsg.js +3 -2
  52. package/dist/server/sdk-origin.js +2 -2
  53. package/dist/server/serialize.js +1 -1
  54. package/dist/server/settings-service.js +10 -2
  55. package/dist/server/skill-discovery.js +161 -0
  56. package/dist/server/skill-tool.js +2 -1
  57. package/dist/server/slash-commands.js +154 -73
  58. package/dist/server/subagent-templates-hant.js +215 -0
  59. package/dist/server/subagent-templates.js +49 -2
  60. package/dist/server/subagents.js +22 -12
  61. package/dist/server/terminals.js +2 -2
  62. package/dist/server/tool-manager.js +6 -19
  63. package/dist/server/universal/driver-base.js +60 -0
  64. package/dist/server/universal/drivers/claude-code.js +463 -0
  65. package/dist/server/universal/drivers/dsh-driver.js +376 -0
  66. package/dist/server/universal/drivers/mock-driver.js +103 -0
  67. package/dist/server/universal/index.js +10 -0
  68. package/dist/server/universal/session-store.js +100 -0
  69. package/dist/server/universal/universal-attachments.js +175 -0
  70. package/dist/server/universal/universal-service.js +166 -0
  71. package/dist/server/universal/universal-session.js +2664 -0
  72. package/dist/server/universal/universal-types.js +4 -0
  73. package/dist/server/update-check.js +24 -9
  74. package/dist/server/worktree-service.js +1 -1
  75. package/dist/server/worktree-tool.js +9 -7
  76. package/package.json +3 -2
  77. package/plugin-sdk/index.d.ts +12 -2
  78. package/plugins/catalog.json +50 -5
  79. package/themes/dark-teal.css +20 -24
  80. package/themes/flow-light.css +1085 -0
  81. package/themes/flow.css +1094 -0
  82. package/themes/md-preview.css +1 -2
  83. package/themes/wallpaper-flow.css +1158 -0
  84. package/themes/wallpaper-obsidian.css +743 -0
  85. package/themes/zhujian-dark.css +0 -7
  86. package/themes/zhujian.css +0 -7
  87. package/themes/zhupi-dark.css +0 -7
  88. package/themes/zhupi.css +0 -7
  89. package/web/dist/assets/{TerminalPanel-Mk4laCAL.js → TerminalPanel-BnViyTlx.js} +2 -2
  90. package/web/dist/assets/index-cCRCYMwT.css +1 -0
  91. package/web/dist/assets/index-fH5vhkAE.js +690 -0
  92. package/web/dist/index.html +2 -2
  93. package/web/dist/sw.js +1 -1
  94. package/web/dist/assets/index-BDLVjBeK.js +0 -690
  95. package/web/dist/assets/index-BQC6lADz.css +0 -1
@@ -251,8 +251,10 @@ export class PluginInstaller {
251
251
  child.on("close", (code) => {
252
252
  if (cancelled)
253
253
  return finish(false, pick(l, "作业已取消", "Job cancelled", "plugininstaller.cancelled"));
254
- if (timedOut)
255
- return finish(false, pick(l, `作业超时(${Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000)} 分钟)已终止`, `Job timed out after ${Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000)} min and was killed`, "plugininstaller.timeout"));
254
+ if (timedOut) {
255
+ const min = Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000);
256
+ return finish(false, pick(l, `作业超时(${min} 分钟)已终止`, `Job timed out after ${min} min and was killed`, "plugininstaller.timeout", { min }));
257
+ }
256
258
  finish(code === 0, code === 0 ? undefined : `exit code ${code}`);
257
259
  });
258
260
  emit({ type: "plugin_job", jobId, action, pluginId, phase: "start" });
@@ -1312,12 +1312,29 @@ export class PluginManager {
1312
1312
  }
1313
1313
  const table = this.loaded.get(pluginId)?.httpRoutes;
1314
1314
  const path = "/" + pathIn.replace(/^\/+/, "");
1315
- const handler = table?.get(`${method.toUpperCase()} ${path}`);
1315
+ let handler = table?.get(`${method.toUpperCase()} ${path}`);
1316
+ if (!handler && table) {
1317
+ const m = method.toUpperCase();
1318
+ // 通配符路由支持(例如 host.route("GET", "/api/web/*", ...) 或以 "/*" 结尾的前缀)
1319
+ for (const [key, fn] of table.entries()) {
1320
+ if (!key.startsWith(`${m} `))
1321
+ continue;
1322
+ const routePath = key.slice(m.length + 1);
1323
+ if (routePath.endsWith("/*")) {
1324
+ const prefix = routePath.slice(0, -2);
1325
+ if (path === prefix || path.startsWith(prefix + "/")) {
1326
+ handler = fn;
1327
+ break;
1328
+ }
1329
+ }
1330
+ }
1331
+ }
1316
1332
  if (!handler) {
1317
1333
  res.status(404).end("not found");
1318
1334
  return;
1319
1335
  }
1320
1336
  try {
1337
+ req.pluginPath = path;
1321
1338
  // 异步 handler(`async (req, res) => …`)的 rejection 不会被这里的 try 接住,
1322
1339
  // 会变成 unhandledRejection 直接杀掉整个服务(插件读文件失败、host.fs 越界
1323
1340
  // 拒绝、上游超时…都会走到这条路上)——用 Promise.resolve().catch 兜住,
@@ -2297,6 +2314,7 @@ export class PluginManager {
2297
2314
  for (const w of [...overlayFileForScan.warnings, ...overlayForScan.warnings])
2298
2315
  uiDiags.push(`override: ${w}`);
2299
2316
  const resolvedSettingsForScan = resolveSettingsValues(settingsSchemaForScan, readStoredSettings(dir), overlayForScan.values, { has: (k) => new PluginSecrets(this.dataDir, dir).has(k) });
2317
+ const hasClient = existsSync(join(dir, "client", "entry.mjs"));
2300
2318
  out.push({
2301
2319
  id: name,
2302
2320
  name: typeof m.name === "string" && m.name ? m.name : name,
@@ -2305,7 +2323,7 @@ export class PluginManager {
2305
2323
  homepage: typeof m.homepage === "string" && m.homepage.trim() ? m.homepage.trim() : undefined,
2306
2324
  icon: typeof m.icon === "string" && m.icon.trim() ? m.icon.trim() : undefined,
2307
2325
  iconSvg: normalizeIconSvg(m.iconSvg),
2308
- hasClient: existsSync(join(dir, "client", "entry.mjs")),
2326
+ hasClient,
2309
2327
  error: this.loaded.get(name)?.info.error,
2310
2328
  // manifest 声明的能力清单(fs/net/tools…)——设置面板展示用
2311
2329
  permissions: Array.isArray(m.permissions)
@@ -2396,8 +2414,8 @@ export class PluginManager {
2396
2414
  .filter((x) => x !== null);
2397
2415
  return rows.length ? rows : undefined;
2398
2416
  })(),
2399
- // 是否有独立视图 tab(manifest "view",缺省 true);纯 renderer 插件写 false
2400
- view: typeof m.view === "boolean" ? m.view : true,
2417
+ // 是否有独立视图 tab(manifest "view",缺省为是否有客户端 entry.mjs);纯 renderer 插件写 false
2418
+ view: typeof m.view === "boolean" ? m.view : hasClient,
2401
2419
  // 客户端 bundle 是否常驻加载(manifest "preload",缺省 false):无视图
2402
2420
  // (view:false)却要顶层代码一直跑(提醒轮询/快捷键/常驻浮窗…)的插件用它。
2403
2421
  preload: m.preload === true,
@@ -3378,13 +3396,75 @@ export class PluginManager {
3378
3396
  }
3379
3397
  };
3380
3398
  fire();
3381
- effects.add(`bgTask:${id}`, () => {
3399
+ // 统一心跳探活循环调度
3400
+ let heartbeatTimer = null;
3401
+ const stopHeartbeat = () => {
3402
+ if (heartbeatTimer) {
3403
+ clearInterval(heartbeatTimer);
3404
+ heartbeatTimer = null;
3405
+ }
3406
+ };
3407
+ const cleanup = () => {
3408
+ stopHeartbeat();
3382
3409
  if (bgTaskTable.delete(id)) {
3383
3410
  if (bgTaskTable.size === 0)
3384
3411
  self.pluginBgTasks.delete(info.id);
3385
3412
  fire();
3386
3413
  }
3387
- });
3414
+ };
3415
+ const removeEffect = effects.add(`bgTask:${id}`, cleanup);
3416
+ if (typeof task?.check === "function") {
3417
+ const checkFn = task.check;
3418
+ const interval = Math.max(50, Math.floor(task.intervalMs ?? 3000));
3419
+ const maxFailures = Math.max(1, Math.floor(task.maxFailures ?? 2));
3420
+ let consecutiveFailures = 0;
3421
+ let inFlight = false;
3422
+ heartbeatTimer = setInterval(async () => {
3423
+ if (inFlight || !bgTaskTable.has(id))
3424
+ return;
3425
+ inFlight = true;
3426
+ try {
3427
+ const res = await checkFn();
3428
+ let alive = false;
3429
+ let nextStatus;
3430
+ if (typeof res === "boolean") {
3431
+ alive = res;
3432
+ }
3433
+ else if (res && typeof res === "object") {
3434
+ alive = !!res.alive;
3435
+ if (typeof res.status === "string") {
3436
+ nextStatus = res.status;
3437
+ }
3438
+ }
3439
+ if (alive) {
3440
+ consecutiveFailures = 0;
3441
+ if (nextStatus !== undefined && nextStatus !== entry.status) {
3442
+ entry.status = nextStatus;
3443
+ fire();
3444
+ }
3445
+ }
3446
+ else {
3447
+ consecutiveFailures++;
3448
+ }
3449
+ }
3450
+ catch {
3451
+ consecutiveFailures++;
3452
+ }
3453
+ finally {
3454
+ inFlight = false;
3455
+ }
3456
+ if (consecutiveFailures >= maxFailures) {
3457
+ removeEffect();
3458
+ try {
3459
+ task.onDead?.("heartbeat_failed");
3460
+ }
3461
+ catch (e) {
3462
+ console.error(`[plugin:${info.id}] bgTask onDead error:`, e);
3463
+ }
3464
+ }
3465
+ }, interval);
3466
+ heartbeatTimer.unref?.();
3467
+ }
3388
3468
  return {
3389
3469
  update: (next) => {
3390
3470
  if (!bgTaskTable.has(id))
@@ -3398,11 +3478,7 @@ export class PluginManager {
3398
3478
  fire();
3399
3479
  },
3400
3480
  unregister: () => {
3401
- if (bgTaskTable.delete(id)) {
3402
- if (bgTaskTable.size === 0)
3403
- this.pluginBgTasks.delete(info.id);
3404
- fire();
3405
- }
3481
+ removeEffect();
3406
3482
  },
3407
3483
  };
3408
3484
  },
@@ -4010,7 +4086,8 @@ export class PluginManager {
4010
4086
  // Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
4011
4087
  // 击穿缓存,让 plugins_reload 后的重新激活能拿到磁盘上的新代码。
4012
4088
  const mod = (await import(pathToFileURL(join(dir, "index.mjs")).href + `?e=${this.epochCounter}`));
4013
- const ret = await mod.default?.activate?.(host);
4089
+ const activateFn = typeof mod.default === "function" ? mod.default : mod.default?.activate;
4090
+ const ret = await activateFn?.(host);
4014
4091
  const gateWarned = self.activatingGates.get(info.id)?.legacyWarned;
4015
4092
  self.activatingGates.delete(info.id);
4016
4093
  // activate() 执行期间经 host 注册产生的运行时诊断(重复工具/命令、ui 丢弃等)
@@ -28,7 +28,7 @@ import { open, stat } from "node:fs/promises";
28
28
  import { basename, extname, posix, sep } from "node:path";
29
29
  import { defineTool } from "@earendil-works/pi-coding-agent";
30
30
  import { Type } from "typebox";
31
- import { pick } from "./i18n.js";
31
+ import { getServerString, pick } from "./i18n.js";
32
32
  import { resolvePathForDirCheck } from "./read-tool.js";
33
33
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, restoreWorkspaceUriFromSessionDir, } from "./remote-ssh-service.js";
34
34
  import { decodeText, isAudioFile, looksLikeText, previewKind } from "./text-sniff.js";
@@ -257,7 +257,15 @@ export function buildPresentResultText(items, lang, title) {
257
257
  const shown = items.filter((i) => i.kind !== "missing");
258
258
  const missing = items.filter((i) => i.kind === "missing");
259
259
  const lines = [];
260
- const head = pick(lang, `已把 ${shown.length} 个文件作为预览卡片展示给用户${title ? `(${title})` : ""}:`, `Presented ${shown.length} file(s) to the user as preview cards${title ? ` (${title})` : ""}:`, "present.files.result.head", { n: shown.length, title: title ?? "" });
260
+ const trimmedTitle = title?.trim();
261
+ const key = trimmedTitle
262
+ ? getServerString(lang, "present.files.result.head.titled")
263
+ ? "present.files.result.head.titled"
264
+ : "present.files.result.head"
265
+ : "present.files.result.head";
266
+ const head = trimmedTitle
267
+ ? pick(lang, `已把 ${shown.length} 个文件作为预览卡片展示给用户(${trimmedTitle}):`, `Presented ${shown.length} file(s) to the user as preview cards (${trimmedTitle}):`, key, { n: shown.length, title: trimmedTitle })
268
+ : pick(lang, `已把 ${shown.length} 个文件作为预览卡片展示给用户:`, `Presented ${shown.length} file(s) to the user as preview cards:`, "present.files.result.head", { n: shown.length, title: "" });
261
269
  lines.push(head);
262
270
  for (const [i, it] of shown.entries()) {
263
271
  const meta = it.kind === "dir"
@@ -79,9 +79,11 @@ export const PRESET_FIELD_GROUPS = {
79
79
  "keepRecentMessages",
80
80
  "showForkedParentSessions",
81
81
  "retainFinishedConversations",
82
+ "openRecentSessionOnProjectSwitch",
82
83
  "bgAutoCleanupMin",
83
84
  "quickPhrases",
84
85
  "quickPhrasesEnabled",
86
+ "minimalNewChat",
85
87
  "devNoCache",
86
88
  "autoReload",
87
89
  ],
@@ -413,6 +415,12 @@ export const PRESET_FIELD_META = {
413
415
  hintZh: "切换对话或新建对话时,已结束(空闲)的对话依然保留在运行列表中,直到手动移出",
414
416
  hintEn: "Keep finished (idle) conversations in the Running Chats list when switching away until manually removed",
415
417
  },
418
+ openRecentSessionOnProjectSwitch: {
419
+ labelZh: "切换项目时打开最近会话",
420
+ labelEn: "Open Recent Session on Project Switch",
421
+ hintZh: "切换到新项目时自动打开该项目最近的会话;关闭后切换项目将直接创建全新空白对话",
422
+ hintEn: "Automatically resume the most recent session when switching projects. When off, always create a fresh blank chat",
423
+ },
416
424
  quickPhrases: {
417
425
  labelZh: "快捷短语列表",
418
426
  labelEn: "Quick Phrases List",
@@ -425,6 +433,12 @@ export const PRESET_FIELD_META = {
425
433
  hintZh: "是否在输入框上方显示快捷短语药丸栏",
426
434
  hintEn: "Display quick phrases bar above composer",
427
435
  },
436
+ minimalNewChat: {
437
+ labelZh: "极简新对话",
438
+ labelEn: "Minimalist New Chat",
439
+ hintZh: "新对话隐藏提示词模板并隐藏快捷短语,呈现现代极简风格",
440
+ hintEn: "Hide prompt templates and quick phrases on new chat for a clean modern look",
441
+ },
428
442
  devNoCache: {
429
443
  labelZh: "开发者免缓存模式",
430
444
  labelEn: "Developer No-Cache Mode",
@@ -275,8 +275,10 @@ const PRESET_FIELD_KINDS = {
275
275
  keepRecentMessages: "number",
276
276
  showForkedParentSessions: "bool",
277
277
  retainFinishedConversations: "bool",
278
+ openRecentSessionOnProjectSwitch: "bool",
278
279
  quickPhrases: "list",
279
280
  quickPhrasesEnabled: "bool",
281
+ minimalNewChat: "bool",
280
282
  devNoCache: "bool",
281
283
  autoReload: "bool",
282
284
  // -- engine ----------------------------------------------------------
@@ -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 = 29;
11
+ export const PROTOCOL_VERSION = 31;
@@ -153,7 +153,8 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
153
153
  parsed = parseScheduleSpec(p.schedule);
154
154
  }
155
155
  catch (err) {
156
- return text(pick(getLang(), `时间写法非法:${String(p.schedule ?? "")}(要 5 字段 cron 如 "0 * * * *" 或相对时间如 "in 30m"):${err.message}`, `Invalid schedule: ${String(p.schedule ?? "")} (want 5-field cron like "0 * * * *" or a delay like "in 30m"): ${err.message}`, "sched.task.bad.schedule", { schedule: String(p.schedule ?? "") }));
156
+ const errorMsg = err.message;
157
+ return text(pick(getLang(), `时间写法非法:${String(p.schedule ?? "")}(要 5 字段 cron 如 "0 * * * *" 或相对时间如 "in 30m"):${errorMsg}`, `Invalid schedule: ${String(p.schedule ?? "")} (want 5-field cron like "0 * * * *" or a delay like "in 30m"): ${errorMsg}`, "sched.task.bad.schedule", { schedule: String(p.schedule ?? ""), error: errorMsg }));
157
158
  }
158
159
  if (parsed.kind === "interval" && Number(parsed.spec) < SCHEDULER_MIN_INTERVAL_MS) {
159
160
  return text(pick(getLang(), `间隔太短(最短 60s,防 token 烧穿)。`, `Interval too short (minimum 60s, prevents token burn).`, "sched.task.interval.too.short"));
@@ -180,7 +180,7 @@ export async function generateScmCommitMessage(opts) {
180
180
  return {
181
181
  ok: false,
182
182
  error: msg.errorMessage ||
183
- pick(lang, `模型异常终止(${msg.stopReason})`, `Model terminated abnormally (${msg.stopReason})`, "scm.commitmsg.model.terminated"),
183
+ pick(lang, `模型异常终止(${msg.stopReason})`, `Model terminated abnormally (${msg.stopReason})`, "scm.commitmsg.model.terminated", { stopReason: msg.stopReason }),
184
184
  };
185
185
  }
186
186
  const raw = msg.content
@@ -204,9 +204,10 @@ export async function generateScmCommitMessage(opts) {
204
204
  };
205
205
  }
206
206
  if (err instanceof Error && /abort/i.test(`${err.name} ${err.message}`)) {
207
+ const secs = Math.round(timeoutMs / 1000);
207
208
  return {
208
209
  ok: false,
209
- error: pick(lang, `生成提交信息超时(${Math.round(timeoutMs / 1000)} 秒)`, `Commit-message generation timed out (${Math.round(timeoutMs / 1000)}s)`, "scm.commitmsg.timeout"),
210
+ error: pick(lang, `生成提交信息超时(${secs} 秒)`, `Commit-message generation timed out (${secs}s)`, "scm.commitmsg.timeout", { secs }),
210
211
  };
211
212
  }
212
213
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -87,8 +87,8 @@ function scanPathForPi(out, env = process.env) {
87
87
  /** 探测 npm / pnpm 全局 prefix 目录(issue #559)。 */
88
88
  function scanGlobalPrefixes(out, env = process.env) {
89
89
  const home = env.HOME || env.USERPROFILE || "";
90
- // 1. npm_config_prefix / PREFIX
91
- const prefix = env.npm_config_prefix || env.PREFIX;
90
+ // 1. NPM_CONFIG_PREFIX / npm_config_prefix / PREFIX
91
+ const prefix = env.NPM_CONFIG_PREFIX || env.npm_config_prefix || env.PREFIX;
92
92
  if (prefix) {
93
93
  addCopy(join(prefix, "lib", "node_modules", PKG, "package.json"), out);
94
94
  addCopy(join(prefix, "node_modules", PKG, "package.json"), out);
@@ -363,7 +363,7 @@ export function serializeMessage(m, seq) {
363
363
  };
364
364
  // 结构化元数据(tool result details)也要下发:present_files 的预览卡片
365
365
  // 就靠它拿 kind/size/excerpt(前端不能靠再打一次 HTTP 才知类型),
366
- // ask_user_question/todo_list 同理。体积封顶,超限整丢(见 TOOL_DETAILS_CAP)。
366
+ // ask_user_question 同理。体积封顶,超限整丢(见 TOOL_DETAILS_CAP)。
367
367
  if (m.details !== undefined) {
368
368
  try {
369
369
  const json = JSON.stringify(m.details);
@@ -14,7 +14,7 @@ import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { findVisionModels, SYSTEM_PROMPT } from "./vision-bridge.js";
15
15
  import { COMMITMSG_SYSTEM_PROMPT } from "./scm-commitmsg.js";
16
16
  import { PLAN_MODE_SYSTEM_PROMPT } from "./plan-mode.js";
17
- import { DEFAULT_TEMPLATES } from "./subagent-templates.js";
17
+ import { DEFAULT_TEMPLATES, localizeTemplate } from "./subagent-templates.js";
18
18
  import { deriveLegacy, foldLegacyIntoDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
19
19
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
20
20
  import { resolveServerLang } from "./i18n.js";
@@ -325,6 +325,7 @@ export class SettingsService {
325
325
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
326
326
  showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
327
327
  retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
328
+ openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
328
329
  visionBridgeEnabled: this.settings.visionBridgeEnabled,
329
330
  visionBridgeModel: this.settings.visionBridgeModel,
330
331
  visionBridgePromptMode: this.settings.visionBridgePromptMode,
@@ -361,7 +362,7 @@ export class SettingsService {
361
362
  disabledMarkers: [],
362
363
  markers: [],
363
364
  }),
364
- subagentTemplates: this.templates.list(),
365
+ subagentTemplates: this.templates.list().map((t) => localizeTemplate(t, this.host.getLocale?.())),
365
366
  subagentDefaultTemplates: DEFAULT_TEMPLATES.map((t) => t.name),
366
367
  subagentDefaultModel: this.settings.subagentDefaultModel ?? null,
367
368
  retryMaxAttempts: this.settings.retryMaxAttempts,
@@ -370,6 +371,7 @@ export class SettingsService {
370
371
  subagentModels: this.collectSubagentModels(),
371
372
  quickPhrases: [...this.settings.quickPhrases],
372
373
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
374
+ minimalNewChat: this.settings.minimalNewChat,
373
375
  quickPhrasesSeeded: this.host.stateStore.getQuickPhrasesSeeded(),
374
376
  mcpServers: mcp.servers,
375
377
  mcpGlobalConfigPath: mcp.globalPath,
@@ -577,6 +579,9 @@ export class SettingsService {
577
579
  if (partial.retainFinishedConversations !== undefined) {
578
580
  this.settings.retainFinishedConversations = Boolean(partial.retainFinishedConversations);
579
581
  }
582
+ if (partial.openRecentSessionOnProjectSwitch !== undefined) {
583
+ this.settings.openRecentSessionOnProjectSwitch = Boolean(partial.openRecentSessionOnProjectSwitch);
584
+ }
580
585
  let sessionsFilterChanged = false;
581
586
  if (partial.showForkedParentSessions !== undefined) {
582
587
  const nextVal = Boolean(partial.showForkedParentSessions);
@@ -654,6 +659,9 @@ export class SettingsService {
654
659
  if (partial.quickPhrasesEnabled !== undefined) {
655
660
  this.settings.quickPhrasesEnabled = partial.quickPhrasesEnabled;
656
661
  }
662
+ if (partial.minimalNewChat !== undefined) {
663
+ this.settings.minimalNewChat = partial.minimalNewChat;
664
+ }
657
665
  // 统一工具开关 live 生效(ActiveSet 加减;失败静默,下次创建/reload 重放)。
658
666
  // 必须在 this.push() 前生效,保证 promptSnapshot 收集到的是最新的活跃工具集与完整提示词!
659
667
  if (toolGatingChanged)
@@ -0,0 +1,161 @@
1
+ /**
2
+ * skill-discovery.ts — 跨引擎技能(Skill)磁盘发现与内容加载。
3
+ *
4
+ * 规范参考:docs/skills.md
5
+ * 支持路径:
6
+ * - 全局 Pi 技能:~/.pi/agent/skills/ 或 agentDir/skills/
7
+ * - 项目 Pi 技能:<cwd>/.pi/skills/
8
+ * - Claude Code 技能:~/.claude/skills/ 与 <cwd>/.claude/skills/
9
+ *
10
+ * 技能结构:
11
+ * 1. 目录形式(标准):<skill-name>/SKILL.md
12
+ * 2. 独立文件形式:<skill-name>.md
13
+ *
14
+ * SKILL.md 规范包含 YAML frontmatter:
15
+ * ---
16
+ * name: skill-name
17
+ * description: 技能说明
18
+ * ---
19
+ * 正文指令...
20
+ */
21
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { basename, join } from "node:path";
24
+ import { decodeText } from "./text-sniff.js";
25
+ /** 解析 SKILL.md 的 YAML frontmatter 提取 name 与 description */
26
+ export function parseSkillFrontmatter(content, fallbackName) {
27
+ const trimmed = content.trim();
28
+ let name = fallbackName;
29
+ let description = "";
30
+ if (trimmed.startsWith("---")) {
31
+ const secondDash = trimmed.indexOf("\n---", 3);
32
+ if (secondDash !== -1) {
33
+ const header = trimmed.slice(3, secondDash);
34
+ for (const line of header.split("\n")) {
35
+ const colon = line.indexOf(":");
36
+ if (colon <= 0)
37
+ continue;
38
+ const key = line.slice(0, colon).trim().toLowerCase();
39
+ let val = line.slice(colon + 1).trim();
40
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
41
+ val = val.slice(1, -1);
42
+ }
43
+ if (key === "name" && val) {
44
+ name = val;
45
+ }
46
+ else if (key === "description" && val) {
47
+ description = val;
48
+ }
49
+ }
50
+ // 若 frontmatter 缺 description,取正文第一行段落
51
+ if (!description) {
52
+ const rest = trimmed.slice(secondDash + 4).trim();
53
+ const firstLine = rest.split("\n").find((l) => l.trim() && !l.trim().startsWith("#"));
54
+ if (firstLine)
55
+ description = firstLine.trim();
56
+ }
57
+ }
58
+ }
59
+ if (!description) {
60
+ const firstHeader = trimmed.split("\n").find((l) => l.trim().startsWith("#"));
61
+ if (firstHeader) {
62
+ description = firstHeader.replace(/^#+\s*/, "").trim();
63
+ }
64
+ else {
65
+ description = `Skill ${name}`;
66
+ }
67
+ }
68
+ return { name, description };
69
+ }
70
+ /**
71
+ * 递归/顺序扫描各候选目录发现技能。
72
+ */
73
+ export function discoverDiskSkills(opts) {
74
+ const results = [];
75
+ const seen = new Set();
76
+ const searchDirs = [];
77
+ const home = homedir();
78
+ // 1. 项目本地技能优先(.pi/skills, .claude/skills)
79
+ if (opts.cwd) {
80
+ searchDirs.push(join(opts.cwd, ".pi", "skills"));
81
+ searchDirs.push(join(opts.cwd, ".claude", "skills"));
82
+ }
83
+ // 2. 全局技能目录(agentDir/skills, ~/.pi/agent/skills, ~/.claude/skills)
84
+ if (opts.agentDir) {
85
+ searchDirs.push(join(opts.agentDir, "skills"));
86
+ }
87
+ if (opts.includeHome !== false) {
88
+ searchDirs.push(join(home, ".pi", "agent", "skills"));
89
+ searchDirs.push(join(home, ".claude", "skills"));
90
+ }
91
+ for (const baseDir of searchDirs) {
92
+ if (!existsSync(baseDir))
93
+ continue;
94
+ try {
95
+ const entries = readdirSync(baseDir, { withFileTypes: true });
96
+ for (const entry of entries) {
97
+ if (entry.name.startsWith("."))
98
+ continue;
99
+ if (entry.isDirectory()) {
100
+ // 目录型:<baseDir>/<entry>/SKILL.md
101
+ const skillMd = join(baseDir, entry.name, "SKILL.md");
102
+ if (existsSync(skillMd)) {
103
+ try {
104
+ const text = decodeText(readFileSync(skillMd));
105
+ const { name, description } = parseSkillFrontmatter(text, entry.name);
106
+ if (!seen.has(name)) {
107
+ seen.add(name);
108
+ results.push({
109
+ name,
110
+ description,
111
+ filePath: skillMd,
112
+ dirPath: join(baseDir, entry.name),
113
+ });
114
+ }
115
+ }
116
+ catch {
117
+ /* 忽略单文件损坏 */
118
+ }
119
+ }
120
+ }
121
+ else if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md") {
122
+ // 单文件型:<baseDir>/<name>.md
123
+ const filePath = join(baseDir, entry.name);
124
+ const base = basename(entry.name, ".md");
125
+ try {
126
+ const text = decodeText(readFileSync(filePath));
127
+ const { name, description } = parseSkillFrontmatter(text, base);
128
+ if (!seen.has(name)) {
129
+ seen.add(name);
130
+ results.push({
131
+ name,
132
+ description,
133
+ filePath,
134
+ dirPath: baseDir,
135
+ });
136
+ }
137
+ }
138
+ catch {
139
+ /* 忽略单文件损坏 */
140
+ }
141
+ }
142
+ }
143
+ }
144
+ catch {
145
+ /* 目录读取权限异常静默跳过 */
146
+ }
147
+ }
148
+ return results;
149
+ }
150
+ /** 读取技能完整指令正文(若含 frontmatter,保留或剥离后返回有效指令) */
151
+ export function readSkillInstruction(filePath) {
152
+ if (!existsSync(filePath))
153
+ return "";
154
+ try {
155
+ const raw = decodeText(readFileSync(filePath)).trim();
156
+ return raw;
157
+ }
158
+ catch {
159
+ return "";
160
+ }
161
+ }
@@ -98,8 +98,9 @@ export function makeSkillTool(host, lang) {
98
98
  }
99
99
  try {
100
100
  const st = statSync(found.filePath);
101
+ const kb = SKILL_TOOL_FILE_CAP / 1024;
101
102
  if (!st.isFile() || st.size <= 0 || st.size > SKILL_TOOL_FILE_CAP) {
102
- return text(pick(L, `技能 ${name} 的文件不可读(不存在/超 ${SKILL_TOOL_FILE_CAP / 1024}KB 上限)。`, `Skill ${name} file unreadable (missing or over the ${SKILL_TOOL_FILE_CAP / 1024}KB cap).`, "skill.file.unreadable", { name }));
103
+ return text(pick(L, `技能 ${name} 的文件不可读(不存在/超 ${kb}KB 上限)。`, `Skill ${name} file unreadable (missing or over the ${kb}KB cap).`, "skill.file.unreadable", { name, kb }));
103
104
  }
104
105
  const body = decodeText(readFileSync(found.filePath).subarray(0, st.size)).trim();
105
106
  if (!body) {