pi-web-ui 0.68.0 → 0.68.2

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 (35) hide show
  1. package/bin/pi-web-ui.mjs +1876 -1876
  2. package/dist/server/agent-service.js +450 -68
  3. package/dist/server/attachments.js +3 -3
  4. package/dist/server/client-state.js +4 -2
  5. package/dist/server/dsh/dsh-agent-service.js +15 -1
  6. package/dist/server/dsh/runtime/cordis.yml +1 -1
  7. package/dist/server/dsh/runtime/goal-rpc.mjs +645 -645
  8. package/dist/server/dsh/runtime/launcher.mjs +164 -164
  9. package/dist/server/dsh/runtime/override.patch.yml +71 -71
  10. package/dist/server/dsh/runtime/runtime-root.mjs +92 -86
  11. package/dist/server/index.js +68 -2
  12. package/dist/server/locales.js +156 -0
  13. package/dist/server/plugins.js +63 -0
  14. package/dist/server/prompt-composer.js +34 -0
  15. package/dist/server/serialize.js +24 -0
  16. package/dist/server/settings-service.js +9 -0
  17. package/dist/server/update-check.js +49 -50
  18. package/dist/server/vision-bridge.js +9 -9
  19. package/extensions/webui.ts +190 -190
  20. package/package.json +6 -2
  21. package/plugins/catalog.json +9 -0
  22. package/web/dist/assets/TerminalPanel-BQ5NTB9Y.js +6 -0
  23. package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
  24. package/web/dist/assets/index-C_I-6Zul.css +10 -0
  25. package/web/dist/assets/index-Ck5pa3XK.js +333 -0
  26. package/web/dist/assets/markdown-DOsihKaR.js +51 -0
  27. package/web/dist/assets/{react-C9ovnpIm.js → react-DIP6JKYk.js} +2 -2
  28. package/web/dist/assets/xterm-B96xOxS9.js +38 -0
  29. package/web/dist/index.html +4 -4
  30. package/web/dist/assets/TerminalPanel-6GBZ9nXN.css +0 -32
  31. package/web/dist/assets/TerminalPanel-CTY_LN4U.js +0 -6
  32. package/web/dist/assets/index-Dc6t3GTo.css +0 -10
  33. package/web/dist/assets/index-fwF-jmiV.js +0 -332
  34. package/web/dist/assets/markdown-DRBrS2Nf.js +0 -51
  35. package/web/dist/assets/xterm-D1D2FVe3.js +0 -38
@@ -16,7 +16,7 @@
16
16
  * all share one conversation list per project.
17
17
  * PI_CODING_AGENT_DIR pi config dir (auth/models/skills) — passed to the SDK
18
18
  */
19
- import { existsSync } from "node:fs";
19
+ import { existsSync, readFileSync } from "node:fs";
20
20
  import { stat } from "node:fs/promises";
21
21
  import { createServer } from "node:http";
22
22
  import { createConnection } from "node:net";
@@ -36,7 +36,8 @@ import { startControlServer } from "./control-socket.js";
36
36
  import { scheduleUploadCleanup } from "./uploads.js";
37
37
  import { ensureWindowsBash, windowsBashDir } from "./ensure-bash.js";
38
38
  import { listThemes, resolveThemeFile } from "./themes.js";
39
- import { PluginManager, resolvePluginClientFile } from "./plugins.js";
39
+ import { installPack, isKnownPack, listPacks, readPackFile, removePack } from "./locales.js";
40
+ import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
40
41
  import { McpBridge } from "./mcp-bridge.js";
41
42
  /** 从 CLI 参数中取 flag 值:支持 --flag value 与 --flag=value 两种写法。
42
43
  * 让 `node dist/server/index.js --host 0.0.0.0 --port 9000` 这类直接启动也能生效,
@@ -76,6 +77,19 @@ const ALLOW_ORIGINS = (process.env.PI_WEB_ALLOW_ORIGINS ?? "")
76
77
  * Authorization: Bearer / X-PI-Token 头、?token= 查询参数或 pi_web_token cookie
77
78
  * 任一匹配即可;供 0.0.0.0 / 反代等暴露场景兜底,未设置则行为不变。 */
78
79
  const AUTH_TOKEN = process.env.PI_WEB_TOKEN?.trim() ?? "";
