pi-web-ui 0.104.4 → 0.105.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 (52) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +2 -2
  4. package/bin/pi-web-ui.mjs +9 -3
  5. package/dist/server/agent-service-daemon.js +7 -7
  6. package/dist/server/agent-service.js +497 -109
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +29 -0
  9. package/dist/server/dispatch-domain-handlers.js +35 -7
  10. package/dist/server/dsh/dsh-agent-service.js +88 -33
  11. package/dist/server/dsh/dsh-serialize.js +16 -1
  12. package/dist/server/ensure-bash.js +7 -2
  13. package/dist/server/file-transfer-routes.js +114 -1
  14. package/dist/server/index.js +347 -68
  15. package/dist/server/load-tools-tool.js +2 -1
  16. package/dist/server/locales.js +5 -0
  17. package/dist/server/markers/marker.js +28 -0
  18. package/dist/server/mcp-bridge.js +20 -6
  19. package/dist/server/pkg-info.js +69 -0
  20. package/dist/server/plugin-facilities.js +18 -9
  21. package/dist/server/plugin-manifest-validate.js +3 -0
  22. package/dist/server/plugin-updater.js +11 -5
  23. package/dist/server/plugins.js +3 -12
  24. package/dist/server/present-files-tool.js +47 -1
  25. package/dist/server/preset-fields.js +14 -0
  26. package/dist/server/preset-share.js +5 -12
  27. package/dist/server/prompt-composer.js +1 -1
  28. package/dist/server/remote-ssh-service.js +158 -5
  29. package/dist/server/serialize.js +15 -4
  30. package/dist/server/session-parser.js +138 -2
  31. package/dist/server/settings-service.js +19 -0
  32. package/dist/server/terminals.js +7 -1
  33. package/dist/server/text-quote.js +64 -2
  34. package/dist/server/tool-manager.js +10 -0
  35. package/dist/server/tool-prompts.js +1 -0
  36. package/dist/server/update-check.js +98 -24
  37. package/dist/server/workspace-snapshot.js +251 -13
  38. package/dist/server/worktree-service.js +262 -0
  39. package/dist/server/worktree-tool.js +173 -0
  40. package/package.json +3 -1
  41. package/plugin-sdk/index.d.ts +14 -1
  42. package/themes/zhujian-dark.css +16 -4
  43. package/themes/zhujian.css +16 -4
  44. package/themes/zhupi-dark.css +16 -4
  45. package/themes/zhupi.css +16 -4
  46. package/web/dist/assets/{TerminalPanel-B7x99tkg.js → TerminalPanel-B9exeXrl.js} +1 -1
  47. package/web/dist/assets/index-BQC6lADz.css +1 -0
  48. package/web/dist/assets/index-D79IKG33.js +690 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-DOrLcjLY.js +0 -680
  52. package/web/dist/assets/index-_H2BS7OX.css +0 -1
@@ -34,6 +34,7 @@ import { VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
34
34
  import { sdkCopies, sdkOriginNote } from "./sdk-origin.js";
35
35
  import { PROTOCOL_VERSION } from "./protocol-version.js";
36
36
  import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
37
+ import { ClientStateStore } from "./client-state.js";
37
38
  import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
38
39
  import { httpHostAllowed } from "./host-guard.js";
39
40
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
@@ -60,8 +61,9 @@ import { SchedulerStore, SchedulerValidationError } from "./scheduler-tasks.js";
60
61
  import { initHttpProxy } from "./http-proxy.js";
61
62
  import { globalLspPool } from "./lsp-tool.js";
62
63
  import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
64
+ import { getAppVersion, getPkgRoot } from "./pkg-info.js";
63
65
  import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, handleRemoteSshMessage, } from "./dispatch-domain-handlers.js";
64
- import { RemoteSshService, setGlobalRemoteSshService } from "./remote-ssh-service.js";
66
+ import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
65
67
  import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
