pi-web-ui 0.88.0 → 0.90.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 (36) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist/server/agent-service.js +464 -68
  3. package/dist/server/attachments.js +39 -0
  4. package/dist/server/auth-cookie.js +23 -0
  5. package/dist/server/client-state.js +35 -0
  6. package/dist/server/composer-drafts.js +20 -2
  7. package/dist/server/conversation-read-tool.js +325 -0
  8. package/dist/server/dsh/dsh-agent-service.js +46 -11
  9. package/dist/server/file-archives.js +258 -0
  10. package/dist/server/file-transfer-routes.js +113 -0
  11. package/dist/server/files-service.js +123 -1
  12. package/dist/server/index.js +361 -14
  13. package/dist/server/marker-service.js +3 -1
  14. package/dist/server/model-admin.js +285 -36
  15. package/dist/server/plugins.js +152 -5
  16. package/dist/server/queue-utils.js +16 -0
  17. package/dist/server/schedule-agent-tool.js +240 -0
  18. package/dist/server/scheduler-tasks.js +414 -0
  19. package/dist/server/settings-service.js +76 -2
  20. package/dist/server/terminals.js +14 -1
  21. package/dist/server/tool-manager.js +16 -1
  22. package/dist/server/update-check.js +253 -19
  23. package/dist/server/webui-context.js +4 -0
  24. package/dist/server/ws-unknown-types.js +44 -0
  25. package/extensions/webui.ts +9 -2
  26. package/package.json +7 -3
  27. package/plugin-sdk/index.d.ts +4 -0
  28. package/plugin-sdk/index.mjs +9 -0
  29. package/plugins/catalog.json +11 -2
  30. package/web/dist/assets/TerminalPanel-BDbdLhpT.js +6 -0
  31. package/web/dist/assets/index-1f_DP8S3.js +380 -0
  32. package/web/dist/assets/index-DeUwDA-C.css +10 -0
  33. package/web/dist/index.html +2 -2
  34. package/web/dist/assets/TerminalPanel-CDH27dNP.js +0 -6
  35. package/web/dist/assets/index-CQg5A74_.js +0 -375
  36. package/web/dist/assets/index-DTEcxHWs.css +0 -10