80
+ /** 语言包下载根(语言包仓库的 raw 文件地址;版本 tag 优先、main 兜底,见 locales.ts)。 */
81
+ const LOCALE_BASE_URL = process.env.PI_WEB_LOCALE_BASE_URL?.trim() || "https://raw.githubusercontent.com/xing-shuyin/pi-web-ui";
82
+ /** 本包版本 —— 下载语言包时优先取同版本 tag,保证 key 对齐。 */
83
+ const APP_VERSION = (() => {
84
+ try {
85
+ // 注意:此处不能用下面的 pkgRoot 常量(TDZ)——直接调函数声明(已提升)。
86
+ const pkg = JSON.parse(readFileSync(join(resolvePkgRoot(), "package.json"), "utf8"));
87
+ return pkg.version ?? "";
88
+ }
89
+ catch {
90
+ return "";
91
+ }
92
+ })();
79
93
  // Root of the SDK default per-project session dirs — chat transcripts live in
80
94
  // <SESSION_DIR_ROOT>/--<cwd>--/, shared with the pi CLI/TUI (getAgentDir
81
95
  // honors PI_CODING_AGENT_DIR).
@@ -252,6 +266,51 @@ const USER_THEMES_DIR = join(DATA_DIR, "themes");
252
266
  app.get("/api/themes", (_req, res) => {
253
267
  res.json({ themes: listThemes(BUILTIN_THEMES_DIR, USER_THEMES_DIR) });
254
268
  });
269
+ // 语言包:核心只随包发布中英,其余按需下载到 <dataDir>/locales/<code>.json。
270
+ // 手工放进去的同名 JSON 也会被识别(离线安装)。PI_WEB_TOKEN 鉴权自动覆盖。
271
+ app.get("/api/locales", (_req, res) => {
272
+ res.json({ packs: listPacks(DATA_DIR) });
273
+ });
274
+ app.get("/api/locales/:code", (req, res) => {
275
+ const code = String(req.params.code ?? "");
276
+ if (!isKnownPack(code)) {
277
+ res.status(404).end("unknown locale");
278
+ return;
279
+ }
280
+ const pack = readPackFile(DATA_DIR, code);
281
+ if (!pack) {
282
+ res.status(404).end("locale not installed");
283
+ return;
284
+ }
285
+ res.setHeader("Cache-Control", "no-cache");
286
+ res.json(pack);
287
+ });
288
+ app.post("/api/locales/:code/install", async (req, res) => {
289
+ const code = String(req.params.code ?? "");
290
+ if (!isKnownPack(code)) {
291
+ res.status(400).json({ error: `unknown locale: ${code}` });
292
+ return;
293
+ }
294
+ try {
295
+ const meta = await installPack(DATA_DIR, code, { baseUrl: LOCALE_BASE_URL, version: APP_VERSION });
296
+ res.json({ ok: true, ...meta });
297
+ }
298
+ catch (e) {
299
+ res.status(502).json({ error: e instanceof Error ? e.message : String(e) });
300
+ }
301
+ });
302
+ app.delete("/api/locales/:code", (req, res) => {
303
+ const code = String(req.params.code ?? "");
304
+ if (!isKnownPack(code)) {
305
+ res.status(404).end("unknown locale");
306
+ return;
307
+ }
308
+ if (!removePack(DATA_DIR, code)) {
309
+ res.status(404).end("locale not installed");
310
+ return;
311
+ }
312
+ res.json({ ok: true });
313
+ });
255
314
  // Serve a theme's full CSS file so the frontend can swap the whole stylesheet.
256
315
  // Registered before the SPA catch-all below (otherwise it'd return index.html).
