pi-web-ui 0.105.1 → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +84 -2
  2. package/README.md +193 -797
  3. package/README.zh-CN.md +186 -625
  4. package/README.zh-TW.md +781 -0
  5. package/bin/frp-manager.mjs +1488 -0
  6. package/bin/pi-web-ui.mjs +27 -0
  7. package/deploy/nginx-subpath.conf +16 -1
  8. package/dist/server/agent-service-daemon.js +34 -0
  9. package/dist/server/agent-service.js +259 -60
  10. package/dist/server/claim-files-tool.js +8 -1
  11. package/dist/server/client-state.js +136 -30
  12. package/dist/server/conversation-read-tool.js +12 -4
  13. package/dist/server/delegate-task.js +9 -1
  14. package/dist/server/dispatch-domain-handlers.js +15 -0
  15. package/dist/server/dsh/dsh-agent-service.js +848 -246
  16. package/dist/server/dsh/dsh-client.js +59 -18
  17. package/dist/server/dsh/dsh-market-service.js +233 -0
  18. package/dist/server/dsh/dsh-serialize.js +11 -3
  19. package/dist/server/dsh/dsh-sessions.js +64 -2
  20. package/dist/server/dsh/preset-clones.js +12 -1
  21. package/dist/server/dsh/runtime/goal-rpc.mjs +183 -45
  22. package/dist/server/durable/durable-agent-service.js +153 -0
  23. package/dist/server/durable/durable-capabilities.js +11 -0
  24. package/dist/server/durable/durable-driver.js +481 -0
  25. package/dist/server/durable/durable-loader.js +38 -0
  26. package/dist/server/durable/durable-models.js +283 -0
  27. package/dist/server/durable/durable-storage.js +42 -0
  28. package/dist/server/durable/durable-tools.js +45 -0
  29. package/dist/server/durable/index.js +8 -0
  30. package/dist/server/engine-capabilities.js +91 -0
  31. package/dist/server/engine-probe.js +391 -0
  32. package/dist/server/global-loader.js +335 -0
  33. package/dist/server/goal-service.js +23 -12
  34. package/dist/server/i18n.js +20 -1
  35. package/dist/server/index.js +286 -71
  36. package/dist/server/locales.js +1 -0
  37. package/dist/server/managed.js +2 -0
  38. package/dist/server/marker-service.js +5 -19
  39. package/dist/server/markers/index.js +1 -3
  40. package/dist/server/mcp-agent-tool.js +10 -7
  41. package/dist/server/mcp-bridge.js +428 -24
  42. package/dist/server/model-admin.js +172 -74
  43. package/dist/server/model-resolver.js +309 -0
  44. package/dist/server/plugin-installer.js +4 -2
  45. package/dist/server/plugins.js +89 -12
  46. package/dist/server/present-files-tool.js +10 -2
  47. package/dist/server/preset-fields.js +14 -0
  48. package/dist/server/preset-share.js +2 -0
  49. package/dist/server/protocol-version.js +1 -1
  50. package/dist/server/schedule-agent-tool.js +2 -1
  51. package/dist/server/scm-commitmsg.js +3 -2
  52. package/dist/server/sdk-origin.js +2 -2
  53. package/dist/server/serialize.js +1 -1
  54. package/dist/server/settings-service.js +10 -2
  55. package/dist/server/skill-discovery.js +161 -0
  56. package/dist/server/skill-tool.js +2 -1
  57. package/dist/server/slash-commands.js +154 -73
  58. package/dist/server/subagent-templates-hant.js +215 -0
  59. package/dist/server/subagent-templates.js +49 -2
  60. package/dist/server/subagents.js +22 -12
  61. package/dist/server/terminals.js +2 -2
  62. package/dist/server/tool-manager.js +6 -19
  63. package/dist/server/universal/driver-base.js +60 -0
  64. package/dist/server/universal/drivers/claude-code.js +463 -0
  65. package/dist/server/universal/drivers/dsh-driver.js +376 -0
  66. package/dist/server/universal/drivers/mock-driver.js +103 -0
  67. package/dist/server/universal/index.js +10 -0
  68. package/dist/server/universal/session-store.js +100 -0
  69. package/dist/server/universal/universal-attachments.js +175 -0
  70. package/dist/server/universal/universal-service.js +166 -0
  71. package/dist/server/universal/universal-session.js +2664 -0
  72. package/dist/server/universal/universal-types.js +4 -0
  73. package/dist/server/update-check.js +24 -9
  74. package/dist/server/worktree-service.js +1 -1
  75. package/dist/server/worktree-tool.js +9 -7
  76. package/package.json +3 -2
  77. package/plugin-sdk/index.d.ts +12 -2
  78. package/plugins/catalog.json +50 -5
  79. package/themes/dark-teal.css +20 -24
  80. package/themes/flow-light.css +1085 -0
  81. package/themes/flow.css +1094 -0
  82. package/themes/md-preview.css +1 -2
  83. package/themes/wallpaper-flow.css +1158 -0
  84. package/themes/wallpaper-obsidian.css +743 -0
  85. package/themes/zhujian-dark.css +0 -7
  86. package/themes/zhujian.css +0 -7
  87. package/themes/zhupi-dark.css +0 -7
  88. package/themes/zhupi.css +0 -7
  89. package/web/dist/assets/{TerminalPanel-Mk4laCAL.js → TerminalPanel-BnViyTlx.js} +2 -2
  90. package/web/dist/assets/index-cCRCYMwT.css +1 -0
  91. package/web/dist/assets/index-fH5vhkAE.js +690 -0
  92. package/web/dist/index.html +2 -2
  93. package/web/dist/sw.js +1 -1
  94. package/web/dist/assets/index-BDLVjBeK.js +0 -690
  95. package/web/dist/assets/index-BQC6lADz.css +0 -1
@@ -24,9 +24,9 @@
24
24
  * 引擎无关模块复用:FilesService(文件树/预览)、scm.ts(git 查询)、
25
25
  * BgServerTracker(后台任务)、TerminalManager(PTY)、uploads.ts。
26
26
  */
27
- import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
27
+ import { DEFAULT_DSH_CAPABILITIES } from "../engine-capabilities.js";
28
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
28
29
  import { basename, dirname, join, resolve, sep } from "node:path";
29
- import { writeJsonAtomicSync } from "../atomic-file.js";
30
30
  import { randomUUID } from "node:crypto";
31
31
  import { homedir } from "node:os";
32
32
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "../bg-servers.js";
@@ -37,20 +37,25 @@ import { FilesService, workspacePath, desktopDirWire } from "../files-service.js
37
37
  import { SandboxManager, isSameOrSubpath } from "../sandbox-service.js";
38
38
  import { QuiesceRejectedError } from "../agent-service.js";
39
39
  import { NATIVE_COMMANDS, parseSlash } from "../slash-commands.js";
40
+ import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
41
+ import { scanAtMentions, formatPromptWithSkills } from "../universal/universal-attachments.js";
40
42
  import { bilingual, pick, resolveServerLang } from "../i18n.js";
41
- // 工具定义说明的归一化(工具卡右键 → 「显示工具详细信息」,见 getToolInfo)。
43
+ import { ModelAdminService } from "../model-admin.js";
42
44
  import { normalizeToolInfo, unsupportedToolInfo } from "../tool-info.js";
43
45
  import { TerminalManager, loadCommands, saveCommandsFile } from "../terminals.js";
44
46
  import { saveUpload } from "../uploads.js";
45
47
  import { checkAll as checkAllUpdates, collectTargets, resolveNpmRegistry } from "../update-check.js";
48
+ import { collectInstalledEngineTargets } from "../engine-probe.js";
46
49
  import { previewKind } from "../text-sniff.js";
47
50
  import { removeQueuedByIndexOrText } from "../queue-utils.js";
48
51
  import { launchOrigin, toServiceInfo } from "../launch-origin.js";
49
52
  import { DshRuntime, loadDeepSeekKey } from "./dsh-client.js";
53
+ import { resolveProviderCredential, listCustomModelsFromConfig, isModelProtocolSupportedByEngine, } from "../model-resolver.js";
54
+ import { loadDshMarketData } from "./dsh-market-service.js";
50
55
  import { formatTextQuote, readTextQuote, messageTextWithQuotes } from "../text-quote.js";
51
56
  import { MarkerService } from "../marker-service.js";
52
57
  import { DshStreamAccumulator, assistantMessageEventToUiMessage, extractDshAssistantRawText, toolResultEventToUiMessage, userMessageEventToUiMessage, } from "./dsh-serialize.js";
53
- import { firstUserText, findSessionFilesForCwd, readSessionLog, replayEventsToMessages, sessionLogPermission, sessionLogPreset, } from "./dsh-sessions.js";
58
+ import { firstUserText, findSessionFilesForCwd, isDshInternalUserMessage, readSessionLog, replayEventsToMessages, sessionLogPermission, sessionLogPreset, sessionLogTitle, } from "./dsh-sessions.js";
54
59
  import { generatePresetClones, PRESET_DEFAULT_ID } from "./preset-clones.js";
55
60
  import { dshContextUsage, lastUsageFromEvents, normalizeDshUsage } from "./dsh-usage.js";
56
61
  import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
