pi-web-ui 0.112.0 → 0.113.1

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 (48) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +1 -7
  3. package/README.zh-CN.md +1 -7
  4. package/README.zh-TW.md +1 -7
  5. package/bin/pi-web-ui.mjs +423 -50
  6. package/dist/gh-comment-781.md +5 -0
  7. package/dist/server/agent-service-daemon.js +29 -4
  8. package/dist/server/agent-service.js +222 -36
  9. package/dist/server/canvas/canvas-agent-tool.js +2 -0
  10. package/dist/server/canvas/canvas-orchestrator.js +40 -1
  11. package/dist/server/canvas/pstack-skills-data.js +498 -0
  12. package/dist/server/control-socket.js +6 -2
  13. package/dist/server/dispatch-domain-handlers.js +36 -11
  14. package/dist/server/dsh/dsh-agent-service.js +52 -4
  15. package/dist/server/durable/durable-driver.js +37 -98
  16. package/dist/server/durable/durable-event-projector.js +253 -0
  17. package/dist/server/engine-probe.js +35 -11
  18. package/dist/server/files-service.js +72 -8
  19. package/dist/server/index.js +74 -50
  20. package/dist/server/model-admin.js +185 -63
  21. package/dist/server/plugins.js +10 -6
  22. package/dist/server/remote-ssh-service.js +110 -12
  23. package/dist/server/serialize.js +1 -1
  24. package/dist/server/settings-service.js +36 -48
  25. package/dist/server/setup-page.js +632 -0
  26. package/dist/server/skill-discovery.js +361 -59
  27. package/dist/server/skill-maintenance.js +231 -0
  28. package/dist/server/skill-tool.js +32 -3
  29. package/dist/server/soft-cap.js +29 -7
  30. package/dist/server/subagents.js +246 -31
  31. package/dist/server/tool-host-factories.js +2 -0
  32. package/dist/server/tool-manager.js +106 -28
  33. package/dist/server/universal/drivers/claude-code.js +96 -4
  34. package/dist/server/universal/universal-session.js +19 -0
  35. package/dist/server/webui-context.js +6 -6
  36. package/dist/test-artifact.md +9 -0
  37. package/dist/test-preview-modal.md +11 -0
  38. package/dist/test-report.html +20 -0
  39. package/package.json +1 -1
  40. package/plugin-sdk/index.d.ts +17 -3
  41. package/plugins/catalog.json +10 -0
  42. package/web/dist/assets/{TerminalPanel-Dqr1dK28.js → TerminalPanel-Ci55JtJL.js} +2 -2
  43. package/web/dist/assets/index-ByiO9f-N.js +2008 -0
  44. package/web/dist/assets/index-ycGLh4a4.css +1 -0
  45. package/web/dist/index.html +2 -2
  46. package/web/dist/sw.js +1 -1
  47. package/web/dist/assets/index-Dh8BX-lP.js +0 -720
  48. package/web/dist/assets/index-DqrC1I_a.css +0 -1
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { join, resolve } from "node:path";
16
16
  import { statSync } from "node:fs";
17
+ import { randomUUID } from "node:crypto";
17
18
  import { VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
18
19
  import { ClientStateStore } from "./client-state.js";
19
20
  import { ClaimStore } from "./claim-store.js";
@@ -593,13 +594,29 @@ export class AgentService {
593
594
  throw new Error("chatFromPlugin: text 为空");
594
595
  if (this.quiesced)
595
596
  throw new QuiesceRejectedError("插件无头调用被拒绝,请等服务器恢复后重试");
597
+ // 本轮运行的稳定标识:随该轮所有 run 事件下发。为何需要:过户会把对话搬到
598
+ // 别的客户端会话(clientId 变),目标会话已有同名 id 时还会就地改名
599
+ // (conversationId 变)——两个键全失效,通道插件靠它认领自己的回包。
600
+ const runId = `pr-${randomUUID()}`;
596
601
  // 1. 绑定已有会话:steer 语义投递,网页端实时可见(微信当远程遥控器用)。
597
602
  // miss/已回收时不抛错,回落无头伪客户端(浏览器关着时微信照常可用)。
598
603
  const target = String(req?.conversationId ?? "").trim();
599
604
  if (target) {
600
605
  const w = await this.wakeConversation(target, text);
601
- if (w.ok)
602
- return { conversationId: target, clientId: w.clientId ?? clientId };
606
+ if (w.ok) {
607
+ // 投递成功:给该对话打上运行 token(过户后事件依旧带它)。
608
+ const owner = w.clientId ? this.clients.get(w.clientId) : undefined;
609
+ if (owner) {
610
+ try {
611
+ const conv = w.conversationId ? owner.getConversation(w.conversationId) : undefined;
612
+ owner.markPluginRun(runId, conv);
613
+ }
614
+ catch {
615
+ /* 打标尽力而为,不影响已投递的请求 */
616
+ }
617
+ }
618
+ return { conversationId: w.conversationId ?? target, clientId: w.clientId ?? clientId, runId };
619
+ }
603
620
  }
604
621
  // 2. 工作空间:不传回落伪客户端当前目录;传了必须存在且非系统目录。
605
622
  const cwdReq = String(req?.cwd ?? "").trim();
@@ -636,9 +653,17 @@ export class AgentService {
636
653
  throw new Error(`chatFromPlugin: 切换思考强度失败(${thinking}):${err.message}`);
637
654
  }
638
655
  }
639
- const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
656
+ // 打运行 token(没真跑起来就不认领,不会污染用户自己下一轮的事件归属)。
657
+ let stampedId = "";
658
+ try {
659
+ stampedId = cs.markPluginRun(runId);
660
+ }
661
+ catch {
662
+ /* 打标尽力而为 */
663
+ }
664
+ const conversationId = stampedId || (cs.readConversationForPlugins()?.conversationId ?? "");
640
665
  void cs.prompt(text);
641
- return { conversationId, clientId };
666
+ return { conversationId, clientId, runId };
642
667
  }