257
316
  app.get("/themes/:id.css", (req, res) => {
@@ -447,6 +506,12 @@ void mcpBridge.load().then(() => {
447
506
  });
448
507
  // 插件扩展点:SDK 工具执行事件(bash/读文件等 start+end)转发给已注册的插件。
449
508
  service.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
509
+ service.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
510
+ // 插件扩展点:对话切换通知(轨迹视图切会话后即重拉;dsh 引擎暂无)。
511
+ service.onConversationChanged = () => pluginMgr.emitConversationChanged();
512
+ // 插件扩展点:当前打开对话的快照(轨迹视图直接显示打开对话的时间线;
513
+ // dsh 引擎无此方法时回退 null,插件显示空态)。
514
+ pluginMgr.conversationProvider = () => service.readConversationForPlugins?.() ?? null;
450
515
  // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
451
516
  // 带上 + 变化时动态注入/移除已有会话。
452
517
  service.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
@@ -820,6 +885,7 @@ wss.on("connection", (ws) => {
820
885
  terminalBash: msg.terminalBash,
821
886
  terminalBashIdleMs: msg.terminalBashIdleMs,
822
887
  editSoftEnabled: msg.editSoftEnabled,
888
+ questionnaireEnabled: msg.questionnaireEnabled,
823
889
  thinkingWrap: msg.thinkingWrap,
824
890
  toolsWrap: msg.toolsWrap,
825
891
  visionBridgeEnabled: msg.visionBridgeEnabled,
@@ -0,0 +1,156 @@
1
+ /**
2
+ * locales — downloadable language packs.
3
+ *
4
+ * Core ships zh/en only (see web/src/i18n.tsx). Every other language lives in
5
+ * `locales/<code>.json` in the git repo (NOT in the npm `files` whitelist, so
6
+ * packs never ship with the package) with shape:
7
+ * { code, nativeName, version, strings: Record<string,string> }
8
+ *
9
+ * On demand the server downloads a pack from PI_WEB_LOCALE_BASE_URL
10
+ * (default: GitHub raw — version tag first, `main` as fallback) into
11
+ * <dataDir>/locales/<code>.json and serves it to the browser. Missing keys
12
+ * fall back to English client-side, so version skew between app and pack is
13
+ * tolerable. Manually dropped <dataDir>/locales/*.json files work too
14
+ * (offline installs) — the list is read from disk.
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ /** Packs available for download (alphabetical by code). */
19
+ export const LOCALE_PACKS = [
20
+ { code: "de", nativeName: "Deutsch" },
21
+ { code: "es", nativeName: "Español" },
22
+ { code: "fr", nativeName: "Français" },
23
+ { code: "it", nativeName: "Italiano" },
24
+ { code: "ja", nativeName: "日本語" },
25
+ { code: "ko", nativeName: "한국어" },
26
+ { code: "pt", nativeName: "Português" },
27
+ { code: "ru", nativeName: "Русский" },
28
+ ];
29
+ export function isKnownPack(code) {
30
+ return LOCALE_PACKS.some((p) => p.code === code);
31
+ }
32
+ export function packMeta(code) {
33
+ return LOCALE_PACKS.find((p) => p.code === code) ?? null;
34
+ }
35
+ export function packPath(dataDir, code) {
36
+ return join(dataDir, "locales", `${code}.json`);
37
+ }
38
+ /** Downloaded packs must look like this (extra fields ignored). */
39
+ export function validatePack(data, code) {
40
+ if (!data || typeof data !== "object")
41
+ return { ok: false, error: "not an object" };
42
+ const d = data;
43
+ if (d["code"] !== code)
44
+ return { ok: false, error: `code mismatch (want ${code})` };
45
+ if (typeof d["nativeName"] !== "string" || !d["nativeName"].trim()) {
46
+ return { ok: false, error: "missing nativeName" };
47
+ }
48
+ if (!d["strings"] || typeof d["strings"] !== "object")
49
+ return { ok: false, error: "missing strings" };
50
+ const strings = {};
51
+ for (const [k, v] of Object.entries(d["strings"])) {
52
+ if (typeof v !== "string")
53
+ return { ok: false, error: `non-string value for ${k}` };
54
+ strings[k] = v;
55
+ }
56
+ if (Object.keys(strings).length === 0)
57
+ return { ok: false, error: "empty strings" };
58
+ return {
59
+ ok: true,
60
+ pack: {
61
+ code,
62
+ nativeName: d["nativeName"].trim(),
63
+ version: typeof d["version"] === "string" ? d["version"] : "unknown",
64
+ strings,
65
+ },
66
+ };
67
+ }
68
+ /** Read an installed pack (null when missing / corrupt — corrupt files are ignored, not deleted). */
69
+ export function readPackFile(dataDir, code) {
70
+ if (!isKnownPack(code))
71
+ return null;
72
+ const file = packPath(dataDir, code);
73
+ if (!existsSync(file))
74
+ return null;
75
+ try {
76
+ const data = JSON.parse(readFileSync(file, "utf8"));
77
+ const v = validatePack(data, code);
78
+ return v.ok ? v.pack : null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ export function listPacks(dataDir) {
85
+ return LOCALE_PACKS.map((meta) => {
86
+ const installed = readPackFile(dataDir, meta.code);
87
+ return { ...meta, installed: installed !== null, version: installed?.version ?? null };
88
+ });
89
+ }
90
+ export function removePack(dataDir, code) {
91
+ if (!isKnownPack(code))
92
+ return false;
93
+ const file = packPath(dataDir, code);
94
+ if (!existsSync(file))
95
+ return false;
96
+ rmSync(file);
97
+ return true;
98
+ }
99
+ const MAX_PACK_BYTES = 4 * 1024 * 1024;
100
+ /**
101
+ * Download a pack and persist it under <dataDir>/locales/<code>.json
102
+ * (atomic write via tmp + rename). Throws on network / validation errors.
103
+ */
104
+ export async function installPack(dataDir, code, opts = {}) {
105
+ const meta = packMeta(code);
106
+ if (!meta)
107
+ throw new Error(`unknown locale: ${code}`);
108
+ const base = (opts.baseUrl ?? "https://raw.githubusercontent.com/xing-shuyin/pi-web-ui").replace(/\/+$/, "");
109
+ const urls = opts.version
110
+ ? [`${base}/v${opts.version}/locales/${code}.json`, `${base}/main/locales/${code}.json`]
111
+ : [`${base}/main/locales/${code}.json`];
112
+ const fetchFn = opts.fetchFn ?? fetch;
113
+ const timeoutMs = opts.timeoutMs ?? 30000;
114
+ let lastError = "";
115
+ for (const url of urls) {
116
+ const ctrl = new AbortController();
117
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
118
+ try {
119
+ const res = await fetchFn(url, { signal: ctrl.signal });
120
+ if (!res.ok) {
121
+ lastError = `HTTP ${res.status} for ${url}`;
122
+ continue;
123
+ }
124
+ const text = await res.text();
125
+ if (text.length > MAX_PACK_BYTES)
126
+ throw new Error(`pack too large (${text.length} bytes)`);
127
+ let data;
128
+ try {
129
+ data = JSON.parse(text);
130
+ }
131
+ catch {
132
+ throw new Error(`invalid JSON from ${url}`);
133
+ }
134
+ const v = validatePack(data, code);
135
+ if (!v.ok)
136
+ throw new Error(`invalid pack ${code}: ${v.error}`);
137
+ mkdirSync(join(dataDir, "locales"), { recursive: true });
138
+ const file = packPath(dataDir, code);
139
+ const tmp = `${file}.${process.pid}.tmp`;
140
+ writeFileSync(tmp, JSON.stringify(v.pack));
141
+ renameSync(tmp, file);
142
+ return { code, nativeName: v.pack.nativeName, version: v.pack.version };
143
+ }
144
+ catch (e) {
145
+ lastError = e instanceof Error ? e.message : String(e);
146
+ // A validation error means the URL answered with wrong content —
147
+ // don't silently retry the fallback for it, surface it directly.
148
+ if (lastError.startsWith("invalid "))
149
+ throw e;
150
+ }
151
+ finally {
152
+ clearTimeout(timer);
153
+ }
154
+ }
155
+ throw new Error(lastError || `download failed for ${code}`);
156
+ }
@@ -457,6 +457,50 @@ export class PluginManager {
457
457
  }
458
458
  }
459
459
  }
460
+ /** index.ts 注入:读取当前打开对话的快照(轨迹类插件经 host.getActiveConversation 调用)。 */
461
+ conversationProvider = undefined;
462
+ /** 当前打开对话的快照(无提供者/暂无对话时返回 null)。 */
463
+ getActiveConversation() {
464
+ try {
465
+ return this.conversationProvider?.() ?? null;
466
+ }
467
+ catch (err) {
468
+ console.error("[plugins] conversationProvider failed:", err);
469
+ return null;
470
+ }
471
+ }
472
+ /** agent-service 调:当前打开对话变了(切历史会话/切 running 对话/新对话)——
473
+ * 轨迹类插件靠它重拉时间线(异常隔离)。 */
474
+ emitConversationChanged() {
475
+ for (const p of this.loaded.values()) {
476
+ if (p.convChangeHandlers.size === 0)
477
+ continue;
478
+ for (const h of p.convChangeHandlers) {
479
+ try {
480
+ h();
481
+ }
482
+ catch (err) {
483
+ console.error(`[plugin:${p.info.id}] conversation-changed handler failed:`, err);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ /** agent-service 调:把运行轨迹事件扇出给所有插件(异常隔离,
489
+ * 与 emitToolEvent 同级;订阅者崩了只记日志,不影响主流程)。 */
490
+ emitRunEvent(ev) {
491
+ for (const p of this.loaded.values()) {
492
+ if (p.runHandlers.size === 0)
493
+ continue;
494
+ for (const h of p.runHandlers) {
495
+ try {
496
+ h(ev);
497
+ }
498
+ catch (err) {
499
+ console.error(`[plugin:${p.info.id}] run-event handler failed:`, err);
500
+ }
501
+ }
502
+ }
503
+ }
460
504
  /** 当前全部插件注册的 AI 工具(扁平化,按插件 id 稳定排序)。 */
461
505
  getAgentTools() {
462
506
  const out = [];
@@ -697,6 +741,8 @@ export class PluginManager {
697
741
  const handlers = new Set();
698
742
  this.messageHandlers.set(info.id, handlers);
699
743
  const toolHandlers = new Set();
744
+ const runHandlers = new Set();
745
+ const convChangeHandlers = new Set();
700
746
  const attachHandlers = new Set();
701
747
  const cwdHandlers = new Set();
702
748
  const httpRoutes = new Map();
@@ -717,6 +763,8 @@ export class PluginManager {
717
763
  this.loaded.set(info.id, {
718
764
  info: { ...info, error: msg },
719
765
  toolHandlers,
766
+ runHandlers,
767
+ convChangeHandlers,
720
768
  attachHandlers,
721
769
  cwdHandlers,
722
770
  httpRoutes,
@@ -732,6 +780,8 @@ export class PluginManager {
732
780
  const p = {
733
781
  info,
734
782
  toolHandlers,
783
+ runHandlers,
784
+ convChangeHandlers,
735
785
  attachHandlers,
736
786
  cwdHandlers,
737
787
  commandUnsubscribers: unregisterCommands,
@@ -774,6 +824,15 @@ export class PluginManager {
774
824
  toolHandlers.add(h);
775
825
  return () => toolHandlers.delete(h);
776
826
  },
827
+ onRunEvent: (h) => {
828
+ runHandlers.add(h);
829
+ return () => runHandlers.delete(h);
830
+ },
831
+ onConversationChanged: (h) => {
832
+ convChangeHandlers.add(h);
833
+ return () => convChangeHandlers.delete(h);
834
+ },
835
+ getActiveConversation: () => self.getActiveConversation(),
777
836
  onAttach: (h) => {
778
837
  attachHandlers.add(h);
779
838
  return () => attachHandlers.delete(h);
@@ -893,6 +952,8 @@ export class PluginManager {
893
952
  info: { ...info },
894
953
  deactivate: typeof ret === "function" ? ret : undefined,
895
954
  toolHandlers,
955
+ runHandlers,
956
+ convChangeHandlers,
896
957
  attachHandlers,
897
958
  cwdHandlers,
898
959
  agentToolUnsubscribers: unregisterTools,
@@ -911,6 +972,8 @@ export class PluginManager {
911
972
  this.loaded.set(info.id, {
912
973
  info: { ...info, error: err.message },
913
974
  toolHandlers,
975
+ runHandlers,
976
+ convChangeHandlers,
914
977
  attachHandlers,
915
978
  cwdHandlers,
916
979
  httpRoutes,
@@ -31,6 +31,25 @@ export const PROMPT_TOKENS = [
31
31
  "skills", // 技能段 <available_skills>
32
32
  "cwd", // Current working directory 行
33
33
  ];
34
+ /** 只读来源(设置面板只读展示、不提供覆盖输入):这些 token 的内容由系统/环境
35
+ * 在每次 run 时动态生成(工具集、项目文件、技能、工作目录、开关状态),用户无法
36
+ * 在设置里预设其内容。反之 soul / guidelines / append 是用户内容层,可编辑。
37
+ * 注意:只读是「设置面板 UI」层面;服务端 override 机制(renderPromptTemplate)
38
+ * 仍保留,以兼容旧配置与编程调用。 */
39
+ export const READONLY_PROMPT_SOURCES = [
40
+ "tools", // 工具列表(运行时时按已注册工具动态生成)
41
+ "pi_docs", // Pi 文档指引(指向已安装 pi 包路径,由安装位置决定)
42
+ "persona", // Windows persona(仅 win32,平台固定)
43
+ "terminal", // 终端工具使用引导(随「终端工具」开关)
44
+ "markers", // 内置标记工具引导(随 markers 开关)
45
+ "context", // 项目上下文(AGENTS.md / CLAUDE.md 收集结果)
46
+ "skills", // 技能段(来自环境/技能文件)
47
+ "cwd", // 当前工作目录
48
+ ];
49
+ /** 仅当 token 是只读来源时返回 true(设置面板用于判断是否展示覆盖输入框)。 */
50
+ export function isReadonlyPromptSource(token) {
51
+ return READONLY_PROMPT_SOURCES.includes(token);
52
+ }
34
53
  /** 默认模板:全部 token 按自然顺序以空行连接 —— 无覆盖、不改动时渲染结果 ≈
35
54
  * SDK 默认拼装的完整提示词。 */
36
55
  export const DEFAULT_PROMPT_TEMPLATE = PROMPT_TOKENS.map((t) => `{{${t}}}`).join("\n\n");
@@ -147,6 +166,21 @@ function buildToolsText(inputs) {
147
166
  "In addition to the tools above, you may have access to other custom tools depending on the project.",
148
167
  ].join("\n\n");
149
168
  }
169
+ /** 工具 schema 只读文本(设置面板「查看当前完整提示词」里展示发给模型的完整
170
+ * 工具定义:name + description + parameters JSON Schema)。 */
171
+ export function buildToolsSchemaText(tools) {
172
+ if (tools.length === 0)
173
+ return "";
174
+ return tools
175
+ .map((t) => {
176
+ const lines = [`## ${t.name}`];
177
+ if (t.description && t.description.trim())
178
+ lines.push(t.description.trim());
179
+ lines.push("", "Parameters (JSON Schema):", JSON.stringify(t.parameters ?? {}, null, 2));
180
+ return lines.join("\n");
181
+ })
182
+ .join("\n\n");
183
+ }
150
184
  /** 计算每个 token 的自动内容(无覆盖时的展开值)。 */
151
185
  export function resolveSectionTexts(inputs) {
152
186
  const cwd = inputs.cwd.replace(/\\/g, "/");
@@ -59,6 +59,30 @@ function serializeAssistantContent(content) {
59
59
  return { type: "unknown", ...b };
60
60
  });
61
61
  }
62
+ /**
63
+ * Hide transient LLM failures while an auto-retry is pending.
64
+ *
65
+ * The SDK finalizes the failed assistant message (message_end, then agent_end
66
+ * with willRetry) BEFORE it slices the message out of state and backs off, so
67
+ * a snapshot taken in between would paint a red error that vanishes one frame
68
+ * later. While `retryActive` the trailing stopReason=error assistant messages
69
+ * are intermediate state: dropped here (retry success → the user never sees
70
+ * them; exhaustion → auto_retry_end clears the flag and the message renders
71
+ * red permanently). Non-trailing content is never touched.
72
+ */
73
+ export function stripTransientRetryErrors(messages, retryActive) {
74
+ if (!retryActive)
75
+ return messages;
76
+ let end = messages.length;
77
+ while (end > 0) {
78
+ const m = messages[end - 1];
79
+ if (m.role === "assistant" && m.stopReason === "error")
80
+ end -= 1;
81
+ else
82
+ break;
83
+ }
84
+ return end === messages.length ? messages : messages.slice(0, end);
85
+ }
62
86
  export function serializeMessage(m, seq) {
63
87
  switch (m.role) {
64
88
  case "user":
@@ -193,6 +193,7 @@ export class SettingsService {
193
193
  terminalBash: this.settings.terminalBash,
194
194
  terminalBashIdleMs: this.settings.terminalBashIdleMs,
195
195
  editSoftEnabled: this.settings.editSoftEnabled,
196
+ questionnaireEnabled: this.settings.questionnaireEnabled,
196
197
  thinkingWrap: this.settings.thinkingWrap,
197
198
  toolsWrap: this.settings.toolsWrap,
198
199
  visionBridgeEnabled: this.settings.visionBridgeEnabled,
@@ -206,6 +207,8 @@ export class SettingsService {
206
207
  effectiveSystemPrompt: promptSnap.full,
207
208
  // 每个来源未覆盖时的默认(自动)内容(「各来源」行预览用)。
208
209
  promptSourceDefaults: promptSnap.texts,
210
+ // 发给模型的工具 schema(name/description/parameters)—— 只读预览。
211
+ toolsSchema: promptSnap.toolsSchema,
209
212
  visionBridgeDefaultPrompt: SYSTEM_PROMPT,
210
213
  visionModels: this.collectVisionModels(),
211
214
  disabledSkills: [...this.settings.disabledSkills],
@@ -320,6 +323,10 @@ export class SettingsService {
320
323
  if (partial.editSoftEnabled !== undefined) {
321
324
  this.settings.editSoftEnabled = partial.editSoftEnabled;
322
325
  }
326
+ // 问卷开关:运行时无需重载(bridge 处实时读取)。
327
+ if (partial.questionnaireEnabled !== undefined) {
328
+ this.settings.questionnaireEnabled = partial.questionnaireEnabled;
329
+ }
323
330
  if (partial.thinkingWrap !== undefined) {
324
331
  this.settings.thinkingWrap = partial.thinkingWrap;
325
332
  }
@@ -425,6 +432,8 @@ export class SettingsService {
425
432
  terminalBash: p.terminalBash ?? this.settings.terminalBash,
426
433
  terminalBashIdleMs: p.terminalBashIdleMs ?? this.settings.terminalBashIdleMs,
427
434
  editSoftEnabled: p.editSoftEnabled ?? this.settings.editSoftEnabled,
435
+ // 问卷开关不进预设——保留当前值。
436
+ questionnaireEnabled: this.settings.questionnaireEnabled,
428
437
  reviewPrompt: p.reviewPrompt ?? this.settings.reviewPrompt,
429
438
  reviewDisabledSkills: [...(p.reviewDisabledSkills ?? this.settings.reviewDisabledSkills)],
430
439
  // 纯 UI 偏好不进预设——保留当前值。
@@ -7,9 +7,8 @@
7
7
  * (and an injected pi-core probe); ClientSession only wires it to the wire
8
8
  * protocol.
9
9
  */
10
- import { spawn } from "node:child_process";
11
- import { readdirSync, readFileSync } from "node:fs";
12
- import { join } from "node:path";
10
+ import { readdirSync, readFileSync, realpathSync, existsSync } from "node:fs";
11
+ import { delimiter, dirname, join } from "node:path";
13
12
  const PI_CORE_PACKAGE = "@earendil-works/pi-coding-agent";
14
13
  const REGISTRY = "https://registry.npmjs.org";
15
14
  const FETCH_TIMEOUT_MS = 8_000;
@@ -157,67 +156,67 @@ function readLocalPackage(dir) {
157
156
  /** How long a pi probe result stays hot (mirrors ClientSession.piCliProbe). */
158
157
  const PI_PROBE_TTL_MS = 10_000;
159
158
  let piCoreProbe = null;
160
- let piCoreProbePending = false;
161
- function refreshPiCoreProbe() {
162
- if (piCoreProbePending)
163
- return;
164
- piCoreProbePending = true;
165
- let proc;
159
+ /** Locate the pi CLI on PATH without spawning anything. */
160
+ function piCliOnPath() {
161
+ const dirs = (process.env.PATH ?? "").split(delimiter);
162
+ for (const dir of dirs) {
163
+ if (!dir)
164
+ continue;
165
+ const candidate = join(dir, "pi");
166
+ if (existsSync(candidate))
167
+ return candidate;
168
+ }
169
+ return null;
170
+ }
171
+ /**
172
+ * Read the pi core version from disk: resolve the `pi` bin (typically a
173
+ * symlink into <global>/node_modules/<pkg>/dist/bundle/cli.js) and walk up to
174
+ * its package.json. FORK-FREE by design — see the note on defaultProbePiCore.
175
+ */
176
+ function readPiCoreVersionFromDisk() {
177
+ const bin = piCliOnPath();
178
+ if (!bin)
179
+ return null;
166
180
  try {
167
- proc = spawn("pi", ["--version"], {
168
- stdio: ["ignore", "pipe", "pipe"],
169
- // Windows: `pi` resolves to a pi.cmd shim — spawn can only
170
- // exec those through a shell (else ENOENT).
171
- shell: process.platform === "win32",
172
- });
181
+ let dir = dirname(realpathSync(bin));
182
+ for (let i = 0; i < 8; i++) {
183
+ const pkgPath = join(dir, "package.json");
184
+ if (existsSync(pkgPath)) {
185
+ try {
186
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
187
+ if (pkg.name === PI_CORE_PACKAGE && pkg.version)
188
+ return pkg.version;
189
+ }
190
+ catch {
191
+ /* unreadable package.json — keep walking */
192
+ }
193
+ }
194
+ const parent = dirname(dir);
195
+ if (parent === dir)
196
+ break;
197
+ dir = parent;
198
+ }
173
199
  }
174
200
  catch {
175
- piCoreProbe = { at: Date.now(), version: null };
176
- piCoreProbePending = false;
177
- return;
201
+ /* ignore */
178
202
  }
179
- let out = "";
180
- const finish = (version) => {
181
- piCoreProbe = { at: Date.now(), version };
182
- piCoreProbePending = false;
183
- };
184
- const timer = setTimeout(() => {
185
- try {
186
- proc.kill();
187
- }
188
- catch {
189
- /* already exited */
190
- }
191
- finish(null);
192
- }, 5000);
193
- proc.stdout?.on("data", (d) => (out += d.toString()));
194
- proc.on("error", () => {
195
- clearTimeout(timer);
196
- finish(null);
197
- });
198
- proc.on("close", (code) => {
199
- clearTimeout(timer);
200
- finish(code === 0 ? parsePiVersionOutput(out) : null);
201
- });
203
+ return null;
202
204
  }
203
205
  /**
204
206
  * Default pi core probe: run the globally installed `pi --version`, memoized
205
207
  * machine-wide for PI_PROBE_TTL_MS so repeated collectTargets calls never
206
- * re-probe. Serves the last known value and refreshes ASYNCHRONOUSLY in the
207
- * background never blocks the event loop. (It previously used spawnSync
208
- * here, which can deadlock the whole server on Android/Termux: fork() in a
209
- * multi-threaded process occasionally leaves the forked child stuck between
210
- * fork and exec while the main thread sits in spawnSync's pipe_read. Mirrors
211
- * ClientSession.isPiCliInstalled(); Windows resolves `pi` to a pi.cmd shim
212
- * that only execs through a shell.)
208
+ * re-probe. Reads the version from disk (pi bin realpath → package.json)
209
+ * instead of spawning `pi --version`. FORK-FREE by design see the note on
210
+ * defaultProbePiCore.
213
211
  */
214
212
  export function defaultProbePiCore() {
215
213
  const now = Date.now();
216
214
  const cached = piCoreProbe;
217
215
  if (cached && now - cached.at < PI_PROBE_TTL_MS)
218
216
  return cached.version;
219
- refreshPiCoreProbe();
220
- return cached?.version ?? null;
217
+ const version = readPiCoreVersionFromDisk();
218
+ piCoreProbe = { at: now, version };
219
+ return version;
221
220
  }
222
221
  /**
223
222
  * Fallback when the CLI probe yields nothing: the version of the vendored pi
@@ -35,15 +35,15 @@ export function findVisionModels(runtime) {
35
35
  * Exported so the settings panel can offer a custom prompt (append to this
36
36
  * default or replace it entirely).
37
37
  */
38
- export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
-
40
- Follow these rules:
41
- 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
- 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
- 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
- 4. Name entities: people, products, companies, colors, style, objects, actions.
45
- 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
- 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
38
+ export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
+
40
+ Follow these rules:
41
+ 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
+ 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
+ 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
+ 4. Name entities: people, products, companies, colors, style, objects, actions.
45
+ 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
+ 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
47
47
  7. Output only the transcript. No preamble, no commentary about the image itself.`;
48
48
  /**
49
49
  * Assemble the final vision-model system prompt from the settings-panel prefs.