pi-web-ui 0.105.1 → 0.106.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 (74) hide show
  1. package/CHANGELOG.md +43 -1
  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 +227 -44
  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 +838 -241
  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/engine-capabilities.js +72 -0
  23. package/dist/server/engine-probe.js +243 -0
  24. package/dist/server/goal-service.js +23 -12
  25. package/dist/server/i18n.js +20 -1
  26. package/dist/server/index.js +171 -66
  27. package/dist/server/locales.js +1 -0
  28. package/dist/server/mcp-agent-tool.js +10 -7
  29. package/dist/server/mcp-bridge.js +428 -24
  30. package/dist/server/model-admin.js +172 -74
  31. package/dist/server/model-resolver.js +221 -0
  32. package/dist/server/plugin-installer.js +4 -2
  33. package/dist/server/plugins.js +71 -11
  34. package/dist/server/present-files-tool.js +10 -2
  35. package/dist/server/preset-fields.js +14 -0
  36. package/dist/server/preset-share.js +2 -0
  37. package/dist/server/protocol-version.js +1 -1
  38. package/dist/server/schedule-agent-tool.js +2 -1
  39. package/dist/server/scm-commitmsg.js +3 -2
  40. package/dist/server/settings-service.js +10 -2
  41. package/dist/server/skill-discovery.js +161 -0
  42. package/dist/server/skill-tool.js +2 -1
  43. package/dist/server/slash-commands.js +154 -73
  44. package/dist/server/subagent-templates-hant.js +215 -0
  45. package/dist/server/subagent-templates.js +49 -2
  46. package/dist/server/subagents.js +22 -12
  47. package/dist/server/terminals.js +2 -2
  48. package/dist/server/tool-manager.js +3 -0
  49. package/dist/server/universal/driver-base.js +56 -0
  50. package/dist/server/universal/drivers/claude-code.js +462 -0
  51. package/dist/server/universal/drivers/dsh-driver.js +376 -0
  52. package/dist/server/universal/drivers/mock-driver.js +103 -0
  53. package/dist/server/universal/index.js +10 -0
  54. package/dist/server/universal/session-store.js +100 -0
  55. package/dist/server/universal/universal-attachments.js +175 -0
  56. package/dist/server/universal/universal-service.js +149 -0
  57. package/dist/server/universal/universal-session.js +2610 -0
  58. package/dist/server/universal/universal-types.js +4 -0
  59. package/dist/server/update-check.js +4 -1
  60. package/dist/server/worktree-service.js +1 -1
  61. package/dist/server/worktree-tool.js +9 -7
  62. package/package.json +3 -2
  63. package/plugin-sdk/index.d.ts +12 -2
  64. package/plugins/catalog.json +39 -5
  65. package/themes/dark-teal.css +20 -23
  66. package/themes/md-preview.css +1 -2
  67. package/themes/wallpaper-obsidian.css +693 -0
  68. package/web/dist/assets/{TerminalPanel-Mk4laCAL.js → TerminalPanel-CfxKLDW9.js} +2 -2
  69. package/web/dist/assets/index-BtcP6BDk.css +1 -0
  70. package/web/dist/assets/index-XVtCzcHR.js +690 -0
  71. package/web/dist/index.html +2 -2
  72. package/web/dist/sw.js +1 -1
  73. package/web/dist/assets/index-BDLVjBeK.js +0 -690
  74. package/web/dist/assets/index-BQC6lADz.css +0 -1
@@ -24,7 +24,7 @@ import { mkdirSync, rmSync } from "node:fs";
24
24
  import { join } from "node:path";
25
25
  import { Type } from "typebox";
26
26
  import { createAgentSessionFromServices, createAgentSessionServices, defineTool, ModelRuntime, SessionManager, } from "@earendil-works/pi-coding-agent";
27
- import { pick } from "./i18n.js";
27
+ import { getServerString, pick } from "./i18n.js";
28
28
  import { parseModelSpec } from "./attachments.js";
29
29
  function allBalancedJsonObjects(raw) {
30
30
  const src = raw.length > 32768 ? raw.slice(-32768) : raw;
@@ -1847,7 +1847,7 @@ export class GoalService {
1847
1847
  }
1848
1848
  const prev = prevFeedback.trim();
1849
1849
  if (prev) {
1850
- return pick(this.lang(), `(审查者本轮未给出新意见,沿用上一轮意见)\n${prev}`, `(the reviewer gave no new feedback this round — carrying the previous round's over)\n${prev}`, "goal.role.review.feedback.prev");
1850
+ return pick(this.lang(), `(审查者本轮未给出新意见,沿用上一轮意见)\n${prev}`, `(the reviewer gave no new feedback this round — carrying the previous round's over)\n${prev}`, "goal.role.review.feedback.prev", { prev });
1851
1851
  }
1852
1852
  return pick(this.lang(), "审查者判 fail 但未给出说明。请复核目标的每一条要求,补齐尚未完成或尚未验证的部分,并在自述里给出可核验的证据(跑过的命令与输出)。", "The reviewer returned fail without a note. Re-check every requirement in the goal, finish what is unfinished or unverified, and back it up with verifiable evidence (the commands you ran and their output).", "goal.role.review.feedback.empty");
1853
1853
  }
@@ -2083,7 +2083,7 @@ export class GoalService {
2083
2083
  textEn: "⚠️ Goal blocked: delegated execution paused (set the goal again to continue)",
2084
2084
  });