643
668
  /** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
644
669
  * 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
@@ -42,6 +42,7 @@ import { SettingsService } from "./settings-service.js";
42
42
  import { GoalService, buildDiffFingerprint, extractErrorSnippetFromSession, lastToolNameOfSession, } from "./goal-service.js";
43
43
  import { buildEvidenceDigest, sessionMessagesOf } from "./goal-evidence.js";
44
44
  import { MarkerService } from "./marker-service.js";
45
+ import { discoverDiskSkills, mergeSkillCollections, readSkillInstruction } from "./skill-discovery.js";
45
46
  import { SlashCommandsService, parseSlash } from "./slash-commands.js";
46
47
  import { ModelAdminService } from "./model-admin.js";
47
48
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
@@ -75,7 +76,7 @@ import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAg
75
76
  import { makeLoadToolsTool } from "./load-tools-tool.js";
76
77
  import { formatCompactSignature } from "./tool-signature.js";
77
78
  import { WebUIContext } from "./webui-context.js";
78
- import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, SOFT_CAP_MIN_TOKENS, SOFT_CAP_MIN_HEADROOM, } from "./soft-cap.js";
79
+ import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, SOFT_CAP_MIN_TOKENS, SOFT_CAP_MIN_HEADROOM, softCapReserveFor, } from "./soft-cap.js";
79
80
  import { makeEditSoftTool } from "./edit-soft-tool.js";
80
81
  // 覆盖 SDK 内置 read:路径是目录时列出目录条目(行为开关 readDirEnabled,默认开)。
81
82
  // 覆盖定义与「与扩展同名工具共存」的注入辅助分在两个文件(后者的依据见 tool-overrides.ts)。
@@ -306,6 +307,8 @@ export class ClientSession {
306
307
  bashKills = new Set();
307
308
  /** Background-server tracking (port snapshots + 后台任务 panel state) —
308
309
  * 自包含模块,见 bg-servers.ts。列表按 CLIENT 存活,不随对话切换/结束消失。 */
310
+ /** 用户直接创建的交互式终端(按 CLIENT/工作区 存活,始终显示,不受单个对话切换、生命周期与过滤影响) */
311
+ userTerminals;
309
312
  /** 文件树 / 预览读写 / SCM 查询 / watcher —— 自包含模块,见 files-service.ts。 */
