pi-web-ui 0.98.0 → 0.100.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 (69) hide show
  1. package/CHANGELOG.md +85 -5
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/bin/pi-web-ui.mjs +174 -36
  5. package/dist/server/agent-service.js +1169 -152
  6. package/dist/server/approval-rules.js +95 -23
  7. package/dist/server/attachments.js +55 -0
  8. package/dist/server/bg-servers.js +82 -2
  9. package/dist/server/claim-files-tool.js +4 -4
  10. package/dist/server/client-state.js +41 -0
  11. package/dist/server/compact-context-tool.js +10 -9
  12. package/dist/server/conversation-read-tool.js +7 -8
  13. package/dist/server/conversation-touches.js +19 -0
  14. package/dist/server/delegate-task.js +10 -14
  15. package/dist/server/dsh/dsh-agent-service.js +116 -12
  16. package/dist/server/edit-soft-tool.js +10 -12
  17. package/dist/server/eval-tool.js +26 -6
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +78 -15
  20. package/dist/server/hashline-engine.js +198 -31
  21. package/dist/server/index.js +55 -9
  22. package/dist/server/load-tools-tool.js +100 -0
  23. package/dist/server/lsp-tool.js +10 -16
  24. package/dist/server/marker-service.js +53 -12
  25. package/dist/server/markers/builtins/action.js +108 -0
  26. package/dist/server/markers/index.js +4 -1
  27. package/dist/server/model-enrich.js +2 -0
  28. package/dist/server/patch-remote-catalog.js +28 -10
  29. package/dist/server/patch-tool.js +74 -38
  30. package/dist/server/plan-manager.js +71 -30
  31. package/dist/server/plan-mode.js +7 -6
  32. package/dist/server/plugin-api-catalog.js +10 -3
  33. package/dist/server/plugin-conversation-view.js +47 -0
  34. package/dist/server/plugins.js +113 -26
  35. package/dist/server/present-files-tool.js +10 -11
  36. package/dist/server/preset-fields.js +693 -0
  37. package/dist/server/preset-share.js +1178 -0
  38. package/dist/server/prompt-composer.js +23 -9
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/read-tool.js +8 -10
  41. package/dist/server/resolve-global-sdk.js +80 -18
  42. package/dist/server/schedule-agent-tool.js +147 -146
  43. package/dist/server/sdk-origin.js +125 -37
  44. package/dist/server/settings-service.js +103 -84
  45. package/dist/server/skill-tool.js +3 -4
  46. package/dist/server/subagents.js +15 -22
  47. package/dist/server/terminals.js +29 -39
  48. package/dist/server/tool-approval.js +3 -1
  49. package/dist/server/tool-manager.js +63 -27
  50. package/dist/server/tool-prompt-overrides.js +158 -0
  51. package/dist/server/tool-prompts.js +42 -0
  52. package/dist/server/tool-signature.js +104 -0
  53. package/dist/server/update-check.js +0 -15
  54. package/dist/server/workspace-snapshot.js +42 -11
  55. package/package.json +5 -3
  56. package/plugin-sdk/README.md +8 -4
  57. package/plugin-sdk/import-check.mjs +210 -0
  58. package/plugin-sdk/index.d.ts +4 -1
  59. package/plugin-sdk/index.mjs +1 -0
  60. package/plugins/catalog.json +33 -2
  61. package/themes/zhupi-dark.css +1 -1
  62. package/themes/zhupi.css +1 -1
  63. package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  64. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  65. package/web/dist/assets/index-BYumAaGi.js +379 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/sw.js +1 -1
  68. package/web/dist/assets/index-2jDtjHvW.css +0 -1
  69. package/web/dist/assets/index-BjdK7s1M.js +0 -368