2085
2085
  try {
2086
- await conv.session.sendUserMessage(pick(this.lang(), `⚠️ 目标执行受阻(${roundsZh})。\n\n目标:${goalText}\n\n原因:${reason}\n\n(委托执行已暂停,不会自己重新派活。要彻底退出目标模式:点目标条右侧的 ■ 停止目标(取消);想继续就重新设定目标。)`, `⚠️ Goal execution blocked (${roundsEn}).\n\nGoal: ${goalText}\n\nReason: ${reason}\n\n(Delegated execution is paused and will not dispatch again by itself. To leave goal mode entirely, press ■ Stop goal (cancel) in the goal bar; to resume, set the goal again.)`, "goal.role.blocked", { round: round, goalText: goalText, reason: reason }), { deliverAs: conv.session.isStreaming ? "steer" : "followUp" });
2086
+ await conv.session.sendUserMessage(pick(this.lang(), `⚠️ 目标执行受阻(${roundsZh})。\n\n目标:${goalText}\n\n原因:${reason}\n\n(委托执行已暂停,不会自己重新派活。要彻底退出目标模式:点目标条右侧的 ■ 停止目标(取消);想继续就重新设定目标。)`, `⚠️ Goal execution blocked (${roundsEn}).\n\nGoal: ${goalText}\n\nReason: ${reason}\n\n(Delegated execution is paused and will not dispatch again by itself. To leave goal mode entirely, press ■ Stop goal (cancel) in the goal bar; to resume, set the goal again.)`, "goal.role.blocked", { round, goalText, reason, rounds: roundsEn, roundsZh, roundsEn }), { deliverAs: conv.session.isStreaming ? "steer" : "followUp" });
2087
2087
  }