310
313
  files = new FilesService({
311
314
  emit: (msg) => this.emit(msg),
@@ -405,12 +408,44 @@ export class ClientSession {
405
408
  get terminals() {
406
409
  return this.conv.terminals;
407
410
  }
411
+ getUserTerminalManager() {
412
+ return this.userTerminals;
413
+ }
414
+ findTerminalManager(terminalId, conversationId) {
415
+ if (this.userTerminals?.has(terminalId)) {
416
+ return this.userTerminals;
417
+ }
418
+ if (conversationId) {
419
+ const convTm = this.convs.get(conversationId)?.terminals;
420
+ if (convTm?.has(terminalId))
421
+ return convTm;
422
+ }
423
+ if (this.conv?.terminals?.has(terminalId)) {
424
+ return this.conv.terminals;
425
+ }
426
+ for (const conv of this.convs.values()) {
427
+ if (conv.terminals?.has(terminalId))
428
+ return conv.terminals;
429
+ }
430
+ return this.getTerminalManager(conversationId);
431
+ }
408
432
  getTerminalManager(conversationId) {
409
433
  return (conversationId ? this.convs.get(conversationId) : this.convs.get(this.activeId))?.terminals;
410
434
  }
411
435
  getTerminalCwd(conversationId) {
412
436
  return (conversationId ? this.convs.get(conversationId) : this.convs.get(this.activeId))?.cwd ?? this.cwd;
413
437
  }
438
+ makeUserTerminalManager() {
439
+ const mgr = new TerminalManager((msg) => {
440
+ if (msg.type === "terminal_list") {
441
+ this.pushTerminals();
442
+ return;
443
+ }
444
+ // 用户终端的输出、退出无条件向前端广播,绝不受 activeId 限制
445
+ this.emit(msg);
446
+ }, this.cwd, () => this.getLang());
447
+ return mgr;
448
+ }
414
449
  makeTerminalManager(conversationId, cwd) {
415
450
  const mgr = new TerminalManager((msg) => this.emitTerminal(conversationId, msg), cwd,
416
451
  // issue #91:终端输入错误按客户端 UI 语言出中英(英文默认)。
@@ -610,8 +645,6 @@ export class ClientSession {
610
645
  // message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
611
646
  // 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
612
647
  conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
613
- // 子代理不走 bindSession——统一收口注入配置覆盖与工具门控
614
- this.applySessionOverrides(conv);
615
648
  // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
616
649
  // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
617
650
  try {
@@ -650,7 +683,7 @@ export class ClientSession {
650
683
  // 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
651
684
  // 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
652
685
  await this.restoreKeyForModel(followModel, resolvedCwd);
653
- await conv.session.setModel(m);
686
+ await this.applySessionModel(conv.session, m);
654
687
  }
655
688
  catch (err) {
656
689
  if (explicitModel) {
@@ -693,6 +726,10 @@ export class ClientSession {
693
726
  });
694
727
  }
695
728
  }
729
+ // 子代理不走 bindSession——统一收口注入配置覆盖与工具门控。
730
+ // 必须在上面换模型(followModel 块)之后调:压缩 reserveTokens 按会话当前
731
+ // 模型的窗口算,提前调就会把子代理的判定线钉在派发者模型上(issue #773)。
732
+ this.applySessionOverrides(conv);
696
733
  // 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
697
734
  // 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
698
735
  conv.kickoff = conv.session
@@ -1131,18 +1168,32 @@ export class ClientSession {
1131
1168
  this.emit(msg);
1132
1169
  }
1133
1170
  pushTerminals(conversation = this.conv) {
1171
+ const userList = this.userTerminals ? this.userTerminals.list() : [];
1172
+ const convList = conversation ? conversation.terminals.list() : [];
1134
1173
  this.emit({
1135
1174
  type: "terminal_list",
1136
- conversationId: conversation.id,
1137
- terminals: conversation.terminals.list(),
1175
+ conversationId: conversation?.id,
1176
+ terminals: [...userList, ...convList],
1138
1177
  });
1139
- for (const output of conversation.terminals.replay()) {
1140
- this.emit({
1141
- type: "terminal_output",
1142
- conversationId: conversation.id,
1143
- terminalId: output.terminalId,
1144
- data: output.data,
1145
- });
1178
+ if (this.userTerminals) {
1179
+ for (const output of this.userTerminals.replay()) {
1180
+ this.emit({
1181
+ type: "terminal_output",
1182
+ conversationId: conversation?.id,
1183
+ terminalId: output.terminalId,
1184
+ data: output.data,
1185
+ });
1186
+ }
1187
+ }
1188
+ if (conversation) {
1189
+ for (const output of conversation.terminals.replay()) {
1190
+ this.emit({
1191
+ type: "terminal_output",
1192
+ conversationId: conversation.id,
1193
+ terminalId: output.terminalId,
1194
+ data: output.data,
1195
+ });
1196
+ }
1146
1197
  }
1147
1198
  }
1148
1199
  /**
@@ -1842,6 +1893,24 @@ export class ClientSession {
1842
1893
  }
1843
1894
  }
1844
1895
  },
1896
+ getActiveConversationId: () => this.activeId,
1897
+ dismissSubagent: async (convId, opts) => {
1898
+ const owner = this.subagentOwnerOf(convId);
1899
+ const curId = owner.convs.has(convId) ? convId : this.subagentCurrentId(convId);
1900
+ const conv = owner.convs.get(curId);
1901
+ if (!conv) {
1902
+ return { ok: false, reason: "not_found" };
1903
+ }
1904
+ if (curId === owner.activeId) {
1905
+ return { ok: false, reason: "active" };
1906
+ }
1907
+ if (!conv.isSubagent && !conv.parentId && !conv.subagentPrompt) {
1908
+ return { ok: false, reason: "not_subagent" };
1909
+ }
1910
+ await owner.dismissConversation(curId, true, opts?.force);
1911
+ const stillThere = owner.convs.has(curId);
1912
+ return stillThere ? { ok: false, reason: "retained" } : { ok: true };
1913
+ },
1845
1914
  getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
1846
1915
  // issue #91:子代理工具返回按客户端 UI 语言出中英(英文默认)。
1847
1916
  lang: () => this.getLang(),
@@ -2347,6 +2416,7 @@ export class ClientSession {
2347
2416
  // Prune dead background tasks every 30s (only spawns netstat/lsof while
2348
2417
  // the list is non-empty). unref: must not keep the process alive.
2349
2418
  this.bg.start();
2419
+ this.userTerminals = this.makeUserTerminalManager();
2350
2420
  if (!ephemeralCleanupScheduled) {
2351
2421
  ephemeralCleanupScheduled = true;
2352
2422
  const timer = setTimeout(() => {
@@ -2590,16 +2660,22 @@ export class ClientSession {
2590
2660
  // 否则按主会话禁用集过滤。预设拿掉 skill 加载器时(minimal/code/ask)
2591
2661
  // 名录同步隐藏——列出来但调不动只是噪音(见 tool-manager.ts 语义总表)。
2592
2662
  skillsOverride: (res) => {
2663
+ const discovered = discoverDiskSkills({
2664
+ cwd: effectiveCwd,
2665
+ agentDir: this.agentDir,
2666
+ workspaceRoots: this.roots,
2667
+ });
2668
+ const allSkills = mergeSkillCollections(res.skills, discovered);
2593
2669
  if (apply && apply.enabledSkills.length > 0) {
2594
2670
  const set = new Set(apply.enabledSkills);
2595
- return { ...res, skills: res.skills.filter((s) => set.has(s.name)) };
2671
+ return { ...res, skills: allSkills.filter((s) => set.has(s.name)) };
2596
2672
  }
2597
2673
  const preset = this.convs.get(ownerId ?? "")?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2598
2674
  if (!presetShowsSkillCatalog(preset))
2599
2675
  return { ...res, skills: [] };
2600
2676
  return {
2601
2677
  ...res,
2602
- skills: res.skills.filter((s) => !this.settingsSvc.current.disabledSkills.includes(s.name)),
2678
+ skills: allSkills.filter((s) => !this.settingsSvc.current.disabledSkills.includes(s.name)),
2603
2679
  };
2604
2680
  },
2605
2681
  // 插件:模板非空扩展白名单时只加载白名单里的;否则按主会话禁用集过滤。
@@ -3507,12 +3583,39 @@ export class ClientSession {
3507
3583
  if (!this.onRunEvent)
3508
3584
  return;
3509
3585
  try {
3510
- this.onRunEvent({ ...ev, conversationId: conv.id, at: Date.now() });
3586
+ this.onRunEvent({
3587
+ ...ev,
3588
+ conversationId: conv.id,
3589
+ clientId: this.clientId,
3590
+ // 通道插件按它认领「自己那一轮」——过户换持有客户端、对话被改 id 都不影响。
3591
+ ...(conv.pluginRunId ? { runId: conv.pluginRunId } : {}),
3592
+ at: Date.now(),
3593
+ });
3511
3594
  }
3512
3595
  catch (err) {
3513
3596
  console.error("[agent-service] onRunEvent failed:", err);
3514
3597
  }
3515
3598
  }
3599
+ /** 插件无头调用(host.chat)标记「本轮由该插件驱动」,返回被打标的对话 id。
3600
+ * 已在流式中(steer 并入在途运行)立即生效;否则等 agent_start 认领。
3601
+ * token 在 run_end 清掉,用户随后自己接着聊的那一轮不会被误认成插件的。 */
3602
+ markPluginRun(runId, conv) {
3603
+ const target = conv ?? this.conv;
3604
+ const id = String(runId ?? "").trim();
3605
+ if (!target || !id)
3606
+ return target?.id ?? "";
3607
+ try {
3608
+ if (target.session.isStreaming)
3609
+ target.pluginRunId = id;
3610
+ else
3611
+ target.pendingPluginRunId = id;
3612
+ }
3613
+ catch {
3614
+ /* isStreaming 读不到就按未启动处理 */
3615
+ target.pendingPluginRunId = id;
3616
+ }
3617
+ return target.id;
3618
+ }
3516
3619
  /** 当前打开对话变了 → 通知插件重拉(切历史会话/切 running 对话/新对话)。
3517
3620
  * 异常隔离——插件坏了只记日志,绝不影响切换流程。 */
3518
3621
  notifyConversationChanged() {
@@ -3711,6 +3814,12 @@ export class ClientSession {
3711
3814
  await conv.session.sendUserMessage(text, conv.session.isStreaming ? { deliverAs: "steer" } : undefined);
3712
3815
  return { ok: true };
3713
3816
  }
3817
+ /** 按 id 取本会话持有的对话(不存在返回 undefined)。
3818
+ * host.chat 命中已有会话时,用它在**对方**会话里校验/定位被唤醒的那条对话。 */
3819
+ getConversation(id) {
3820
+ const key = String(id ?? "").trim();
3821
+ return key ? this.convs.get(key) : undefined;
3822
+ }
3714
3823
  /** issue #231:本客户端内按稳定键定位调度唤醒目标。
3715
3824
  * sessionFile 优先(压缩/重启后内存对话 id 已变,落盘会话文件才是同一会话);
3716
3825
  * 只有没给 sessionFile 时才按内存 id 找,且 id 必须附带 cwd 一致才认 ——
@@ -4007,13 +4116,19 @@ export class ClientSession {
4007
4116
  case "tool_execution_update": {
4008
4117
  const text = extractPartialText(event.partialResult);
4009
4118
  if (text) {
4119
+ // issue #782: SDK onUpdate(partialResult) sends a cumulative snapshot (e.g. bash).
4120
+ // To avoid O(n^2) bandwidth inflation for long outputs while retaining realtime view,
4121
+ // slice the latest tail (64KB cap). Send with mode="replace" so the client replaces
4122
+ // rather than accumulating prev + delta.
4123
+ const safeText = text.length > 64 * 1024 ? text.slice(text.length - 64 * 1024) : text;
4010
4124
  this.emit({
4011
4125
  type: "tool_delta",
4012
4126
  conversationId: conv.id,
4013
4127
  seq: ++conv.deltaSeq,
4014
4128
  toolCallId: event.toolCallId,
4015
4129
  toolName: event.toolName,
4016
- delta: text,
4130
+ delta: safeText,
4131
+ mode: "replace",
4017
4132
  });
4018
4133
  }
4019
4134
  break;
@@ -4132,6 +4247,10 @@ export class ClientSession {
4132
4247
  return a.role === "assistant" && typeof a.stopReason === "string";
4133
4248
  });
4134
4249
  this.emitRun(conv, lastAssistant?.stopReason ? { type: "run_end", stopReason: lastAssistant.stopReason } : { type: "run_end" });
4250
+ // 本轮已收尾:插件运行 token 到刺杀 —— 用户随后在同一对话里自己接着聊的
4251
+ // 那一轮不得再被当成插件驱动的(否则微信会回传网页端用户的轮次)。
4252
+ conv.pluginRunId = undefined;
4253
+ conv.pendingPluginRunId = undefined;
4135
4254
  }
4136
4255
  catch {
4137
4256
  /* 轨迹尽力而为 */
@@ -4348,6 +4467,11 @@ export class ClientSession {
4348
4467
  case "agent_start": {
4349
4468
  // 本轮已正式进入流式(session.isStreaming=true),清除首轮启动期投递标记(#589)。
4350
4469
  conv.promptInFlight = false;
4470
+ // 插件投递的待认领 token 在本轮真的开跑时转正(未开跑的不认领,避免污染下一轮)。
4471
+ if (conv.pendingPluginRunId) {
4472
+ conv.pluginRunId = conv.pendingPluginRunId;
4473
+ conv.pendingPluginRunId = undefined;
4474
+ }
4351
4475
  // 轨迹事件:新一轮开始(任务文本由 prompt() 暂存;steer/内部续跑
4352
4476
  // 无暂存时省略,插件回退为「继续执行」)。
4353
4477
  const task = conv.pendingTask;
@@ -6449,7 +6573,7 @@ export class ClientSession {
6449
6573
  }
6450
6574
  return;
6451
6575
  }
6452
- await this.session.setModel(model);
6576
+ await this.applySessionModel(this.session, model);
6453
6577
  }
6454
6578
  catch {
6455
6579
  // model no longer resolvable / key gone — keep the conversation default
@@ -6467,7 +6591,7 @@ export class ClientSession {
6467
6591
  /**
6468
6592
  * 统一会话配置与门控收口方法(单一事实源)。
6469
6593
  * 无论是新建、切换、回滚、编辑重问、看门狗重置还是设置变更:
6470
- * 统一应用重试次数、压缩防爆保留值、codemode 预算以及工具门控(含 planMode/delegateMode/禁用名单/权限预设)。
6594
+ * 统一应用重试次数、压缩保留值(按会话自己的模型与软上限重算)、codemode 预算以及工具门控(含 planMode/delegateMode/禁用名单/权限预设)。
6471
6595
  * 彻底杜绝各业务入口散落调用与遗漏。
6472
6596
  */
6473
6597
  applySessionOverrides(target) {
@@ -6500,21 +6624,59 @@ export class ClientSession {
6500
6624
  }
6501
6625
  }
6502
6626
  }
6503
- /** 确保各存活会话的 SDK compaction reserveTokens 保持默认值(issue #716)。
6504
- * 软上限由 pi-web-ui 主动管控(triggerSoftCapCompactionIfExceeded),
6505
- * 不再将 W - C 注入 SDK reserveTokens,从数学上杜绝换模型重算泄漏。 */
6627
+ /** 逐会话重算 SDK compaction reserveTokens(issue #229 → #716 → #773)。
6628
+ * 软上限双层管控:
6629
+ * - 回合内层:reserve = max(默认 16384, cw - cap)。SDK 在每次工具调用间隙的
6630
+ * _compactBeforeNextAssistantResponse 就会在 cap 处压缩——自治长跑(子代理、
6631
+ * 单回合几十次工具调用)全程没有空闲态,只有这一层拦得住(issue #773)。
6632
+ * - 空闲态层:triggerSoftCapCompactionIfExceeded,负责 reserve 管不到的场景
6633
+ * (cap 中途下调 / 附件注入超阈 / 从磁盘恢复的已超阈会话)。
6634
+ *
6635
+ * #716 当初把 reserve 锁死在默认值,怕的是「换模型残留上一模型的 W - C」。
6636
+ * 所以这里必须用**每个会话自己的活模型**算,且每次都完整重算、不累加——
6637
+ * 残留状态不存在,泄漏也就无从发生(换模型一律走 applySessionModel,其他重算点:
6638
+ * 新建/切换、设置变更、reload、AI 主动压缩后,见 applySessionOverrides 等)。
6639
+ * cap 关闭/非法/压不下来时回落默认 16384 = 原样的物理兜底线。 */
6506
6640
  applyCompactionOverrides() {
6641
+ const s = this.settingsSvc.current;
6507
6642
  for (const c of this.convs.values()) {
6643
+ let reserve = DEFAULT_COMPACTION_RESERVE_TOKENS;
6508
6644
  try {
6509
- c.session.settingsManager.applyOverrides({
6510
- compaction: { reserveTokens: DEFAULT_COMPACTION_RESERVE_TOKENS },
6511
- });
6645
+ const cw = contextWindowOf(c.session);
6646
+ if (cw > 0) {
6647
+ const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(c.session));
6648
+ // keepRecentTokens 读活值:用户可在 settings.json 覆盖,压缩尾部就按它留。
6649
+ let keepRecent = 0;
6650
+ try {
6651
+ keepRecent = c.session.settingsManager.getCompactionKeepRecentTokens(c.session.model) ?? 0;
6652
+ }
6653
+ catch {
6654
+ keepRecent = 0;
6655
+ }
6656
+ reserve = softCapReserveFor(cw, cap, keepRecent) ?? DEFAULT_COMPACTION_RESERVE_TOKENS;
6657
+ }
6658
+ }
6659
+ catch {
6660
+ // 会话未就绪/已释放 → 只回默认值,不连累其他会话。
6661
+ }
6662
+ try {
6663
+ c.session.settingsManager.applyOverrides({ compaction: { reserveTokens: reserve } });
6512
6664
  }
6513
6665
  catch {
6514
6666
  // 会话未就绪或已释放 → 其 runtime 创建时统一注入。
6515
6667
  }
6516
6668
  }
6517
6669
  }
6670
+ /** 会话换模型的唯一入口(issue #716/#773):先把模型换上,立即按新模型的窗口
6671
+ * 重算该会话的 compaction reserveTokens。
6672
+ *
6673
+ * reserve 依赖会话**当前**模型(cw - cap),任何绕过此处的裸 session.setModel()
6674
+ * 都会让判定线卡在上一模型的 W - C 上(子代理因此在长回合里不压缩,issue #773)。
6675
+ * 新增换模型路径必须走这里,不要直接 setModel。 */
6676
+ async applySessionModel(session, model) {
6677
+ await session.setModel(model);
6678
+ this.applyCompactionOverrides();
6679
+ }
6518
6680
  /** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
6519
6681
  applyCodemodeOverrides() {
6520
6682
  const mode = this.settingsSvc.current.codemodeMode ?? "on";
@@ -6566,7 +6728,9 @@ export class ClientSession {
6566
6728
  if (!session || session.isStreaming)
6567
6729
  return false;
6568
6730
  const contextWindow = contextWindowOf(session);
6569
- const cap = this.activeSoftCap(contextWindow);
6731
+ // 用**本会话**的模型算按模型覆盖:子代理/后台对话的模型未必等于当前活动对话,
6732
+ // 串用会拿错 cap(issue #773)。
6733
+ const cap = this.activeSoftCap(contextWindow, session);
6570
6734
  if (!cap || cap <= 0)
6571
6735
  return false;
6572
6736
  const currentTokens = this.getEffectiveContextTokens(conv);
@@ -6590,11 +6754,12 @@ export class ClientSession {
6590
6754
  return false;
6591
6755
  }
6592
6756
  }
6593
- /** 当前活动对话的生效软上限(快照底栏标记线用;null = 关闭/未知)。 */
6594
- activeSoftCap(contextWindow) {
6757
+ /** 生效软上限(快照底栏标记线用;null = 关闭/未知)。
6758
+ * session 缺省 = 当前活动会话;压缩触发方必须传自己那个会话来算按模型覆盖。 */
6759
+ activeSoftCap(contextWindow, session = this.session) {
6595
6760
  try {
6596
6761
  const s = this.settingsSvc.current;
6597
- const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(this.session));
6762
+ const cap = effectiveSoftCap(s.softCapTokens, s.softCapByModel, modelKeyOf(session));
6598
6763
  if (!cap || cap < SOFT_CAP_MIN_TOKENS)
6599
6764
  return null;
6600
6765
  if (contextWindow > 0 && cap >= contextWindow - SOFT_CAP_MIN_HEADROOM)
@@ -7009,8 +7174,25 @@ export class ClientSession {
7009
7174
  error: res.error,
7010
7175
  });
7011
7176
  }
7012
- /** 从远程仓库拉取单个技能的完整 SKILL.md 内容 */
7177
+ /** 拉取单个技能的完整 SKILL.md 内容(支持本地已安装与远程仓库) */
7013
7178
  async fetchSkillContent(repo, skillId) {
7179
+ if (repo === "local" || !repo) {
7180
+ const diskSkills = discoverDiskSkills({
7181
+ cwd: this.cwd,
7182
+ agentDir: this.agentDir,
7183
+ });
7184
+ const matched = diskSkills.find((s) => s.name.toLowerCase() === skillId.toLowerCase());
7185
+ if (matched) {
7186
+ const content = readSkillInstruction(matched.filePath);
7187
+ this.emit({
7188
+ type: "skill_content_result",
7189
+ ok: true,
7190
+ skillId,
7191
+ content,
7192
+ });
7193
+ return;
7194
+ }
7195
+ }
7014
7196
  const res = await fetchRemoteSkillContent({
7015
7197
  repo,
7016
7198
  skillId,
@@ -9147,6 +9329,10 @@ export class ClientSession {
9147
9329
  conv.unsubscribe?.();
9148
9330
  conv.unsubscribe = undefined;
9149
9331
  this.clearConversationToolStates(conv);
9332
+ // 强杀重建:上一轮的运行已经没了(agent_end 不会再发,run_end 不会到达带 runId),
9333
+ // 残留的插件运行 token 必须清掉——否则用户随后自己聊的那一轮会被当插件驱动。
9334
+ conv.pluginRunId = undefined;
9335
+ conv.pendingPluginRunId = undefined;
9150
9336
  disposeEvalSession(conv.id);
9151
9337
  await conv.runtime.dispose();
9152
9338
  // #485:dispose 挂起期间会话可能已被强行关闭移出(forceDismiss 走
@@ -9394,7 +9580,7 @@ export class ClientSession {
9394
9580
  const mid = `${p}/${prevModel.id}`;
9395
9581
  // 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
9396
9582
  await this.restoreKeyForModel(mid, this.cwd);
9397
- await this.session.setModel(prevModel);
9583
+ await this.applySessionModel(this.session, prevModel);
9398
9584
  modelRestored = true;
9399
9585
  }
9400
9586
  catch {
@@ -12007,7 +12193,7 @@ export class ClientSession {
12007
12193
  try {
12008
12194
  const pm = prevModel;
12009
12195
  await this.restoreKeyForModel(`${pm.provider}/${pm.id}`, targetConv.cwd);
12010
- await this.session.setModel(prevModel);
12196
+ await this.applySessionModel(this.session, prevModel);
12011
12197
  }
12012
12198
  catch {
12013
12199
  // keep default
@@ -12256,7 +12442,7 @@ export class ClientSession {
12256
12442
  const pm = prevModel;
12257
12443
  // 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
12258
12444
  await this.restoreKeyForModel(`${pm.provider}/${pm.id}`, this.cwd);
12259
- await this.session.setModel(prevModel);
12445
+ await this.applySessionModel(this.session, prevModel);
12260
12446
  }
12261
12447
  catch {
12262
12448
  // model no longer resolvable — keep the default
@@ -13191,13 +13377,12 @@ export class ClientSession {
13191
13377
  throw new Error(`模型不存在:${modelId}`);
13192
13378
  // 先恢复 provider key,再 setModel(否则 checkAuth 鉴权失败)
13193
13379
  await this.restoreKeyForModel(modelId, this.cwd);
13194
- await this.session.setModel(model);
13380
+ await this.applySessionModel(this.session, model);
13195
13381
  // Immediately remember the model + the key it uses for the current
13196
13382
  // project (not only after a turn). This is what makes project switching
13197
13383
  // restore both the model and the provider key.
13198
13384
  this.rememberProjectModel(modelId);
13199
- // 换模型后按新模型的窗口重算软上限覆盖(按模型覆盖可能不同,issue #229)。
13200
- this.applyCompactionOverrides();
13385
+ // 换模型后按新模型的窗口重算软上限覆盖已由 applySessionModel 完成(issue #229/#773)。
13201
13386
  // 切换成功 → 立即通知插件(#542:不发消息也能收到);失败路径落在 catch 里,不发。
13202
13387
  this.notifyPluginModelChange();
13203
13388
  }
@@ -13342,6 +13527,7 @@ export class ClientSession {
13342
13527
  // TerminateProcess + 状态清理,句柄由 OS 在进程退出时回收。
13343
13528
  for (const conv of this.convs.values())
13344
13529
  conv.terminals.killAll({ shutdown: true });
13530
+ this.userTerminals?.killAll({ shutdown: true });
13345
13531
  if (this.snapshotTimer) {
13346
13532
  clearTimeout(this.snapshotTimer);
13347
13533
  this.snapshotTimer = null;
@@ -84,6 +84,8 @@ const VALID_ROLES = new Set([
84
84
  "api",
85
85
  "memory",
86
86
  "end",
87
+ "pstack",
88
+ "skill",
87
89
  ]);
88
90
  const canvasSchema = Type.Object({
89
91
  action: Type.Union([
@@ -17,6 +17,8 @@ import { saveCanvasRuntimeState, loadCanvasGraph, saveCanvasGraph, isSafeGraphId
17
17
  import { isInsideGitRepo, normalizeWirePath } from "../worktree-service.js";
18
18
  import { execFile } from "node:child_process";
19
19
  import { promisify } from "node:util";
20
+ import { PSTACK_SKILLS_MAP } from "./pstack-skills-data.js";
21
+ import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
20
22
  const exec = promisify(execFile);
21
23
  export class CanvasOrchestrator {
22
24
  dataDir;
@@ -243,7 +245,12 @@ export class CanvasOrchestrator {
243
245
  this.activeExecutions.delete(execKey);
244
246
  return;
245
247
  }
246
- node.currentAction = `[${node.engine.toUpperCase()}] 启动 ${node.model} 执行中 (${node.role})...`;
248
+ const roleDetail = node.role === "pstack"
249
+ ? `pstack: ${String(node.config?.skill || "poteto-mode")}`
250
+ : node.role === "skill"
251
+ ? `skill: ${String(node.config?.skillName || node.config?.skill || "soul")}`
252
+ : node.role;
253
+ node.currentAction = `[${node.engine.toUpperCase()}] 启动 ${node.model} 执行中 (${roleDetail})...`;
247
254
  this.broadcast({
248
255
  type: "canvas_node_event",
249
256
  graphId: graph.id,
@@ -293,6 +300,38 @@ export class CanvasOrchestrator {
293
300
  !isCanvasPassthroughRole(node.role)) {
294
301
  prompt += `\n\n【首节点启动指引】: 当前为流水线首节点。请结合当前工作区代码库现状,排查梳理项目架构规范与待实现的核心任务,输出明确的分工契约交由下游节点接力执行。`;
295
302
  }
303
+ if (node.role === "pstack") {
304
+ const skillKey = String(node.config?.skill ?? "poteto-mode").trim();
305
+ const item = PSTACK_SKILLS_MAP[skillKey] || PSTACK_SKILLS_MAP["poteto-mode"];
306
+ const skillTitle = item ? `${item.icon} ${item.nameZh} (${item.id})` : skillKey;
307
+ const skillDoc = item?.content ? item.content.slice(0, 4500) : "";
308
+ prompt = `【Pstack 严谨工程专项工作依据 · ${skillTitle}】\n${skillDoc}\n\n【Pstack 执行守则】\n1. 深入优先、拒绝 AI 废话(Unslop):严禁生成无实质意义的虚浮描述和表面修补代码;\n2. 拿实证说话:完成修改后必须提供可复现的验证依据(测试输出、运行诊断或精确行为证据);\n3. 遵循所选 Skill(${skillKey})的全部非妥协原则(Non-negotiables)开展本节点任务。\n\n【本节点任务与上下文】\n${prompt}`;
309
+ }
310
+ else if (node.role === "skill") {
311
+ const targetSkillName = String(node.config?.skillName ?? node.config?.skill ?? "").trim();
312
+ let skillInstruction = "";
313
+ let foundSkillTitle = targetSkillName || "未指定技能";
314
+ if (targetSkillName) {
315
+ const diskSkills = discoverDiskSkills({
316
+ cwd: resolvedCwd || this.baseCwd,
317
+ dataDir: this.dataDir,
318
+ scanAncestors: true,
319
+ });
320
+ const matched = diskSkills.find((s) => s.name.toLowerCase() === targetSkillName.toLowerCase());
321
+ if (matched) {
322
+ skillInstruction = readSkillInstruction(matched.filePath);
323
+ foundSkillTitle = matched.name;
324
+ }
325
+ else {
326
+ const pstackItem = PSTACK_SKILLS_MAP[targetSkillName.toLowerCase()];
327
+ if (pstackItem) {
328
+ skillInstruction = pstackItem.content;
329
+ foundSkillTitle = `${pstackItem.icon} ${pstackItem.nameZh} (${pstackItem.id})`;
330
+ }
331
+ }
332
+ }
333
+ prompt = `【技能之魂 (Soul of Skill) · ${foundSkillTitle}】\n${skillInstruction ? `你当前以此 Skill 的规约与方法论作为你的核心灵魂与行动指南:\n${skillInstruction.slice(0, 4500)}` : `以「${foundSkillTitle}」技能要求为核心灵魂与行为准则。`}\n\n【执行契约】\n必须完全以该 Skill 的专业角色与标准推进工作,结合上游交付物严谨执行。\n\n【本节点任务与上下文】\n${prompt}`;
334
+ }
296
335
  let outputSummary = "";
297
336
  // AI 条件裁决(config.aiJudge=true):条件节点走一次轻量问答做语义判定,
298
337
  // 只能回“结论:通过/不通过”,下游按它分流;失败回落关键词。未开启还是零 token 透传。