@@ -247,6 +247,45 @@ export async function buildAttachmentMessages(ctx, attachments) {
247
247
  /** Cap for reading a file in "lines" mode (selected slice is inlined). */
248
248
  const MAX_LINES_READ_BYTES = 2 * 1024 * 1024;
249
249
  for (const [idx, att] of attachments.entries()) {
250
+ // Quoted conversation (left-panel right-click / global-search quote):
251
+ // `path` is unused — the reference travels in conversationId (running
252
+ // conversation, incl. subagents) or sessionPath (history transcript).
253
+ // The transcript is NOT inlined here (it can be huge and goes stale);
254
+ // the model fetches it on demand with the conversation_read tool.
255
+ if (att.mode === "conversation") {
256
+ const convId = att.conversationId;
257
+ const sessPath = att.sessionPath;
258
+ const id = typeof convId === "string" && convId.trim() ? convId.trim() : undefined;
259
+ const sp = typeof sessPath === "string" && sessPath.trim() ? sessPath.trim() : undefined;
260
+ const title = att.name ?? id ?? sp ?? "conversation";
261
+ if (!id && !sp) {
262
+ ctx.emit({
263
+ type: "notice",
264
+ level: "warning",
265
+ text: `对话引用缺少 id/path,已跳过`,
266
+ textEn: `Conversation reference without id/path, skipped`,
267
+ });
268
+ continue;
269
+ }
270
+ const ref = id ? `id="${attr(id)}"` : `path="${attr(sp)}"`;
271
+ const how = id
272
+ ? `Use the conversation_read tool with id="${attr(id)}" to read its messages.`
273
+ : `Use the conversation_read tool with path="${attr(sp)}" to read its transcript.`;
274
+ out.push({
275
+ message: {
276
+ customType: "file",
277
+ content: [
278
+ {
279
+ type: "text",
280
+ text: `\n<conversation-ref ${ref} title="${attr(title)}">\nThe user quoted another conversation "${attr(title)}". ${how} Do not guess its contents.\n用户引用了另一个对话,别猜它的内容,用 conversation_read 去读。\n</conversation-ref>`,
281
+ },
282
+ ],
283
+ display: true,
284
+ details: { name: title, path: id ?? sp, mode: "conversation", conversationId: id, sessionPath: sp },
285
+ },
286
+ });
287
+ continue;
288
+ }
250
289
  // Granted web page (page-picker extension): `path` is the page origin,
251
290
  // NOT a workspace path — never stat/read it. The model gets the exact
252
291
  // browser_page target plus the fact that this page is already granted,
@@ -0,0 +1,23 @@
1
+ /** True when the browser connection is TLS: direct (`socket.encrypted`,
2
+ * express `req.secure`) or via a TLS-terminating proxy (`x-forwarded-proto`
3
+ * / RFC 7239 `forwarded`). */
4
+ export function isTlsRequest(req) {
5
+ if (req.socket?.encrypted)
6
+ return true;
7
+ if (req.secure === true)
8
+ return true;
9
+ const proto = req.headers?.["x-forwarded-proto"];
10
+ const first = Array.isArray(proto) ? proto[0] : proto;
11
+ if (typeof first === "string" && first.split(",")[0]?.trim().toLowerCase() === "https")
12
+ return true;
13
+ const fwd = req.headers?.forwarded;
14
+ const fwdFirst = Array.isArray(fwd) ? fwd[0] : fwd;
15
+ if (typeof fwdFirst === "string" && /(?:^|[;,]\s*)proto=https(?:[;,]|$)/i.test(fwdFirst))
16
+ return true;
17
+ return false;
18
+ }
19
+ /** Build the `Set-Cookie` value for `pi_web_token`. `encodedValue` is already
20
+ * `encodeURIComponent`'d (or `""` when clearing). */
21
+ export function buildPiWebTokenCookie(encodedValue, maxAge, secure) {
22
+ return `pi_web_token=${encodedValue}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
23
+ }
@@ -11,6 +11,26 @@ import { dirname, isAbsolute, resolve } from "node:path";
11
11
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
12
12
  /** 大模型 API 出错自动重试次数的默认值(SDK 默认 3)。 */
13
13
  export const DEFAULT_RETRY_MAX_ATTEMPTS = 6;
14
+ /** 归一化插件 AI 工具禁用名单:只收非空字符串(去重,上限 256 个)。
15
+ * 与 disabledAgentTools 不同——插件工具名是动态的(注册才知道),不能按
16
+ * 固定目录校验;未知/已卸载插件的条目刻意保留(重装后仍保持关闭)。
17
+ * 纯函数,可单测。 */
18
+ export function normalizeDisabledPluginTools(v) {
19
+ if (!Array.isArray(v))
20
+ return [];
21
+ const out = [];
22
+ for (const x of v) {
23
+ if (typeof x !== "string")
24
+ continue;
25
+ const name = x.trim();
26
+ if (!name || name.length > 128 || out.includes(name))
27
+ continue;
28
+ out.push(name);
29
+ if (out.length >= 256)
30
+ break;
31
+ }
32
+ return out;
33
+ }
14
34
  /** 归一化重试次数:非数值回落默认,钳制到 [0, 100] 整数。 */
15
35
  export function normalizeRetryMaxAttempts(v) {
16
36
  const n = Math.floor(Number(v));
@@ -51,11 +71,24 @@ export function normalizeUiLayout(v) {
51
71
  const order = arr(o.order, 200);
52
72
  const groups = dict(o.groups, 200);
53
73
  const labels = dict(o.labels, 200);
74
+ // 用户对齐:只收 start/center/end(手改脏值回落丢弃,不污染合并结果)。
75
+ let align;
76
+ if (o.align && typeof o.align === "object" && !Array.isArray(o.align)) {
77
+ align = {};
78
+ for (const [k, val] of Object.entries(o.align).slice(0, 200)) {
79
+ if (k.length > 0 && k.length <= 96 && (val === "start" || val === "center" || val === "end")) {
80
+ align[k] = val;
81
+ }
82
+ }
83
+ if (Object.keys(align).length === 0)
84
+ align = undefined;
85
+ }
54
86
  return {
55
87
  ...(hidden ? { hidden } : {}),
56
88
  ...(shown ? { shown } : {}),
57
89
  ...(order ? { order } : {}),
58
90
  ...(groups ? { groups } : {}),
91
+ ...(align ? { align } : {}),
59
92
  ...(labels ? { labels } : {}),
60
93
  };
61
94
  }
@@ -327,6 +360,7 @@ export class ClientStateStore {
327
360
  disabledSkills: stored?.disabledSkills ?? [],
328
361
  disabledExtensions: stored?.disabledExtensions ?? [],
329
362
  disabledAgentTools: legacyToDisabled(stored ?? {}),
363
+ disabledPluginTools: normalizeDisabledPluginTools(stored?.disabledPluginTools),
330
364
  // 新字段已存在时遗留三开关以它为准推导(旧文件才读遗留值),保证两边一致。
331
365
  terminalToolsEnabled: stored?.disabledAgentTools !== undefined
332
366
  ? deriveLegacy(legacyToDisabled(stored)).terminalToolsEnabled
@@ -378,6 +412,7 @@ export class ClientStateStore {
378
412
  disabledSkills: settings.disabledSkills ?? cur.disabledSkills ?? [],
379
413
  disabledExtensions: settings.disabledExtensions ?? cur.disabledExtensions ?? [],
380
414
  disabledAgentTools: normalizeDisabledAgentTools(settings.disabledAgentTools ?? cur.disabledAgentTools),
415
+ disabledPluginTools: normalizeDisabledPluginTools(settings.disabledPluginTools ?? cur.disabledPluginTools),
381
416
  terminalToolsEnabled: settings.terminalToolsEnabled ?? cur.terminalToolsEnabled ?? false,
382
417
  terminalBash: settings.terminalBash ?? cur.terminalBash ?? false,
383
418
  terminalBashIdleMs: settings.terminalBashIdleMs ?? cur.terminalBashIdleMs ?? 15_000,
@@ -41,6 +41,13 @@ function isValidDraft(d) {
41
41
  const o = d;
42
42
  return typeof o.text === "string" && typeof o.ts === "number" && typeof o.updatedAt === "number";
43
43
  }
44
+ /** clear 水位:sessionId → clear 时刻(max(旧条目 ts, Date.now()))。
45
+ * 模块级(非实例级):同进程每个 ClientSession 各有一个 ComposerDraftsStore
46
+ * 实例(agent-service.ts:1922),跨 tab 的 prompt-clear 与陈旧写落在不同
47
+ * 实例上,水位必须跨实例可见。进程重启即失 —— 重启后文件态本身已干净
48
+ * (clear 落盘删 key),late-save 无处可达。
49
+ * ponytail: 内存水位,TTL/持久化按需加(当前重启语义已够用)。 */
50
+ const clearedAt = new Map();
44
51
  export class ComposerDraftsStore {
45
52
  filePath;
46
53
  cache = null;
@@ -98,10 +105,16 @@ export class ComposerDraftsStore {
98
105
  return d ? { text: d.text, ts: d.ts } : undefined;
99
106
  }
100
107
  /** 存一条草稿:空文本 = 删除;同 key 上 ts 更大的才覆盖(last-write-wins,
101
- * `>=` 让同 ts 的重发幂等)。只有实际变化才写盘。 */
108
+ * `>=` 让同 ts 的重发幂等)。只有实际变化才写盘。
109
+ * clear 时间戳守卫:prompt() 清掉草稿后才 landing 的旧 `draft_update`
110
+ * (防抖延迟 / 跨 tab 陈旧写,ts <= clearTs)直接丢弃,不复活存储
111
+ * (reload-resurrect,见 clearedAt)。*/
102
112
  save(sessionId, text, ts) {
103
113
  if (!sessionId)
104
114
  return;
115
+ const cut = clearedAt.get(sessionId);
116
+ if (cut !== undefined && ts <= cut)
117
+ return;
105
118
  const map = this.load();
106
119
  const norm = normalizeDraftText(text);
107
120
  if (norm === undefined) {
@@ -119,11 +132,16 @@ export class ComposerDraftsStore {
119
132
  map[sessionId] = { text: norm, ts, updatedAt: Date.now() };
120
133
  this.persist();
121
134
  }
122
- /** 发送成功 / 会话删除后清掉(有 key 才写盘)。 */
135
+ /** 发送成功 / 会话删除后清掉(有 key 才写盘)。同时记录 clear 时间戳
136
+ * (max(旧条目 ts, Date.now())):之后 ts <= 该水位的 save 一律丢弃,
137
+ * 拦住 prompt() 清掉之后才 landing 的旧 `draft_update`。
138
+ * 模块级共享:同进程多 ClientSession(多 tab)共用同一水位。 */
123
139
  clear(sessionId) {
124
140
  if (!sessionId)
125
141
  return;
126
142
  const map = this.load();
143
+ const prevTs = map[sessionId]?.ts ?? 0;
144
+ clearedAt.set(sessionId, Math.max(prevTs, Date.now()));
127
145
  if (map[sessionId] !== undefined) {
128
146
  delete map[sessionId];
129
147
  this.persist();
@@ -0,0 +1,325 @@
1
+ // ---------------------------------------------------------------------------
2
+ // conversation-read-tool.ts — 让 AI(含子代理)读取别的对话
3
+ // ---------------------------------------------------------------------------
4
+ // 背景:用户在左栏有「运行的对话」(含子代理)与「历史对话」,也常想让 AI
5
+ // 「结合另一个对话的内容回答」。此前 AI 既不知道别的对话的 id,也没有干净的
6
+ // 读取通道(只能用 read/bash 翻转录 jsonl,既难找路径又难解析)。
7
+ //
8
+ // 本工具提供只读双通道:
9
+ // action=list → 运行中对话(本标签页的全部 conversation,含子代理)+
10
+ // 历史会话转录(scope=current 仅当前项目,all 跨全部项目);
11
+ // action=read → 按 id 读运行中对话的实时消息(含未落盘的),或按 path 读
12
+ // 历史转录(只接受会话列表里的路径,任意文件不给读)。
13
+ //
14
+ // 转录文本走 transcriptText/formatTranscript 纯函数(有单测);文件解析走
15
+ // parseTranscriptLines(jsonl 逐行,坏行跳过)。输出按条数 + 字符数双封顶,
16
+ // 长对话分多次 offset 翻页。跨标签页的实时运行读不到——以落盘历史为准,
17
+ // description 里会告诉模型这一点。
18
+ //
19
+ // 双语约定(issue #91):definition 走 bilingual(en, zh) 内联双语;per-call
20
+ // 返回文本按 lang 取 pick(lang, zh, en, key, vars),缺表回落英文内联。
21
+ // ---------------------------------------------------------------------------
22
+ import { defineTool } from "@earendil-works/pi-coding-agent";
23
+ import { Type } from "typebox";
24
+ import { bilingual, pick } from "./i18n.js";
25
+ /** AgentMessage → 转录最小结构(角色原样保留,内容不动,格式化延后)。 */
26
+ export function toTranscriptInput(m) {
27
+ const role = m.role;
28
+ const r = typeof role === "string" ? role : "unknown";
29
+ const base = { role: r };
30
+ const anyM = m;
31
+ if (typeof anyM.content !== "undefined")
32
+ base.content = anyM.content;
33
+ if (typeof anyM.toolName === "string")
34
+ base.toolName = anyM.toolName;
35
+ if (typeof anyM.isError === "boolean")
36
+ base.isError = anyM.isError;
37
+ if (typeof anyM.command === "string")
38
+ base.command = anyM.command;
39
+ if (typeof anyM.output === "string")
40
+ base.output = anyM.output;
41
+ if (typeof anyM.summary === "string")
42
+ base.summary = anyM.summary;
43
+ if (typeof anyM.details !== "undefined")
44
+ base.details = anyM.details;
45
+ if (typeof anyM.timestamp === "number")
46
+ base.timestamp = anyM.timestamp;
47
+ return base;
48
+ }
49
+ /** 内容块 → 纯文本:text 拼接;图片占位;具名块(toolCall 等)留名;其余占位。 */
50
+ function textOfContent(content) {
51
+ if (typeof content === "string")
52
+ return content;
53
+ if (!Array.isArray(content))
54
+ return "";
55
+ const parts = [];
56
+ for (const b of content) {
57
+ if (!b || typeof b !== "object")
58
+ continue;
59
+ const blk = b;
60
+ if (blk.type === "text" && typeof blk.text === "string") {
61
+ parts.push(blk.text);
62
+ }
63
+ else if (blk.type === "image") {
64
+ parts.push("[image]");
65
+ }
66
+ else if (typeof blk.name === "string" && blk.name) {
67
+ parts.push(`[tool call: ${blk.name}]`);
68
+ }
69
+ else {
70
+ parts.push("[…]");
71
+ }
72
+ }
73
+ return parts.join("\n");
74
+ }
75
+ /** 附件 aside 的短名(details.name/path),非附件返回空。 */
76
+ function attachmentName(details) {
77
+ if (!details || typeof details !== "object")
78
+ return "";
79
+ const d = details;
80
+ if (typeof d.name === "string" && d.name)
81
+ return d.name;
82
+ if (typeof d.path === "string" && d.path)
83
+ return d.path.split(/[\\/]/).pop() ?? d.path;
84
+ return "";
85
+ }
86
+ /** 单条转录消息 → 可读文本行(角色标签 + 内容,不截断,截断由 format 统一做)。 */
87
+ export function transcriptText(m) {
88
+ switch (m.role) {
89
+ case "bashExecution":
90
+ return `[bash $ ${m.command ?? ""}]\n${m.output ?? ""}`;
91
+ case "branchSummary":
92
+ return `[branch summary]\n${m.summary ?? ""}`;
93
+ case "compactionSummary":
94
+ return `[compaction summary]\n${m.summary ?? ""}`;
95
+ case "toolResult": {
96
+ const head = `[tool result${m.toolName ? ` (${m.toolName})` : ""}${m.isError ? " ERROR" : ""}]`;
97
+ const body = textOfContent(m.content);
98
+ return body ? `${head}\n${body}` : head;
99
+ }
100
+ case "custom": {
101
+ const name = attachmentName(m.details);
102
+ const body = textOfContent(m.content);
103
+ const head = name ? `[attachment: ${name}]` : "[note]";
104
+ return body ? `${head}\n${body}` : head;
105
+ }
106
+ case "user":
107
+ case "assistant":
108
+ return textOfContent(m.content);
109
+ default: {
110
+ const body = textOfContent(m.content);
111
+ return body ? `[${m.role}]\n${body}` : `[${m.role}]`;
112
+ }
113
+ }
114
+ }
115
+ /** 角色标签(列表行里的序号前缀用)。 */
116
+ function roleLabel(m) {
117
+ if (m.role === "toolResult")
118
+ return `tool result${m.toolName ? ` (${m.toolName})` : ""}`;
119
+ return m.role;
120
+ }
121
+ function trunc(s, cap) {
122
+ return s.length <= cap ? s : `${s.slice(0, cap)}\n… [truncated]`;
123
+ }
124
+ /** 转录分页格式化:序号形如 [12/135 user],尾部带翻页提示位(调用方拼 header)。 */
125
+ export function formatTranscript(messages, opts) {
126
+ const total = messages.length;
127
+ const offset = Math.max(0, Math.floor(opts?.offset ?? 0));
128
+ const limit = Math.min(200, Math.max(1, Math.floor(opts?.limit ?? 50)));
129
+ const perMsgCap = Math.max(100, Math.floor(opts?.perMsgCap ?? 2000));
130
+ const maxChars = Math.min(60000, Math.max(1000, Math.floor(opts?.maxChars ?? 20000)));
131
+ const from = Math.min(offset, total);
132
+ const to = Math.min(from + limit, total);
133
+ const lines = [];
134
+ for (let i = from; i < to; i++) {
135
+ const m = messages[i];
136
+ lines.push(`[${i + 1}/${total} ${roleLabel(m)}]\n${trunc(transcriptText(m).trim(), perMsgCap)}`);
137
+ }
138
+ let text = lines.join("\n\n");
139
+ let truncated = to < total;
140
+ if (text.length > maxChars) {
141
+ text = `${text.slice(0, maxChars)}\n… [truncated]`;
142
+ truncated = true;
143
+ }
144
+ if (total === 0)
145
+ text = "";
146
+ return { text, total, from, to, truncated };
147
+ }
148
+ /**
149
+ * 转录 jsonl → 转录消息(message 条目取 message;compaction/branch_summary
150
+ * 取 summary;坏行跳过)。纯函数:文件读取由宿主做,单测直接喂文本。
151
+ */
152
+ export function parseTranscriptLines(text) {
153
+ const out = [];
154
+ for (const line of text.split("\n")) {
155
+ const t = line.trim();
156
+ if (!t)
157
+ continue;
158
+ let e;
159
+ try {
160
+ e = JSON.parse(t);
161
+ }
162
+ catch {
163
+ continue;
164
+ }
165
+ if (e?.type === "message" && e.message && typeof e.message.role === "string") {
166
+ const msg = e.message;
167
+ const m = { role: msg.role };
168
+ if (typeof msg.content !== "undefined")
169
+ m.content = msg.content;
170
+ if (typeof msg.toolName === "string")
171
+ m.toolName = msg.toolName;
172
+ if (typeof msg.isError === "boolean")
173
+ m.isError = msg.isError;
174
+ if (typeof msg.details !== "undefined")
175
+ m.details = msg.details;
176
+ if (typeof msg.timestamp === "number")
177
+ m.timestamp = msg.timestamp;
178
+ out.push(m);
179
+ continue;
180
+ }
181
+ if ((e?.type === "compaction" || e?.type === "branch_summary") && typeof e.summary === "string") {
182
+ out.push({
183
+ role: e.type === "compaction" ? "compactionSummary" : "branchSummary",
184
+ summary: e.summary,
185
+ });
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+ /** 大小写不敏感子串(空 query 全匹配)。 */
191
+ function matchesHay(hay, q) {
192
+ return q === "" || hay.toLowerCase().includes(q);
193
+ }
194
+ export function filterRunning(list, query) {
195
+ const q = query.trim().toLowerCase();
196
+ if (!q)
197
+ return list;
198
+ return list.filter((c) => matchesHay(c.id, q) || matchesHay(c.title, q) || matchesHay(c.cwd, q));
199
+ }
200
+ export function filterHistory(list, query) {
201
+ const q = query.trim().toLowerCase();
202
+ if (!q)
203
+ return list;
204
+ return list.filter((s) => matchesHay(s.path, q) || matchesHay(s.name ?? "", q) || matchesHay(s.firstMessage, q));
205
+ }
206
+ /** 短 id/路径展示(列表行里路径太长只留尾部)。 */
207
+ export function shortPath(p, keep = 48) {
208
+ return p.length <= keep ? p : `…${p.slice(p.length - keep)}`;
209
+ }
210
+ export function makeConversationReadTool(host, lang) {
211
+ const getLang = lang ?? (() => "en");
212
+ const text = (t, details = {}) => ({
213
+ content: [{ type: "text", text: t }],
214
+ details,
215
+ });
216
+ return defineTool({
217
+ name: "conversation_read",
218
+ label: "Read another conversation",
219
+ description: bilingual('Read ANOTHER conversation\'s messages: a running conversation of this client (including subagents — use its conversation id like "c3", see action=list) or a persisted history session transcript (use its file path). ' +
220
+ 'Use it when the user references another chat (a quoted conversation, a pasted conversation id, or "see the other chat about X"). ' +
221
+ "action=list shows running conversations (id, title, project, streaming state) plus history sessions; action=read returns one transcript paged (offset/limit, capped chars — re-call with a larger offset for the rest). " +
222
+ "Only sessions from the session list can be read (arbitrary file paths are refused). " +
223
+ "Live runs in OTHER browser tabs are not readable here — they appear in history once persisted.", "读取**另一个对话**的消息:本客户端的运行中对话(含子代理——用 action=list 查 conversation id,如 c3)或已落盘的历史会话转录(用它的文件 path)。" +
224
+ "用户引用了别的对话(引用 chip、粘过来的对话 id、“看看之前那个关于 X 的对话”)时用它。" +
225
+ "action=list 列运行中对话(id、标题、项目、是否进行中)与历史会话;action=read 取某一份转录(offset/limit 翻页、字符封顶——后文用更大的 offset 再取)。" +
226
+ "只能读会话列表里的转录(任意文件路径会被拒绝)。" +
227
+ "其他浏览器标签页里的实时运行在这里读不到——它们落盘后会出现在历史里。"),
228
+ promptSnippet: "read another conversation's messages (running incl. subagents, or history transcript)",
229
+ parameters: Type.Object({
230
+ action: Type.Optional(Type.String({
231
+ description: 'list = show running conversations + history sessions; read = fetch one transcript. Default "list".',
232
+ })),
233
+ scope: Type.Optional(Type.String({
234
+ description: 'list only: "current" = this project, "all" = every project. Default "all".',
235
+ })),
236
+ query: Type.Optional(Type.String({ description: "list only: case-insensitive filter over id/title/path/first message." })),
237
+ id: Type.Optional(Type.String({ description: 'read only: running conversation id (e.g. "c3"), from action=list.' })),
238
+ path: Type.Optional(Type.String({ description: "read only: history session file path, from action=list." })),
239
+ offset: Type.Optional(Type.Number({ description: "read only: first message index (0-based). Default 0." })),
240
+ limit: Type.Optional(Type.Number({ description: "read only: max messages to return (1-200). Default 50." })),
241
+ maxChars: Type.Optional(Type.Number({ description: "read only: max characters (1000-60000). Default 20000." })),
242
+ }),
243
+ execute: async (_id, p, _signal, _onUpdate, ctx) => {
244
+ const action = (p.action ?? "list").trim().toLowerCase();
245
+ if (action === "list") {
246
+ const scopeRaw = (p.scope ?? "all").trim().toLowerCase();
247
+ if (scopeRaw !== "current" && scopeRaw !== "all") {
248
+ return text(pick(getLang(), `scope 非法:${p.scope}(只能是 current 或 all)。`, `Invalid scope: ${p.scope} (must be "current" or "all").`, "convread.list.bad.scope", { "p.scope": p.scope }));
249
+ }
250
+ const scope = scopeRaw;
251
+ const query = typeof p.query === "string" ? p.query : "";
252
+ const running = filterRunning(host.listRunningConversations(), query);
253
+ const history = filterHistory(await host.listHistorySessions(scope, ctx.cwd), query);
254
+ const L = getLang();
255
+ const runLines = running.map((c) => `- ${c.id} · ${c.title} · ${c.isSubagent ? (L === "zh" ? "子代理" : "subagent") : L === "zh" ? "对话" : "chat"}${c.isStreaming ? (L === "zh" ? "(进行中)" : " (streaming)") : ""} · ${c.messageCount} msgs · ${c.cwd}`);
256
+ const histLines = history.map((s) => `- ${shortPath(s.path)} · ${s.name || s.firstMessage || (L === "zh" ? "(空对话)" : "(empty)")}${s.messageCount ? ` · ${s.messageCount} msgs` : ""}`);
257
+ const head = L === "zh"
258
+ ? `运行中对话(${running.length})+ 历史会话(${history.length},scope=${scope}):`
259
+ : `Running conversations (${running.length}) + history sessions (${history.length}, scope=${scope}):`;
260
+ const runHead = L === "zh" ? "【运行中】" : "[running]";
261
+ const histHead = L === "zh" ? "【历史】" : "[history]";
262
+ const empty = L === "zh" ? "(无)" : "(none)";
263
+ const tail = L === "zh"
264
+ ? `读某一份:conversation_read(action="read", id="c…") 或 conversation_read(action="read", path="…"),长转录用 offset/limit 翻页。`
265
+ : `To read one: conversation_read(action="read", id="c…") or conversation_read(action="read", path="…"); page long transcripts with offset/limit.`;
266
+ return text(`${head}\n${runHead}\n${runLines.join("\n") || empty}\n${histHead}\n${histLines.join("\n") || empty}\n${tail}`, { running, history, scope });
267
+ }
268
+ if (action === "read") {
269
+ const id = typeof p.id === "string" && p.id.trim() ? p.id.trim() : undefined;
270
+ const path = typeof p.path === "string" && p.path.trim() ? p.path.trim() : undefined;
271
+ if ((id && path) || (!id && !path)) {
272
+ return text(pick(getLang(), `action=read 需要且只需要 id 或 path 其中之一(id 读运行中对话,path 读历史转录)。`, `action=read needs exactly one of id or path (id = running conversation, path = history transcript).`, "convread.read.bad.args"));
273
+ }
274
+ const opts = { offset: p.offset, limit: p.limit, maxChars: p.maxChars };
275
+ if (id) {
276
+ const found = host.readRunningConversation(id);
277
+ if (!found) {
278
+ return text(pick(getLang(), `未找到运行中对话 ${id}(可能已关闭;用 action=list 看当前列表,落盘的可按 path 读历史)。`, `Running conversation ${id} not found (may be closed; use action=list for the current list, or read persisted ones by path).`, "convread.read.id.not.found", { id }));
279
+ }
280
+ const f = formatTranscript(found.messages, opts);
281
+ const L = getLang();
282
+ const head = L === "zh"
283
+ ? `对话「${found.title}」(id=${id}${found.isSubagent ? ",子代理" : ""},${found.cwd},共 ${f.total} 条,${f.from + 1}-${f.to}):`
284
+ : `Conversation "${found.title}" (id=${id}${found.isSubagent ? ", subagent" : ""}, ${found.cwd}, ${f.total} messages, showing ${f.from + 1}-${f.to}):`;
285
+ const more = f.truncated && f.total > 0
286
+ ? L === "zh"
287
+ ? `\n…还有后文(offset=${f.to} 再取)。`
288
+ : `\n…more below (re-call with offset=${f.to}).`
289
+ : "";
290
+ const emptyNote = f.total === 0 ? (L === "zh" ? "(该对话暂无消息)" : "(no messages yet)") : "";
291
+ return text(`${head}\n${f.text || emptyNote}${more}`, {
292
+ id,
293
+ title: found.title,
294
+ total: f.total,
295
+ from: f.from,
296
+ to: f.to,
297
+ });
298
+ }
299
+ const found = await host.readHistorySession(path);
300
+ if (!found) {
301
+ return text(pick(getLang(), `读不到历史会话 ${path}(不在会话列表里:只能读 action=list 列出的转录路径)。`, `Cannot read history session ${path} (not in the session list: only transcripts from action=list can be read).`, "convread.read.path.not.found", { path }));
302
+ }
303
+ const f = formatTranscript(found.messages, opts);
304
+ const L = getLang();
305
+ const head = L === "zh"
306
+ ? `历史会话「${found.title || found.sessionPath}」(${found.cwd},共 ${f.total} 条,${f.from + 1}-${f.to}):`
307
+ : `History session "${found.title || found.sessionPath}" (${found.cwd}, ${f.total} messages, showing ${f.from + 1}-${f.to}):`;
308
+ const more = f.truncated && f.total > 0
309
+ ? L === "zh"
310
+ ? `\n…还有后文(offset=${f.to} 再取)。`
311
+ : `\n…more below (re-call with offset=${f.to}).`
312
+ : "";
313
+ const emptyNote = f.total === 0 ? (L === "zh" ? "(该会话暂无消息)" : "(no messages yet)") : "";
314
+ return text(`${head}\n${f.text || emptyNote}${more}`, {
315
+ path: found.sessionPath,
316
+ title: found.title,
317
+ total: f.total,
318
+ from: f.from,
319
+ to: f.to,
320
+ });
321
+ }
322
+ return text(pick(getLang(), `action 非法:${p.action}(只能是 list 或 read)。`, `Invalid action: ${p.action} (must be "list" or "read").`, "convread.bad.action", { "p.action": p.action }));
323
+ },
324
+ });
325
+ }
@@ -39,6 +39,7 @@ import { TerminalManager, loadCommands, saveCommandsFile } from "../terminals.js
39
39
  import { saveUpload } from "../uploads.js";
40
40
  import { checkAll as checkAllUpdates, collectTargets, resolveNpmRegistry } from "../update-check.js";
41
41
  import { previewKind } from "../text-sniff.js";
42
+ import { removeQueuedByIndexOrText } from "../queue-utils.js";
42
43
  import { launchOrigin, toServiceInfo } from "../launch-origin.js";
43
44
  import { DshRuntime, loadDeepSeekKey } from "./dsh-client.js";
44
45
  import { DshStreamAccumulator, assistantMessageEventToUiMessage, toolResultEventToUiMessage, userMessageEventToUiMessage, } from "./dsh-serialize.js";
@@ -1535,17 +1536,19 @@ export class DshClientSession {
1535
1536
  await this.promptConv(conv, text, attachments, queue, sysPrefix);
1536
1537
  }
1537
1538
  /**
1538
- * Remove ONE queued prompt text (the ✕ on a pending bubble). DSH queues are
1539
+ * Remove ONE queued prompt (the ✕ on a pending bubble). DSH queues are
1539
1540
  * display-only — the prompt was already handed to the runtime inbox, so this
1540
1541
  * only drops the pending bubble from the UI (there is no per-item runtime
1541
- * cancel). Removes the first occurrence of `text`.
1542
+ * cancel). `index` is the clicked bubble's position (duplicate texts need
1543
+ * it); mismatch or omission falls back to first-occurrence text match.
1542
1544
  */
1543
- removeQueued(kind, text) {
1545
+ removeQueued(kind, text, index) {
1544
1546
  const conv = this.conv;
1545
1547
  const arr = kind === "steer" ? conv.queue.steering : conv.queue.followUp;
1546
- const i = arr.indexOf(text);
1547
- if (i >= 0)
1548
- arr.splice(i, 1);
1548
+ const next = removeQueuedByIndexOrText(arr, text, index);
1549
+ if (next.length !== arr.length) {
1550
+ arr.splice(0, arr.length, ...next);
1551
+ }
1549
1552
  this.flushSnapshot();
1550
1553
  }
1551
1554
  /** 向指定会话发提示(审查注入/重发用;不处理 fromDisk fork 与命名)。 */
@@ -2114,7 +2117,8 @@ export class DshClientSession {
2114
2117
  });
2115
2118
  return;
2116
2119
  }
2117
- if (conv.terminals.countBlockingLive() > 0 && !force) {
2120
+ // issue #181:只看用户终端——AI bash 随对话一起释放,不得阻断移出。
2121
+ if (conv.terminals.countUserBlockingLive() > 0 && !force) {
2118
2122
  this.emit({
2119
2123
  type: "notice",
2120
2124
  level: "warning",
@@ -2123,7 +2127,7 @@ export class DshClientSession {
2123
2127
  });
2124
2128
  return;
2125
2129
  }
2126
- // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放。
2130
+ // 没动过的空 shell与 AI bash 不拦截:随对话一起释放。
2127
2131
  // force + active:先让出 active(切到其他对话或新建),再移除。
2128
2132
  if (id === this.activeId) {
2129
2133
  const other = [...this.convs.values()].find((c) => c.id !== id);
@@ -2435,11 +2439,21 @@ export class DshClientSession {
2435
2439
  async copyEntry(src, destDir, move) {
2436
2440
  await this.files.copyEntry(src, destDir, move);
2437
2441
  }
2442
+ /** 文件树右键菜单:在资源管理器中定位 / 默认应用打开(issue #187)。 */
2443
+ async revealEntry(path) {
2444
+ await this.files.revealEntry(path);
2445
+ }
2446
+ async openDefaultEntry(path) {
2447
+ await this.files.openDefaultEntry(path);
2448
+ }
2438
2449
  async completePath(input) {
2439
2450
  await this.files.completePath(input);
2440
2451
  }
2441
- async makeDir(input) {
2442
- await this.files.makeDir(input);
2452
+ async makeDir(input, setAsCwd = false) {
2453
+ const created = await this.files.makeDir(input);
2454
+ if (created && setAsCwd) {
2455
+ await this.setCwd(created);
2456
+ }
2443
2457
  }
2444
2458
  // -----------------------------------------------------------------------
2445
2459
  // 模型 / 思考
@@ -2568,6 +2582,8 @@ export class DshClientSession {
2568
2582
  disabledExtensions: this.settings.disabledExtensions,
2569
2583
  // DSH engine: no unified tool gating (no subagent/edit_soft); empty keeps protocol complete.
2570
2584
  disabledAgentTools: [],
2585
+ // DSH has no plugin host: no plugin AI tools exist here; empty keeps protocol complete.
2586
+ disabledPluginTools: [],
2571
2587
  terminalToolsEnabled: this.settings.terminalToolsEnabled,
2572
2588
  terminalBash: this.settings.terminalBash,
2573
2589
  terminalBashIdleMs: this.settings.terminalBashIdleMs,
@@ -3602,7 +3618,9 @@ export class DshClientSession {
3602
3618
  }
3603
3619
  async checkUpdatesAll(force = false) {
3604
3620
  try {
3605
- const targets = collectTargets(join(homedir(), ".pi", "agent"), DshClientSession.currentAppVersion());
3621
+ const targets = collectTargets(join(homedir(), ".pi", "agent"), DshClientSession.currentAppVersion(), undefined, {
3622
+ projectCwd: this.cwd,
3623
+ });
3606
3624
  const items = await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(join(homedir(), ".pi", "agent")));
3607
3625
  if (force) {
3608
3626
  // 强制模式:忽略缓存(默认 Fetcher 带 TTL,直接再查一次即可)。
@@ -3618,6 +3636,7 @@ export class DshClientSession {
3618
3636
  latestPublishedAt: i.latestPublishedAt ?? null,
3619
3637
  upToDate: i.upToDate,
3620
3638
  error: i.error,
3639
+ ...(i.source ? { source: i.source } : {}),
3621
3640
  })),
3622
3641
  });
3623
3642
  }
@@ -3819,6 +3838,22 @@ export class DshClientSession {
3819
3838
  error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
3820
3839
  });
3821
3840
  }
3841
+ async refreshBuiltinModels(reqId) {
3842
+ this.emit({
3843
+ type: "refresh_builtin_result",
3844
+ reqId,
3845
+ ok: false,
3846
+ error: pick(this.getLang(), "DSH 引擎走运行时内置模型,无官方目录可刷新", "The DSH engine uses runtime-built-in models; no official catalog to refresh", "dsh.provider.builtin.refresh.unsupported"),
3847
+ });
3848
+ }
3849
+ async appendBuiltinModel(_providerId, _model, reqId) {
3850
+ this.emit({
3851
+ type: "append_builtin_result",
3852
+ reqId,
3853
+ ok: false,
3854
+ error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
3855
+ });
3856
+ }
3822
3857
  async cloneProvider(_provider, reqId) {
3823
3858
  const error = pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.clone.unsupported");
3824
3859
  const errorEn = "DSH engine does not support custom providers";