pi-web-ui 0.105.0 → 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 +58 -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 +146 -32
  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-B9exeXrl.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-BQC6lADz.css +0 -1
  74. package/web/dist/assets/index-D79IKG33.js +0 -690
@@ -19,6 +19,7 @@ import { spawn } from "node:child_process";
19
19
  import { createHash, randomUUID } from "node:crypto";
20
20
  import { createRequire } from "node:module";
21
21
  import * as fsPromises from "node:fs/promises";
22
+ import { DEFAULT_PI_CAPABILITIES } from "./engine-capabilities.js";
22
23
  import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, statSync, mkdirSync, watch, writeFileSync, } from "node:fs";
23
24
  import { homedir } from "node:os";
24
25
  import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
@@ -28,6 +29,7 @@ import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentS
28
29
  import { Type } from "typebox";
29
30
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
30
31
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
32
+ import { collectInstalledEngineTargets } from "./engine-probe.js";
31
33
  import { checkPluginUpdates } from "./plugin-updater.js";
32
34
  import { getAppVersion } from "./pkg-info.js";
33
35
  import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
@@ -49,8 +51,8 @@ import { ModelAdminService } from "./model-admin.js";
49
51
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
50
52
  import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
51
53
  import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
52
- import { pick, resolveServerLang } from "./i18n.js";
53
- import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
54
+ import { isTraditionalLocale, pick, resolveServerLang } from "./i18n.js";
55
+ import { SubagentTemplatesStore, localizeTemplate, pickTemplatePrompt, } from "./subagent-templates.js";
54
56
  import { ApprovalRulesStore, extractTargetPath } from "./approval-rules.js";
55
57
  import { ComposerDraftsStore } from "./composer-drafts.js";
56
58
  import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGate } from "./sandbox-service.js";
@@ -111,6 +113,7 @@ import { makeWorktreeTool, WORKTREE_TOOL_NAME } from "./worktree-tool.js";
111
113
  import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktree-service.js";
112
114
  import { sameSessionFile } from "./scheduler-tasks.js";
113
115
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
116
+ import { scanAtMentions } from "./universal/universal-attachments.js";
114
117
  import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
115
118
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
116
119
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
@@ -639,8 +642,89 @@ export class ClientSession {
639
642
  const conv = this.convs.get(convId);
640
643
  return conv?.session ? toSubagentSnapshot(conv) : undefined;
641
644
  }
642
- listSubagentSnapshots(scope) {
643
- return listSubagentSnapshots(this.convs.values(), scope);
645
+ /** B20:跨会话解析 —— 本会话没有就去「当前持有方」取(过户把子代理整体搬走后,
646
+ * 旧 host 闭包仍指向源会话,按 id 全局查才能看到还在跑的子代理,而不是误判
647
+ * 「已移出/不存在」)。findSubagentOwner 按别名表把旧 id 解析成改名后的当前 id。 */
648
+ subagentSnapshotAnywhere(convId) {
649
+ if (this.convs.has(convId))
650
+ return this.getSubagentSnapshot(convId);
651
+ const found = this.findSubagentOwner?.(convId);
652
+ return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
653
+ }
654
+ /** B20:convId 当前由哪个 ClientSession 持有(本会话优先;查不到兜底本会话)。 */
655
+ subagentOwnerOf(convId) {
656
+ if (!convId)
657
+ return this;
658
+ if (this.convs.has(convId))
659
+ return this;
660
+ return this.findSubagentOwner?.(convId)?.session ?? this;
661
+ }
662
+ /** B20:解析到当前(可能被过户改名)的对话 id;查不到原样返回。 */
663
+ subagentCurrentId(convId) {
664
+ if (this.convs.has(convId))
665
+ return convId;
666
+ return this.findSubagentOwner?.(convId)?.convId ?? convId;
667
+ }
668
+ listSubagentSnapshots(scope, forSelfId) {
669
+ const own = listSubagentSnapshots(this.convs.values(), scope);
670
+ // B20:带 forSelfId 才并入会话外本族(祖先链能走到 forSelfId 的子代理,
671
+ // 过户搬走后 wait_all 的「无参展开」与 list 仍能看到它们);不传 = 只列本会话。
672
+ if (!forSelfId || !this.allSubagentSessions)
673
+ return own;
674
+ const seen = new Set(own.map((s) => s.convId));
675
+ const out = [...own];
676
+ for (const other of this.allSubagentSessions()) {
677
+ if (other === this)
678
+ continue;
679
+ for (const s of other.listSubagentSnapshots(scope)) {
680
+ if (seen.has(s.convId))
681
+ continue;
682
+ if (!this.subagentInFamilyOf(s, forSelfId))
683
+ continue;
684
+ seen.add(s.convId);
685
+ out.push(s);
686
+ }
687
+ }
688
+ return out;
689
+ }
690
+ /** B20:parentId 链向上能否走到 selfId(防环,最多 64 跳)。链上每一跳都按
691
+ * 当前持有方 + 别名解析:过户撞 id 改名后,自省 id 与孩子们记录的 parentId
692
+ * 都可能还是建时旧 id(c1→c2),不比显式相等,比的是「解析后的当前 id」。 */
693
+ subagentInFamilyOf(s, selfId) {
694
+ let curId = s.parentId;
695
+ const seen = new Set();
696
+ let n = 0;
697
+ while (curId && n++ < 64 && !seen.has(curId)) {
698
+ seen.add(curId);
699
+ if (curId === selfId)
700
+ return true;
701
+ const found = this.findSubagentOwner?.(curId);
702
+ if (!found)
703
+ return false;
704
+ if (found.convId === selfId)
705
+ return true;
706
+ const snap = found.session === this
707
+ ? this.getSubagentSnapshot(found.convId)
708
+ : found.session.getSubagentSnapshot(found.convId);
709
+ if (!snap)
710
+ return false;
711
+ curId = snap.parentId;
712
+ }
713
+ return false;
714
+ }
715
+ /** B20:subagentHost.spawnSubagent 的委托入口(在**当前**会话上执行模板校验与真正
716
+ * spawn)—— 过户后由 host 按 parentId 的持有方调用,保证新子代理注册进持有方
717
+ * 的 convs(左栏「不见/错位」、cwd 跟错项目才不再发生)。 */
718
+ async spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist) {
719
+ // 模板:存在且启用时应用;传了名字但不可用 → 抛错让工具转给 AI。
720
+ const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
721
+ if (templateName && (!tpl || !tpl.enabled)) {
722
+ throw new Error(pick(this.getLang(), `子代理模板不可用:${templateName}(不存在或已停用)`, `Subagent template unavailable: ${templateName} (missing or disabled)`, "agent.subagent.template.unavailable", { templateName: templateName }));
723
+ }
724
+ // B20:parentId 是建时旧 id 时先解析成当前 id(过户撞 id 改名后,新子代理
725
+ // 的 parentId 必须指向改名后的主对话,否则族展开/lists 都认不出它)。
726
+ const canonParent = parentId ? (this.findSubagentOwner?.(parentId)?.convId ?? parentId) : parentId;
727
+ return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, canonParent, persist);
644
728
  }
