pi-web-ui 0.88.0 → 0.89.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.
@@ -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));
@@ -327,6 +347,7 @@ export class ClientStateStore {
327
347
  disabledSkills: stored?.disabledSkills ?? [],
328
348
  disabledExtensions: stored?.disabledExtensions ?? [],
329
349
  disabledAgentTools: legacyToDisabled(stored ?? {}),
350
+ disabledPluginTools: normalizeDisabledPluginTools(stored?.disabledPluginTools),
330
351
  // 新字段已存在时遗留三开关以它为准推导(旧文件才读遗留值),保证两边一致。
331
352
  terminalToolsEnabled: stored?.disabledAgentTools !== undefined
332
353
  ? deriveLegacy(legacyToDisabled(stored)).terminalToolsEnabled
@@ -378,6 +399,7 @@ export class ClientStateStore {
378
399
  disabledSkills: settings.disabledSkills ?? cur.disabledSkills ?? [],
379
400
  disabledExtensions: settings.disabledExtensions ?? cur.disabledExtensions ?? [],
380
401
  disabledAgentTools: normalizeDisabledAgentTools(settings.disabledAgentTools ?? cur.disabledAgentTools),
402
+ disabledPluginTools: normalizeDisabledPluginTools(settings.disabledPluginTools ?? cur.disabledPluginTools),
381
403
  terminalToolsEnabled: settings.terminalToolsEnabled ?? cur.terminalToolsEnabled ?? false,
382
404
  terminalBash: settings.terminalBash ?? cur.terminalBash ?? false,
383
405
  terminalBashIdleMs: settings.terminalBashIdleMs ?? cur.terminalBashIdleMs ?? 15_000,
@@ -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
+ }
@@ -2114,7 +2114,8 @@ export class DshClientSession {
2114
2114
  });
2115
2115
  return;
2116
2116
  }
2117
- if (conv.terminals.countBlockingLive() > 0 && !force) {
2117
+ // issue #181:只看用户终端——AI bash 随对话一起释放,不得阻断移出。
2118
+ if (conv.terminals.countUserBlockingLive() > 0 && !force) {
2118
2119
  this.emit({
2119
2120
  type: "notice",
2120
2121
  level: "warning",
@@ -2123,7 +2124,7 @@ export class DshClientSession {
2123
2124
  });
2124
2125
  return;
2125
2126
  }
2126
- // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放。
2127
+ // 没动过的空 shell与 AI bash 不拦截:随对话一起释放。
2127
2128
  // force + active:先让出 active(切到其他对话或新建),再移除。
2128
2129
  if (id === this.activeId) {
2129
2130
  const other = [...this.convs.values()].find((c) => c.id !== id);
@@ -2435,6 +2436,13 @@ export class DshClientSession {
2435
2436
  async copyEntry(src, destDir, move) {
2436
2437
  await this.files.copyEntry(src, destDir, move);
2437
2438
  }
2439
+ /** 文件树右键菜单:在资源管理器中定位 / 默认应用打开(issue #187)。 */
2440
+ async revealEntry(path) {
2441
+ await this.files.revealEntry(path);
2442
+ }
2443
+ async openDefaultEntry(path) {
2444
+ await this.files.openDefaultEntry(path);
2445
+ }
2438
2446
  async completePath(input) {
2439
2447
  await this.files.completePath(input);
2440
2448
  }
@@ -2568,6 +2576,8 @@ export class DshClientSession {
2568
2576
  disabledExtensions: this.settings.disabledExtensions,
2569
2577
  // DSH engine: no unified tool gating (no subagent/edit_soft); empty keeps protocol complete.
2570
2578
  disabledAgentTools: [],
2579
+ // DSH has no plugin host: no plugin AI tools exist here; empty keeps protocol complete.
2580
+ disabledPluginTools: [],
2571
2581
  terminalToolsEnabled: this.settings.terminalToolsEnabled,
2572
2582
  terminalBash: this.settings.terminalBash,
2573
2583
  terminalBashIdleMs: this.settings.terminalBashIdleMs,
@@ -3602,7 +3612,9 @@ export class DshClientSession {
3602
3612
  }
3603
3613
  async checkUpdatesAll(force = false) {
3604
3614
  try {
3605
- const targets = collectTargets(join(homedir(), ".pi", "agent"), DshClientSession.currentAppVersion());
3615
+ const targets = collectTargets(join(homedir(), ".pi", "agent"), DshClientSession.currentAppVersion(), undefined, {
3616
+ projectCwd: this.cwd,
3617
+ });
3606
3618
  const items = await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(join(homedir(), ".pi", "agent")));
3607
3619
  if (force) {
3608
3620
  // 强制模式:忽略缓存(默认 Fetcher 带 TTL,直接再查一次即可)。
@@ -3618,6 +3630,7 @@ export class DshClientSession {
3618
3630
  latestPublishedAt: i.latestPublishedAt ?? null,
3619
3631
  upToDate: i.upToDate,
3620
3632
  error: i.error,
3633
+ ...(i.source ? { source: i.source } : {}),
3621
3634
  })),
3622
3635
  });
3623
3636
  }
@@ -3819,6 +3832,22 @@ export class DshClientSession {
3819
3832
  error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
3820
3833
  });
3821
3834
  }