@@ -20,17 +20,18 @@ export function makePatchTool(options) {
20
20
  const getLang = options.lang ?? (() => "en");
21
21
  return defineTool({
22
22
  name: PATCH_TOOL_NAME,
23
- promptSnippet: "apply content-hashed, line-anchored patches to workspace files (prevents stale edits, line drift, and indentation hallucination)",
23
+ promptSnippet: "apply content-hashed, line-anchored patches to files",
24
24
  label: "Apply Hashline patch",
25
25
  description: `Apply content-hashed, line-anchored patches to workspace files — prevents stale edits, line drift, and indentation hallucination.
26
26
  Each file section starts with \`[path#TAG]\` (or \`[path]\` if the hash is unknown yet). Operations:
27
27
  - \`PUT N.=M:\` replace lines N..M (inclusive) with the following \`+TEXT\` lines.
28
- - \`PUT N*:\` replace the whole syntactic block starting at line N (closing brace/indent auto-resolved).
29
- - \`PUT <N:\` insert before line N (\`<1\` = head of file); \`PUT >N:\` insert after (\`>$\` = end).
30
- - \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines and save to register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
31
- - \`REM\` delete file; \`MV dest/path\` move/rename file.
32
- - Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line).
33
- On divergence the engine attempts a 3-way merge. After success the tool returns the next anchor tag and live LSP diagnostics.`,
28
+ - \`PUT N*:\` replace the syntactic block starting at line N (closing brace/indent auto-resolved).
29
+ - \`PUT <N:\` / \`PUT >N:\` insert before / after line N (\`<1\` = head, \`>$\` = end).
30
+ - \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines into a register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
31
+ - \`REM\` delete file; \`MV dest/path\` move/rename.
32
+ - Create a file: bare \`[path]\` header (no tag) on a nonexistent path + \`PUT <1:\` / \`PUT >$:\` \`+TEXT\` content.
33
+ - Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line). Divergence triggers a 3-way merge.
34
+ Success returns the next anchor tag and live LSP diagnostics.`,
34
35
  parameters: Type.Object({
35
36
  patch: Type.String({
36
37
  description: "The complete Hashline patch text containing one or more [path#TAG] sections with PUT/CUT/REM/MV operations.",
@@ -38,7 +39,7 @@ On divergence the engine attempts a 3-way merge. After success the tool returns
38
39
  timeout: Type.Optional(Type.Number({
39
40
  minimum: 1,
40
41
  maximum: 300,
41
- description: "Optional execution timeout in seconds (1-300).",
42
+ description: "Optional execution timeout in seconds.",
42
43
  })),
43
44
  }),
44
45
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
@@ -61,41 +62,76 @@ On divergence the engine attempts a 3-way merge. After success the tool returns
61
62
  details: emptyReport,
62
63
  };
63
64
  }
64
- const report = applyHashlinePatch(patchText, {
65
- cwd,
66
- snapshotStore: globalSnapshotStore,
67
- });
68
- if (!report.ok) {
65
+ // timeout 此前是死参数:schema 声明了 1-300 秒,execute 从未读取,大补丁
66
+ // 卡住只能等 20 分钟看门狗(issue #462)。这里用 Promise.race 实现真实
67
+ // 超时,覆盖 await 长尾(实时 LSP 诊断等);applyHashlinePatch 是同步
68
+ // 本地文件操作,同步段无法被中断,race 只能兜异步部分。
69
+ const timeoutSec = params.timeout ? Math.min(Math.max(1, params.timeout), 300) : null;
70
+ const finish = async () => {
71
+ const report = applyHashlinePatch(patchText, {
72
+ cwd,
73
+ snapshotStore: globalSnapshotStore,
74
+ });
75
+ if (!report.ok) {
76
+ return {
77
+ content: [
78
+ {
79
+ type: "text",
80
+ text: pick(L, `补丁应用失败:\n${report.summary}`, `Patch Failed:\n${report.summary}`),
81
+ },
82
+ ],
83
+ details: report,
84
+ };
85
+ }
86
+ const textOutput = [report.summary];
87
+ // 为成功修改的文件输出最新的头部标签,方便 Agent 连续进行下一步修改
88
+ for (const r of report.results) {
89
+ if (r.op !== "deleted" && r.newHash) {
90
+ const targetPath = r.newPath || r.filePath;
91
+ textOutput.push(pick(L, `\n${targetPath} 的下一处编辑锚点:\`${formatHashlineHeader(targetPath, r.newHash)}\``, `\nNext edit anchor for ${targetPath}: \`${formatHashlineHeader(targetPath, r.newHash)}\``));
92
+ try {
93
+ const fullPath = resolve(cwd, targetPath);
94
+ const diags = await getLiveLspDiagnostics(fullPath, cwd);
95
+ if (diags) {
96
+ textOutput.push(pick(L, `\n${targetPath} 的实时 LSP 诊断:\n${diags}`, `\nLive LSP diagnostics for ${targetPath}:\n${diags}`));
97
+ }
98
+ }
99
+ catch { }
100
+ }
101
+ }
69
102
  return {
70
- content: [
71
- {
72
- type: "text",
73
- text: pick(L, `补丁应用失败:\n${report.summary}`, `Patch Failed:\n${report.summary}`),
74
- },
75
- ],
103
+ content: [{ type: "text", text: textOutput.join("\n") }],
76
104
  details: report,
77
105
  };
106
+ };
107
+ if (!timeoutSec)
108
+ return finish();
109
+ const timeoutReply = {
110
+ content: [
111
+ {
112
+ type: "text",
113
+ text: pick(L, `补丁执行超时(${timeoutSec}s)。补丁可能已部分应用,请检查目标文件后重试。`, `Patch execution timed out (${timeoutSec}s). The patch may have been partially applied; check the target files and retry.`),
114
+ },
115
+ ],
116
+ details: {
117
+ ok: false,
118
+ summary: `Execution timed out after ${timeoutSec}s`,
119
+ results: [],
120
+ error: "timeout",
121
+ },
122
+ };
123
+ let timer;
124
+ try {
125
+ return await Promise.race([
126
+ finish(),
127
+ new Promise((resolveTimeout) => {
128
+ timer = setTimeout(() => resolveTimeout(timeoutReply), timeoutSec * 1000);
129
+ }),
130
+ ]);
78
131
  }
79
- const textOutput = [report.summary];
80
- // 为成功修改的文件输出最新的头部标签,方便 Agent 连续进行下一步修改
81
- for (const r of report.results) {
82
- if (r.op !== "deleted" && r.newHash) {
83
- const targetPath = r.newPath || r.filePath;
84
- textOutput.push(pick(L, `\n${targetPath} 的下一处编辑锚点:\`${formatHashlineHeader(targetPath, r.newHash)}\``, `\nNext edit anchor for ${targetPath}: \`${formatHashlineHeader(targetPath, r.newHash)}\``));
85
- try {
86
- const fullPath = resolve(cwd, targetPath);
87
- const diags = await getLiveLspDiagnostics(fullPath, cwd);
88
- if (diags) {
89
- textOutput.push(pick(L, `\n${targetPath} 的实时 LSP 诊断:\n${diags}`, `\nLive LSP diagnostics for ${targetPath}:\n${diags}`));
90
- }
91
- }
92
- catch { }
93
- }
132
+ finally {
133
+ clearTimeout(timer);
94
134
  }
95
- return {
96
- content: [{ type: "text", text: textOutput.join("\n") }],
97
- details: report,
98
- };
99
135
  },
100
136
  });
101
137
  }
@@ -11,13 +11,26 @@
11
11
  * - 模型可通过 customTool `plan_update` 更新
12
12
  * - 客户端也可通过协议消息 `plan_update` 调整
13
13
  * - 状态自动同步到快照 `UiState.plan`
14
+ *
15
+ * 存储模型与隔离设计(防新会话串台):
16
+ * - 持久化源(plansBySession):以真实唯一的 SDK sessionId 为主键,落盘至 plans.json。
17
+ * - 运行时缓存(plansByConv):以会话槽位 conversationId 为主键,仅存活于进程内存,绝不落盘。
18
+ * - 历史文件清洗:严格过滤形如 /^c\d+$/ 的易变短 ID,防止服务重启后新会话被上一个会话的任务附体。
14
19
  */
15
20
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
16
21
  import { dirname } from "node:path";
17
22
  const VALID_STATUSES = new Set(["pending", "in_progress", "done", "failed"]);
23
+ /** 判断是否为易变的临时 conversationId(如 c1, c2, c99 等)。此类短 ID 绝不入持久化文件。 */
24
+ function isEphemeralConvId(id) {
25
+ return /^c\d+$/.test(id);
26
+ }
18
27
  export class PlanManager {
19
28
  filePath;
20
- plans = new Map();
29
+ /** 按持久化 sessionId 存储的真实计划状态(落盘至 plans.json)。 */
30
+ plansBySession = new Map();
31
+ /** 按运行时 conversationId 存储的临时计划缓存(进程内存态,不落盘)。 */
32
+ plansByConv = new Map();
33
+ /** conversationId 到 sessionId 的映射。 */
21
34
  convToSession = new Map();
22
35
  constructor(filePath) {
23
36
  this.filePath = filePath;
@@ -31,8 +44,12 @@ export class PlanManager {
31
44
  try {
32
45
  const raw = JSON.parse(readFileSync(this.filePath, "utf8"));
33
46
  for (const [key, val] of Object.entries(raw)) {
47
+ // 严格过滤:形如 c1, c2 的临时 conversationId 绝不作为持久化会话键载入,
48
+ // 防止服务重启或历史残留时污染新分配的相同 ID 对话。
49
+ if (isEphemeralConvId(key))
50
+ continue;
34
51
  if (val && typeof val === "object" && Array.isArray(val.steps)) {
35
- this.plans.set(key, val);
52
+ this.plansBySession.set(key, val);
36
53
  }
37
54
  }
38
55
  }
@@ -46,7 +63,10 @@ export class PlanManager {
46
63
  try {
47
64
  mkdirSync(dirname(this.filePath), { recursive: true });
48
65
  const obj = {};
49
- for (const [k, v] of this.plans.entries()) {
66
+ for (const [k, v] of this.plansBySession.entries()) {
67
+ // 双重防护:临时 conversationId 绝不落盘
68
+ if (isEphemeralConvId(k))
69
+ continue;
50
70
  obj[k] = v;
51
71
  }
52
72
  const tmp = `${this.filePath}.tmp.${Date.now()}`;
@@ -60,32 +80,38 @@ export class PlanManager {
60
80
  /** 绑定 conversationId 与 sessionId。若 sessionId 已有落盘计划,立即恢复给 conversationId。 */
61
81
  bindSession(conversationId, sessionId) {
62
82
  this.convToSession.set(conversationId, sessionId);
63
- const existing = this.plans.get(sessionId);
83
+ // 绑定(或重新绑定)session 时,先清除当前 conversationId 上次残留的内存状态
84
+ this.plansByConv.delete(conversationId);
85
+ const existing = this.plansBySession.get(sessionId);
64
86
  if (existing) {
65
- this.plans.set(conversationId, existing);
87
+ this.plansByConv.set(conversationId, existing);
66
88
  return existing;
67
89
  }
68
- const convExisting = this.plans.get(conversationId);
69
- if (convExisting) {
70
- this.plans.set(sessionId, convExisting);
71
- this.save();
72
- return convExisting;
73
- }
90
+ // 绝不从 conversationId 逆向污染全新 sessionId!全新会话以空状态起步。
74
91
  return null;
75
92
  }
93
+ /** 解绑并清理指定 conversationId 的运行时内存计划与映射(在会话移除/销毁时调用)。 */
94
+ unbindConversation(conversationId) {
95
+ this.plansByConv.delete(conversationId);
96
+ this.convToSession.delete(conversationId);
97
+ }
76
98
  /** 获取指定会话的计划状态。优先使用 conversationId,若无则回退查找绑定的 sessionId。 */
77
- getPlan(conversationId) {
78
- const direct = this.plans.get(conversationId);
79
- if (direct)
80
- return direct;
81
- const sessionId = this.convToSession.get(conversationId);
99
+ getPlan(id) {
100
+ const directConv = this.plansByConv.get(id);
101
+ if (directConv)
102
+ return directConv;
103
+ const sessionId = this.convToSession.get(id);
82
104
  if (sessionId) {
83
- const bySession = this.plans.get(sessionId);
105
+ const bySession = this.plansBySession.get(sessionId);
84
106
  if (bySession) {
85
- this.plans.set(conversationId, bySession);
107
+ this.plansByConv.set(id, bySession);
86
108
  return bySession;
87
109
  }
88
110
  }
111
+ // 兼容以 sessionId 直接查询
112
+ const directSession = this.plansBySession.get(id);
113
+ if (directSession)
114
+ return directSession;
89
115
  return null;
90
116
  }
91
117
  /** 设置/全量更新指定会话的计划(可选绑定 sessionId 进行稳定落盘)。 */
@@ -110,13 +136,18 @@ export class PlanManager {
110
136
  activeStepId: effectiveActiveId,
111
137
  updatedAt: Date.now(),
112
138
  };
113
- this.plans.set(conversationId, state);
139
+ this.plansByConv.set(conversationId, state);
114
140
  const effectiveSessionId = sessionId ?? this.convToSession.get(conversationId);
115
141
  if (effectiveSessionId) {
116
142
  this.convToSession.set(conversationId, effectiveSessionId);
117
- this.plans.set(effectiveSessionId, state);
143
+ if (normalizedSteps.length === 0) {
144
+ this.plansBySession.delete(effectiveSessionId);
145
+ }
146
+ else {
147
+ this.plansBySession.set(effectiveSessionId, state);
148
+ }
149
+ this.save();
118
150
  }
119
- this.save();
120
151
  return state;
121
152
  }
122
153
  /** 增量更新单个步骤的状态或内容。 */
@@ -160,17 +191,17 @@ export class PlanManager {
160
191
  activeStepId: nextActive,
161
192
  updatedAt: Date.now(),
162
193
  };
163
- this.plans.set(conversationId, nextState);
194
+ this.plansByConv.set(conversationId, nextState);
164
195
  const sessId = this.convToSession.get(conversationId);
165
196
  if (sessId) {
166
- this.plans.set(sessId, nextState);
197
+ this.plansBySession.set(sessId, nextState);
198
+ this.save();
167
199
  }
168
- this.save();
169
200
  return nextState;
170
201
  }
171
202
  /** 增量删除单个步骤。 */
172
203
  deleteStep(conversationId, stepId) {
173
- const current = this.plans.get(conversationId);
204
+ const current = this.getPlan(conversationId);
174
205
  if (!current)
175
206
  return null;
176
207
  const idx = current.steps.findIndex((s) => s.id === stepId);
@@ -187,12 +218,17 @@ export class PlanManager {
187
218
  activeStepId: nextActive,
188
219
  updatedAt: Date.now(),
189
220
  };
190
- this.plans.set(conversationId, nextState);
221
+ this.plansByConv.set(conversationId, nextState);
222
+ const sessId = this.convToSession.get(conversationId);
223
+ if (sessId) {
224
+ this.plansBySession.set(sessId, nextState);
225
+ this.save();
226
+ }
191
227
  return nextState;
192
228
  }
193
229
  /** 增量新增步骤。 */
194
230
  addStep(conversationId, step, afterStepId) {
195
- const current = this.plans.get(conversationId);
231
+ const current = this.getPlan(conversationId);
196
232
  const existingSteps = current?.steps ?? [];
197
233
  const normalized = {
198
234
  id: String(step.id ?? `step-${Date.now()}`),
@@ -224,15 +260,20 @@ export class PlanManager {
224
260
  activeStepId: nextActive,
225
261
  updatedAt: Date.now(),
226
262
  };
227
- this.plans.set(conversationId, nextState);
263
+ this.plansByConv.set(conversationId, nextState);
264
+ const sessId = this.convToSession.get(conversationId);
265
+ if (sessId) {
266
+ this.plansBySession.set(sessId, nextState);
267
+ this.save();
268
+ }
228
269
  return nextState;
229
270
  }
230
271
  /** 清除指定会话的计划。 */
231
272
  clearPlan(conversationId) {
232
- this.plans.delete(conversationId);
273
+ this.plansByConv.delete(conversationId);
233
274
  const sessId = this.convToSession.get(conversationId);
234
275
  if (sessId) {
235
- this.plans.delete(sessId);
276
+ this.plansBySession.delete(sessId);
236
277
  this.convToSession.delete(conversationId);
237
278
  }
238
279
  this.save();
@@ -67,18 +67,19 @@ const BLOCKED_TOOLS = new Set([
67
67
  const TERMINAL_WRITE_TOOLS = new Set(["terminal_input", "terminal_key"]);
68
68
  /**
69
69
  * 三个只读闸门(计划 / 审查者 / 目标审查)共用的「派发类」工具名:它们会把活
70
- * 派到**别的会话**执行(delegate_task 走子代理 spawn 通道;schedule_task 到期
70
+ * 派到**别的会话**执行(delegate_task 走子代理 spawn 通道;schedule 到期
71
71
  * 唤醒对话跑 prompt),而这三道闸门都是会话级的 —— 放行即绕过。
72
72
  *
73
73
  * 名单以 server/tool-manager.ts 实际注册的工具名为事实源(#436):历史名单里的
74
74
  * spawn / spawn_agent / subagent_spawn / schedule_agent / host_schedule /
75
75
  * create_goal / set_goal / start_goal_wizard / create_conversation /
76
- * fork_conversation / schedule / set_plan_mode 等都是协议消息名或从未注册的
77
- * 幽灵名,一个真实工具都没拦住,反而掩盖了 schedule_task 这类真实旁路工具
78
- * 完全可用的事实。subagent 是单 action 工具,由各闸门按 action 细分(只读
79
- * action 放行,见各闸门的判定函数)。
76
+ * fork_conversation / set_plan_mode 等都是协议消息名或从未注册的幽灵名,一个
77
+ * 真实工具都没拦住,反而掩盖了 schedule 这类真实旁路工具完全可用的事实。
78
+ * subagent 是单 action 工具,由各闸门按 action 细分(只读 action 放行,见各闸门
79
+ * 的判定函数);schedule(create/list/cancel)则整工具拒——调度面在计划/审查
80
+ * 回合都不需要,宁可保守。
80
81
  */
81
- export const SESSION_DISPATCH_TOOLS = new Set(["delegate_task", "schedule_task"]);
82
+ export const SESSION_DISPATCH_TOOLS = new Set(["delegate_task", "schedule"]);
82
83
  /**
83
84
  * 计划模式下也禁掉的「旁路工具」(真实派发类,见 SESSION_DISPATCH_TOOLS):
84
85
  * 它们能在**别的会话**里干活,而闸门是会话级的 —— 子代理/排程对话的
@@ -14,6 +14,7 @@ export const SLOT_EXAMPLES = {
14
14
  "contextmenu.file": `{ "contextmenu.file": [{ "id": "mail", "label": "发到邮箱", "kind": "action", "action": "my:send" }] }`,
15
15
  "contextmenu.toolcall": `{ "ui": { "contextmenu.toolcall": [{ "id": "m", "label": "工具菜单", "kind": "action", "action": "my:m" }] } }`,
16
16
  "settings.pages": `{ "settings": [{ "id": "conf", "label": "邮箱设置", "kind": "page" }] }`,
17
+ "tasks.panel": `{ "ui": { "tasks.panel": [{ "id": "pm2", "label": "pm2 托管的应用", "kind": "view" }] } }`,
17
18
  "leftpanel.sessions": `{ "ui": { "leftpanel.sessions": [{ "id": "m", "label": "会话区", "kind": "action", "action": "my:m" }] } }`,
18
19
  "chat.header": `{ "ui": { "chat.header": [{ "id": "m", "label": "会话题头", "kind": "action", "action": "my:m" }] } }`,
19
20
  "chat.empty": `{ "ui": { "chat.empty": [{ "id": "m", "label": "空态", "kind": "action", "action": "my:m" }] } }`,
@@ -69,7 +70,7 @@ export const HOST_METHODS = [
69
70
  name: "registerAgentTool",
70
71
  needs: "tools",
71
72
  summary: "给 AI 注册工具(插件给模型加能力,与 AI 写插件方向相反)",
72
- example: `host.registerAgentTool({ name: "mail_list", description: "…", execute: async () => ({}) })`,
73
+ example: `host.registerAgentTool({ name: "mail", description: "…", execute: async () => ({}) })`,
73
74
  },
74
75
  {
75
76
  name: "onToolPre",
@@ -176,8 +177,8 @@ export const HOST_METHODS = [
176
177
  {
177
178
  name: "getActiveConversation",
178
179
  needs: "-",
179
- summary: "读当前打开对话快照(只读引用,广播前抽摘要)",
180
- example: `host.getActiveConversation()`,
180
+ summary: "读对话快照:{clientId} 取该标签页正在看的对话,缺省=最近活跃的非子代理会话",
181
+ example: `host.getActiveConversation({ clientId })`,
181
182
  },
182
183
  {
183
184
  name: "onConversationChanged",
@@ -185,6 +186,12 @@ export const HOST_METHODS = [
185
186
  summary: "订阅切对话(轨迹插件重拉时间线)",
186
187
  example: `host.onConversationChanged(() => {})`,
187
188
  },
189
+ {
190
+ name: "onClientModelChanged",
191
+ needs: "-",
192
+ summary: "订阅模型切换成功(回调带 clientId/对话/model;失败与重复不发)",
193
+ example: `host.onClientModelChanged((snap) => {})`,
194
+ },
188
195
  {
189
196
  name: "storage",
190
197
  needs: "-",
@@ -0,0 +1,47 @@
1
+ /**
2
+ * 插件会话快照的「选哪个会话」策略(issue #542,纯函数,零宿主/零 SDK 依赖)。
3
+ *
4
+ * 背景:`host.getActiveConversation()` 原来只认「全局 lastActiveAt 最大者」,
5
+ * 于是两个标签页各看一个对话时,插件读到的是另一个标签页的会话;子代理跑起来
6
+ * 比用户正在看的对话还勤,也会把父对话挤出快照。这里把选会话的两条口径拆成
7
+ * 纯函数,让 agent-service 只负责取数据、这里负责判定(可单测)。
8
+ *
9
+ * 另外附一个模型变更事件去重键:`host.onClientModelChanged` 只在模型真的换了
10
+ * 的时候发一次(重复点同一个模型、重连重放 set_model 都不该重复触发订阅者)。
11
+ */
12
+ /** 单客户端内选会话:给了 `active` 就优先认它(= 该标签页正在看的对话),
13
+ * 否则退回归属本客户端的「最近活跃」会话;`includeSubagents=false`(缺省)时
14
+ * 跳过子代理对话。找不到任何符合条件的会话 → null(调用方据此回落)。
15
+ *
16
+ * `conversations` 只遍历一遍(Map.values() 直传,不额外建数组)。 */
17
+ export function pickClientConversation(conversations, opts = {}) {
18
+ const include = opts.includeSubagents === true;
19
+ const active = opts.active;
20
+ if (active && (include || !active.isSubagent))
21
+ return active;
22
+ let best = null;
23
+ for (const c of conversations) {
24
+ if (!include && c.isSubagent)
25
+ continue;
26
+ if (!best || c.lastActiveAt > best.lastActiveAt)
27
+ best = c;
28
+ }
29
+ return best;
30
+ }
31
+ /** 跨客户端回落:最近活跃的**非子代理**会话(`at` 最大者)。
32
+ * 缺省语义(不传 clientId / clientId 不认识)走这条 —— 与 #542 之前的行为
33
+ * 一致,只多一条「子代理不算数」。 */
34
+ export function pickLatestClientSnapshot(snapshots) {
35
+ let best = null;
36
+ for (const s of snapshots) {
37
+ if (!s || s.isSubagent)
38
+ continue;
39
+ if (!best || s.at > best.at)
40
+ best = s;
41
+ }
42
+ return best;
43
+ }
44
+ /** 模型变更事件的去重键:同一客户端、同一对话、同一模型 = 同一件事。 */
45
+ export function modelChangeKey(snap) {
46
+ return `${snap.clientId}\u0000${snap.conversationId}\u0000${snap.model ?? ""}`;
47
+ }