2088
2088
  catch {
2089
2089
  // Best-effort.
@@ -2095,7 +2095,7 @@ export class GoalService {
2095
2095
  roleConvTitle(goalText) {
2096
2096
  const brief = goalText.replace(/\s+/g, " ").trim().slice(0, 40);
2097
2097
  const withTail = goalText.trim().length > 40 ? "…" : "";
2098
- return pick(this.lang(), `[目标执行] ${brief}${withTail}`, `[Goal executor] ${brief}${withTail}`, "goal.role.conv_title");
2098
+ return pick(this.lang(), `[目标执行] ${brief}${withTail}`, `[Goal executor] ${brief}${withTail}`, "goal.role.conv_title", { brief, withTail });
2099
2099
  }
2100
2100
  /** 拉起执行对话失败(配额满 / runtime 创建失败):目标模式只有这一条路径,
2101
2101
  * 没有可降级的对象 —— 当场中止循环并把原因摆到目标条上(用户可在左栏关掉几个
@@ -2129,20 +2129,22 @@ export class GoalService {
2129
2129
  /** 委托执行的角色轮提示词:执行者(干活)与审查者(判定)。双语走 pick。 */ executorRoundPrompt(goalText, round, budget, feedback) {
2130
2130
  const rounds = this.roundsLabel(budget);
2131
2131
  const prev = feedback.trim();
2132
- return pick(this.lang(), `【目标 · 第 ${round}${rounds} 轮】\n\n${goalText}\n\n${prev ? `上一轮审查意见:\n${prev}\n\n` : ""}要求:\n- 直接修改工作区(不要只在回复里描述改动),做完用一段话说明「改了什么、怎么验证的」。\n- 禁止向用户提问(本对话由服务端自动驱动,弹窗会被按取消返回)。\n- 禁止派生或等待其他子代理(轮次由服务端控制,你只负责这一轮)。`, `[Goal · round ${round}${rounds}]\n\n${goalText}\n\n${prev ? `Review feedback from the previous round:\n${prev}\n\n` : ""}Requirements:\n- Change the workspace directly (don't just describe it), then summarize in one paragraph what you changed and how you verified it.\n- Do NOT ask the user anything (this conversation is server-driven; dialogs are auto-cancelled).\n- Do NOT spawn or wait for other subagents (the server owns the rounds; you own this one only).`, "goal.role.exec");
2132
+ return pick(this.lang(), `【目标 · 第 ${round}${rounds} 轮】\n\n${goalText}\n\n${prev ? `上一轮审查意见:\n${prev}\n\n` : ""}要求:\n- 直接修改工作区(不要只在回复里描述改动),做完用一段话说明「改了什么、怎么验证的」。\n- 禁止向用户提问(本对话由服务端自动驱动,弹窗会被按取消返回)。\n- 禁止派生或等待其他子代理(轮次由服务端控制,你只负责这一轮)。`, `[Goal · round ${round}${rounds}]\n\n${goalText}\n\n${prev ? `Review feedback from the previous round:\n${prev}\n\n` : ""}Requirements:\n- Change the workspace directly (don't just describe it), then summarize in one paragraph what you changed and how you verified it.\n- Do NOT ask the user anything (this conversation is server-driven; dialogs are auto-cancelled).\n- Do NOT spawn or wait for other subagents (the server owns the rounds; you own this one only).`, "goal.role.exec", { round, rounds, goalText, prev });
2133
2133
  }
2134
2134
  /** 审查起止卡的文案(进消息流给人看的;结论 feedback 截断,details 不进大文本)。 */
2135
2135
  reviewCardText(kind, round, budget, feedback) {
2136
2136
  const rounds = this.roundsLabel(budget);
2137
2137
  const fb = feedback.trim().replace(/\s+/g, " ").slice(0, 300);
2138
2138
  if (kind === "start") {
2139
- return pick(this.lang(), `🔍 第 ${round}${rounds} 轮审查开始(本回合只回 verdict JSON;审查进行中发消息会自动排队,不用等)`, `🔍 Review round ${round}${rounds} started (reply with only the verdict JSON this round; messages sent mid-review are queued automatically)`, "goal.role.card.start");
2139
+ return pick(this.lang(), `🔍 第 ${round}${rounds} 轮审查开始(本回合只回 verdict JSON;审查进行中发消息会自动排队,不用等)`, `🔍 Review round ${round}${rounds} started (reply with only the verdict JSON this round; messages sent mid-review are queued automatically)`, "goal.role.card.start", { round, rounds });
2140
2140
  }
2141
- return pick(this.lang(), kind === "pass"
2142
- ? `✅ 第 ${round}${rounds} 轮审查通过${fb ? `:${fb}` : ""}`
2143
- : `❌ 第 ${round}${rounds} 轮未通过${fb ? `:${fb}` : ""}`, kind === "pass"
2144
- ? `✅ Review round ${round}${rounds} passed${fb ? `: ${fb}` : ""}`
2145
- : `❌ Review round ${round}${rounds} failed${fb ? `: ${fb}` : ""}`, "goal.role.card.result");
2141
+ const specificKey = kind === "pass" ? "goal.role.card.pass" : "goal.role.card.fail";
2142
+ const key = getServerString(this.lang(), specificKey) ? specificKey : "goal.role.card.result";
2143
+ const fbZh = fb ? `:${fb}` : "";
2144
+ const fbEn = fb ? `: ${fb}` : "";
2145
+ return pick(this.lang(), kind === "pass" ? `✅ 第 ${round}${rounds} 轮审查通过${fbZh}` : `❌ 第 ${round}${rounds} 轮未通过${fbZh}`, kind === "pass"
2146
+ ? `✅ Review round ${round}${rounds} passed${fbEn}`
2147
+ : `❌ Review round ${round}${rounds} failed${fbEn}`, key, { round, rounds, fb: fbEn, fbZh, fbEn, feedback: fb });
2146
2148
  }
2147
2149
  reviewerRoundPrompt(goalText, round, budget, execOutput, planDesc = "", evidence = "") {
2148
2150
  const rounds = this.roundsLabel(budget);
@@ -2162,7 +2164,16 @@ export class GoalService {
2162
2164
  const evidenceBlockEn = ev
2163
2165
  ? `\n\n# Executor's recent tool & command evidence (auto-collected, output tails only, may be truncated)\n${ev}`
2164
2166
  : "";
2165
- return pick(this.lang(), `你是严格、独立的验收者。只判断目标是否被完全满足:不要相信描述,去看工作区的实际状态。\n\n【目标】\n${goalText}\n\n【这是第 ${round}${rounds} 轮】${planBlockZh}\n\n【执行者本轮自述】\n${out || "(执行者本轮没有给出自述)"}${evidenceBlockZh}\n\n你可以用只读手段核实:read / grep / scm(只读 git)/ 只读 bash(跑测试)。\n\n判定口径:\n- 只判【执行者本轮自述】里**声称已完成**的条目;本轮没声称完成的后续阶段不构成 fail 理由(目标写成「完成阶段 3 并收尾后续」也不代表这一轮要做完所有阶段)。\n- 忽略与目标无关的本地改动(其它项目的补丁、工具/模型配置、临时文件)。\n- 声称完成但自述与证据里都没有对应命令输出或文件证据的,必须 fail,并点名缺哪条命令的输出。\n- feedback 不得为空:fail 时必须给出可以直接动手改的具体待改项。\n\n只输出一个 JSON 对象,不要有任何其他文本、不要代码围栏、不要复述下面的形状示例。本回合写类与派发类工具会被服务端直接拒绝(不要试)。字段:verdict 只能填 pass(目标已完全满足,一句话说明满足了什么)或 fail(未满足,给出可以直接动手改的具体待改项);feedback 是一句话说明。形状示例(不要照抄尖括号里的占位符):\n{"verdict":"<pass|fail>","feedback":"<一句话说明>"}\n[goal-review]`, `You are a strict, independent acceptor. Judge only whether the goal is fully satisfied: do not trust the summary — inspect the actual workspace state.\n\n# Goal\n${goalText}\n\n# This is round ${round}${rounds}${planBlockEn}\n\n# Executor's summary this round\n${out || "(the executor produced no summary)"}${evidenceBlockEn}\n\nYou may verify with read-only means: read / grep / scm (read-only git) / read-only bash (run tests).\n\nJudging rules:\n- Judge only the items the executor's summary **claims to have completed this round**; later phases it did not claim this round are NOT grounds for fail (a goal phrased as "finish phase 3 and wrap up the rest" does not mean all phases must land this round).\n- Ignore local changes unrelated to the goal (other projects' patches, tool/model settings, scratch files).\n- If a claimed item has no matching command output or file evidence in the summary or the evidence above, you MUST fail and name which command's output is missing.\n- feedback must not be empty: on fail, give concrete items the executor can act on directly.\n\nReply with ONLY one JSON object — no other text, no code fences, do not echo the shape example below. Write and dispatch tools are blocked by the server during this round — do not try them. Fields: verdict must be pass (goal fully satisfied, say what in one sentence) or fail (not satisfied, give concrete items the executor must fix); feedback is one short sentence. Shape example (do not copy the placeholders in angle brackets):\n{"verdict":"<pass|fail>","feedback":"<one sentence>"}\n[goal-review]`, "goal.role.review");
2167
+ return pick(this.lang(), `你是严格、独立的验收者。只判断目标是否被完全满足:不要相信描述,去看工作区的实际状态。\n\n【目标】\n${goalText}\n\n【这是第 ${round}${rounds} 轮】${planBlockZh}\n\n【执行者本轮自述】\n${out || "(执行者本轮没有给出自述)"}${evidenceBlockZh}\n\n你可以用只读手段核实:read / grep / scm(只读 git)/ 只读 bash(跑测试)。\n\n判定口径:\n- 只判【执行者本轮自述】里**声称已完成**的条目;本轮没声称完成的后续阶段不构成 fail 理由(目标写成「完成阶段 3 并收尾后续」也不代表这一轮要做完所有阶段)。\n- 忽略与目标无关的本地改动(其它项目的补丁、工具/模型配置、临时文件)。\n- 声称完成但自述与证据里都没有对应命令输出或文件证据的,必须 fail,并点名缺哪条命令的输出。\n- feedback 不得为空:fail 时必须给出可以直接动手改的具体待改项。\n\n只输出一个 JSON 对象,不要有任何其他文本、不要代码围栏、不要复述下面的形状示例。本回合写类与派发类工具会被服务端直接拒绝(不要试)。字段:verdict 只能填 pass(目标已完全满足,一句话说明满足了什么)或 fail(未满足,给出可以直接动手改的具体待改项);feedback 是一句话说明。形状示例(不要照抄尖括号里的占位符):\n{"verdict":"<pass|fail>","feedback":"<一句话说明>"}\n[goal-review]`, `You are a strict, independent acceptor. Judge only whether the goal is fully satisfied: do not trust the summary — inspect the actual workspace state.\n\n# Goal\n${goalText}\n\n# This is round ${round}${rounds}${planBlockEn}\n\n# Executor's summary this round\n${out || "(the executor produced no summary)"}${evidenceBlockEn}\n\nYou may verify with read-only means: read / grep / scm (read-only git) / read-only bash (run tests).\n\nJudging rules:\n- Judge only the items the executor's summary **claims to have completed this round**; later phases it did not claim this round are NOT grounds for fail (a goal phrased as "finish phase 3 and wrap up the rest" does not mean all phases must land this round).\n- Ignore local changes unrelated to the goal (other projects' patches, tool/model settings, scratch files).\n- If a claimed item has no matching command output or file evidence in the summary or the evidence above, you MUST fail and name which command's output is missing.\n- feedback must not be empty: on fail, give concrete items the executor can act on directly.\n\nReply with ONLY one JSON object — no other text, no code fences, do not echo the shape example below. Write and dispatch tools are blocked by the server during this round — do not try them. Fields: verdict must be pass (goal fully satisfied, say what in one sentence) or fail (not satisfied, give concrete items the executor must fix); feedback is one short sentence. Shape example (do not copy the placeholders in angle brackets):\n{"verdict":"<pass|fail>","feedback":"<one sentence>"}\n[goal-review]`, "goal.role.review", {
2168
+ goalText,
2169
+ round,
2170
+ rounds,
2171
+ out: out || "(the executor produced no summary)",
2172
+ planBlockEn,
2173
+ evidenceBlockEn,
2174
+ planBlockZh,
2175
+ evidenceBlockZh,
2176
+ });
2166
2177
  }
2167
2178
  verdictRetryPrompt() {
2168
2179
  return pick(this.lang(), `你上一条回复没有给出约定的 JSON。现在只回一个 JSON 对象,不要有任何其他文本或代码围栏:\n{"verdict":"pass|fail","feedback":"…"}\n[goal-review]`, `Your last reply did not contain the required JSON. Reply with ONLY one JSON object now — no other text, no code fences:\n{"verdict":"pass|fail","feedback":"..."}\n[goal-review]`, "goal.role.review.retry");
@@ -21,7 +21,9 @@
21
21
  * messages etc.). Tool DEFINITIONS (description/promptSnippet/promptGuidelines)
22
22
  * are concise English-only. No keys needed.
23
23
  * - Template DATA (subagent_templates content, user overrides) stays zh/en
24
- * fields — it is user-editable config, not code copy.
24
+ * fields — it is user-editable config, not code copy. The built-ins also
25
+ * ship a Traditional Chinese view (subagent-templates-hant.ts), picked by
26
+ * the raw locale via isTraditionalLocale — not by the ServerLang.
25
27
  *
26
28
  * Pure functions + a tiny in-memory registry (no node imports) — unit-tested.
27
29
  * Tables are loaded from `<dataDir>/locales/*.json` at startup (see
@@ -44,6 +46,23 @@ export function resolveServerLang(locale) {
44
46
  export function isZh(lang) {
45
47
  return lang === "zh";
46
48
  }
49
+ /**
50
+ * True for Traditional-script Chinese UI locales ("zh-TW", "zh-HK", "zh-MO",
51
+ * "zh-Hant", "zh-Hant-TW", …). Bare "zh", "zh-CN" and anything with a Hans
52
+ * subtag are Simplified. Same rule as the browser's pickLocale: the script
53
+ * subtag wins over the region ("zh-Hans-HK" is Simplified).
54
+ *
55
+ * `resolveServerLang` folds every zh* into "zh" (the Simplified inline copy), so
56
+ * code that ships a Traditional variant of Chinese DATA needs the raw locale.
57
+ */
58
+ export function isTraditionalLocale(locale) {
59
+ if (typeof locale !== "string")
60
+ return false;
61
+ const parts = locale.trim().toLowerCase().replace(/_/g, "-").split("-");
62
+ if (parts[0] !== "zh" || parts.includes("hans"))
63
+ return false;
64
+ return parts.includes("hant") || parts.includes("tw") || parts.includes("hk") || parts.includes("mo");
65
+ }
47
66
  /* ------------------------------------------------------------------ */
48
67
  /* translator tables */
49
68
  /* ------------------------------------------------------------------ */
@@ -52,7 +52,7 @@ import { validateClientId } from "./ws-client-id.js";
52
52
  import { PendingCommandQueue } from "./ws-pending-queue.js";
53
53
  import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, unloadServerStrings, } from "./locales.js";
54
54
  import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
55
- import { buildPluginJobArgs, confirmPluginInstall, inspectInstallSpec, PluginInstaller } from "./plugin-installer.js";
55
+ import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
56
56
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
57
57
  import { McpBridge } from "./mcp-bridge.js";
58
58
  import { createMcpHotReload } from "./mcp-hot-reload.js";
@@ -341,13 +341,15 @@ if (AUTH_TOKEN) {
341
341
  }
342
342
  /** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
343
343
  const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
344
- /** 启动参数显式指定的引擎(--engine pi|dsh 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
344
+ /** 启动参数显式指定的引擎(--engine pi|dsh|claude 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
345
345
  const EXPLICIT_ENGINE_ARG = cliFlag("--engine") ?? process.env.PI_WEB_ENGINE;
346
- let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "dsh"
347
- ? "dsh"
348
- : EXPLICIT_ENGINE_ARG === "pi"
349
- ? "pi"
350
- : (sharedStateStore.getDefaultEngine() ?? "pi");
346
+ let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "claude"
347
+ ? "claude"
348
+ : EXPLICIT_ENGINE_ARG === "dsh"
349
+ ? "dsh"
350
+ : EXPLICIT_ENGINE_ARG === "pi"
351
+ ? "pi"
352
+ : (sharedStateStore.getDefaultEngine() ?? "pi");
351
353
  /** 默认引擎标识(兼容 /api/health 等读取)。 */
352
354
  const ENGINE = currentDefaultEngine;
353
355
  /** 每个客户端(浏览器标签页 clientId)当前激活的引擎。支持多标签页同时跑不同引擎 + 零重启热切。 */
@@ -1086,10 +1088,14 @@ const heartbeatTimer = setInterval(() => {
1086
1088
  // Unref'd so it never blocks exit: heartbeat alone must not hold the event loop open.
1087
1089
  heartbeatTimer.unref?.();
1088
1090
  // 引擎分发:PI_WEB_ENGINE=dsh 时使用 DeepSeek Harness 引擎(server/dsh/),
1091
+ // PI_WEB_ENGINE=claude 时使用通用底座下的 Claude Code 驱动(server/universal/),
1089
1092
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
1090
1093
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
1094
+ import { UniversalAgentService, ClaudeCodeDriver, probeClaudeCode } from "./universal/index.js";
1095
+ import { probeAllEngines, probeEngine, getCachedEngineStatuses } from "./engine-probe.js";
1091
1096
  let piServiceInstance = null;
1092
1097
  let dshServiceInstance = null;
1098
+ let claudeServiceInstance = null;
1093
1099
  let wireEngineHooks = null;
1094
1100
  let sharedSocketCount = 0;
1095
1101
  let sharedQuiesced = false;
@@ -1099,9 +1105,28 @@ function activeEngines() {
1099
1105
  list.push(piServiceInstance);
1100
1106
  if (dshServiceInstance)
1101
1107
  list.push(dshServiceInstance);
1108
+ if (claudeServiceInstance)
1109
+ list.push(claudeServiceInstance);
1102
1110
  return list;
1103
1111
  }
1104
1112
  function ensureEngine(engine) {
1113
+ if (engine === "claude") {
1114
+ if (!claudeServiceInstance) {
1115
+ claudeServiceInstance = new UniversalAgentService({
1116
+ cwd: CWD,
1117
+ dataDir: DATA_DIR,
1118
+ agentDir: getAgentDir(),
1119
+ stateStore: sharedStateStore,
1120
+ driverFactory: (cwd) => new ClaudeCodeDriver(cwd, { agentDir: getAgentDir() }),
1121
+ });
1122
+ for (let i = 0; i < sharedSocketCount; i++)
1123
+ claudeServiceInstance.noteSocketOpen();
1124
+ if (sharedQuiesced)
1125
+ claudeServiceInstance.quiesce();
1126
+ wireEngineHooks?.(claudeServiceInstance);
1127
+ }
1128
+ return claudeServiceInstance;
1129
+ }
1105
1130
  if (engine === "dsh") {
1106
1131
  if (!dshServiceInstance) {
1107
1132
  dshServiceInstance = new DshAgentService(CWD, sharedStateStore, DATA_DIR, getAgentDir());
@@ -1566,11 +1591,12 @@ function pushNoticeToAll(level, text, textEn) {
1566
1591
  }
1567
1592
  }
1568
1593
  }
1569
- // MCP 工具桥:读取配置启动外部 MCP 服务器(stdio),把它们的
1594
+ // MCP 工具桥:读取配置启动外部 MCP 服务器(stdio / HTTP streamable-http),把它们的
1570
1595
  // 工具并入与插件工具相同的 customTools 管线;单服务器失败不炸进程。
1571
1596
  const mcpBridge = new McpBridge(DATA_DIR, (...a) => console.log("[mcp]", ...a), {
1572
1597
  agentDir: getAgentDir(),
1573
1598
  cwd: CWD,
1599
+ onToolsChanged: () => service.applyPluginAgentTools(),
1574
1600
  });
1575
1601
  ClientSession.mcpBridge = mcpBridge;
1576
1602
  pluginMgr.mcpBridge = mcpBridge;
@@ -1905,11 +1931,133 @@ wss.on("connection", (ws) => {
1905
1931
  })
1906
1932
  .catch(() => { });
1907
1933
  };
1934
+ const handleSwitchEngine = async (msg) => {
1935
+ const targetEngine = msg.engine === "claude" ? "claude" : msg.engine === "dsh" ? "dsh" : msg.engine === "pi" ? "pi" : null;
1936
+ if (!targetEngine) {
1937
+ send({
1938
+ type: "notice",
1939
+ level: "error",
1940
+ text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh / claude)`,
1941
+ textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh, claude)`,
1942
+ });
1943
+ return;
1944
+ }
1945
+ if (!clientId)
1946
+ return;
1947
+ // 闸门:非 pi 引擎需确认宿主环境中已安装对应的全局包/运行时,未安装时拒绝切换
1948
+ if (targetEngine !== "pi") {
1949
+ const probe = await probeEngine(targetEngine);
1950
+ if (!probe.installed) {
1951
+ send({
1952
+ type: "notice",
1953
+ level: "warning",
1954
+ text: `引擎 ${targetEngine.toUpperCase()} 尚未安装全局包(${probe.packageName ?? targetEngine}),请先安装后再切换`,
1955
+ textEn: `Engine ${targetEngine.toUpperCase()} global package (${probe.packageName ?? targetEngine}) is not installed; please install it before switching`,
1956
+ });
1957
+ return;
1958
+ }
1959
+ }
1960
+ const prevEngine = resolveClientEngine(clientId);
1961
+ if (prevEngine === targetEngine) {
1962
+ setClientEngine(clientId, targetEngine);
1963
+ return;
1964
+ }
1965
+ // 从旧引擎解绑当前 socket 的推送
1966
+ try {
1967
+ ensureEngine(prevEngine).detach(clientId, send);
1968
+ }
1969
+ catch {
1970
+ /* best effort */
1971
+ }
1972
+ setClientEngine(clientId, targetEngine);
1973
+ attachDone = false;
1974
+ if (!closed) {
1975
+ send(readyMsg(clientId));
1976
+ }
1977
+ const cid = clientId;
1978
+ const nextSvc = ensureEngine(targetEngine);
1979
+ nextSvc
1980
+ .attach(cid, send)
1981
+ .then((newCs) => {
1982
+ if (closed) {
1983
+ nextSvc.detach(cid, send);
1984
+ return;
1985
+ }
1986
+ nextSvc.applyPluginCommandCatalog();
1987
+ newCs.flushSnapshot(true);
1988
+ newCs.pushSettings();
1989
+ void newCs.refreshSessions();
1990
+ void newCs.pushProjects();
1991
+ void newCs.listModels();
1992
+ // 切换引擎后重新广播插件状态与面板项,确保跨引擎切换时自定义布局与插件图标完全一致
1993
+ pluginMgr
1994
+ .ensureLoaded(() => newCs.getLang())
1995
+ .then((plugins) => {
1996
+ if (closed)
1997
+ return;
1998
+ send({ type: "plugins", plugins, epoch: pluginMgr.epoch });
1999
+ send({ type: "plugin_panel_items", groups: pluginMgr.panelGroups() });
2000
+ })
2001
+ .catch(() => { });
2002
+ attachDone = true;
2003
+ for (const m of pending.drain())
2004
+ dispatch(m);
2005
+ if (targetEngine === "claude") {
2006
+ void probeClaudeCode().then((probe) => {
2007
+ if (!probe.installed) {
2008
+ newCs.emitNotice("warning", "已热切换至 Claude Code 引擎。检测到未安装 Claude Code CLI,请在终端执行 npm i -g @anthropic-ai/claude-code 安装并运行 claude 完成登录。", "Switched to Claude Code engine. Claude Code CLI not found; run: npm i -g @anthropic-ai/claude-code and log in with claude.");
2009
+ }
2010
+ else {
2011
+ newCs.emitNotice("info", "已热切换至 Claude Code 引擎(已连接本地 CLI 登录态,无需在页面配置 API Key)", "Switched to Claude Code engine (connected to local CLI login session, no API Key needed)");
2012
+ }
2013
+ });
2014
+ }
2015
+ else if (targetEngine === "dsh") {
2016
+ newCs.emitNotice("info", "已热切换至 DSH 引擎(其他引擎后台会话保持运行,可随时切回)", "Switched to DSH engine in-place (other background conversations keep running)");
2017
+ }
2018
+ else {
2019
+ newCs.emitNotice("info", "已热切换至 pi 引擎(其他引擎后台会话保持运行,可随时切回)", "Switched to pi engine in-place (other background conversations keep running)");
2020
+ }
2021
+ })
2022
+ .catch((err) => {
2023
+ // 切换失败时事务回滚:原样切回 prevEngine,避免状态悬挂
2024
+ setClientEngine(cid, prevEngine);
2025
+ ensureEngine(prevEngine)
2026
+ .attach(cid, send)
2027
+ .then((rollbackCs) => {
2028
+ rollbackCs.flushSnapshot(true);
2029
+ attachDone = true;
2030
+ for (const m of pending.drain())
2031
+ dispatch(m);
2032
+ })
2033
+ .catch(() => {
2034
+ attachDone = true;
2035
+ });
2036
+ send({
2037
+ type: "notice",
2038
+ level: "error",
2039
+ text: `切换引擎失败,已恢复至 ${prevEngine} 引擎:${err.message}`,
2040
+ textEn: `Failed to switch engine, rolled back to ${prevEngine}: ${err.message}`,
2041
+ });
2042
+ });
2043
+ };
1908
2044
  const dispatch = (msg) => {
1909
2045
  if (!clientId) {
1910
2046
  pending.push(msg);
1911
2047
  return;
1912
2048
  }
2049
+ // switch_engine 为宿主级控制消息:豁免 cs 初始化与 attachDone 门禁,确保任何异常状态下都能自由切回!
2050
+ if (msg.type === "switch_engine") {
2051
+ void handleSwitchEngine(msg);
2052
+ return;
2053
+ }
2054
+ if (msg.type === "check_engines") {
2055
+ void probeAllEngines(msg.force).then((engines) => {
2056
+ if (!closed)
2057
+ send({ type: "engines_status", engines });
2058
+ });
2059
+ return;
2060
+ }
1913
2061
  const cs = service.get(clientId);
1914
2062
  if (!cs || !attachDone) {
1915
2063
  // Session not ready yet (hello processing / plugin chain) — hold the command.
@@ -2066,6 +2214,10 @@ wss.on("connection", (ws) => {
2066
2214
  break;
2067
2215
  case "check_updates_all":
2068
2216
  void cs.checkUpdatesAll(msg.force === true);
2217
+ void probeAllEngines(true).then((engines) => {
2218
+ if (!closed)
2219
+ send({ type: "engines_status", engines });
2220
+ });
2069
2221
  break;
2070
2222
  case "check_plugin_updates":
2071
2223
  if (typeof cs.checkPluginUpdates === "function") {
@@ -2105,64 +2257,6 @@ wss.on("connection", (ws) => {
2105
2257
  setTimeout(() => void scheduleQuit(), 400);
2106
2258
  break;
2107
2259
  }
2108
- case "switch_engine": {
2109
- const targetEngine = msg.engine === "dsh" ? "dsh" : msg.engine === "pi" ? "pi" : null;
2110
- if (!targetEngine) {
2111
- send({
2112
- type: "notice",
2113
- level: "error",
2114
- text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh)`,
2115
- textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh)`,
2116
- });
2117
- break;
2118
- }
2119
- const prevEngine = resolveClientEngine(clientId);
2120
- if (prevEngine === targetEngine) {
2121
- setClientEngine(clientId, targetEngine);
2122
- break;
2123
- }
2124
- // 从旧引擎解绑当前 socket 的推送(不中止旧引擎后台正在运行的会话)
2125
- ensureEngine(prevEngine).detach(clientId, send);
2126
- setClientEngine(clientId, targetEngine);
2127
- attachDone = false;
2128
- if (!closed) {
2129
- send(readyMsg(clientId));
2130
- }
2131
- const cid = clientId;
2132
- const nextSvc = ensureEngine(targetEngine);
2133
- nextSvc
2134
- .attach(cid, send)
2135
- .then((newCs) => {
2136
- if (closed) {
2137
- nextSvc.detach(cid, send);
2138
- return;
2139
- }
2140
- nextSvc.applyPluginCommandCatalog();
2141
- newCs.flushSnapshot(true);
2142
- newCs.pushSettings();
2143
- void newCs.refreshSessions();
2144
- void newCs.pushProjects();
2145
- attachDone = true;
2146
- for (const m of pending.drain())
2147
- dispatch(m);
2148
- newCs.emitNotice("info", targetEngine === "dsh"
2149
- ? "已热切换至 DSH 引擎(pi 引擎后台会话保持运行,可随时切回)"
2150
- : "已热切换至 pi 引擎(DSH 引擎后台会话保持运行,可随时切回)", targetEngine === "dsh"
2151
- ? "Switched to DSH engine in-place (pi background conversations keep running)"
2152
- : "Switched to pi engine in-place (DSH background conversations keep running)");
2153
- })
2154
- .catch((err) => {
2155
- pending.clear();
2156
- attachDone = true;
2157
- send({
2158
- type: "notice",
2159
- level: "error",
2160
- text: `切换引擎失败:${err.message}`,
2161
- textEn: `Failed to switch engine: ${err.message}`,
2162
- });
2163
- });
2164
- break;
2165
- }
2166
2260
  default: {
2167
2261
  // 未知 type 只计数 + 节流 warn,不改变已知类型行为。
2168
2262
  // default 分支里 msg 已收窄成 never,type 需从宽化后取。
@@ -2194,6 +2288,7 @@ wss.on("connection", (ws) => {
2194
2288
  serverVersion: VERSION,
2195
2289
  protocolVersion: PROTOCOL_VERSION,
2196
2290
  engine: resolveClientEngine(cid),
2291
+ engineCapabilities: ensureEngine(resolveClientEngine(cid)).getCapabilities?.(),
2197
2292
  // This package's own version. `serverVersion` is the pi SDK's,
2198
2293
  // and the client used to learn ours from the update check —
2199
2294
  // which a managed instance never runs.
@@ -2202,6 +2297,7 @@ wss.on("connection", (ws) => {
2202
2297
  managed: MANAGED,
2203
2298
  tabs: TABS ? [...TABS] : undefined,
2204
2299
  service: SERVICE_INFO ?? undefined,
2300
+ engines: getCachedEngineStatuses(),
2205
2301
  });
2206
2302
  ws.on("message", (data) => {
2207
2303
  tracked.isAlive = true;
@@ -2228,11 +2324,20 @@ wss.on("connection", (ws) => {
2228
2324
  // saveUpload 的两条路径都从这里来,入口统一拦一次即可)。
2229
2325
  const cid = validateClientId(msg.clientId) ?? randomUUID();
2230
2326
  clientId = cid;
2327
+ if (msg.locale) {
2328
+ const code = msg.locale.trim().slice(0, 16);
2329
+ if (code)
2330
+ sharedStateStore.saveLocale(cid, code);
2331
+ }
2231
2332
  // issue #295:ready 先行 —— 传输握手不等待会话初始化。attach 会进 SDK 的
2232
2333
  // resourceLoader.reload 等同步目录扫描,坏挂载/家目录下可能阻塞数十秒;
2233
2334
  // ready 在握手里先发,前端立刻离开「正在连接」(快照随后到)。
2234
2335
  if (!closed) {
2235
2336
  send(readyMsg(cid));
2337
+ void probeAllEngines().then((engines) => {
2338
+ if (!closed)
2339
+ send({ type: "engines_status", engines });
2340
+ });
2236
2341
  }
2237
2342
  // attach 慢提示:本体继续等,不取消;完成后照常走快照流程。
2238
2343
  const slowTimer = setTimeout(() => {
@@ -27,6 +27,7 @@ export const LOCALE_PACKS = [
27
27
  { code: "ko", nativeName: "한국어" },
28
28
  { code: "pt", nativeName: "Português" },
29
29
  { code: "ru", nativeName: "Русский" },
30
+ { code: "tr", nativeName: "Türkçe" },
30
31
  // Traditional Chinese packs. Core "zh" is Simplified; generated from it
31
32
  // by OpenCC + glossaries (scripts/zh-tw-locale).
32
33
  { code: "zh-Hant", nativeName: "繁體中文" },
@@ -90,10 +90,10 @@ export function makeMcpManageTool(host, lang) {
90
90
  if (action === "list") {
91
91
  const { servers, globalPath, projectPath } = host.listServers();
92
92
  if (servers.length === 0) {
93
- return reply(pick(L, `当前未配置任何 MCP 服务器。\n项目配置:${projectPath}\n全局配置:${globalPath}`, `No MCP servers configured.\nProject config: ${projectPath}\nGlobal config: ${globalPath}`, "mcp_manage.list.empty"), { count: 0 });
93
+ return reply(pick(L, `当前未配置任何 MCP 服务器。\n项目配置:${projectPath}\n全局配置:${globalPath}`, `No MCP servers configured.\nProject config: ${projectPath}\nGlobal config: ${globalPath}`, "mcp_manage.list.empty", { projectPath, globalPath }), { count: 0 });
94
94
  }
95
95
  const lines = servers.map(formatServerLine).join("\n");
96
- return reply(pick(L, `已配置的 MCP 服务器(${servers.length}):\n${lines}`, `Configured MCP servers (${servers.length}):\n${lines}`, "mcp_manage.list.ok", { count: servers.length }), { count: servers.length, servers: servers.map((s) => ({ name: s.name, scope: s.scope, status: s.status })) });
96
+ return reply(pick(L, `已配置的 MCP 服务器(${servers.length}):\n${lines}`, `Configured MCP servers (${servers.length}):\n${lines}`, "mcp_manage.list.ok", { count: servers.length, lines }), { count: servers.length, servers: servers.map((s) => ({ name: s.name, scope: s.scope, status: s.status })) });
97
97
  }
98
98
  if (action === "check") {
99
99
  const q = (params.query ?? params.name ?? params.package ?? "").trim();
@@ -105,7 +105,7 @@ export function makeMcpManageTool(host, lang) {
105
105
  return reply(pick(L, `未找到匹配「${q}」的 MCP 服务器(installed=false)。可使用 action="install" 安装。`, `No MCP server matching "${q}" is installed (installed=false). Use action="install" to install it.`, "mcp_manage.check.not_installed", { query: q }), { query: q, installed: false, running: false });
106
106
  }
107
107
  const lines = res.matches.map(formatServerLine).join("\n");
108
- return reply(pick(L, `已找到匹配「${q}」的 MCP 服务器(installed=true, running=${res.running}):\n${lines}`, `Found MCP server matching "${q}" (installed=true, running=${res.running}):\n${lines}`, "mcp_manage.check.found", { query: q }), {
108
+ return reply(pick(L, `已找到匹配「${q}」的 MCP 服务器(installed=true, running=${res.running}):\n${lines}`, `Found MCP server matching "${q}" (installed=true, running=${res.running}):\n${lines}`, "mcp_manage.check.found", { query: q, running: res.running, lines }), {
109
109
  query: q,
110
110
  installed: true,
111
111
  running: res.running,
@@ -131,15 +131,17 @@ export function makeMcpManageTool(host, lang) {
131
131
  description: params.description,
132
132
  });
133
133
  if (!res.ok) {
134
- return reply(pick(L, `MCP 服务器安装失败:${res.error ?? "未知错误"}`, `Failed to install MCP server: ${res.error ?? "unknown error"}`, "mcp_manage.install.fail"), { ok: false, error: res.error });
134
+ const errorText = res.error ?? (L === "zh" ? "未知错误" : "unknown error");
135
+ return reply(pick(L, `MCP 服务器安装失败:${res.error ?? "未知错误"}`, `Failed to install MCP server: ${res.error ?? "unknown error"}`, "mcp_manage.install.fail", { error: errorText }), { ok: false, error: res.error });
135
136
  }
136
137
  const toolNames = (res.tools ?? []).map((t) => `${res.name}_${t.name}`);
138
+ const toolsJoined = toolNames.join(", ");
137
139
  const toolHint = toolNames.length > 0
138
- ? pick(L, `\n已暴露工具(${toolNames.length}):${toolNames.join(", ")}`, `\nExposed tools (${toolNames.length}): ${toolNames.join(", ")}`, "mcp_manage.install.tools", { count: toolNames.length })
140
+ ? pick(L, `\n已暴露工具(${toolNames.length}):${toolsJoined}`, `\nExposed tools (${toolNames.length}): ${toolsJoined}`, "mcp_manage.install.tools", { count: toolNames.length, tools: toolsJoined })
139
141
  : res.error
140
142
  ? `\n⚠️ ${res.error}`
141
143
  : "";
142
- return reply(pick(L, `已安装 MCP 服务器「${res.name}」(作用域:${res.scope},状态:${res.status})。${toolHint}`, `Installed MCP server "${res.name}" (scope: ${res.scope}, status: ${res.status}).${toolHint}`, "mcp_manage.install.ok", { name: res.name ?? "", scope: res.scope ?? "project", status: res.status ?? "stopped" }), {
144
+ return reply(pick(L, `已安装 MCP 服务器「${res.name}」(作用域:${res.scope},状态:${res.status})。${toolHint}`, `Installed MCP server "${res.name}" (scope: ${res.scope}, status: ${res.status}).${toolHint}`, "mcp_manage.install.ok", { name: res.name ?? "", scope: res.scope ?? "project", status: res.status ?? "stopped", toolHint }), {
143
145
  ok: true,
144
146
  name: res.name,
145
147
  scope: res.scope,
@@ -155,7 +157,8 @@ export function makeMcpManageTool(host, lang) {
155
157
  }
156
158
  const res = await host.removeServer(name, params.scope);
157
159
  if (!res.ok) {
158
- return reply(pick(L, `移除 MCP 服务器「${name}」失败:${res.error ?? "不存在"}`, `Failed to remove MCP server "${name}": ${res.error ?? "not found"}`, "mcp_manage.remove.fail", { name }), { ok: false, name, error: res.error });
160
+ const errorText = res.error ?? (L === "zh" ? "不存在" : "not found");
161
+ return reply(pick(L, `移除 MCP 服务器「${name}」失败:${res.error ?? "不存在"}`, `Failed to remove MCP server "${name}": ${res.error ?? "not found"}`, "mcp_manage.remove.fail", { name, error: errorText }), { ok: false, name, error: res.error });
159
162
  }
160
163
  return reply(pick(L, `已移除 MCP 服务器「${name}」并同步工具列表。`, `Removed MCP server "${name}" and synced tools.`, "mcp_manage.remove.ok", { name }), { ok: true, name });
161
164
  }