3835
+ async refreshBuiltinModels(reqId) {
3836
+ this.emit({
3837
+ type: "refresh_builtin_result",
3838
+ reqId,
3839
+ ok: false,
3840
+ error: pick(this.getLang(), "DSH 引擎走运行时内置模型,无官方目录可刷新", "The DSH engine uses runtime-built-in models; no official catalog to refresh", "dsh.provider.builtin.refresh.unsupported"),
3841
+ });
3842
+ }
3843
+ async appendBuiltinModel(_providerId, _model, reqId) {
3844
+ this.emit({
3845
+ type: "append_builtin_result",
3846
+ reqId,
3847
+ ok: false,
3848
+ error: pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.custom.unsupported"),
3849
+ });
3850
+ }
3822
3851
  async cloneProvider(_provider, reqId) {
3823
3852
  const error = pick(this.getLang(), "DSH 引擎不支持自定义 provider", "The DSH engine does not support custom providers", "dsh.provider.clone.unsupported");
3824
3853
  const errorEn = "DSH engine does not support custom providers";
@@ -1176,6 +1176,109 @@ export class FilesService {
1176
1176
  }
1177
1177
  return join(dir, `${stem} copy ${Date.now()}${ext}`);
1178
1178
  }
1179
+ /** 系统原生打开/定位的公共执行体(issue #187):cmd/args 已按平台组装好。
1180
+ * spawn 成功即算送达(explorer/open 都是 daemon 式返回,exit code 不可信);
1181
+ * ENOENT(headless/无桌面)等失败一律 warning notice,绝不抛。 */
1182
+ async spawnDetached(cmd, args, okText, okTextEn) {
1183
+ const fail = (detail) => this.host.emit({
1184
+ type: "notice",
1185
+ level: "warning",
1186
+ text: "无法打开系统文件管理:" + detail + "(远端/无桌面主机不支持)",
1187
+ textEn: "Cannot open system file manager: " + detail + " (unsupported on remote/headless hosts)",
1188
+ });
1189
+ try {
1190
+ const { spawn } = await import("node:child_process");
1191
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
1192
+ if (typeof child.unref === "function")
1193
+ child.unref();
1194
+ const launched = await new Promise((resolve) => {
1195
+ let done = false;
1196
+ const settle = (v) => {
1197
+ if (!done) {
1198
+ done = true;
1199
+ resolve(v);
1200
+ }
1201
+ };
1202
+ child.on("spawn", () => settle(true));
1203
+ child.on("error", () => settle(false));
1204
+ // 极端平台无 spawn 事件时兜底放行(进程已脱离,成败不再可知)。
1205
+ setTimeout(() => settle(true), 3000);
1206
+ });
1207
+ if (!launched) {
1208
+ fail(cmd);
1209
+ return;
1210
+ }
1211
+ this.host.emit({ type: "notice", level: "info", text: okText, textEn: okTextEn });
1212
+ }
1213
+ catch (e) {
1214
+ fail(e.message);
1215
+ }
1216
+ }
1217
+ /** 在系统资源管理器中定位(issue #187):文件→打开目录并选中该文件,目录→直接打开。
1218
+ * 只读操作(不改文件),保护根/盘符根也允许;@root 本体与越界路径拒绝。 */
1219
+ async revealEntry(path) {
1220
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "warning", text, textEn });
1221
+ try {
1222
+ const fsp = await import("node:fs/promises");
1223
+ const { dirname } = await import("node:path");
1224
+ const t = this.resolveOpTarget(path);
1225
+ if (!t) {
1226
+ err("此处不可定位:" + path, "Cannot reveal here: " + path);
1227
+ return;
1228
+ }
1229
+ const st = await fsp.stat(t.abs).catch(() => null);
1230
+ if (!st) {
1231
+ err("文件不存在:" + path, "Not found: " + path);
1232
+ return;
1233
+ }
1234
+ const isDir = st.isDirectory();
1235
+ const segs = path.split("/");
1236
+ const base = segs[segs.length - 1] ?? path;
1237
+ if (process.platform === "win32") {
1238
+ // /select, 与路径分两个 argv 传(explorer 对此格式稳定支持,路径含空格也无碍)。
1239
+ await this.spawnDetached("explorer.exe", isDir ? [t.abs] : ["/select,", t.abs], "已在资源管理器中显示:" + base, "Revealed in File Explorer: " + base);
1240
+ }
1241
+ else if (process.platform === "darwin") {
1242
+ await this.spawnDetached("open", isDir ? [t.abs] : ["-R", t.abs], "已在访达中显示:" + base, "Revealed in Finder: " + base);
1243
+ }
1244
+ else {
1245
+ // Linux 无统一选中语义:打开其父目录(目录则打开自身)。
1246
+ await this.spawnDetached("xdg-open", [isDir ? t.abs : dirname(t.abs)], "已打开所在目录:" + base, "Opened containing folder: " + base);
1247
+ }
1248
+ }
1249
+ catch (e) {
1250
+ err("定位失败:" + e.message, "Reveal failed: " + e.message);
1251
+ }
1252
+ }
1253
+ /** 用系统默认应用打开文件(issue #187):仅文件;目录请用 reveal。 */
1254
+ async openDefaultEntry(path) {
1255
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "warning", text, textEn });
1256
+ try {
1257
+ const fsp = await import("node:fs/promises");
1258
+ const t = this.resolveOpTarget(path);
1259
+ if (!t) {
1260
+ err("此处不可打开:" + path, "Cannot open here: " + path);
1261
+ return;
1262
+ }
1263
+ const st = await fsp.stat(t.abs).catch(() => null);
1264
+ if (!st) {
1265
+ err("文件不存在:" + path, "Not found: " + path);
1266
+ return;
1267
+ }
1268
+ if (!st.isFile()) {
1269
+ err("请选择文件(目录请用“在资源管理器中显示”)", 'Please select a file (use "Reveal" for folders)');
1270
+ return;
1271
+ }
1272
+ const segs = path.split("/");
1273
+ const base = segs[segs.length - 1] ?? path;
1274
+ // explorer 直接跟路径即走默认关联打开(含空格路径单 argv,无拆分问题)。
1275
+ const cmd = process.platform === "win32" ? "explorer.exe" : process.platform === "darwin" ? "open" : "xdg-open";
1276
+ await this.spawnDetached(cmd, [t.abs], "已用默认应用打开:" + base, "Opened with default app: " + base);
1277
+ }
1278
+ catch (e) {
1279
+ err("打开失败:" + e.message, "Open failed: " + e.message);
1280
+ }
1281
+ }
1179
1282
  /**
1180
1283
  * Path completion for the cwd input: expand ~/relative paths, list the parent
1181
1284
  * directory, and return prefix matches (dirs first, capped).