66
68
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
67
69
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
@@ -113,6 +115,12 @@ try {
113
115
  catch (err) {
114
116
  console.warn(`[data] 无法创建数据目录 ${DATA_DIR}: ${err.message}`);
115
117
  }
118
+ try {
119
+ mkdirSync(CWD, { recursive: true });
120
+ }
121
+ catch (err) {
122
+ console.warn(`[cwd] 无法创建工作区目录 ${CWD}: ${err.message}`);
123
+ }
116
124
  // issue #295:工作区直接就是家目录时,SDK 初始化期的同步目录扫描会落在 $HOME 上
117
125
  // (iCloud 占位符/外部卷坏挂载 → scandir/open 内核挂起 → 事件循环假死,hello 后无
118
126
  // ready)。新装服务默认已是 ~/pi-web-ui(见 bin/pi-web-ui.mjs serviceOptions);
@@ -172,18 +180,8 @@ const LOCALE_BASE_URL = process.env.PI_WEB_LOCALE_BASE_URL?.trim() || "https://r
172
180
  * and always fell back to `main`. Reading it lazily costs one branch and
173
181
  * gives the real number.
174
182
  */
175
- let appVersionCache = null;
176
183
  function appVersion() {
177
- if (appVersionCache === null) {
178
- try {
179
- const pkg = JSON.parse(readFileSync(join(resolvePkgRoot(), "package.json"), "utf8"));
180
- appVersionCache = pkg.version ?? "";
181
- }
182
- catch {
183
- appVersionCache = "";
184
- }
185
- }
186
- return appVersionCache;
184
+ return getAppVersion();
187
185
  }
188
186
  /** On-disk web-build id: the main JS bundle hash from the built index.html.
189
187
  * Changes on every rebuild — stale pages compare and reload themselves.
@@ -341,8 +339,39 @@ if (AUTH_TOKEN) {
341
339
  : "unauthorized: PI_WEB_TOKEN required (?token=…)");
342
340
  });
343
341
  }
344
- /** 引擎选择:--engine pi|dsh > PI_WEB_ENGINE > 默认 pi。重启生效。 */
345
- const ENGINE = (cliFlag("--engine") ?? process.env.PI_WEB_ENGINE) === "dsh" ? "dsh" : "pi";
342
+ /** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
343
+ const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
344
+ /** 启动参数显式指定的引擎(--engine pi|dsh 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
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");
351
+ /** 默认引擎标识(兼容 /api/health 等读取)。 */
352
+ const ENGINE = currentDefaultEngine;
353
+ /** 每个客户端(浏览器标签页 clientId)当前激活的引擎。支持多标签页同时跑不同引擎 + 零重启热切。 */
354
+ const clientEngines = new Map();
355
+ function resolveClientEngine(clientId) {
356
+ const mem = clientEngines.get(clientId);
357
+ if (mem)
358
+ return mem;
359
+ if (!EXPLICIT_ENGINE_ARG) {
360
+ const saved = sharedStateStore.getClientEngine(clientId);
361
+ if (saved) {
362
+ clientEngines.set(clientId, saved);
363
+ return saved;
364
+ }
365
+ }
366
+ clientEngines.set(clientId, currentDefaultEngine);
367
+ return currentDefaultEngine;
368
+ }
369
+ function setClientEngine(clientId, engine) {
370
+ clientEngines.set(clientId, engine);
371
+ currentDefaultEngine = engine;
372
+ sharedStateStore.saveClientEngine(clientId, engine);
373
+ sharedStateStore.saveDefaultEngine(engine);
374
+ }
346
375
  /** PI_WEB_MANAGED=1: this instance is updated by whoever deploys it. */
347
376
  const MANAGED = isManaged();
348
377
  /** Who started this process: a platform service manager (launchd / systemd /
@@ -364,7 +393,7 @@ app.get("/api/health", (_req, res) => {
364
393
  // issue #260:服务实际加载的是自带副本,不是全局 pi CLI 那份。这里把两份都报出来,
365
394
  // 用户就不用猜「为什么升了全局 SDK 不生效」。(纯新增字段,piVersion 语义不变。)
366
395
  piSdkCopies: sdkCopies(),
367
- engine: ENGINE,
396
+ engine: currentDefaultEngine,
368
397
  });
369
398
  });
370
399
  /**
@@ -420,6 +449,10 @@ app.get("/api/file", async (req, res) => {
420
449
  const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
421
450
  const cs = cid ? service.get(cid) : undefined;
422
451
  const root = cs?.cwd ?? CWD;
452
+ if (isRemoteWorkspaceUri(root)) {
453
+ await serveRemoteWorkspaceFile(req, res, root, raw, { isDownload: req.query.download === "1", allowAllTypes: false }, remoteSshService);
454
+ return;
455
+ }
423
456
  const absWire = isAbsoluteWirePath(raw);
424
457
  let abs;
425
458
  if (absWire) {
@@ -513,6 +546,19 @@ app.get("/api/preview/*splat", async (req, res) => {
513
546
  const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
514
547
  const cs = cid ? service.get(cid) : undefined;
515
548
  const root = cs?.cwd ?? CWD;
549
+ if (isRemoteWorkspaceUri(root)) {
550
+ if (captured === "__abs__") {
551
+ res.status(400).end("bad absolute preview path");
552
+ return;
553
+ }
554
+ const remoteTarget = captured.startsWith(ABS_MARKER) ? captured.slice(ABS_MARKER.length) : captured;
555
+ if (captured.startsWith(ABS_MARKER) && !remoteTarget.startsWith("/")) {
556
+ res.status(400).end("bad absolute preview path");
557
+ return;
558
+ }
559
+ await serveRemoteWorkspaceFile(req, res, root, remoteTarget, { isDownload: false, allowAllTypes: true }, remoteSshService);
560
+ return;
561
+ }
516
562
  // Express decodes %XX in the wildcard, so this is back to the wire
517
563
  // form (filenames never contain "/", so per-segment encoding from
518
564
  // the client round-trips exactly).
@@ -563,15 +609,7 @@ const here = dirname(fileURLToPath(import.meta.url)); // <pkg>/dist/server or <p
563
609
  // Resolve the package root robustly: dev runs from <repo>/server (tsx), prod
564
610
  // from <pkg>/dist/server — the ancestor that actually has package.json wins.
565
611
  function resolvePkgRoot() {
566
- // 可选:显式指定 pkgRoot(如部署在自定义目录时),否则按候选路径探测。
567
- if (process.env.PI_WEB_PKG_ROOT)
568
- return process.env.PI_WEB_PKG_ROOT;
569
- const candidates = [resolve(here, ".."), resolve(here, "..", ".."), resolve(here, "..", "..", "..")];
570
- for (const c of candidates) {
571
- if (existsSync(join(c, "package.json")))
572
- return c;
573
- }
574
- return candidates[0];
612
+ return getPkgRoot();
575
613
  }
576
614
  const pkgRoot = resolvePkgRoot();
577
615
  // Theme CSS files: complete standalone stylesheets. Builtin themes ship in
@@ -1017,7 +1055,9 @@ const heartbeatTimer = setInterval(() => {
1017
1055
  else {
1018
1056
  tracked.missedPings = 0;
1019
1057
  }
1058
+ const prevLatencyMs = tracked.latencyMs;
1020
1059
  tracked.isAlive = false;
1060
+ tracked.pingSentAt = performance.now();
1021
1061
  try {
1022
1062
  ws.ping();
1023
1063
  }
@@ -1031,7 +1071,12 @@ const heartbeatTimer = setInterval(() => {
1031
1071
  // 广播背压:缓冲积压严重时跳过心跳推送
1032
1072
  if (ws.bufferedAmount <= BROADCAST_BACKPRESSURE_MAX_BYTES) {
1033
1073
  try {
1034
- ws.send(payload);
1074
+ if (typeof prevLatencyMs === "number" && Number.isFinite(prevLatencyMs)) {
1075
+ ws.send(JSON.stringify({ ...message, latencyMs: prevLatencyMs }));
1076
+ }
1077
+ else {
1078
+ ws.send(payload);
1079
+ }
1035
1080
  }
1036
1081
  catch { }
1037
1082
  }
@@ -1043,11 +1088,183 @@ heartbeatTimer.unref?.();
1043
1088
  // 引擎分发:PI_WEB_ENGINE=dsh 时使用 DeepSeek Harness 引擎(server/dsh/),
1044
1089
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
1045
1090
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
1046
- const service = ENGINE === "dsh"
1047
- ? new DshAgentService(CWD, join(DATA_DIR, "client-state.json"), DATA_DIR, getAgentDir())
1048
- : new AgentService(CWD,
1049
- // Per-client persisted UI state: last-used workspace + recent projects.
1050
- join(DATA_DIR, "client-state.json"));
1091
+ let piServiceInstance = null;
1092
+ let dshServiceInstance = null;
1093
+ let wireEngineHooks = null;
1094
+ let sharedSocketCount = 0;
1095
+ let sharedQuiesced = false;
1096
+ function activeEngines() {
1097
+ const list = [];
1098
+ if (piServiceInstance)
1099
+ list.push(piServiceInstance);
1100
+ if (dshServiceInstance)
1101
+ list.push(dshServiceInstance);
1102
+ return list;
1103
+ }
1104
+ function ensureEngine(engine) {
1105
+ if (engine === "dsh") {
1106
+ if (!dshServiceInstance) {
1107
+ dshServiceInstance = new DshAgentService(CWD, sharedStateStore, DATA_DIR, getAgentDir());
1108
+ for (let i = 0; i < sharedSocketCount; i++)
1109
+ dshServiceInstance.noteSocketOpen();
1110
+ if (sharedQuiesced)
1111
+ dshServiceInstance.quiesce();
1112
+ wireEngineHooks?.(dshServiceInstance);
1113
+ }
1114
+ return dshServiceInstance;
1115
+ }
1116
+ if (!piServiceInstance) {
1117
+ piServiceInstance = new AgentService(CWD, sharedStateStore);
1118
+ for (let i = 0; i < sharedSocketCount; i++)
1119
+ piServiceInstance.noteSocketOpen();
1120
+ if (sharedQuiesced)
1121
+ piServiceInstance.quiesce();
1122
+ wireEngineHooks?.(piServiceInstance);
1123
+ }
1124
+ return piServiceInstance;
1125
+ }
1126
+ // 启动时预热默认引擎实例
1127
+ ensureEngine(currentDefaultEngine);
1128
+ const service = {
1129
+ attach(clientId, send) {
1130
+ return ensureEngine(resolveClientEngine(clientId)).attach(clientId, send);
1131
+ },
1132
+ detach(clientId, send) {
1133
+ const eng = clientEngines.get(clientId);
1134
+ if (eng) {
1135
+ ensureEngine(eng).detach(clientId, send);
1136
+ }
1137
+ else {
1138
+ for (const s of activeEngines())
1139
+ s.detach(clientId, send);
1140
+ }
1141
+ },
1142
+ get(clientId) {
1143
+ if (!clientId)
1144
+ return undefined;
1145
+ const eng = clientEngines.get(clientId);
1146
+ if (eng)
1147
+ return ensureEngine(eng).get(clientId);
1148
+ for (const s of activeEngines()) {
1149
+ const cs = s.get(clientId);
1150
+ if (cs)
1151
+ return cs;
1152
+ }
1153
+ return undefined;
1154
+ },
1155
+ async disposeAll() {
1156
+ await Promise.all(activeEngines().map((s) => s.disposeAll()));
1157
+ },
1158
+ recordInterruptedRuns() {
1159
+ for (const s of activeEngines())
1160
+ s.recordInterruptedRuns();
1161
+ },
1162
+ noteSocketOpen() {
1163
+ sharedSocketCount++;
1164
+ for (const s of activeEngines())
1165
+ s.noteSocketOpen();
1166
+ },
1167
+ noteSocketClose() {
1168
+ sharedSocketCount = Math.max(0, sharedSocketCount - 1);
1169
+ for (const s of activeEngines())
1170
+ s.noteSocketClose();
1171
+ },
1172
+ isQuiesced() {
1173
+ return sharedQuiesced || activeEngines().some((s) => s.isQuiesced());
1174
+ },
1175
+ quiesce() {
1176
+ sharedQuiesced = true;
1177
+ for (const s of activeEngines())
1178
+ s.quiesce();
1179
+ },
1180
+ unquiesce() {
1181
+ sharedQuiesced = false;
1182
+ for (const s of activeEngines())
1183
+ s.unquiesce();
1184
+ },
1185
+ quiesceInfo() {
1186
+ for (const s of activeEngines()) {
1187
+ const info = s.quiesceInfo();
1188
+ if (info.quiesced)
1189
+ return info;
1190
+ }
1191
+ return { quiesced: false };
1192
+ },
1193
+ serviceStatus() {
1194
+ const primary = ensureEngine(currentDefaultEngine);
1195
+ const base = primary.serviceStatus();
1196
+ let active = 0;
1197
+ let pending = 0;
1198
+ for (const s of activeEngines()) {
1199
+ active += s.activeConversations();
1200
+ pending += s.pendingMessages();
1201
+ }
1202
+ return {
1203
+ ...base,
1204
+ activeConversations: active,
1205
+ pendingMessages: pending,
1206
+ };
1207
+ },
1208
+ activeConversations() {
1209
+ let n = 0;
1210
+ for (const s of activeEngines())
1211
+ n += s.activeConversations();
1212
+ return n;
1213
+ },
1214
+ pendingMessages() {
1215
+ let n = 0;
1216
+ for (const s of activeEngines())
1217
+ n += s.pendingMessages();
1218
+ return n;
1219
+ },
1220
+ applyPluginAgentTools() {
1221
+ for (const s of activeEngines())
1222
+ s.applyPluginAgentTools();
1223
+ },
1224
+ applyPluginCommandCatalog() {
1225
+ for (const s of activeEngines())
1226
+ s.applyPluginCommandCatalog();
1227
+ },
1228
+ refreshBackgroundServers() {
1229
+ for (const s of activeEngines())
1230
+ s.refreshBackgroundServers();
1231
+ },
1232
+ setLocale(clientId, locale) {
1233
+ return ensureEngine(resolveClientEngine(clientId)).setLocale(clientId, locale);
1234
+ },
1235
+ takeOverConversation(targetId, ownerId, convId) {
1236
+ const targetSvc = ensureEngine(resolveClientEngine(targetId));
1237
+ if (typeof targetSvc.takeOverConversation === "function") {
1238
+ return targetSvc.takeOverConversation(targetId, ownerId, convId);
1239
+ }
1240
+ return Promise.resolve();
1241
+ },
1242
+ peekElsewhereQuestion(targetId, ownerId, convId) {
1243
+ const targetSvc = ensureEngine(resolveClientEngine(targetId));
1244
+ if (typeof targetSvc.peekElsewhereQuestion === "function") {
1245
+ return targetSvc.peekElsewhereQuestion(targetId, ownerId, convId);
1246
+ }
1247
+ return Promise.resolve();
1248
+ },
1249
+ answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled) {
1250
+ const targetSvc = ensureEngine(resolveClientEngine(targetId));
1251
+ if (typeof targetSvc.answerElsewhereQuestion === "function") {
1252
+ return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled);
1253
+ }
1254
+ return Promise.resolve();
1255
+ },
1256
+ readConversationForPlugins(options) {
1257
+ if (options?.clientId) {
1258
+ const eng = resolveClientEngine(options.clientId);
1259
+ return ensureEngine(eng).readConversationForPlugins?.(options) ?? null;
1260
+ }
1261
+ return piServiceInstance?.readConversationForPlugins?.(options) ?? null;
1262
+ },
1263
+ chatFromPlugin(pluginId, req) {
1264
+ const piSvc = ensureEngine("pi");
1265
+ return piSvc.chatFromPlugin(pluginId, req);
1266
+ },
1267
+ };
1051
1268
  // Server-string tables (issue #91 v2): packs' `serverStrings` sections feed
1052
1269
  // pick() lookup for non-zh/en UI languages (missing key → English fallback).
1053
1270
  initAttachmentStore(DATA_DIR);
@@ -1198,7 +1415,7 @@ const scheduler = new SchedulerStore(DATA_DIR, {
1198
1415
  executor: async (task) => {
1199
1416
  let result;
1200
1417
  try {
1201
- const svc = service;
1418
+ const svc = ensureEngine("pi");
1202
1419
  if (typeof svc.chatFromScheduler !== "function" && typeof svc.wakeConversation !== "function") {
1203
1420
  result = { ok: false, error: "当前引擎不支持定时任务(仅标准 pi 引擎)" };
1204
1421
  }
@@ -1302,9 +1519,9 @@ const scheduler = new SchedulerStore(DATA_DIR, {
1302
1519
  // issue #291:任务删除(含单次任务跑完自删)后回收其伪客户端,
1303
1520
  // 否则 scheduler:<taskId> 会话会永久占据其他客户端的 elsewhere 列表。
1304
1521
  onTaskRemoved: (taskId) => {
1305
- const svc = service;
1522
+ const svc = piServiceInstance;
1306
1523
  try {
1307
- svc.releaseSchedulerClient?.(taskId);
1524
+ svc?.releaseSchedulerClient?.(taskId);
1308
1525
  }
1309
1526
  catch {
1310
1527
  // 回收失败不影响任务删除
@@ -1374,43 +1591,44 @@ void mcpBridge.load().then(() => {
1374
1591
  // 播种在 load 之后:否则指纹可能记在 load 读到的版本之前,白重载一次。
1375
1592
  mcpHotReload.start();
1376
1593
  });
1377
- // 插件扩展点:SDK 工具执行事件(bash/读文件等 start+end)转发给已注册的插件。
1378
- service.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
1379
- // 插件扩展点(P1-5):bash/read 执行前后的拦截(pre 拒/问即拦、post 脱敏补上下文;
1380
- // 只覆盖已接管的这两处,DSH 引擎无 customTool 注册面不接)。
1381
- service.toolGuard = {
1382
- pre: (req, lang) => pluginMgr.evaluateToolPre(req, lang),
1383
- post: (req, lang) => pluginMgr.evaluateToolPost(req, lang),
1594
+ // 插件与宿主钩子统一挂载器:无论引擎在启动时预热还是运行期按需懒加载,都一致注入全部回调。
1595
+ wireEngineHooks = (svc) => {
1596
+ svc.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
1597
+ svc.toolGuard = {
1598
+ pre: (req, lang) => pluginMgr.evaluateToolPre(req, lang),
1599
+ post: (req, lang) => pluginMgr.evaluateToolPost(req, lang),
1600
+ };
1601
+ svc.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
1602
+ svc.onConversationChanged = () => pluginMgr.emitConversationChanged();
1603
+ svc.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
1604
+ svc.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
1605
+ svc.pluginCommandsProvider = () => pluginMgr.listCommands();
1606
+ svc.pluginBgTasksProvider = () => pluginMgr.bgTasks();
1607
+ svc.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1608
+ svc.onClientCwdChanged = (cwd, roots) => {
1609
+ pluginMgr.notifyCwd(cwd);
1610
+ pluginMgr.notifyWorkspaceRoots(roots);
1611
+ };
1612
+ svc.onQuit = scheduleQuit;
1613
+ if ("schedulerStore" in svc) {
1614
+ svc.schedulerStore = scheduler;
1615
+ }
1384
1616
  };
1385
- service.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
1386
- // 插件扩展点:对话切换通知(轨迹视图切会话后即重拉;dsh 引擎暂无)。
1387
- service.onConversationChanged = () => pluginMgr.emitConversationChanged();
1617
+ for (const s of activeEngines())
1618
+ wireEngineHooks(s);
1388
1619
  // 插件扩展点:当前打开对话的快照(轨迹视图直接显示打开对话的时间线;
1389
1620
  // dsh 引擎无此方法时回退 null,插件显示空态)。#542:透传 {clientId} 选本标签页的对话。
1390
1621
  pluginMgr.conversationProvider = (opts) => service.readConversationForPlugins?.(opts) ?? null;
1391
- // 插件扩展点:模型切换成功事件(#542;dsh 引擎无此钩子 = 不发事件)。
1392
- service.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
1393
1622
  // 插件扩展点:无头调用 agent(微信通道等经 host.chat 投递外部消息,无浏览器也能跑)。
1394
1623
  pluginMgr.chatProvider = (pluginId, req) => service.chatFromPlugin?.(pluginId, req) ?? Promise.reject(new Error("当前引擎不支持无头调用(仅标准 pi 引擎)"));
1395
- // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
1396
- // 带上 + 变化时动态注入/移除已有会话。
1397
- service.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
1398
1624
  pluginMgr.onAgentToolsChanged = () => {
1399
1625
  service.applyPluginAgentTools();
1400
1626
  void pluginMgr.pushToAll().catch(() => { });
1401
1627
  };
1402
1628
  // 插件扩展点:插件斜杠命令(registerCommand)→ 命令选择器目录 + prompt 拦截执行。
1403
1629
  pluginMgr.onCommandsChanged = () => service.applyPluginCommandCatalog();
1404
- service.pluginCommandsProvider = () => pluginMgr.listCommands();
1405
1630
  // 插件扩展点:插件常驻后台任务(registerBackgroundTask)→ 并入「后台任务」面板。
1406
1631
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1407
- service.pluginBgTasksProvider = () => pluginMgr.bgTasks();
1408
- service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1409
- // 定时任务 Agent 工具的数据源(schedule 单 action:create/list/cancel):标准 pi 引擎的
1410
- // AgentService 才有 schedulerStore 字段,DSH service 没有 —— 有才设。
1411
- if ("schedulerStore" in service) {
1412
- service.schedulerStore = scheduler;
1413
- }
1414
1632
  // ---------------------------------------------------------------------------
1415
1633
  // 插件扩展点 v2(并行任务在 server/plugins.ts 加 host.conversations/prompt/
1416
1634
  // steer/abortRun/chatWait/fs.watch/scm/bash/schedule/models/onStats/onStreaming/
@@ -1426,10 +1644,10 @@ if ("schedulerStore" in service) {
1426
1644
  {
1427
1645
  // SAFETY: This compatibility bridge only assigns optional plugin hooks; consumers test their presence.
1428
1646
  const pm = pluginMgr;
1429
- /** 挑一个客户端会话:标准 pi 引擎走 service.pluginClient(),DSH/未知引擎无此方法即 undefined。 */
1647
+ /** 挑一个客户端会话:标准 pi 引擎走 piServiceInstance.pluginClient(),DSH/未知引擎无此方法即 undefined。 */
1430
1648
  const pickClient = () => {
1431
1649
  try {
1432
- return service instanceof AgentService ? service.pluginClient() : undefined;
1650
+ return piServiceInstance ? piServiceInstance.pluginClient() : undefined;
1433
1651
  }
1434
1652
  catch {
1435
1653
  return undefined;
@@ -1516,7 +1734,7 @@ if ("schedulerStore" in service) {
1516
1734
  pm.llmProvider = async (pluginId, req) => {
1517
1735
  try {
1518
1736
  // SAFETY: Only invoked after the optional method is checked; request fields are narrowed below.
1519
- const svc = service;
1737
+ const svc = ensureEngine("pi");
1520
1738
  if (typeof svc.completeForPlugins !== "function")
1521
1739
  return { ok: false, error: "当前引擎不支持 LLM 直调(仅标准 pi 引擎)" };
1522
1740
  return await svc.completeForPlugins(pluginId, (req ?? {}));
@@ -1526,13 +1744,6 @@ if ("schedulerStore" in service) {
1526
1744
  }
1527
1745
  };
1528
1746
  }
1529
- // 插件宿主工作区实时跟随当前项目:任意客户端 set_cwd 成功后同步给
1530
- // PluginManager,编辑器等工作区跟随型插件随即切根(详见 plugins.ts notifyCwd)。
1531
- service.onClientCwdChanged = (cwd, roots) => {
1532
- pluginMgr.notifyCwd(cwd);
1533
- // 工作区根(宿主侧多根,issue #146):插件宿主的「工作区内」判定要跟着变。
1534
- pluginMgr.notifyWorkspaceRoots(roots);
1535
- };
1536
1747
  // ---------------------------------------------------------------------------
1537
1748
  // Self-update
1538
1749
  // ---------------------------------------------------------------------------
@@ -1601,7 +1812,17 @@ wss.on("connection", (ws) => {
1601
1812
  ws.on("pong", () => {
1602
1813
  tracked.isAlive = true;
1603
1814
  tracked.missedPings = 0;
1815
+ if (typeof tracked.pingSentAt === "number") {
1816
+ tracked.latencyMs = Math.max(0, Math.round(performance.now() - tracked.pingSentAt));
1817
+ }
1604
1818
  });
1819
+ tracked.pingSentAt = performance.now();
1820
+ try {
1821
+ ws.ping();
1822
+ }
1823
+ catch {
1824
+ /* ignore */
1825
+ }
1605
1826
  // Count attached sockets (the control socket reports REAL sockets, not
1606
1827
  // cached client-session objects).
1607
1828
  service.noteSocketOpen();
@@ -1884,6 +2105,64 @@ wss.on("connection", (ws) => {
1884
2105
  setTimeout(() => void scheduleQuit(), 400);
1885
2106
  break;
1886
2107
  }
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
+ }
1887
2166
  default: {
1888
2167
  // 未知 type 只计数 + 节流 warn,不改变已知类型行为。
1889
2168
  // default 分支里 msg 已收窄成 never,type 需从宽化后取。
@@ -1908,13 +2187,13 @@ wss.on("connection", (ws) => {
1908
2187
  }
1909
2188
  }
1910
2189
  };
1911
- /** ready 握手帧:首连与重复 hello 的幂等回包共用同一构造,避免两处漂移。 */
2190
+ /** ready 握手帧:首连、重复 hello 与引擎热切共用同一构造,按 clientId 动态携带所属引擎。 */
1912
2191
  const readyMsg = (cid) => ({
1913
2192
  type: "ready",
1914
2193
  clientId: cid,
1915
2194
  serverVersion: VERSION,
1916
2195
  protocolVersion: PROTOCOL_VERSION,
1917
- engine: ENGINE,
2196
+ engine: resolveClientEngine(cid),
1918
2197
  // This package's own version. `serverVersion` is the pi SDK's,
1919
2198
  // and the client used to learn ours from the update check —
1920
2199
  // which a managed instance never runs.
@@ -42,7 +42,8 @@ export function makeLoadToolsTool(host, lang) {
42
42
  promptGuidelines: [
43
43
  "When a task needs a tool that is only listed in the catalog (name + one-line summary, no schema yet), " +
44
44
  "call load_tools with its name first instead of guessing arguments",
45
- "Load every tool you expect to need in ONE call — each load re-declares the tool set",
45
+ "Core tools (bash, read, edit, write) are always active — never pass them to load_tools",
46
+ "Tool loading is additive across turns — never reload tools that have already been loaded",
46
47
  ],
47
48
  parameters: Type.Object({
48
49
  tools: Type.Array(Type.String(), {
@@ -27,6 +27,11 @@ export const LOCALE_PACKS = [
27
27
  { code: "ko", nativeName: "한국어" },
28
28
  { code: "pt", nativeName: "Português" },
29
29
  { code: "ru", nativeName: "Русский" },
30
+ // Traditional Chinese packs. Core "zh" is Simplified; generated from it
31
+ // by OpenCC + glossaries (scripts/zh-tw-locale).
32
+ { code: "zh-Hant", nativeName: "繁體中文" },
33
+ { code: "zh-HK", nativeName: "繁體中文(香港)" },
34
+ { code: "zh-TW", nativeName: "繁體中文(台灣)" },
30
35
  ];
31
36
  export function isKnownPack(code) {
32
37
  return LOCALE_PACKS.some((p) => p.code === code);
@@ -23,6 +23,8 @@ function splitArgs(body) {
23
23
  }
24
24
  return { args, kwargs };
25
25
  }
26
+ const KNOWN_MARKER_TOOLS = new Set(["todo", "notify", "conv", "rename", "title", "action", "suggest"]);
27
+ const TRAILING_INCOMPLETE_MARKER_RE = /[ \t]*\[\[\s*(?:todo|notify|conv|rename|title|action|suggest)(?:\s*:[^\]]*)?$/i;
26
28
  export function parseMarkers(text) {
27
29
  const tokens = [];
28
30
  TOKEN_RE.lastIndex = 0;
@@ -36,3 +38,29 @@ export function parseMarkers(text) {
36
38
  }
37
39
  return tokens;
38
40
  }
41
+ /**
42
+ * 从助手展示文本中剥离内联状态标记([[todo:...]] / [[notify:...]] / [[conv:rename:...]] / [[action:suggest:...]] 等)。
43
+ * 仅剥离已知标记命名空间,避免误删正文或代码中的普通双括号内容;
44
+ * `stripTrailingIncomplete` 为 true 时同步剥离流式末尾尚未闭合的半截标记。
45
+ */
46
+ export function stripMarkers(text, options) {
47
+ if (!text || !text.includes("[["))
48
+ return text;
49
+ let out = text.replace(TOKEN_RE, (raw, tool, _op, body) => {
50
+ if (body.includes("[["))
51
+ return raw;
52
+ if (!KNOWN_MARKER_TOOLS.has(tool.toLowerCase()))
53
+ return raw;
54
+ return "";
55
+ });
56
+ if (options?.stripTrailingIncomplete) {
57
+ out = out.replace(TRAILING_INCOMPLETE_MARKER_RE, "");
58
+ }
59
+ if (out === text)
60
+ return text;
61
+ // 清理因剥离首尾标记残留在行首/段首/段尾的空行与空白
62
+ return out
63
+ .replace(/^[ \t]+\n/gm, "\n")
64
+ .replace(/\n{3,}/g, "\n\n")
65
+ .trim();
66
+ }