@@ -145,6 +150,7 @@ const DEFAULT_SETTINGS = {
145
150
  keepRecentMessages: DEFAULT_KEEP_RECENT_MESSAGES,
146
151
  showForkedParentSessions: false,
147
152
  retainFinishedConversations: false,
153
+ openRecentSessionOnProjectSwitch: true,
148
154
  disabledPlugins: [],
149
155
  uiLayout: {},
150
156
  reviewPrompt: "",
@@ -152,6 +158,7 @@ const DEFAULT_SETTINGS = {
152
158
  defaultPermissionPreset: PERMISSION_DEFAULT_PRESET,
153
159
  quickPhrases: [],
154
160
  quickPhrasesEnabled: true,
161
+ minimalNewChat: false,
155
162
  promptTemplate: "",
156
163
  promptOverrides: {},
157
164
  };
@@ -180,6 +187,7 @@ export class DshClientSession {
180
187
  goalPrefs = { reviewModel: null, maxRounds: 2, locked: false };
181
188
  sinks = new Set();
182
189
  pendingNotices = [];
190
+ sessionDrafts = new Map();
183
191
  snapshotTimer = null;
184
192
  snapRev = 0;
185
193
  version = 0;
@@ -187,6 +195,9 @@ export class DshClientSession {
187
195
  emittedRev = 0;
188
196
  disposed = false;
189
197
  model = DEFAULT_MODEL;
198
+ modelProvider = "deepseek";
199
+ modelDisplayName = "DeepSeek V4 Flash";
200
+ modelVision = false;
190
201
  thinkingLevel = "high";
191
202
  /** P0-1 watchdog:60s 窗口内最多自动重启 2 次,超限升级为报错 notice。 */
192
203
  static RUNTIME_RESTART_WINDOW_MS = 60_000;
@@ -220,6 +231,7 @@ export class DshClientSession {
220
231
  bg;
221
232
  sandboxes;
222
233
  markerSvc;
234
+ modelAdmin;
223
235
  /** 插件扩展点(index.ts 注入)。 */
224
236
  onToolEvent;
225
237
  pluginToolsProvider;
@@ -259,6 +271,13 @@ export class DshClientSession {
259
271
  getCwd: () => this.cwd,
260
272
  getActiveCwd: () => this.cwd,
261
273
  });
274
+ this.modelAdmin = new ModelAdminService({
275
+ agentDir: this.agentDir,
276
+ emit: (msg) => this.emit(msg),
277
+ flushSnapshot: () => this.flushSnapshot(),
278
+ isDisposed: () => this.disposed,
279
+ pushModels: async () => this.listModels(),
280
+ });
262
281
  this.bg = new BgServerTracker({
263
282
  emit: (msg) => this.emit(msg),
264
283
  flushSnapshot: () => this.flushSnapshot(),
@@ -296,6 +315,11 @@ export class DshClientSession {
296
315
  locked: gPrefs.locked,
297
316
  };
298
317
  }
318
+ // 恢复上次使用的模型(按 DSH 引擎独立记录:项目记忆 > 全局默认)
319
+ const savedModel = stateStore.getProjectModel(clientId, cwd, "dsh") ?? stateStore.getDefaultModel("dsh");
320
+ if (savedModel) {
321
+ cs.applySavedModel(savedModel);
322
+ }
299
323
  // 恢复上次使用的设置(跨重连存活;DSH 忽略无行为字段但回显保持 UI 一致)。
300
324
  const savedSettings = stateStore.getSettings(clientId);
301
325
  if (savedSettings) {
@@ -321,11 +345,13 @@ export class DshClientSession {
321
345
  keepRecentMessages: normalizeKeepRecentMessages(savedSettings.keepRecentMessages),
322
346
  showForkedParentSessions: savedSettings.showForkedParentSessions ?? false,
323
347
  retainFinishedConversations: savedSettings.retainFinishedConversations ?? false,
348
+ openRecentSessionOnProjectSwitch: savedSettings.openRecentSessionOnProjectSwitch ?? true,
324
349
  disabledPlugins: savedSettings.disabledPlugins ?? [],
325
350
  uiLayout: normalizeUiLayout(savedSettings.uiLayout),
326
351
  reviewPrompt: savedSettings.reviewPrompt,
327
352
  quickPhrases: savedSettings.quickPhrases ?? [],
328
353
  quickPhrasesEnabled: savedSettings.quickPhrasesEnabled ?? true,
354
+ minimalNewChat: savedSettings.minimalNewChat ?? false,
329
355
  promptTemplate: savedSettings.promptTemplate ?? "",
330
356
  promptOverrides: savedSettings.promptOverrides ?? {},
331
357
  defaultAgentPreset: savedSettings.defaultAgentPreset ?? PRESET_DEFAULT_ID,
@@ -334,11 +360,35 @@ export class DshClientSession {
334
360
  : PERMISSION_DEFAULT_PRESET,
335
361
  };
336
362
  }
337
- // 第一个 conversation = 新会话(每客户端独立 sessionId,避免多标签页/多
338
- // 客户端共享同一 JSONL 互相串会话)。历史会话经 switch_session 恢复。
363
+ // 恢复最近会话(若有)或新建空白会话(避免刷新页面后丢失历史变成空白新对话)
339
364
  cs.makeRuntime();
340
- const first = cs.addConversation(`web-${randomUUID().slice(0, 12)}`, cwd, false, cs.settings.defaultAgentPreset);
341
- cs.activeId = first.id;
365
+ const recentFiles = findSessionFilesForCwd(cs.sessionRoot, cwd).filter((f) => !basename(dirname(f)).startsWith("review-"));
366
+ let resumedConv = null;
367
+ for (const file of recentFiles) {
368
+ try {
369
+ const { events } = readSessionLog(file);
370
+ const hasRealMessages = events.some((e) => (e.type === "user/message" && !isDshInternalUserMessage(e.data)) ||
371
+ e.type === "assistant/message");
372
+ if (hasRealMessages) {
373
+ const sid = basename(dirname(file));
374
+ const conv = cs.addConversation(sid, cwd, true, cs.settings.defaultAgentPreset, file);
375
+ conv.fromDisk = true;
376
+ conv.sessionFile = file;
377
+ resumedConv = conv;
378
+ break;
379
+ }
380
+ }
381
+ catch {
382
+ continue;
383
+ }
384
+ }
385
+ if (resumedConv) {
386
+ cs.activeId = resumedConv.id;
387
+ }
388
+ else {
389
+ const first = cs.addConversation(`web-${randomUUID().slice(0, 12)}`, cwd, false, cs.settings.defaultAgentPreset);
390
+ cs.activeId = first.id;
391
+ }
342
392
  cs.attachRuntimeEvents();
343
393
  // 每次启动成功(含初次/换模型/watchdog 重启)后重新注册插件工具桥,
344
394
  // 因为重 spawn 后的 ctx.tools 是全新的,需要重新 sync 插件工具。
@@ -558,6 +608,7 @@ export class DshClientSession {
558
608
  cwd: this.cwd,
559
609
  provider: "deepseek-official",
560
610
  model: this.model,
611
+ modelProvider: this.modelProvider,
561
612
  sessionRoot: this.sessionRoot,
562
613
  dataDir: this.dataDir,
563
614
  agentDir: this.agentDir,
@@ -631,6 +682,7 @@ export class DshClientSession {
631
682
  ...(this.activeId ? { conversationId: this.activeId } : {}),
632
683
  ...(conversationTitle ? { conversationTitle } : {}),
633
684
  });
685
+ this.flushSnapshot();
634
686
  }
635
687
  else if (method === "tools.call.request") {
636
688
  // 工具桥(#15):模型调了插件工具 → 服务端跑插件实现 → tools/call-result 回传。
@@ -660,6 +712,7 @@ export class DshClientSession {
660
712
  // 恢复到一张已经没人在等的问卷。
661
713
  if (this.pendingQuestion?.id === id)
662
714
  this.pendingQuestion = null;
715
+ this.flushSnapshot();
663
716
  try {
664
717
  await this.runtime.answerQuestion(id, answers, cancelled);
665
718
  }
@@ -828,11 +881,12 @@ export class DshClientSession {
828
881
  return title === DEFAULT_CONV_TITLE || title === DEFAULT_CONV_TITLE_EN;
829
882
  }
830
883
  /** 新建(或切换)一个 conversation。existing 的 sessionId 续聊最近 JSONL。 */
831
- addConversation(sessionId, cwd, replay = true, preset) {
884
+ addConversation(sessionId, cwd, replay = true, preset, sessionFilePath) {
832
885
  const id = this.nextConversationId();
833
886
  const conv = {
834
887
  id,
835
888
  sessionId,
889
+ sessionFile: sessionFilePath,
836
890
  agentPreset: this.resolvePreset(preset),
837
891
  presetLocked: false,
838
892
  assignedGen: -1,
@@ -864,9 +918,15 @@ export class DshClientSession {
864
918
  if (replay) {
865
919
  // 从磁盘 JSONL 回放历史消息(DSH 事件流不重放历史)。
866
920
  try {
867
- const files = findSessionFilesForCwd(this.sessionRoot, cwd).filter((f) => basename(dirname(f)) === sessionId);
868
- if (files.length > 0) {
869
- const { header, events } = readSessionLog(files[0]);
921
+ let targetFile = sessionFilePath && existsSync(sessionFilePath) ? sessionFilePath : null;
922
+ if (!targetFile) {
923
+ const files = findSessionFilesForCwd(this.sessionRoot, cwd).filter((f) => basename(dirname(f)) === sessionId);
924
+ if (files.length > 0)
925
+ targetFile = files[0];
926
+ }
927
+ if (targetFile) {
928
+ conv.sessionFile = targetFile;
929
+ const { header, events } = readSessionLog(targetFile);
870
930
  conv.messages = replayEventsToMessages(events);
871
931
  for (const m of conv.messages)
872
932
  conv.messageIds.add(m.id);
@@ -937,12 +997,42 @@ export class DshClientSession {
937
997
  }
938
998
  break;
939
999
  }
940
- if (srcKind === "agent-instructions" || srcKind === "plugin")
1000
+ if (isDshInternalUserMessage(ev.data))
941
1001
  break;
942
1002
  const msg = userMessageEventToUiMessage(ev.data);
943
- // 重复文本(DSH 有时重放同一用户消息)→ 去重。
944
1003
  const text = messageTextWithQuotes(msg);
945
- if (text && conv.messages.some((m) => m.role === "user" && messageTextWithQuotes(m) === text)) {
1004
+ const cleanText = text
1005
+ .replace(/\n\[(?:文件引用|File reference|上传文件|Uploaded file|图片附件|Image attachment):[\s\S]*$/u, "")
1006
+ .trim();
1007
+ // 1. 优先查找是否有暂存的本地乐观用户消息(u-pending- 开头)
1008
+ // DSH 运行时回抛的消息往往带有 \n[File reference: ...] 附件说明,需要替换原乐观消息避免出现两条气泡
1009
+ const pendingIdx = conv.messages.findIndex((m) => m.role === "user" && typeof m.id === "string" && m.id.startsWith("u-pending-"));
1010
+ if (pendingIdx !== -1) {
1011
+ const pendingMsg = conv.messages[pendingIdx];
1012
+ const pendingText = messageTextWithQuotes(pendingMsg).trim();
1013
+ if (pendingText === text || pendingText === cleanText || text.startsWith(pendingText)) {
1014
+ conv.messageIds.delete(pendingMsg.id);
1015
+ conv.messageIds.add(msg.id);
1016
+ conv.messages[pendingIdx] = msg;
1017
+ // 图片附件异步补图处理
1018
+ const imgRefs = (ev.data.content ?? [])
1019
+ .filter((b) => b?.type === "image")
1020
+ .map((b) => b.attachment)
1021
+ .filter((r) => !!r && typeof r.attachmentId === "string" && typeof r.mediaType === "string");
1022
+ if (imgRefs.length > 0) {
1023
+ void this.hydrateImageBlocks(conv, msg, imgRefs);
1024
+ }
1025
+ break;
1026
+ }
1027
+ }
1028
+ // 2. 重复文本(DSH 有时重放同一用户消息)→ 去重。
1029
+ if (cleanText &&
1030
+ conv.messages.some((m) => {
1031
+ if (m.role !== "user")
1032
+ return false;
1033
+ const mt = messageTextWithQuotes(m).trim();
1034
+ return mt === text || mt === cleanText;
1035
+ })) {
946
1036
  break;
947
1037
  }
948
1038
  this.appendMessage(conv, msg);
@@ -1266,6 +1356,21 @@ export class DshClientSession {
1266
1356
  });
1267
1357
  }
1268
1358
  }
1359
+ guessSessionFile(conv) {
1360
+ if (conv.sessionFile && existsSync(conv.sessionFile))
1361
+ return conv.sessionFile;
1362
+ try {
1363
+ const files = findSessionFilesForCwd(this.sessionRoot, conv.cwd).filter((f) => basename(dirname(f)) === conv.sessionId);
1364
+ if (files.length > 0) {
1365
+ conv.sessionFile = files[0];
1366
+ return files[0];
1367
+ }
1368
+ }
1369
+ catch {
1370
+ /* ignore */
1371
+ }
1372
+ return undefined;
1373
+ }
1269
1374
  buildLightState(rev) {
1270
1375
  const conv = this.conv;
1271
1376
  const tokens = conv.tokens;
@@ -1289,20 +1394,23 @@ export class DshClientSession {
1289
1394
  homeDir: HOME_WIRE,
1290
1395
  desktopDir: DESKTOP_WIRE,
1291
1396
  sessionId: conv.sessionId,
1397
+ sessionFile: this.guessSessionFile(conv),
1292
1398
  conversationId: this.activeId,
1293
1399
  sandbox: this.sandboxes.getByCwd(this.cwd) ?? null,
1294
1400
  rev,
1295
1401
  streamingMessage: conv.streaming ? conv.streaming.toUiMessage(conv.lastEventAt, this.model, "deepseek") : null,
1296
1402
  isStreaming: conv.isStreaming,
1403
+ draft: this.sessionDrafts.get(conv.sessionId) ?? null,
1297
1404
  model: {
1298
1405
  id: this.model,
1299
- name: DSH_MODELS.find((m) => m.id === this.model)?.name ?? this.model,
1300
- provider: "deepseek",
1406
+ name: this.modelDisplayName || (DSH_MODELS.find((m) => m.id === this.model)?.name ?? this.model),
1407
+ provider: this.modelProvider || "deepseek",
1301
1408
  // dsh-llm-deepseek adapter:仅 vision-exp 模型 inputModalities 含 image
1302
- vision: DSH_MODELS.find((m) => m.id === this.model)?.vision ?? false,
1409
+ vision: this.modelVision,
1303
1410
  },
1304
1411
  thinkingLevel: this.thinkingLevel,
1305
1412
  availableThinkingLevels: ["high"],
1413
+ engineCapabilities: DEFAULT_DSH_CAPABILITIES,
1306
1414
  agentPreset: { id: conv.agentPreset, name: this.presetName(conv.agentPreset), locked: conv.presetLocked },
1307
1415
  permission: conv.permissionPreset ?? null,
1308
1416
  queue: { steering: conv.queue.steering, followUp: conv.queue.followUp },
@@ -1316,6 +1424,9 @@ export class DshClientSession {
1316
1424
  stats,
1317
1425
  };
1318
1426
  }
1427
+ getCapabilities() {
1428
+ return DEFAULT_DSH_CAPABILITIES;
1429
+ }
1319
1430
  // -----------------------------------------------------------------------
1320
1431
  // socket / 通知
1321
1432
  // -----------------------------------------------------------------------
@@ -1327,6 +1438,7 @@ export class DshClientSession {
1327
1438
  this.emitConversations();
1328
1439
  this.emitGoalStatus();
1329
1440
  this.pushSettings();
1441
+ this.pushDefaultModel();
1330
1442
  this.pushAgentPresets();
1331
1443
  this.pushPermission();
1332
1444
  void this.refreshPermissionOptions().catch(() => { });
@@ -1426,14 +1538,19 @@ export class DshClientSession {
1426
1538
  // 不该在列表里缺席——issue #140;空白新对话仍然不入列)。
1427
1539
  if (!conv.listed && !this.shownInRunningList(conv))
1428
1540
  continue;
1541
+ const sf = this.guessSessionFile(conv);
1542
+ const isPinned = Boolean(this.stateStore?.isSessionPinned(this.cwd, sf || "") ||
1543
+ this.stateStore?.isSessionPinned(this.cwd, conv.sessionId));
1429
1544
  list.push({
1430
1545
  id: conv.id,
1431
1546
  sessionId: conv.sessionId,
1547
+ ...(sf ? { sessionFile: sf } : {}),
1432
1548
  title: conv.title,
1433
1549
  cwd: conv.cwd,
1434
1550
  messageCount: conv.messages.length,
1435
1551
  isStreaming: conv.isStreaming,
1436
1552
  isSubagent: false,
1553
+ pinned: isPinned,
1437
1554
  // DSH Agent 预设(左栏徽标/详情用;pi 引擎不填)。
1438
1555
  agentPreset: conv.agentPreset,
1439
1556
  presetLocked: conv.presetLocked,
@@ -1737,7 +1854,19 @@ export class DshClientSession {
1737
1854
  // 新会话默认权限预设(与当前一致时 apply 无事件零噪音)。
1738
1855
  await this.ensurePermissionDefault(conv);
1739
1856
  this.flushSnapshot();
1740
- const blocks = await this.buildContentBlocks(sysPrefix ? `${sysPrefix}${text}` : text, attachments);
1857
+ const allSkills = [
1858
+ ...this.skillsCache.map((s) => ({
1859
+ name: s.name,
1860
+ description: s.description,
1861
+ filePath: "",
1862
+ dirPath: "",
1863
+ })),
1864
+ ...discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir }),
1865
+ ];
1866
+ const scanResult = scanAtMentions(text, this.cwd, allSkills, attachments ?? []);
1867
+ const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
1868
+ const promptText = formatPromptWithSkills(text, scanResult.detectedSkills);
1869
+ const blocks = await this.buildContentBlocks(sysPrefix ? `${sysPrefix}${promptText}` : promptText, effectiveAttachments);
1741
1870
  // 乐观落地用户消息(id 用暂定值;user/message 事件到达时按内容去重)。
1742
1871
  const optimistic = {
1743
1872
  id: `u-pending-${Date.now()}-${conv.deltaSeq++}`,
@@ -1799,6 +1928,9 @@ export class DshClientSession {
1799
1928
  forkConversation(prev) {
1800
1929
  const fork = this.addConversation(`fork-${randomUUID().slice(0, 12)}`, this.cwd, false, prev.agentPreset);
1801
1930
  fork.title = prev.title;
1931
+ // 继承原会话的所有消息历史,使得 UI 界面上完整保留所有轮次的历史消息
1932
+ fork.messages = [...prev.messages];
1933
+ fork.messageIds = new Set(prev.messageIds);
1802
1934
  this.activeId = fork.id;
1803
1935
  // P2-19:原会话有 active goal(DSH same-session 语义)→ 提示随会话存档。
1804
1936
  const hadGoal = prev.goal.goal !== null && prev.goal.verdict === "pending";
@@ -2141,14 +2273,30 @@ export class DshClientSession {
2141
2273
  if (sessionId.startsWith("review-"))
2142
2274
  continue;
2143
2275
  const { events } = readSessionLog(file);
2276
+ const count = events.filter((e) => (e.type === "user/message" && !isDshInternalUserMessage(e.data)) ||
2277
+ e.type === "assistant/message" ||
2278
+ e.type === "tool/result").length;
2279
+ // 过滤无消息空会话(仅有初始化 preset 事件的空壳不展示在历史列表)
2280
+ if (count === 0)
2281
+ continue;
2282
+ const isPinned = Boolean(this.stateStore?.isSessionPinned(this.cwd, file) || this.stateStore?.isSessionPinned(this.cwd, sessionId));
2283
+ const storedTitle = this.stateStore?.getSessionTitle(this.cwd, file) ?? this.stateStore?.getSessionTitle(this.cwd, sessionId);
2284
+ const explicitTitle = storedTitle ??
2285
+ sessionLogTitle(events) ??
2286
+ [...this.convs.values()].find((c) => c.sessionId === sessionId && !DshClientSession.isDefaultTitle(c.title))
2287
+ ?.title;
2288
+ const firstMsg = firstUserText(events, this.getLang());
2289
+ const displayName = this.resolveSessionDisplayName(sessionId, explicitTitle, firstMsg);
2144
2290
  summaries.push({
2145
2291
  path: file,
2146
2292
  sessionId,
2147
- name: sessionId,
2148
- firstMessage: firstUserText(events, this.getLang()),
2149
- messageCount: events.filter((e) => e.type === "user/message" || e.type === "assistant/message" || e.type === "tool/result").length,
2293
+ name: explicitTitle,
2294
+ displayName,
2295
+ firstMessage: firstMsg,
2296
+ messageCount: count,
2150
2297
  modified: statSync(file).mtimeMs,
2151
2298
  source: "web",
2299
+ pinned: isPinned,
2152
2300
  });
2153
2301
  }
2154
2302
  catch {
@@ -2161,12 +2309,91 @@ export class DshClientSession {
2161
2309
  this.emit({ type: "sessions", sessions: [] });
2162
2310
  }
2163
2311
  }
2164
- async renameSession(_path, _name) {
2312
+ /** 引擎自属的会话展示名解析回调(定制 DSH 的首条提取 + 模型自动总结命名 + 用户显式重命名记忆) */
2313
+ resolveSessionDisplayName(sessionId, explicitTitle, firstMsg) {
2314
+ const storedTitle = this.stateStore?.getSessionTitle(this.cwd, sessionId);
2315
+ if (storedTitle && !DshClientSession.isDefaultTitle(storedTitle)) {
2316
+ return storedTitle;
2317
+ }
2318
+ if (explicitTitle && !DshClientSession.isDefaultTitle(explicitTitle)) {
2319
+ return explicitTitle;
2320
+ }
2321
+ if (firstMsg && !DshClientSession.isDefaultTitle(firstMsg)) {
2322
+ return firstMsg;
2323
+ }
2324
+ return this.defaultTitle();
2325
+ }
2326
+ async pinSession(path, pinned) {
2327
+ const target = path.trim() || this.conv.sessionFile || this.conv.sessionId;
2328
+ if (this.stateStore && target) {
2329
+ this.stateStore.setSessionPinned(this.cwd, target, pinned);
2330
+ }
2331
+ this.emitConversations();
2332
+ void this.pushSessions();
2333
+ }
2334
+ async setConversationPinned(id, pinned) {
2335
+ const conv = this.convs.get(id);
2336
+ if (conv) {
2337
+ const key = conv.sessionFile || conv.sessionId;
2338
+ if (this.stateStore && key) {
2339
+ this.stateStore.setSessionPinned(this.cwd, key, pinned);
2340
+ }
2341
+ this.emitConversations();
2342
+ void this.pushSessions();
2343
+ }
2344
+ }
2345
+ saveDraft(sessionId, text, ts) {
2346
+ if (!text) {
2347
+ this.sessionDrafts.delete(sessionId);
2348
+ }
2349
+ else {
2350
+ this.sessionDrafts.set(sessionId, { text, ts: ts || Date.now() });
2351
+ }
2352
+ }
2353
+ async renameSession(path, name) {
2354
+ const trimmed = (name ?? "").trim();
2355
+ if (!trimmed)
2356
+ return;
2357
+ const absPath = path.trim() ? resolve(path.trim()) : "";
2358
+ const sid = absPath ? basename(dirname(absPath)) : "";
2359
+ for (const conv of this.convs.values()) {
2360
+ if (conv.sessionId === sid || conv.sessionFile === absPath || conv.id === path.trim()) {
2361
+ conv.title = trimmed;
2362
+ }
2363
+ }
2364
+ if (this.stateStore) {
2365
+ if (absPath)
2366
+ this.stateStore.saveSessionTitle(this.cwd, absPath, trimmed);
2367
+ if (sid)
2368
+ this.stateStore.saveSessionTitle(this.cwd, sid, trimmed);
2369
+ }
2370
+ this.emitConversations();
2371
+ this.flushSnapshot();
2372
+ await this.pushSessions();
2165
2373
  this.emit({
2166
2374
  type: "notice",
2167
- level: "warning",
2168
- text: "DSH 引擎暂不支持重命名会话",
2169
- textEn: "The DSH engine does not support renaming sessions yet",
2375
+ level: "info",
2376
+ text: `已重命名会话为「${trimmed}」`,
2377
+ textEn: `Renamed session to "${trimmed}"`,
2378
+ });
2379
+ }
2380
+ getToolPrompt(name) {
2381
+ this.emit({
2382
+ type: "tool_prompt",
2383
+ name,
2384
+ found: false,
2385
+ unsupported: true,
2386
+ });
2387
+ }
2388
+ getCompactedMessages(compactionMessageId, conversationId) {
2389
+ const conv = conversationId ? this.convs.get(conversationId) : this.conv;
2390
+ const msg = conv?.messages.find((m) => m.id === compactionMessageId);
2391
+ const compacted = msg?.details?.compactedMessages ?? [];
2392
+ this.emit({
2393
+ type: "compacted_messages_result",
2394
+ compactionMessageId,
2395
+ conversationId: conv?.id ?? this.activeId,
2396
+ messages: compacted,
2170
2397
  });
2171
2398
  }
2172
2399
  async renameConversation(id, name) {
@@ -2177,7 +2404,16 @@ export class DshClientSession {
2177
2404
  if (!conv)
2178
2405
  return;
2179
2406
  conv.title = trimmed;
2407
+ const key = conv.sessionFile || conv.sessionId;
2408
+ if (this.stateStore && key) {
2409
+ this.stateStore.saveSessionTitle(this.cwd, key, trimmed);
2410
+ if (conv.sessionId && conv.sessionFile) {
2411
+ this.stateStore.saveSessionTitle(this.cwd, conv.sessionId, trimmed);
2412
+ }
2413
+ }
2180
2414
  this.emitConversations();
2415
+ this.flushSnapshot();
2416
+ await this.pushSessions();
2181
2417
  }
2182
2418
  async deleteSession(path) {
2183
2419
  try {
@@ -2285,16 +2521,26 @@ export class DshClientSession {
2285
2521
  /** 切换会话:读 JSONL 回放 → 新建 conversation(同一 sessionId 续聊)。 */
2286
2522
  async switchSession(path, wantSessionId) {
2287
2523
  try {
2524
+ const resolvedPath = path.trim() ? resolve(path.trim()) : "";
2288
2525
  const explicitSid = wantSessionId?.trim() ?? "";
2289
- const sessionId = explicitSid || basename(dirname(resolve(path)));
2526
+ const sessionId = explicitSid || (resolvedPath ? basename(dirname(resolvedPath)) : "");
2290
2527
  // 同一 sessionId 已在运行 → 直接切过去。
2291
2528
  for (const conv of this.convs.values()) {
2292
2529
  if (conv.sessionId === sessionId || conv.id === sessionId) {
2293
2530
  await this.switchConversation(conv.id);
2531
+ this.emit({
2532
+ type: "transition_progress",
2533
+ kind: "session",
2534
+ target: path,
2535
+ phase: "done",
2536
+ progress: 100,
2537
+ text: "会话加载完成",
2538
+ textEn: "Session loaded",
2539
+ });
2294
2540
  return;
2295
2541
  }
2296
2542
  }
2297
- if (!path.trim() && explicitSid) {
2543
+ if (!resolvedPath && explicitSid) {
2298
2544
  const candidateFile = join(this.sessionRoot, explicitSid, "session.jsonl");
2299
2545
  if (!existsSync(candidateFile)) {
2300
2546
  this.emit({
@@ -2333,15 +2579,35 @@ export class DshClientSession {
2333
2579
  const prev = this.conv;
2334
2580
  // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
2335
2581
  prev.listed = this.shouldRetainDshConversation(prev);
2336
- const conv = this.addConversation(sessionId, this.cwd, true);
2582
+ const conv = this.addConversation(sessionId, this.cwd, true, undefined, resolvedPath || undefined);
2337
2583
  conv.fromDisk = true; // 磁盘回放 → prompt 时 fork
2584
+ if (resolvedPath)
2585
+ conv.sessionFile = resolvedPath;
2338
2586
  this.activeId = conv.id;
2339
2587
  this.emitConversations();
2340
2588
  this.pushTerminals();
2341
2589
  this.pushSettings();
2342
2590
  this.flushSnapshot(true);
2591
+ this.emit({
2592
+ type: "transition_progress",
2593
+ kind: "session",
2594
+ target: path,
2595
+ phase: "done",
2596
+ progress: 100,
2597
+ text: "会话加载完成",
2598
+ textEn: "Session loaded",
2599
+ });
2343
2600
  }
2344
2601
  catch (err) {
2602
+ this.emit({
2603
+ type: "transition_progress",
2604
+ kind: "session",
2605
+ target: path,
2606
+ phase: "error",
2607
+ progress: 100,
2608
+ text: `切换会话失败:${err.message}`,
2609
+ textEn: `Failed to switch session: ${err.message}`,
2610
+ });
2345
2611
  this.emit({
2346
2612
  type: "notice",
2347
2613
  level: "error",
@@ -2357,24 +2623,34 @@ export class DshClientSession {
2357
2623
  userPatchDir() {
2358
2624
  return join(this.dataDir, "dsh-patches");
2359
2625
  }
2360
- /** 列出 <dataDir>/dsh-patches/*.yml(按文件名序),带文件信息。 */
2626
+ /** 列出 <dataDir>/dsh-patches/*.yml 以及 *.yml.disabled(按文件名序),带文件信息与启停状态。 */
2361
2627
  async listDshPatches() {
2362
2628
  const dir = this.userPatchDir();
2363
2629
  const files = [];
2364
2630
  try {
2365
2631
  const { readdirSync } = await import("node:fs");
2366
2632
  for (const name of readdirSync(dir)) {
2367
- if (!name.startsWith(".") && /\.ya?ml$/iu.test(name)) {
2368
- try {
2369
- const st = statSync(join(dir, name));
2370
- if (st.isFile()) {
2371
- files.push({ name, path: join(dir, name), size: st.size, mtimeMs: st.mtimeMs });
2372
- }
2373
- }
2374
- catch {
2375
- /* skip unreadable */
2633
+ if (name.startsWith("."))
2634
+ continue;
2635
+ const isYaml = /\.ya?ml$/iu.test(name);
2636
+ const isDisabledYaml = /\.ya?ml\.disabled$/iu.test(name);
2637
+ if (!isYaml && !isDisabledYaml)
2638
+ continue;
2639
+ try {
2640
+ const st = statSync(join(dir, name));
2641
+ if (st.isFile()) {
2642
+ files.push({
2643
+ name,
2644
+ path: join(dir, name),
2645
+ size: st.size,
2646
+ mtimeMs: st.mtimeMs,
2647
+ disabled: isDisabledYaml,
2648
+ });
2376
2649
  }
2377
2650
  }
2651
+ catch {
2652
+ /* skip unreadable */
2653
+ }
2378
2654
  }
2379
2655
  }
2380
2656
  catch {
@@ -2406,6 +2682,141 @@ export class DshClientSession {
2406
2682
  }
2407
2683
  await this.listDshPatches();
2408
2684
  }
2685
+ /** 安装/添加 DSH 用户 patch(写入 <dataDir>/dsh-patches/<id>.yml 并重载运行时)。 */
2686
+ async installDshPatch(rawSpec, rawId) {
2687
+ const spec = rawSpec.trim().replace(/^['"]|['"]$/g, "");
2688
+ if (!spec) {
2689
+ this.emit({
2690
+ type: "notice",
2691
+ level: "error",
2692
+ text: "补丁包名或路径不能为空",
2693
+ textEn: "Patch package name or path cannot be empty",
2694
+ });
2695
+ return;
2696
+ }
2697
+ // 推导合法 id(仅允许字母数字横线下划线)
2698
+ let id = (rawId ?? "").trim();
2699
+ if (!id) {
2700
+ const base = basename(spec.replace(/[\\/]+$/, ""));
2701
+ id = base.replace(/^dsh-plugin-|^dsh-/, "").replace(/[^a-zA-Z0-9_-]+/g, "-");
2702
+ }
2703
+ id = id.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || `patch-${Date.now().toString(36)}`;
2704
+ const dir = this.userPatchDir();
2705
+ mkdirSync(dir, { recursive: true });
2706
+ // 规范化包名/路径:Windows 路径转为正斜杠以确保 YAML 兼容性
2707
+ const normalizedSpec = spec.replace(/\\/g, "/");
2708
+ const escapedName = normalizedSpec.replace(/'/g, "''");
2709
+ const yamlContent = `# DSH user patch generated by pi-web-ui\n- insert:\n - id: ${id}\n name: '${escapedName}'\n config: {}\n`;
2710
+ const targetFile = join(dir, `${id}.yml`);
2711
+ const disabledFile = join(dir, `${id}.yml.disabled`);
2712
+ try {
2713
+ if (existsSync(disabledFile)) {
2714
+ rmSync(disabledFile, { force: true });
2715
+ }
2716
+ writeFileSync(targetFile, yamlContent, "utf8");
2717
+ this.emit({
2718
+ type: "notice",
2719
+ level: "info",
2720
+ text: `已添加补丁 ${id},正在重启 DSH 运行时...`,
2721
+ textEn: `Added patch ${id}, restarting DSH runtime...`,
2722
+ });
2723
+ }
2724
+ catch (err) {
2725
+ this.emit({
2726
+ type: "notice",
2727
+ level: "error",
2728
+ text: `写入补丁失败:${err.message}`,
2729
+ textEn: `Failed to write patch: ${err.message}`,
2730
+ });
2731
+ return;
2732
+ }
2733
+ await this.rescanDshPatches();
2734
+ }
2735
+ /** 切换 DSH 用户 patch 启用/停用状态(重命名为 *.yml.disabled 或 *.yml)。 */
2736
+ async toggleDshPatch(name, enabled) {
2737
+ const safeName = basename(name);
2738
+ if (!safeName || safeName !== name) {
2739
+ return;
2740
+ }
2741
+ const dir = this.userPatchDir();
2742
+ const currentPath = join(dir, safeName);
2743
+ if (!existsSync(currentPath)) {
2744
+ await this.listDshPatches();
2745
+ return;
2746
+ }
2747
+ try {
2748
+ if (enabled && safeName.endsWith(".disabled")) {
2749
+ const activeName = safeName.replace(/\.disabled$/, "");
2750
+ renameSync(currentPath, join(dir, activeName));
2751
+ }
2752
+ else if (!enabled && !safeName.endsWith(".disabled")) {
2753
+ renameSync(currentPath, join(dir, `${safeName}.disabled`));
2754
+ }
2755
+ }
2756
+ catch (err) {
2757
+ this.emit({
2758
+ type: "notice",
2759
+ level: "error",
2760
+ text: `切换补丁状态失败:${err.message}`,
2761
+ textEn: `Failed to toggle patch state: ${err.message}`,
2762
+ });
2763
+ return;
2764
+ }
2765
+ await this.rescanDshPatches();
2766
+ }
2767
+ /** 删除指定的 DSH 用户 patch 文件并重启运行时。 */
2768
+ async deleteDshPatch(name) {
2769
+ const safeName = basename(name);
2770
+ if (!safeName || safeName !== name) {
2771
+ return;
2772
+ }
2773
+ const dir = this.userPatchDir();
2774
+ const filePath = join(dir, safeName);
2775
+ if (!existsSync(filePath)) {
2776
+ await this.listDshPatches();
2777
+ return;
2778
+ }
2779
+ try {
2780
+ rmSync(filePath, { force: true });
2781
+ this.emit({
2782
+ type: "notice",
2783
+ level: "info",
2784
+ text: `已删除补丁 ${safeName},正在重载...`,
2785
+ textEn: `Deleted patch ${safeName}, reloading...`,
2786
+ });
2787
+ }
2788
+ catch (err) {
2789
+ this.emit({
2790
+ type: "notice",
2791
+ level: "error",
2792
+ text: `删除补丁失败:${err.message}`,
2793
+ textEn: `Failed to delete patch: ${err.message}`,
2794
+ });
2795
+ return;
2796
+ }
2797
+ await this.rescanDshPatches();
2798
+ }
2799
+ /** 拉取 DSH 插件市场数据并推送给客户端。 */
2800
+ async fetchDshMarket(force = false) {
2801
+ try {
2802
+ const data = await loadDshMarketData(this.dataDir, force);
2803
+ this.emit({
2804
+ type: "dsh_market_data",
2805
+ count: data.count,
2806
+ updated: data.updated,
2807
+ categories: data.categories,
2808
+ plugins: data.plugins,
2809
+ });
2810
+ }
2811
+ catch (err) {
2812
+ this.emit({
2813
+ type: "notice",
2814
+ level: "warning",
2815
+ text: `拉取 DSH 插件市场失败:${err.message}`,
2816
+ textEn: `Failed to fetch DSH plugin market: ${err.message}`,
2817
+ });
2818
+ }
2819
+ }
2409
2820
  // -----------------------------------------------------------------------
2410
2821
  // 项目 / 文件 / SCM / 搜索
2411
2822
  // -----------------------------------------------------------------------
@@ -2717,6 +3128,8 @@ export class DshClientSession {
2717
3128
  for (const ev of events) {
2718
3129
  // P1-14:索引范围 = user/assistant 文本 + tool-result 工具输出。
2719
3130
  if (ev.type === "user/message" || ev.type === "assistant/message" || ev.type === "tool/result") {
3131
+ if (ev.type === "user/message" && isDshInternalUserMessage(ev.data))
3132
+ continue;
2720
3133
  const blocks = ev.data?.message?.content ??
2721
3134
  ev.data?.content ??
2722
3135
  [];
@@ -2746,14 +3159,21 @@ export class DshClientSession {
2746
3159
  // 审查会话不进搜索。
2747
3160
  if (sessionId.startsWith("review-"))
2748
3161
  continue;
2749
- if (all.includes(q) ||
2750
- sessionId.toLowerCase().includes(q) ||
2751
- firstUserText(events, this.getLang()).toLowerCase().includes(q)) {
3162
+ const firstMsg = firstUserText(events, this.getLang());
3163
+ if (all.includes(q) || sessionId.toLowerCase().includes(q) || firstMsg.toLowerCase().includes(q)) {
3164
+ const storedTitle = this.stateStore?.getSessionTitle(this.cwd, file) ?? this.stateStore?.getSessionTitle(this.cwd, sessionId);
3165
+ const explicitTitle = storedTitle ??
3166
+ sessionLogTitle(events) ??
3167
+ [...this.convs.values()].find((c) => c.sessionId === sessionId && !DshClientSession.isDefaultTitle(c.title))?.title;
3168
+ const displayName = this.resolveSessionDisplayName(sessionId, explicitTitle, firstMsg);
2752
3169
  results.push({
2753
3170
  path: file,
2754
- name: sessionId,
2755
- firstMessage: firstUserText(events, this.getLang()),
2756
- messageCount: events.filter((e) => e.type === "user/message" || e.type === "assistant/message" || e.type === "tool/result").length,
3171
+ name: explicitTitle ?? sessionId,
3172
+ displayName,
3173
+ firstMessage: firstMsg,
3174
+ messageCount: events.filter((e) => (e.type === "user/message" && !isDshInternalUserMessage(e.data)) ||
3175
+ e.type === "assistant/message" ||
3176
+ e.type === "tool/result").length,
2757
3177
  modified: statSync(file).mtimeMs,
2758
3178
  source: "web",
2759
3179
  anchors: anchors.slice(0, 10),
@@ -2817,10 +3237,12 @@ export class DshClientSession {
2817
3237
  // -----------------------------------------------------------------------
2818
3238
  // 模型 / 思考
2819
3239
  // -----------------------------------------------------------------------
2820
- /** P2-17 动态模型 id 缓存(adapter 目录查询结果;setModel 校验用)。 */
3240
+ /** P2-17 动态与自定义模型 id 缓存(adapter 目录与 models.json 自定义模型;setModel 校验用)。 */
2821
3241
  dynamicModels = new Set();
3242
+ /** 缓存自定义模型及动态适配器模型元数据,用于 setModel 快速解析。 */
3243
+ customModelsMap = new Map();
2822
3244
  async listModels() {
2823
- // 以本地表为底(定价/上下文窗口/vision 标记),运行时 adapter 目录动态
3245
+ // 以本地表为底(定价/上下文窗口/vision 标记),运行时 adapter 目录与 models.json 自定义模型动态
2824
3246
  // 扩展——新模型自动出现在选择器,无需改代码。
2825
3247
  const known = new Map(DSH_MODELS.map((m) => [m.id, m]));
2826
3248
  let dynamic = [];
@@ -2834,40 +3256,163 @@ export class DshClientSession {
2834
3256
  const seen = new Set();
2835
3257
  const models = [];
2836
3258
  this.dynamicModels.clear();
2837
- for (const m of dynamic) {
2838
- if (seen.has(m.id))
2839
- continue;
3259
+ this.customModelsMap.clear();
3260
+ // 1. DSH 官方内置模型
3261
+ for (const m of DSH_MODELS) {
3262
+ const canonicalId = `deepseek/${m.id}`;
2840
3263
  seen.add(m.id);
2841
- const local = known.get(m.id);
2842
- const vision = local?.vision ?? m.inputModalities?.includes("image") ?? false;
2843
- if (!local)
2844
- this.dynamicModels.add(m.id);
3264
+ seen.add(canonicalId);
3265
+ this.dynamicModels.add(m.id);
3266
+ this.dynamicModels.add(canonicalId);
3267
+ const meta = {
3268
+ id: canonicalId,
3269
+ bareId: m.id,
3270
+ name: m.name,
3271
+ provider: m.provider,
3272
+ reasoning: true,
3273
+ vision: m.vision,
3274
+ };
3275
+ this.customModelsMap.set(canonicalId, meta);
3276
+ this.customModelsMap.set(m.id, meta);
2845
3277
  models.push({
2846
- id: m.id,
2847
- name: local?.name ?? m.name ?? m.id,
2848
- provider: "deepseek",
3278
+ id: canonicalId,
3279
+ name: m.name,
3280
+ provider: m.provider,
2849
3281
  reasoning: true,
2850
- vision,
3282
+ vision: m.vision,
2851
3283
  });
2852
3284
  }
2853
- for (const m of DSH_MODELS) {
2854
- if (seen.has(m.id))
3285
+ // 2. 运行时动态目录(adapter 发现)
3286
+ for (const m of dynamic) {
3287
+ const canonicalId = m.id.includes("/") ? m.id : `deepseek/${m.id}`;
3288
+ const bareId = m.id.includes("/") ? m.id.slice(m.id.indexOf("/") + 1) : m.id;
3289
+ if (seen.has(m.id) || seen.has(canonicalId))
2855
3290
  continue;
2856
3291
  seen.add(m.id);
3292
+ seen.add(canonicalId);
3293
+ this.dynamicModels.add(m.id);
3294
+ this.dynamicModels.add(canonicalId);
3295
+ const local = known.get(bareId) ?? known.get(m.id);
3296
+ const vision = local?.vision ?? m.inputModalities?.includes("image") ?? false;
3297
+ const name = local?.name ?? m.name ?? bareId;
3298
+ const meta = {
3299
+ id: canonicalId,
3300
+ bareId,
3301
+ name,
3302
+ provider: "deepseek",
3303
+ reasoning: true,
3304
+ vision,
3305
+ };
3306
+ this.customModelsMap.set(canonicalId, meta);
3307
+ this.customModelsMap.set(bareId, meta);
2857
3308
  models.push({
2858
- id: m.id,
2859
- name: m.name,
2860
- provider: m.provider,
3309
+ id: canonicalId,
3310
+ name,
3311
+ provider: "deepseek",
2861
3312
  reasoning: true,
2862
- vision: m.vision,
3313
+ vision,
2863
3314
  });
2864
3315
  }
3316
+ // 3. 用户在 models.json 中配置的第三方自定义端点模型(针对性过滤 DSH 不支持的协议,如 anthropic-messages)
3317
+ try {
3318
+ const custom = listCustomModelsFromConfig(this.agentDir, (entry) => isModelProtocolSupportedByEngine("dsh", entry));
3319
+ for (const c of custom) {
3320
+ const canonicalId = `${c.providerId}/${c.modelId}`;
3321
+ if (seen.has(canonicalId))
3322
+ continue;
3323
+ seen.add(canonicalId);
3324
+ seen.add(c.modelId);
3325
+ this.dynamicModels.add(canonicalId);
3326
+ this.dynamicModels.add(c.modelId);
3327
+ const meta = {
3328
+ id: canonicalId,
3329
+ bareId: c.modelId,
3330
+ name: c.name,
3331
+ provider: c.providerId,
3332
+ reasoning: c.reasoning ?? true,
3333
+ vision: c.vision ?? false,
3334
+ };
3335
+ this.customModelsMap.set(canonicalId, meta);
3336
+ this.customModelsMap.set(c.modelId, meta);
3337
+ models.push({
3338
+ id: canonicalId,
3339
+ name: c.name,
3340
+ provider: c.providerId,
3341
+ reasoning: c.reasoning ?? true,
3342
+ vision: c.vision ?? false,
3343
+ });
3344
+ }
3345
+ }
3346
+ catch {
3347
+ /* models.json 不存在或解析错误 → 静默忽略 */
3348
+ }
2865
3349
  this.emit({ type: "models", models });
2866
3350
  }
2867
- /** 换模型 = 重启运行时。 */
3351
+ /** 解析模型 ID 对应的服务商、元数据与裸模型 ID。 */
3352
+ resolveModelMeta(modelId) {
3353
+ const normId = modelId.trim();
3354
+ const hasSlash = normId.includes("/");
3355
+ let targetProvider = hasSlash ? normId.slice(0, normId.indexOf("/")) : "";
3356
+ let bareModelId = hasSlash ? normId.slice(normId.indexOf("/") + 1) : normId;
3357
+ let meta = this.customModelsMap.get(normId) ?? this.customModelsMap.get(bareModelId);
3358
+ if (!meta) {
3359
+ const localDsh = DSH_MODELS.find((m) => m.id === normId || m.id === bareModelId || `deepseek/${m.id}` === normId);
3360
+ if (localDsh) {
3361
+ meta = {
3362
+ id: `deepseek/${localDsh.id}`,
3363
+ bareId: localDsh.id,
3364
+ name: localDsh.name,
3365
+ provider: "deepseek",
3366
+ reasoning: true,
3367
+ vision: localDsh.vision,
3368
+ };
3369
+ }
3370
+ else {
3371
+ try {
3372
+ const customList = listCustomModelsFromConfig(this.agentDir, (entry) => isModelProtocolSupportedByEngine("dsh", entry));
3373
+ const hit = customList.find((c) => `${c.providerId}/${c.modelId}` === normId || c.modelId === normId || c.modelId === bareModelId);
3374
+ if (hit) {
3375
+ meta = {
3376
+ id: `${hit.providerId}/${hit.modelId}`,
3377
+ bareId: hit.modelId,
3378
+ name: hit.name,
3379
+ provider: hit.providerId,
3380
+ reasoning: hit.reasoning ?? true,
3381
+ vision: hit.vision ?? false,
3382
+ };
3383
+ }
3384
+ }
3385
+ catch {
3386
+ /* ignore */
3387
+ }
3388
+ }
3389
+ }
3390
+ if (meta) {
3391
+ targetProvider = meta.provider;
3392
+ bareModelId = meta.bareId;
3393
+ }
3394
+ else if (!targetProvider) {
3395
+ targetProvider = "deepseek";
3396
+ }
3397
+ const known = !!meta ||
3398
+ DSH_MODELS.some((m) => m.id === normId || m.id === bareModelId) ||
3399
+ this.dynamicModels.has(normId) ||
3400
+ this.dynamicModels.has(bareModelId);
3401
+ return { meta, targetProvider, bareModelId, known };
3402
+ }
3403
+ /** 应用已保存的模型配置到当前 session 实例(启动/恢复/切换工作区时用)。 */
3404
+ applySavedModel(modelId) {
3405
+ const res = this.resolveModelMeta(modelId);
3406
+ if (res.known || res.meta) {
3407
+ this.model = res.bareModelId;
3408
+ this.modelProvider = res.targetProvider;
3409
+ this.modelDisplayName = res.meta?.name ?? res.bareModelId;
3410
+ this.modelVision = res.meta?.vision ?? false;
3411
+ }
3412
+ }
3413
+ /** 换模型 = 重启运行时。支持官方模型与第三方自定义端点模型。 */
2868
3414
  async setModel(modelId) {
2869
- // 校验:本地表 + 运行时动态目录(P2-17)。
2870
- const known = DSH_MODELS.some((m) => m.id === modelId) || this.dynamicModels.has(modelId);
3415
+ const { meta, targetProvider, bareModelId, known } = this.resolveModelMeta(modelId);
2871
3416
  if (!known) {
2872
3417
  this.emit({
2873
3418
  type: "notice",
@@ -2877,8 +3422,18 @@ export class DshClientSession {
2877
3422
  });
2878
3423
  return;
2879
3424
  }
2880
- if (modelId === this.model)
3425
+ if (bareModelId === this.model && targetProvider === this.modelProvider)
2881
3426
  return;
3427
+ // 解析服务商 BaseURL 与 API Key(如果是自定义 Provider)
3428
+ const cred = resolveProviderCredential(this.agentDir, targetProvider);
3429
+ if (targetProvider !== "deepseek" && !cred.apiKey && !process.env.DEEPSEEK_API_KEY) {
3430
+ this.emit({
3431
+ type: "notice",
3432
+ level: "warning",
3433
+ text: `服务商「${targetProvider}」未配置 API Key,请在模型与服务商设置中填写`,
3434
+ textEn: `Provider "${targetProvider}" has no API Key configured. Please configure it in Model Settings.`,
3435
+ });
3436
+ }
2882
3437
  // P0-2 竞态告知:换模型 = 强杀运行时 → 进行中的 run 全部中止。
2883
3438
  if ([...this.convs.values()].some((c) => c.isStreaming)) {
2884
3439
  this.emit({
@@ -2888,10 +3443,20 @@ export class DshClientSession {
2888
3443
  textEn: "Conversations are running; switching models aborts all of them (DSH model switch restarts the runtime)",
2889
3444
  });
2890
3445
  }
2891
- this.model = modelId;
3446
+ this.model = bareModelId;
3447
+ this.modelProvider = targetProvider;
3448
+ this.modelDisplayName = meta?.name ?? bareModelId;
3449
+ this.modelVision = meta?.vision ?? false;
3450
+ // 持久化当前项目的模型选择(按 DSH 引擎独立记录)
3451
+ this.stateStore?.saveProjectModel(this.clientId, this.cwd, modelId, "dsh");
2892
3452
  try {
2893
- await this.runtime.restart(modelId);
2894
- this.emit({ type: "notice", level: "info", text: `已切换到 ${modelId}`, textEn: `Switched to ${modelId}` });
3453
+ await this.runtime.restart(bareModelId, targetProvider);
3454
+ this.emit({
3455
+ type: "notice",
3456
+ level: "info",
3457
+ text: `已切换到 ${this.modelDisplayName}`,
3458
+ textEn: `Switched to ${this.modelDisplayName}`,
3459
+ });
2895
3460
  }
2896
3461
  catch (err) {
2897
3462
  this.emit({
@@ -2903,6 +3468,46 @@ export class DshClientSession {
2903
3468
  }
2904
3469
  this.flushSnapshot(true);
2905
3470
  }
3471
+ async setDefaultModel(modelId) {
3472
+ try {
3473
+ const res = this.resolveModelMeta(modelId);
3474
+ if (!res.known && !res.meta) {
3475
+ throw new Error(`未知模型:${modelId}`);
3476
+ }
3477
+ this.stateStore?.saveDefaultModel(modelId, "dsh");
3478
+ this.pushDefaultModel();
3479
+ this.emit({
3480
+ type: "notice",
3481
+ level: "info",
3482
+ text: `🌍 已设全局默认模型 ${modelId}(新项目自动使用,项目记忆优先)`,
3483
+ textEn: `🌍 Global default model set to ${modelId} (new projects follow it; project memory wins)`,
3484
+ });
3485
+ }
3486
+ catch (err) {
3487
+ this.emit({
3488
+ type: "notice",
3489
+ level: "error",
3490
+ text: `设置全局默认模型失败:${err.message}`,
3491
+ textEn: `Failed to set global default model: ${err.message}`,
3492
+ });
3493
+ }
3494
+ this.flushSnapshot();
3495
+ }
3496
+ clearDefaultModel() {
3497
+ this.stateStore?.saveDefaultModel("", "dsh");
3498
+ this.pushDefaultModel();
3499
+ this.emit({
3500
+ type: "notice",
3501
+ level: "info",
3502
+ text: "🌍 已清除全局默认模型(新项目回到系统默认)",
3503
+ textEn: "🌍 Global default model cleared (new projects use the system default)",
3504
+ });
3505
+ this.flushSnapshot();
3506
+ }
3507
+ pushDefaultModel() {
3508
+ const def = this.stateStore?.getDefaultModel("dsh");
3509
+ this.emit({ type: "default_model", modelId: def ? def : null });
3510
+ }
2906
3511
  setThinking(level) {
2907
3512
  if (level !== "high") {
2908
3513
  this.emit({
@@ -2960,6 +3565,7 @@ export class DshClientSession {
2960
3565
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
2961
3566
  showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
2962
3567
  retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
3568
+ openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
2963
3569
  // DSH 无 skill 全文注入概念,给空保协议完整。
2964
3570
  skillsFullText: [],
2965
3571
  visionBridgeEnabled: false,
@@ -3001,6 +3607,7 @@ export class DshClientSession {
3001
3607
  subagentModels: [],
3002
3608
  quickPhrases: [...this.settings.quickPhrases],
3003
3609
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
3610
+ minimalNewChat: this.settings.minimalNewChat,
3004
3611
  quickPhrasesSeeded: this.stateStore.getQuickPhrasesSeeded(),
3005
3612
  };
3006
3613
  this.emit({ type: "settings_state", settings });
@@ -3054,6 +3661,8 @@ export class DshClientSession {
3054
3661
  this.settings.showForkedParentSessions = Boolean(partial.showForkedParentSessions);
3055
3662
  if (partial.retainFinishedConversations !== undefined)
3056
3663
  this.settings.retainFinishedConversations = Boolean(partial.retainFinishedConversations);
3664
+ if (partial.openRecentSessionOnProjectSwitch !== undefined)
3665
+ this.settings.openRecentSessionOnProjectSwitch = Boolean(partial.openRecentSessionOnProjectSwitch);
3057
3666
  if (partial.disabledPlugins !== undefined)
3058
3667
  this.settings.disabledPlugins = partial.disabledPlugins;
3059
3668
  if (partial.uiLayout !== undefined)
@@ -3069,6 +3678,8 @@ export class DshClientSession {
3069
3678
  }
3070
3679
  if (partial.quickPhrasesEnabled !== undefined)
3071
3680
  this.settings.quickPhrasesEnabled = partial.quickPhrasesEnabled;
3681
+ if (partial.minimalNewChat !== undefined)
3682
+ this.settings.minimalNewChat = partial.minimalNewChat;
3072
3683
  const prevMarkerGuidance = this.markerSvc.buildGuidance();
3073
3684
  this.markerSvc.setAll({
3074
3685
  markersEnabled: partial.markersEnabled,
@@ -3101,11 +3712,13 @@ export class DshClientSession {
3101
3712
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
3102
3713
  showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
3103
3714
  retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
3715
+ openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
3104
3716
  disabledPlugins: this.settings.disabledPlugins,
3105
3717
  uiLayout: normalizeUiLayout(this.settings.uiLayout),
3106
3718
  reviewPrompt: this.settings.reviewPrompt,
3107
3719
  quickPhrases: this.settings.quickPhrases,
3108
3720
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
3721
+ minimalNewChat: this.settings.minimalNewChat,
3109
3722
  defaultAgentPreset: this.settings.defaultAgentPreset,
3110
3723
  promptTemplate: this.settings.promptTemplate ?? "",
3111
3724
  promptOverrides: this.settings.promptOverrides ?? {},
@@ -3498,6 +4111,7 @@ export class DshClientSession {
3498
4111
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
3499
4112
  showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
3500
4113
  retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
4114
+ openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
3501
4115
  disabledPlugins: this.settings.disabledPlugins,
3502
4116
  uiLayout: normalizeUiLayout(this.settings.uiLayout),
3503
4117
  reviewPrompt: this.settings.reviewPrompt,
@@ -3969,6 +4583,30 @@ export class DshClientSession {
3969
4583
  commands.push({ ...c, source: "builtin" });
3970
4584
  seen.add(c.name);
3971
4585
  }
4586
+ // 技能命令:运行时技能 + 磁盘技能
4587
+ for (const s of this.skillsCache) {
4588
+ const name = `skill:${s.name}`;
4589
+ if (seen.has(name))
4590
+ continue;
4591
+ commands.push({
4592
+ name,
4593
+ description: s.description,
4594
+ source: "skill",
4595
+ });
4596
+ seen.add(name);
4597
+ }
4598
+ const diskSkills = discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir });
4599
+ for (const s of diskSkills) {
4600
+ const name = `skill:${s.name}`;
4601
+ if (seen.has(name))
4602
+ continue;
4603
+ commands.push({
4604
+ name,
4605
+ description: s.description,
4606
+ source: "skill",
4607
+ });
4608
+ seen.add(name);
4609
+ }
3972
4610
  for (const cmd of this.pluginCommandsProvider?.() ?? []) {
3973
4611
  if (seen.has(cmd.name))
3974
4612
  continue;
@@ -3986,6 +4624,19 @@ export class DshClientSession {
3986
4624
  }
3987
4625
  /** 拦截执行斜杠命令;返回 true 表示已处理(不发给模型)。 */
3988
4626
  async execSlash(name, args) {
4627
+ if (name.startsWith("skill:")) {
4628
+ const skillName = name.slice(6);
4629
+ const diskSkills = discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir });
4630
+ const found = diskSkills.find((s) => s.name.toLowerCase() === skillName.toLowerCase());
4631
+ if (found) {
4632
+ const instruction = readSkillInstruction(found.filePath);
4633
+ const skillPrompt = instruction
4634
+ ? `[Skill: ${found.name}]\n${instruction}\n\n[User Prompt]\n${args || "执行此技能"}`
4635
+ : args || name;
4636
+ await this.prompt(skillPrompt);
4637
+ return true;
4638
+ }
4639
+ }
3989
4640
  switch (name) {
3990
4641
  case "new": {
3991
4642
  const first = args.trim();
@@ -4006,7 +4657,11 @@ export class DshClientSession {
4006
4657
  return true;
4007
4658
  }
4008
4659
  const q = args.trim().toLowerCase();
4009
- const all = [...DSH_MODELS, ...[...this.dynamicModels].map((id) => ({ id, name: id }))];
4660
+ const all = [
4661
+ ...DSH_MODELS,
4662
+ ...[...this.dynamicModels].map((id) => ({ id, name: id })),
4663
+ ...[...this.customModelsMap.values()].map((m) => ({ id: m.id, name: m.name })),
4664
+ ];
4010
4665
  const hit = all.find((m) => m.id === q || m.name?.toLowerCase().includes(q));
4011
4666
  if (hit) {
4012
4667
  await this.setModel(hit.id);
@@ -4127,6 +4782,7 @@ export class DshClientSession {
4127
4782
  try {
4128
4783
  const targets = collectTargets(join(homedir(), ".pi", "agent"), DshClientSession.currentAppVersion(), undefined, {
4129
4784
  projectCwd: this.cwd,
4785
+ extraTargets: collectInstalledEngineTargets(),
4130
4786
  });
4131
4787
  const items = await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(join(homedir(), ".pi", "agent")));
4132
4788
  if (force) {
@@ -4161,9 +4817,28 @@ export class DshClientSession {
4161
4817
  detail: pick(this.getLang(), "DSH 引擎不需要 pi CLI", "The DSH engine does not need the pi CLI", "dsh.engine.no.cli"),
4162
4818
  });
4163
4819
  }
4164
- /** DSH 是否就绪:auth.json 的 deepseek key 或环境变量 DEEPSEEK_API_KEY 任一即可。 */
4820
+ /** DSH 是否就绪:auth.json 的 deepseek key、环境变量 DEEPSEEK_API_KEY 或自定义 Provider 凭据任一即可。 */
4165
4821
  isDshConfigured() {
4166
- return !!loadDeepSeekKey(this.agentDir) || !!process.env.DEEPSEEK_API_KEY;
4822
+ if (loadDeepSeekKey(this.agentDir) || process.env.DEEPSEEK_API_KEY)
4823
+ return true;
4824
+ if (this.modelProvider && this.modelProvider !== "deepseek") {
4825
+ const cred = resolveProviderCredential(this.agentDir, this.modelProvider);
4826
+ if (cred.apiKey)
4827
+ return true;
4828
+ }
4829
+ try {
4830
+ const custom = listCustomModelsFromConfig(this.agentDir, (entry) => isModelProtocolSupportedByEngine("dsh", entry));
4831
+ if (custom.length > 0) {
4832
+ for (const c of custom) {
4833
+ if (resolveProviderCredential(this.agentDir, c.providerId).apiKey)
4834
+ return true;
4835
+ }
4836
+ }
4837
+ }
4838
+ catch {
4839
+ /* ignore */
4840
+ }
4841
+ return false;
4167
4842
  }
4168
4843
  /** 下拉框里的 deepseek-official 归一到 auth.json 的 deepseek 槽位(loadDeepSeekKey 只读它)。 */
4169
4844
  normalizeDshProvider(provider) {
@@ -4171,206 +4846,101 @@ export class DshClientSession {
4171
4846
  return pid === "deepseek-official" ? "deepseek" : pid;
4172
4847
  }
4173
4848
  async setProviderApiKey(provider, apiKey) {
4174
- const key = apiKey.trim();
4175
- if (!key) {
4176
- this.emit({ type: "notice", level: "error", text: "请填写 API 密钥", textEn: "Enter an API key" });
4177
- return;
4178
- }
4179
- try {
4180
- // 与 pi 引擎同形状:{ <provider>: { type: "api_key", key } }。
4181
- const authPath = join(this.agentDir, "auth.json");
4182
- let auth = {};
4183
- try {
4184
- auth = JSON.parse(readFileSync(authPath, "utf8"));
4185
- }
4186
- catch {
4187
- /* new file */
4188
- }
4189
- auth[this.normalizeDshProvider(provider)] = { type: "api_key", key };
4190
- writeJsonAtomicSync(authPath, auth);
4191
- this.emit({
4192
- type: "notice",
4193
- level: "info",
4194
- text: `✅ 已保存 ${provider.trim()} 的 API 密钥`,
4195
- textEn: `Saved API key`,
4196
- });
4197
- if (this.runtime.alive)
4198
- await this.runtime.restart(this.model);
4199
- this.flushSnapshot();
4200
- }
4201
- catch (err) {
4202
- this.emit({
4203
- type: "notice",
4204
- level: "error",
4205
- text: `保存 key 失败:${err.message}`,
4206
- textEn: `Failed to save key: ${err.message}`,
4207
- });
4849
+ await this.modelAdmin.setProviderApiKey(provider, apiKey);
4850
+ if (this.runtime.alive && (provider === "deepseek" || provider === "deepseek-official")) {
4851
+ await this.runtime.restart(this.model);
4208
4852
  }
4853
+ this.flushSnapshot();
4209
4854
  }
4210
4855
  async clearProviderApiKey(provider) {
4211
- const pid = this.normalizeDshProvider(provider);
4212
- try {
4213
- const authPath = join(this.agentDir, "auth.json");
4214
- const auth = JSON.parse(readFileSync(authPath, "utf8"));
4215
- if (!(pid in auth)) {
4216
- this.emit({ type: "notice", level: "info", text: `${pid} 没有已保存的密钥`, textEn: `No saved key` });
4217
- return;
4218
- }
4219
- delete auth[pid];
4220
- writeJsonAtomicSync(authPath, auth);
4221
- this.emit({
4222
- type: "notice",
4223
- level: "info",
4224
- text: `🗑 已清除 ${pid} 的密钥,该服务商回到未配置状态`,
4225
- textEn: "Cleared",
4226
- });
4227
- if (this.runtime.alive && pid === "deepseek")
4228
- await this.runtime.restart(this.model);
4229
- this.flushSnapshot();
4230
- }
4231
- catch (err) {
4232
- this.emit({
4233
- type: "notice",
4234
- level: "error",
4235
- text: `清除失败:${err.message}`,
4236
- textEn: `Clear failed: ${err.message}`,
4237
- });
4856
+ await this.modelAdmin.clearProviderApiKey(provider);
4857
+ if (this.runtime.alive && (provider === "deepseek" || provider === "deepseek-official")) {
4858
+ await this.runtime.restart(this.model);
4238
4859
  }
4860
+ this.flushSnapshot();
4239
4861
  }
4240
- startProviderOAuth(_provider) {
4241
- this.emit({
4242
- type: "notice",
4243
- level: "warning",
4244
- text: "当前引擎不支持 OAuth 登录",
4245
- textEn: "The current engine does not support OAuth login",
4246
- });
4862
+ startProviderOAuth(provider) {
4863
+ this.modelAdmin.startProviderOAuth(provider);
4864
+ }
4865
+ replyProviderOAuth(flowId, promptId, value) {
4866
+ this.modelAdmin.replyProviderOAuth(flowId, promptId, value);
4867
+ }
4868
+ cancelProviderOAuth(flowId) {
4869
+ this.modelAdmin.cancelProviderOAuth(flowId);
4247
4870
  }
4248
- replyProviderOAuth(_flowId, _promptId, _value) { }
4249
- cancelProviderOAuth(_flowId) { }
4250
4871
  listProviderOAuthFlows() {
4251
- this.emit({ type: "provider_oauth_flows", flows: [] });
4872
+ this.modelAdmin.listProviderOAuthFlows();
4252
4873
  }
4253
4874
  async logoutProviderOAuth(provider) {
4254
- this.emit({
4255
- type: "provider_oauth_logout_result",
4256
- provider,
4257
- ok: false,
4258
- error: "当前引擎不支持 OAuth 登录",
4259
- });
4875
+ return this.modelAdmin.logoutProviderOAuth(provider);
4260
4876
  }
4261
4877
  async listModelsConfig() {
4262
- this.emit({ type: "models_config", providers: [] });
4878
+ return this.modelAdmin.listModelsConfig();
4263
4879
  }
4264
4880
  async reloadModelsConfig() {
4265
- this.emit({
4266
- type: "notice",
4267
- level: "warning",
4268
- text: "DSH 引擎不支持自定义 provider",
4269
- textEn: "The DSH engine does not support custom providers",
4270
- });
4881
+ return this.modelAdmin.reloadModelsConfig();
4271
4882
  }
4272
- async saveModelConfig(_providerId, _config) {
4273
- this.emit({
4274
- type: "notice",
4275
- level: "warning",
4276
- text: "DSH 引擎使用内置 DeepSeek 模型,不支持自定义模型配置",
4277
- textEn: "The DSH engine uses the built-in DeepSeek model",
4278
- });
4883
+ async saveModelConfig(providerId, config) {
4884
+ await this.modelAdmin.saveModelConfig(providerId, config);
4885
+ if (this.runtime.alive && (providerId === "deepseek" || providerId === "deepseek-official")) {
4886
+ await this.runtime.restart(this.model);
4887
+ }
4279
4888
  }
4280
- async deleteModelConfig(_providerId) {
4281
- this.emit({
4282
- type: "notice",
4283
- level: "warning",
4284
- text: "DSH 引擎不支持自定义模型配置",
4285
- textEn: "The DSH engine does not support custom model configs",
4889
+ deleteModelConfig(providerId) {
4890
+ return this.modelAdmin.deleteModelConfig(providerId).then(async () => {
4891
+ if (this.runtime.alive && (providerId === "deepseek" || providerId === "deepseek-official")) {
4892
+ await this.runtime.restart(this.model);
4893
+ }
4286
4894
  });
4287
4895
  }
4288
4896
  async listProviders() {
4289
- this.emit({
4290
- type: "providers_status",
4291
- providers: [
4292
- {
4293
- id: "deepseek-official",
4294
- name: pick(this.getLang(), "DeepSeek 官方", "DeepSeek Official", "dsh.provider.deepseek.official"),
4295
- configured: this.isDshConfigured(),
4296
- source: loadDeepSeekKey(this.agentDir) ? "stored" : process.env.DEEPSEEK_API_KEY ? "environment" : undefined,
4297
- supportsApiKey: true,
4298
- supportsOAuth: false,
4299
- usingOAuth: false,
4300
- },
4301
- ],
4302
- });
4897
+ return this.modelAdmin.listProviders();
4303
4898
  }
4304
4899
  listProviderKeys() {
4305
- this.emit({ type: "provider_keys", keys: {} });
4900
+ this.modelAdmin.listProviderKeys();
4306
4901
  }
4307
- async addProviderKey(_provider, _apiKey, _name) {
4308
- this.emit({
4309
- type: "notice",
4310
- level: "warning",
4311
- text: "DSH 引擎不支持多密钥",
4312
- textEn: "The DSH engine does not support multiple keys",
4313
- });
4902
+ async addProviderKey(provider, apiKey, name) {
4903
+ await this.modelAdmin.addProviderKey(provider, apiKey, name);
4904
+ if (this.runtime.alive && (provider === "deepseek" || provider === "deepseek-official")) {
4905
+ await this.runtime.restart(this.model);
4906
+ }
4314
4907
  }
4315
- async activateProviderKey(_provider, _keyName) {
4316
- this.emit({
4317
- type: "notice",
4318
- level: "warning",
4319
- text: "DSH 引擎不支持多密钥",
4320
- textEn: "The DSH engine does not support multiple keys",
4321
- });
4908
+ async activateProviderKey(provider, keyName) {
4909
+ await this.modelAdmin.activateProviderKey(provider, keyName);
4910
+ if (this.runtime.alive && (provider === "deepseek" || provider === "deepseek-official")) {
4911
+ await this.runtime.restart(this.model);
4912
+ }
4322
4913
  }
4323
- async removeProviderKey(_provider, _keyName) {
4324
- this.emit({
4325
- type: "notice",
4326
- level: "warning",
4327
- text: "DSH 引擎不支持多密钥",
4328
- textEn: "The DSH engine does not support multiple keys",
4329
- });
4914
+ async removeProviderKey(provider, keyName) {
4915
+ await this.modelAdmin.removeProviderKey(provider, keyName);
4916
+ if (this.runtime.alive && (provider === "deepseek" || provider === "deepseek-official")) {
4917
+ await this.runtime.restart(this.model);
4918
+ }
4330
4919
  }
4331
- async fetchModelsList(reqId, _baseUrl, _apiKey, _authHeader, _api) {
4332
- this.emit({
4333
- type: "fetch_models_result",
4334
- reqId,
4335
- ok: false,
4336
- error: pick(this.getLang(), "DSH 引擎不支持自定义 provider 探测", "The DSH engine does not support custom provider probing", "dsh.provider.probing.unsupported"),
4337
- });
4920
+ async fetchModelsList(reqId, baseUrl, apiKey, authHeader, api, providerId) {
4921
+ return this.modelAdmin.fetchModelsList(reqId, baseUrl, apiKey, authHeader, api, () => this.getLang(), providerId);
4338
4922
  }
4339
- async refreshProviderModels(_providerId, reqId) {
4340
- this.emit({
4341
- type: "refresh_provider_result",
4342
- reqId,
4343
- ok: false,
4344
- error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
4345
- });
4923
+ async testModelConnection(reqId, baseUrl, apiKey, authHeader, api, providerId) {
4924
+ return this.modelAdmin.testConnection(reqId, baseUrl, apiKey, authHeader, api, () => this.getLang(), providerId);
4925
+ }
4926
+ async refreshProviderModels(providerId, reqId) {
4927
+ return this.modelAdmin.refreshProviderModels(providerId, reqId, () => this.getLang());
4346
4928
  }
4347
4929
  async refreshBuiltinModels(reqId) {
4348
- this.emit({
4349
- type: "refresh_builtin_result",
4350
- reqId,
4351
- ok: false,
4352
- error: pick(this.getLang(), "DSH 引擎走运行时内置模型,无官方目录可刷新", "The DSH engine uses runtime-built-in models; no official catalog to refresh", "dsh.provider.builtin.refresh.unsupported"),
4353
- });
4930
+ return this.modelAdmin.refreshBuiltinModels(reqId);
4354
4931
  }
4355
- async appendBuiltinModel(_providerId, _model, reqId) {
4356
- this.emit({
4357
- type: "append_builtin_result",
4358
- reqId,
4359
- ok: false,
4360
- error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
4361
- });
4932
+ async appendBuiltinModel(providerId, model, reqId) {
4933
+ return this.modelAdmin.appendBuiltinModel(providerId, model, reqId);
4934
+ }
4935
+ async cloneProvider(provider, reqId) {
4936
+ return this.modelAdmin.cloneProvider(provider, reqId);
4362
4937
  }
4363
- async cloneProvider(_provider, reqId) {
4364
- const error = pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.clone.unsupported");
4365
- const errorEn = "DSH engine does not support custom providers";
4366
- this.emit({ type: "notice", level: "error", text: error, textEn: errorEn });
4367
- this.emit({ type: "clone_provider_result", reqId, ok: false, error });
4938
+ async enrichModels(reqId, ids, hints) {
4939
+ return this.modelAdmin.enrichModels(reqId, ids, hints);
4368
4940
  }
4369
- async enrichModels(reqId, _ids, _hints) {
4370
- const error = pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported");
4371
- this.emit({ type: "enrich_models_result", reqId, ok: false, error });
4941
+ abortEnrichModels(reqId) {
4942
+ this.modelAdmin.abortEnrichModels(reqId);
4372
4943
  }
4373
- abortEnrichModels(_reqId) { }
4374
4944
  // -----------------------------------------------------------------------
4375
4945
  // 其他
4376
4946
  // -----------------------------------------------------------------------
@@ -4503,9 +5073,14 @@ export class DshClientSession {
4503
5073
  this.cwd = abs;
4504
5074
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
4505
5075
  this.stateStore.remember(this.clientId, abs);
5076
+ // 恢复新工作区的记忆模型(按 DSH 引擎独立记录:项目记忆 > 全局默认)
5077
+ const savedModel = this.stateStore.getProjectModel(this.clientId, abs, "dsh") ?? this.stateStore.getDefaultModel("dsh");
5078
+ if (savedModel) {
5079
+ this.applySavedModel(savedModel);
5080
+ }
4506
5081
  // 换项目 = 重启运行时(initialize 固定 cwd)。
4507
5082
  try {
4508
- await this.runtime.restart(this.model);
5083
+ await this.runtime.restart(this.model, this.modelProvider);
4509
5084
  }
4510
5085
  catch (err) {
4511
5086
  this.emit({
@@ -4519,8 +5094,31 @@ export class DshClientSession {
4519
5094
  // (与 pi 的 displaceActive 语义一致);空白的直接弃(不列)。
4520
5095
  const prev = this.conv;
4521
5096
  prev.listed = this.shouldRetainDshConversation(prev) || prev.messages.length > 0;
4522
- // 新项目 → 新会话。
4523
- this.activeId = this.addConversation(`web-${randomUUID().slice(0, 12)}`, abs, false).id;
5097
+ // 新项目 → 恢复最近历史会话(若有)或新建空白会话
5098
+ const openRecent = this.settings.openRecentSessionOnProjectSwitch ?? true;
5099
+ const recentFiles = openRecent
5100
+ ? findSessionFilesForCwd(this.sessionRoot, abs).filter((f) => !basename(dirname(f)).startsWith("review-"))
5101
+ : [];
5102
+ let resumedConv = null;
5103
+ for (const file of recentFiles) {
5104
+ try {
5105
+ const { events } = readSessionLog(file);
5106
+ const hasRealMessages = events.some((e) => (e.type === "user/message" && !isDshInternalUserMessage(e.data)) ||
5107
+ e.type === "assistant/message");
5108
+ if (hasRealMessages) {
5109
+ const sid = basename(dirname(file));
5110
+ const conv = this.addConversation(sid, abs, true, undefined, file);
5111
+ conv.fromDisk = true;
5112
+ conv.sessionFile = file;
5113
+ resumedConv = conv;
5114
+ break;
5115
+ }
5116
+ }
5117
+ catch {
5118
+ continue;
5119
+ }
5120
+ }
5121
+ this.activeId = (resumedConv ?? this.addConversation(`web-${randomUUID().slice(0, 12)}`, abs, false)).id;
4524
5122
  // 旧项目非活跃 conversation 回收(pi 的 displaceActive 语义:切走后
4525
5123
  // 非 streaming / 无终端 / 未列出的旧会话从内存移除,磁盘 JSONL 可回放恢复)。
4526
5124
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
@@ -4594,6 +5192,7 @@ export class DshClientSession {
4594
5192
  this.retentionOnce = null;
4595
5193
  }
4596
5194
  this.bg.stop();
5195
+ this.modelAdmin.dispose();
4597
5196
  for (const conv of this.convs.values())
4598
5197
  conv.terminals.killAll();
4599
5198
  try {
@@ -4826,6 +5425,9 @@ export class DshAgentService {
4826
5425
  }
4827
5426
  this.clients.clear();
4828
5427
  }
5428
+ getCapabilities() {
5429
+ return DEFAULT_DSH_CAPABILITIES;
5430
+ }
4829
5431
  /** dsh engine keeps no interrupted-run record — resume is pi-only. */
4830
5432
  recordInterruptedRuns() {
4831
5433
  /* no-op */