645
729
  subagentRunOutcome(conv) {
646
730
  return subagentRunOutcome(conv);
@@ -1257,6 +1341,13 @@ export class ClientSession {
1257
1341
  if (fromRunId === toRunId) {
1258
1342
  throw new Error("Cannot hand off to oneself");
1259
1343
  }
1344
+ // B20:toRunId 可能已随过户搬去另一会话(主机 host 闭包仍指向旧会话)——
1345
+ // 委托给持有它的会话执行,否则「Target subagent not found」。
1346
+ const owner = this.subagentOwnerOf(toRunId);
1347
+ if (owner !== this) {
1348
+ await owner.handoffSubagent(fromRunId, toRunId, payload);
1349
+ return;
1350
+ }
1260
1351
  const toConv = this.convs.get(toRunId);
1261
1352
  if (!toConv) {
1262
1353
  throw new Error(`Target subagent ${toRunId} not found`);
@@ -1319,41 +1410,52 @@ export class ClientSession {
1319
1410
  }
1320
1411
  subagentHost = {
1321
1412
  spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist) => {
1322
- // 模板:存在且启用时应用;传了名字但不可用 → 抛错让工具转给 AI。
1323
- const tpl = templateName ? this.subagentTemplates.get(templateName) : undefined;
1324
- if (templateName && (!tpl || !tpl.enabled)) {
1325
- throw new Error(pick(this.getLang(), `子代理模板不可用:${templateName}(不存在或已停用)`, `Subagent template unavailable: ${templateName} (missing or disabled)`, "agent.subagent.template.unavailable", { templateName: templateName }));
1326
- }
1327
- // 模型优先级:显式 model 参数 > 模板自带模型 > 设置面板默认模型;都不给 = 跟随主对话。
1328
- return this.spawnSubagentConversation(prompt, type, cwd, tpl, model, parentId, persist);
1413
+ // B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
1414
+ // 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
1415
+ // 否则新子代理注册进旧会话、目标页左栏「不见/错位」。
1416
+ const owner = parentId ? this.subagentOwnerOf(parentId) : this;
1417
+ return owner.spawnSubagentViaHost(prompt, type, cwd, templateName, model, parentId, persist);
1418
+ },
1419
+ getSubagent: (convId) => {
1420
+ // B20:本会话查不到就去「当前持有方」查 —— 过户把子代理整体搬走后,
1421
+ // 旧 host 仍指向源会话(搬不动闭包),不跨会话解析 wait_all/get_result
1422
+ // 会以为子代理「已移出/不存在」而其实还在跑。
1423
+ if (this.convs.has(convId))
1424
+ return this.getSubagentSnapshot(convId);
1425
+ const found = this.findSubagentOwner?.(convId);
1426
+ return found && found.session !== this ? found.session.getSubagentSnapshot(found.convId) : undefined;
1329
1427
  },
1330
- getSubagent: (convId) => this.getSubagentSnapshot(convId),
1331
- listSubagents: (scope) => this.listSubagentSnapshots(scope),
1428
+ listSubagents: (scope, forSelfId) => this.listSubagentSnapshots(scope, forSelfId),
1332
1429
  handoffSubagent: async (fromRunId, toRunId, payload) => {
1333
1430
  await this.handoffSubagent(fromRunId, toRunId, payload);
1334
1431
  },
1335
1432
  steerSubagent: async (convId, message) => {
1336
- const conv = this.convs.get(convId);
1433
+ const owner = this.subagentOwnerOf(convId);
1434
+ const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
1435
+ const conv = owner.convs.get(curId);
1337
1436
  if (!conv?.session)
1338
1437
  return;
1339
1438
  await conv.session.sendUserMessage(message, conv.session.isStreaming ? { deliverAs: "steer" } : undefined);
1340
1439
  },
1341
1440
  stopSubagent: async (convId) => {
1342
- const conv = this.convs.get(convId);
1441
+ const owner = this.subagentOwnerOf(convId);
1442
+ const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
1443
+ const conv = owner.convs.get(curId);
1343
1444
  if (conv) {
1344
1445
  conv.promptInFlight = false;
1345
1446
  if (conv.session.isStreaming || !conv.session.isIdle) {
1346
- await this.interruptRun(conv, pick(this.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1447
+ await owner.interruptRun(conv, pick(owner.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1347
1448
  }
1348
1449
  }
1349
1450
  },
1350
1451
  getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
1351
1452
  // issue #91:子代理工具返回按客户端 UI 语言出中英(英文默认)。
1352
1453
  lang: () => this.getLang(),
1353
- // 只向 AI 暴露 enabled 的模板(停用的对 AI 不可见)。
1454
+ // 只向 AI 暴露 enabled 的模板(停用的对 AI 不可见)。繁中界面用繁中视图(同设置页)。
1354
1455
  listTemplates: () => this.subagentTemplates
1355
1456
  .list()
1356
1457
  .filter((t) => t.enabled)
1458
+ .map((t) => localizeTemplate(t, this.getLocale()))
1357
1459
  .map((t) => ({
1358
1460
  name: t.name,
1359
1461
  description: t.description,
@@ -1658,6 +1760,7 @@ export class ClientSession {
1658
1760
  void this.pushSessions();
1659
1761
  },
1660
1762
  getMcpServers: () => this.listMcpServers(),
1763
+ getLocale: () => this.getLocale(),
1661
1764
  }, this.subagentTemplates, this.approvalRules);
1662
1765
  this.goalSvc = new GoalService({
1663
1766
  clientId,
@@ -2001,8 +2104,8 @@ export class ClientSession {
2001
2104
  systemPromptOverride: (base) => {
2002
2105
  if (typeof base === "string" && base) {
2003
2106
  this.lastBaseSystemPrompt = base;
2004
- if (apply && apply.promptMode === "replace" && pickTemplatePrompt(apply, this.getLang()).trim()) {
2005
- return pickTemplatePrompt(apply, this.getLang());
2107
+ if (apply && apply.promptMode === "replace" && this.templatePrompt(apply).trim()) {
2108
+ return this.templatePrompt(apply);
2006
2109
  }
2007
2110
  }
2008
2111
  return undefined;
@@ -2012,8 +2115,8 @@ export class ClientSession {
2012
2115
  if (!apply)
2013
2116
  this.lastSdkAppendFiles = base.slice();
2014
2117
  const out = [...base];
2015
- if (apply && apply.promptMode === "append" && pickTemplatePrompt(apply, this.getLang()).trim()) {
2016
- out.push(pickTemplatePrompt(apply, this.getLang()));
2118
+ if (apply && apply.promptMode === "append" && this.templatePrompt(apply).trim()) {
2119
+ out.push(this.templatePrompt(apply));
2017
2120
  }
2018
2121
  // 主会话自定义「追加」已并入组合模板的 {{append}} 覆盖,不再在此注入。
2019
2122
  // 计划模式:只规划不实施 —— 硬闸门(server/plan-mode.ts 拒写类/旁路
@@ -2130,7 +2233,7 @@ export class ClientSession {
2130
2233
  // 把灵魂段换成模板提示词,自动段保留;SYSTEM.md 情形已在
2131
2234
  // systemPromptOverride 整体替换,此处边界不存在会自然跳过。
2132
2235
  if (apply) {
2133
- const tplPrompt = pickTemplatePrompt(apply, this.getLang()).trim();
2236
+ const tplPrompt = this.templatePrompt(apply).trim();
2134
2237
  if (apply.promptMode !== "replace" || !tplPrompt)
2135
2238
  return undefined;
2136
2239
  const boundary = core.indexOf("\n\nAvailable tools:");
@@ -2223,7 +2326,7 @@ export class ClientSession {
2223
2326
  ? !sessionManager.getEntries().some((e) => e.type === "message")
2224
2327
  : sessionManager.buildSessionContext().messages.length === 0;
2225
2328
  if (isBlank) {
2226
- const savedModelId = this.stateStore.getProjectModel(this.clientId, effectiveCwd) ?? this.stateStore.getDefaultModel();
2329
+ const savedModelId = this.stateStore.getProjectModel(this.clientId, effectiveCwd, "pi") ?? this.stateStore.getDefaultModel("pi");
2227
2330
  if (savedModelId) {
2228
2331
  const slash = savedModelId.indexOf("/");
2229
2332
  if (slash > 0 && slash < savedModelId.length - 1) {
@@ -2344,7 +2447,12 @@ export class ClientSession {
2344
2447
  // spawn 的 parentId(子代理记到真正的派发会话名下)+ wait_all 的
2345
2448
  // selfConvId(调用者自身永不计入等待,防 self-wait deadlock)。
2346
2449
  ...(ownerId
2347
- ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined, ownerId)
2450
+ ? makeSubagentTools(withSubagentOwner(this.subagentHost, ownerId), undefined,
2451
+ // B20:selfId 必须调用时刻解析,不能死用建时旧 id —— 过户撞 id
2452
+ // 改名后 wait_all 的「排除自身/展开后代」要按 runtime 的当前归属查。
2453
+ () => bridgeAnchor.session
2454
+ ? (this.findConversationHome?.(bridgeAnchor.session)?.convId ?? ownerId)
2455
+ : ownerId)
2348
2456
  : makeSubagentTools(this.subagentHost)),
2349
2457
  // 结构化派单(六段式 + 服务端校验;执行体复用子代理 spawn 通道)。
2350
2458
  // owner 包装与上面同理:子代理记到真正的派发会话名下。
@@ -2400,8 +2508,8 @@ export class ClientSession {
2400
2508
  }),
2401
2509
  // 延迟加载入口(延迟加载模式默认开):系统提示词只给未加载工具的
2402
2510
  // 名字 + 一行摘要,模型用本工具把要用的工具拉进本对话(schema 才随之下发)。
2403
- // 本事常在活跃集(见 applyToolGating 的 forceActive),关掉延迟加载后
2404
- // 它也无害(目录为空,调用会告诉模型没东西可加载)。
2511
+ // 延迟加载开启时常驻在活跃集(见 applyToolGating 的 forceActive);
2512
+ // 延迟加载未开启时不激活、不暴露给模型。
2405
2513
  makeLoadToolsTool(this.loadToolsHost(ownerId), () => this.getLang()),
2406
2514
  // 技能全文按名加载(名录在 {{skills}} 段):模型不再拼路径调 read。
2407
2515
  // 子代理会话同样注册(owner 即真正派发的父对话,读该会话 loader)。
@@ -3704,6 +3812,14 @@ export class ClientSession {
3704
3812
  // 每条 assistant 气泡流式结束 → 立即解析其中的内联标记:每个气泡各自
3705
3813
  // 生效(不再等整轮 agent_end),同一轮里先前消息的标记也不再丢。
3706
3814
  const mm = event.message;
3815
+ if (!conv.turnFirstTokenSeen && mm?.role === "assistant") {
3816
+ conv.turnFirstTokenSeen = true;
3817
+ const durationMs = conv.turnStartAt ? Math.max(1, Date.now() - conv.turnStartAt) : undefined;
3818
+ this.emitRun(conv, {
3819
+ type: "turn_first_token",
3820
+ ...(durationMs !== undefined ? { durationMs } : {}),
3821
+ });
3822
+ }
3707
3823
  if (mm?.role === "user") {
3708
3824
  // 用户消息定稿(无论是空闲首轮提问,还是流式期间从 steer/followUp 队列出队落盘):
3709
3825
  // SDK 在 _emit(message_end) 返回后的同一同步 tick 内执行 sessionManager.appendMessage,
@@ -3738,6 +3854,8 @@ export class ClientSession {
3738
3854
  break;
3739
3855
  }
3740
3856
  case "turn_start": {
3857
+ conv.turnFirstTokenSeen = false;
3858
+ conv.turnStartAt = Date.now();
3741
3859
  this.emitRun(conv, { type: "turn_start" });
3742
3860
  break;
3743
3861
  }
@@ -3746,6 +3864,14 @@ export class ClientSession {
3746
3864
  break;
3747
3865
  }
3748
3866
  case "message_update": {
3867
+ if (!conv.turnFirstTokenSeen) {
3868
+ conv.turnFirstTokenSeen = true;
3869
+ const durationMs = conv.turnStartAt ? Math.max(1, Date.now() - conv.turnStartAt) : undefined;
3870
+ this.emitRun(conv, {
3871
+ type: "turn_first_token",
3872
+ ...(durationMs !== undefined ? { durationMs } : {}),
3873
+ });
3874
+ }
3749
3875
  // Live assistant-message increment, deliberately OUTSIDE the snapshot
3750
3876
  // channel: send() drops snapshots under backpressure (big sessions),
3751
3877
  // but this small message must always get through or the UI freezes on
@@ -4125,6 +4251,7 @@ export class ClientSession {
4125
4251
  // 这个 key 必须整个缺席(不能是显式的 undefined——前端 delta 合并是
4126
4252
  // {...ui, ...d.state} 整批覆盖,显式 undefined 会把上次全量带回的草稿洗掉)。
4127
4253
  ...(withDraft ? { draft: this.draftForSnapshot() } : {}),
4254
+ engineCapabilities: DEFAULT_PI_CAPABILITIES,
4128
4255
  tools: state.tools.map((t) => t.name),
4129
4256
  version: ++this.version,
4130
4257
  piConfigured: this.isPiConfigured(),
@@ -4132,6 +4259,9 @@ export class ClientSession {
4132
4259
  stats,
4133
4260
  };
4134
4261
  }
4262
+ getCapabilities() {
4263
+ return DEFAULT_PI_CAPABILITIES;
4264
+ }
4135
4265
  /** Emit one snapshot update — incremental when possible, full otherwise.
4136
4266
  *
4137
4267
  * Persisted messages are content-immutable with reference-stable objects
@@ -4272,6 +4402,7 @@ export class ClientSession {
4272
4402
  ...(conversationTitle ? { conversationTitle } : {}),
4273
4403
  });
4274
4404
  }
4405
+ this.flushSnapshot();
4275
4406
  });
4276
4407
  }
4277
4408
  /** 前端回答模型提问(question_answer → 恢复 askUser 的 Promise)。id 需匹配
@@ -4293,6 +4424,7 @@ export class ClientSession {
4293
4424
  this.emit({ type: "question_retracted", id });
4294
4425
  // 同上:角标消失也要即时推送(否则要等到 run 结束别处才知道问完了)。
4295
4426
  this.emitConversations();
4427
+ this.flushSnapshot();
4296
4428
  return true;
4297
4429
  }
4298
4430
  /** 快照侧的待答提问(UiState.pendingQuestion):只带当前对话的问卷——切回
@@ -5042,6 +5174,12 @@ export class ClientSession {
5042
5174
  * 投错。(注意不能用 runtime 对象比:SDK 会把工厂返回值包成新的 AgentSessionRuntime
5043
5175
  * 实例,而 `runtime.session` 与本工厂的 `created.session` 是同一个对象。) */
5044
5176
  findConversationHome = undefined;
5177
+ /** B20 跨会话子代理归属(attach 时由 AgentService 接线,见 findConversationHome 同款):
5178
+ * - findSubagentOwner:按 convId 找当前持有它的 ClientSession —— 过户把对话(含子代理
5179
+ * 后代)整体搬去另一会话后,旧 host 闭包仍指向源会话,subagent 工具族靠它现查持有方;
5180
+ * - allSubagentSessions:全部客户端会话(wait_all/list 的「本族跨会话展开」用)。 */
5181
+ findSubagentOwner = undefined;
5182
+ allSubagentSessions = undefined;
5045
5183
  /** issue #145 跨客户端同会话感知 —— attach 时由 AgentService 接线:
5046
5184
  * - findSessionOwner:别处是否已持有同一 session 文件(查重建第二个 writer 用);
5047
5185
  * - listProjectRunners:别处在同一 cwd 下正在跑的对话(同项目并行感知用);
@@ -5222,6 +5360,7 @@ export class ClientSession {
5222
5360
  try {
5223
5361
  const targets = collectTargets(this.agentDir, ClientSession.currentAppVersion(), undefined, {
5224
5362
  projectCwd: this.convs.get(this.activeId)?.cwd ?? this.cwd,
5363
+ extraTargets: collectInstalledEngineTargets(),
5225
5364
  });
5226
5365
  const items = await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(this.agentDir));
5227
5366
  let pluginItems = [];
@@ -5690,7 +5829,7 @@ export class ClientSession {
5690
5829
  * message yet (the SDK only flushes a model_change to disk once one exists). */
5691
5830
  rememberProjectModel(modelId) {
5692
5831
  const cwd = this.cwd;
5693
- this.stateStore.saveProjectModel(this.clientId, cwd, modelId);
5832
+ this.stateStore.saveProjectModel(this.clientId, cwd, modelId, "pi");
5694
5833
  const slash = modelId.indexOf("/");
5695
5834
  if (slash <= 0)
5696
5835
  return;
@@ -5708,7 +5847,7 @@ export class ClientSession {
5708
5847
  * the user switches via the picker. Silent on failure (model no longer in catalog).
5709
5848
  * Fallback chain: project memory > GLOBAL default model > SDK default (no-op). */
5710
5849
  async restoreProjectModelForCwd(cwd) {
5711
- const savedModel = this.stateStore.getProjectModel(this.clientId, cwd) ?? this.stateStore.getDefaultModel();
5850
+ const savedModel = this.stateStore.getProjectModel(this.clientId, cwd, "pi") ?? this.stateStore.getDefaultModel("pi");
5712
5851
  if (!savedModel)
5713
5852
  return;
5714
5853
  try {
@@ -6414,8 +6553,11 @@ export class ClientSession {
6414
6553
  /* session 未就绪:下次创建/reload 会再应用 */
6415
6554
  }
6416
6555
  }
6556
+ else {
6557
+ disabled.add(LOAD_TOOLS_TOOL_NAME);
6558
+ }
6417
6559
  applyAgentToolsGating(session, [...disabled], targetPreset, {
6418
- // load_tools 不在任何预设白名单里,又必须永远可用(ask 预设本来就无工具,不强加)。
6560
+ // load_tools 不在任何预设白名单里,又必须在延迟加载开启时永远可用(ask 预设本来就无工具,不强加;非延迟加载模式不激活)。
6419
6561
  forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME] : [],
6420
6562
  });
6421
6563
  const ownerId = conv?.id;
@@ -6977,6 +7119,16 @@ export class ClientSession {
6977
7119
  getLang() {
6978
7120
  return resolveServerLang(this.stateStore.get(this.clientId).locale);
6979
7121
  }
7122
+ /** Raw UI locale as the browser reported it ("zh-TW", "zh-HK", …). Unlike
7123
+ * getLang() it is NOT folded: zh-TW / zh-HK / zh-Hant all resolve to "zh"
7124
+ * there, so Traditional-script data variants must key off this instead. */
7125
+ getLocale() {
7126
+ return this.stateStore.get(this.clientId).locale;
7127
+ }
7128
+ /** 子代理模板的系统提示词:繁中界面先套繁中视图(localizeTemplate),再按服务端语言选 zh/en。 */
7129
+ templatePrompt(apply) {
7130
+ return pickTemplatePrompt(localizeTemplate(apply, this.getLocale()), this.getLang());
7131
+ }
6980
7132
  /** Persist the browser UI locale (hello.locale / set_locale) and refresh
6981
7133
  * lang-aware prompt segments. Reuses the settings reload path, so it is
6982
7134
  * streaming-safe (deferred to agent_end mid-run, same as settings). */
@@ -6985,9 +7137,16 @@ export class ClientSession {
6985
7137
  if (!code)
6986
7138
  return;
6987
7139
  const prev = this.getLang();
7140
+ const prevTraditional = isTraditionalLocale(this.getLocale());
6988
7141
  this.stateStore.saveLocale(this.clientId, code);
6989
- if (this.getLang() === prev)
6990
- return; // same server language — nothing to re-render
7142
+ if (this.getLang() === prev) {
7143
+ // Same server language (every zh* folds to "zh") — no runtime reload needed. But
7144
+ // Simplified ↔ Traditional changes the built-in subagent templates' view, so
7145
+ // re-push the settings snapshot for an open settings panel.
7146
+ if (isTraditionalLocale(this.getLocale()) !== prevTraditional)
7147
+ this.settingsSvc.push();
7148
+ return;
7149
+ }
6991
7150
  await this.applySettingsReload();
6992
7151
  }
6993
7152
  // ---------------------------------------------------------------------------
@@ -7598,13 +7757,17 @@ export class ClientSession {
7598
7757
  // Attach files as independent nextTurn context messages (asides) so the
7599
7758
  // user message stays clean; they render as separate attachment cards.
7600
7759
  // SDK 的流式队列只消费用户消息;引用须与对应队列项一起入队和撤回。
7760
+ const scan = scanAtMentions(trimmedText, this.cwd, [], attachments ?? []);
7761
+ const effectiveAttachments = scan.detectedAttachments.length > 0 ? [...(attachments ?? []), ...scan.detectedAttachments] : attachments;
7601
7762
  const streamingQuotes = s.isStreaming
7602
- ? (attachments ?? [])
7763
+ ? (effectiveAttachments ?? [])
7603
7764
  .filter((a) => a.mode === "quote")
7604
7765
  .map((a) => readTextQuote(a.quote))
7605
7766
  .filter((q) => q !== null)
7606
7767
  : [];
7607
- const nonQuoteAttachments = streamingQuotes.length ? attachments?.filter((a) => a.mode !== "quote") : attachments;
7768
+ const nonQuoteAttachments = streamingQuotes.length
7769
+ ? effectiveAttachments?.filter((a) => a.mode !== "quote")
7770
+ : effectiveAttachments;
7608
7771
  const asides = nonQuoteAttachments && nonQuoteAttachments.length > 0
7609
7772
  ? await buildAttachmentMessages({
7610
7773
  cwd: this.cwd,
@@ -8911,6 +9074,10 @@ export class ClientSession {
8911
9074
  }
8912
9075
  return undefined;
8913
9076
  }
9077
+ /** B20:本会话是否持有该对话(AgentService/daemon 按 convId 跨客户端找持有方用)。 */
9078
+ hasConversation(convId) {
9079
+ return this.convs.has(convId);
9080
+ }
8914
9081
  /** 过户用的对话摘要(AgentService 拼移动集合 + 容量检查用)。 */
8915
9082
  takeoverBriefs() {
8916
9083
  return [...this.convs.values()].map((c) => {
@@ -9647,10 +9814,12 @@ export class ClientSession {
9647
9814
  const sessions = new Map();
9648
9815
  for (const s of visibleInfos) {
9649
9816
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
9817
+ const displayName = s.name?.trim() || (s.firstMessage ? s.firstMessage.trim().replace(/\s+/g, " ") : undefined);
9650
9818
  sessions.set(s.path, {
9651
9819
  path: s.path,
9652
9820
  ...(s.id ? { sessionId: s.id } : {}),
9653
9821
  name: s.name,
9822
+ displayName,
9654
9823
  firstMessage: s.firstMessage,
9655
9824
  messageCount: s.messageCount,
9656
9825
  modified: s.modified.getTime(),
@@ -10576,6 +10745,15 @@ export class ClientSession {
10576
10745
  const sessionFile = conv.session.sessionFile;
10577
10746
  if (sessionFile && resolve(sessionFile) === targetPath) {
10578
10747
  await this.switchConversation(conv.id);
10748
+ this.emit({
10749
+ type: "transition_progress",
10750
+ kind: "session",
10751
+ target: targetPath,
10752
+ phase: "done",
10753
+ progress: 100,
10754
+ text: "会话加载完成",
10755
+ textEn: "Session loaded",
10756
+ });
10579
10757
  return;
10580
10758
  }
10581
10759
  }
@@ -11520,13 +11698,16 @@ export class ClientSession {
11520
11698
  // lifecycle (removal is deferred until the active conversation is
11521
11699
  // safely switched away).
11522
11700
  const displaced = this.displaceActive();
11701
+ const openRecent = this.settingsSvc?.current.openRecentSessionOnProjectSwitch ?? true;
11523
11702
  // Prefer the target project's own most recently active conversation;
11524
11703
  // only create a fresh one (resuming its most recent session) when the
11525
11704
  // project has none open yet.
11526
11705
  let target;
11527
- for (const c of this.convs.values()) {
11528
- if (c.cwd === abs && (!target || c.lastActiveAt > target.lastActiveAt)) {
11529
- target = c;
11706
+ if (openRecent) {
11707
+ for (const c of this.convs.values()) {
11708
+ if (c.cwd === abs && (!target || c.lastActiveAt > target.lastActiveAt)) {
11709
+ target = c;
11710
+ }
11530
11711
  }
11531
11712
  }
11532
11713
  if (target) {
@@ -11543,8 +11724,8 @@ export class ClientSession {
11543
11724
  target: abs,
11544
11725
  phase: "fs",
11545
11726
  progress: 28,
11546
- text: `正在同步目录与检查最近会话:${abs}`,
11547
- textEn: `Validating workspace & checking recent session: ${abs}`,
11727
+ text: openRecent ? `正在同步目录与检查最近会话:${abs}` : `正在切换工作目录:${abs}`,
11728
+ textEn: openRecent ? `Validating workspace & checking recent session: ${abs}` : `Switching workspace: ${abs}`,
11548
11729
  });
11549
11730
  this.flushSnapshot();
11550
11731
  // 让出事件循环,确保首帧进度在同步磁盘扫描前真正发往浏览器
@@ -11563,7 +11744,7 @@ export class ClientSession {
11563
11744
  // blank instead.
11564
11745
  let resumeSkipped = null;
11565
11746
  // 别处无可见行时不扫目录(首访切项目的常见情形零开销)。
11566
- if ((this.listExternalRunning?.() ?? []).length > 0) {
11747
+ if (openRecent && (this.listExternalRunning?.() ?? []).length > 0) {
11567
11748
  try {
11568
11749
  const recentPath = await findMostRecentSessionFileFast(sessionBaseDir, abs);
11569
11750
  const recent = recentPath ? resolve(recentPath) : undefined;
@@ -11580,7 +11761,9 @@ export class ClientSession {
11580
11761
  const terminals = this.makeTerminalManager(conversationId, abs);
11581
11762
  // #235:manager+runtime 一起建,转录链损坏时修最近文件后重试一次
11582
11763
  // (见 openManagerAndRuntime)。blank(别处在跑)是全新空会话,不会坏。
11583
- const opened = await this.openManagerAndRuntime(() => (resumeSkipped ? SessionManager.create(sessionBaseDir) : SessionManager.continueRecent(sessionBaseDir)), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId), {
11764
+ const opened = await this.openManagerAndRuntime(() => resumeSkipped || !openRecent
11765
+ ? SessionManager.create(sessionBaseDir)
11766
+ : SessionManager.continueRecent(sessionBaseDir), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId), {
11584
11767
  cwd: sessionBaseDir,
11585
11768
  agentDir: this.agentDir,
11586
11769
  sessionManager: m,
@@ -11623,7 +11806,7 @@ export class ClientSession {
11623
11806
  // #436:同 switchSession —— 续聊最近会话若从转录回放恢复了 planMode,
11624
11807
  // 工厂里的门控当时读不到它,注册后补一次。
11625
11808
  this.applyToolGating(conv.session, conv.agentPreset);
11626
- if (resumeSkipped) {
11809
+ if (resumeSkipped && openRecent) {
11627
11810
  this.emit(resumeSkipped.isStreaming
11628
11811
  ? {
11629
11812
  type: "notice",
@@ -12091,7 +12274,7 @@ export class ClientSession {
12091
12274
  const id = modelId.slice(slash + 1);
12092
12275
  if (!mr.getModel(provider, id))
12093
12276
  throw new Error(`模型不存在:${modelId}`);
12094
- this.stateStore.saveDefaultModel(modelId);
12277
+ this.stateStore.saveDefaultModel(modelId, "pi");
12095
12278
  const active = this.modelAdmin.getActiveKeyName(provider);
12096
12279
  if (active)
12097
12280
  this.stateStore.saveDefaultProviderKey(provider, active);
@@ -12122,7 +12305,7 @@ export class ClientSession {
12122
12305
  }
12123
12306
  /** Clear the GLOBAL default model (new projects fall back to the SDK default). */
12124
12307
  clearDefaultModel() {
12125
- this.stateStore.clearDefaultModel();
12308
+ this.stateStore.saveDefaultModel("", "pi");
12126
12309
  try {
12127
12310
  this.session.settingsManager.setDefaultModelAndProvider(undefined, undefined);
12128
12311
  }
@@ -12140,7 +12323,7 @@ export class ClientSession {
12140
12323
  }
12141
12324
  /** Push the current global default model (attach + after every change). */
12142
12325
  pushDefaultModel() {
12143
- this.emit({ type: "default_model", modelId: this.stateStore.getDefaultModel() ?? null });
12326
+ this.emit({ type: "default_model", modelId: this.stateStore.getDefaultModel("pi") ?? null });
12144
12327
  }
12145
12328
  /** 切换模型,失败时抛出(无头路径专用:插件 host.chat / 定时任务)。
12146
12329
  * setModel 为兼容 UI 把异常吞成 notice(面板要能看到原因、调用方是 fire-and-forget),
@@ -84,8 +84,15 @@ export function makeClaimFilesTool(host, lang) {
84
84
  ttlMs,
85
85
  })));
86
86
  const L = getLang();
87
+ const ttl = fmtTtl(ttlMs);
87
88
  const okLine = claimed.length > 0
88
- ? pick(L, `已认领 ${claimed.length} 个(${claimed.map((c) => c.path).join("、")}),约 ${fmtTtl(ttlMs)} 后过期(你发 prompt 自动续)。`, `Claimed ${claimed.length} (${claimed.map((c) => c.path).join(", ")}), expiring in ~${fmtTtl(ttlMs)} (refreshed by your prompts).`, "claimfiles.claim.ok", { n: claimed.length })
89
+ ? pick(L, `已认领 ${claimed.length} 个(${claimed.map((c) => c.path).join("、")}),约 ${ttl} 后过期(你发 prompt 自动续)。`, `Claimed ${claimed.length} (${claimed.map((c) => c.path).join(", ")}), expiring in ~${ttl} (refreshed by your prompts).`, "claimfiles.claim.ok", {
90
+ n: claimed.length,
91
+ paths: claimed.map((c) => c.path).join(", "),
92
+ pathsZh: claimed.map((c) => c.path).join("、"),
93
+ pathsEn: claimed.map((c) => c.path).join(", "),
94
+ ttl,
95
+ })
89
96
  : "";
90
97
  const clashLine = conflicts.length > 0
91
98
  ? pick(L, `先到先得,以下已被别人认领(没抢占):${conflicts.map((c) => `${c.path}(「${c.claim.ownerTitle}」${c.claim.note ? `:${c.claim.note}` : ""})`).join(";")} —— 绕行,或问用户。`, `First-wins; already claimed by others (not overridden): ${conflicts.map((c) => `${c.path} ("${c.claim.ownerTitle}"${c.claim.note ? `: ${c.claim.note}` : ""})`).join("; ")} — steer clear or ask the user.`, "claimfiles.claim.conflict", { n: conflicts.length })