pi-web-ui 0.100.0 → 0.102.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 (82) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/README.md +46 -44
  3. package/README.zh-CN.md +41 -39
  4. package/bin/pi-web-ui.mjs +17 -19
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9884 -12815
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +41 -167
  10. package/dist/server/ask-user-question-tool.js +104 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/bash-tool.js +83 -0
  13. package/dist/server/browser-page-tool.js +207 -0
  14. package/dist/server/client-id-utils.js +51 -0
  15. package/dist/server/client-state.js +38 -2
  16. package/dist/server/compaction-markers.js +34 -1
  17. package/dist/server/context-budget-runner.js +43 -0
  18. package/dist/server/dangling-tools.js +18 -5
  19. package/dist/server/delegate-mode.js +1 -0
  20. package/dist/server/dispatch-domain-handlers.js +631 -0
  21. package/dist/server/dispatch-plugin-handlers.js +300 -0
  22. package/dist/server/dsh/dsh-agent-service.js +30 -5
  23. package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
  24. package/dist/server/goal-evidence.js +9 -2
  25. package/dist/server/goal-service.js +1 -1
  26. package/dist/server/hashline-engine.js +1 -1
  27. package/dist/server/index.js +191 -969
  28. package/dist/server/left-panel-running.js +115 -0
  29. package/dist/server/lsp-tool.js +40 -12
  30. package/dist/server/markers-list-tool.js +34 -0
  31. package/dist/server/market-service.js +277 -0
  32. package/dist/server/mcp-bridge.js +137 -30
  33. package/dist/server/mcp-hot-reload.js +84 -27
  34. package/dist/server/mcp-manager.js +215 -0
  35. package/dist/server/message-entry-resolver.js +32 -0
  36. package/dist/server/orphan-manager.js +44 -0
  37. package/dist/server/persona-chain.js +63 -0
  38. package/dist/server/plan-mode.js +2 -0
  39. package/dist/server/plan-update-tool.js +96 -0
  40. package/dist/server/plugin-api-catalog.js +20 -0
  41. package/dist/server/plugin-facilities.js +13 -3
  42. package/dist/server/plugin-installer.js +6 -1
  43. package/dist/server/plugin-ui-slots.js +39 -0
  44. package/dist/server/plugins.js +72 -38
  45. package/dist/server/preset-fields.js +35 -0
  46. package/dist/server/preset-share.js +9 -0
  47. package/dist/server/process-utils.js +30 -0
  48. package/dist/server/prompt-assembler.js +80 -0
  49. package/dist/server/protocol-version.js +1 -1
  50. package/dist/server/scm-commitmsg.js +74 -0
  51. package/dist/server/serialize.js +97 -7
  52. package/dist/server/session-branch.js +367 -0
  53. package/dist/server/session-parser.js +235 -0
  54. package/dist/server/session-search.js +158 -0
  55. package/dist/server/settings-service.js +28 -1
  56. package/dist/server/skill-content-filler.js +33 -0
  57. package/dist/server/subagent-handoff.js +18 -0
  58. package/dist/server/subagent-helpers.js +88 -0
  59. package/dist/server/terminals.js +155 -58
  60. package/dist/server/tool-guards.js +527 -0
  61. package/dist/server/tool-host-factories.js +217 -0
  62. package/dist/server/tool-manager.js +30 -5
  63. package/dist/server/wait-subscription-scan.js +46 -1
  64. package/dist/server/workspace-snapshot.js +18 -0
  65. package/extensions/webui.ts +90 -24
  66. package/package.json +1 -1
  67. package/plugin-sdk/README.md +17 -0
  68. package/plugin-sdk/index.d.ts +17 -0
  69. package/plugin-sdk/index.mjs +5 -0
  70. package/plugins/catalog.json +20 -0
  71. package/themes/aetheris.css +3 -1
  72. package/themes/translucent.css +8 -1
  73. package/themes/transparent.css +9 -1
  74. package/themes/zhupi-dark.css +3 -14
  75. package/themes/zhupi.css +2 -16
  76. package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
  77. package/web/dist/assets/index-CP71PHb6.js +680 -0
  78. package/web/dist/assets/index-ytRwL6j0.css +1 -0
  79. package/web/dist/index.html +2 -2
  80. package/web/dist/sw.js +1 -1
  81. package/web/dist/assets/index-B-E2EM_0.css +0 -1
  82. package/web/dist/assets/index-BYumAaGi.js +0 -379
@@ -0,0 +1,207 @@
1
+ /**
2
+ * 浏览器页面工具(标准 pi 引擎的 browser_page customTool)
3
+ *
4
+ * 模型调 browser_page → 服务端发 page_request 给浏览器 → 前端转 page-picker
5
+ * 扩展 → 扩展操作目标页面 → 前端回 page_response → 工具结果回到模型。
6
+ *
7
+ * op 的语义(read/click/type/…)属于**扩展侧**,服务端只透传,不解读也不校验
8
+ * ——所以参数说明写在 tool description 里让模型知道怎么用,不在这里分支处理。
9
+ *
10
+ * 从 agent-service.ts 抽出为独立模块。
11
+ */
12
+ import { Type } from "typebox";
13
+ import { BROWSER_PAGE_TOOL_NAME } from "./tool-manager.js";
14
+ /** timeoutMs 默认值。对面是扩展不是人,超时必须自己兜住。 */
15
+ const PAGE_CALL_DEFAULT_TIMEOUT_MS = 30_000;
16
+ /** 夹取区间:太小会误杀慢页面(拿不到结果还白跑一趟),太大就把模型拖到
17
+ * 工具看门狗(20 分钟)附近了。 */
18
+ const PAGE_CALL_MIN_TIMEOUT_MS = 1_000;
19
+ const PAGE_CALL_MAX_TIMEOUT_MS = 120_000;
20
+ /** timeoutMs 归一:非有限数字/缺省 → 默认;其余夹在 [1000, 120000]。
21
+ * 工具入口与页桥(pageCall)共用,防手写脏值绕过 schema。 */
22
+ export function normalizePageCallTimeoutMs(v) {
23
+ const n = typeof v === "number" && Number.isFinite(v) ? Math.floor(v) : PAGE_CALL_DEFAULT_TIMEOUT_MS;
24
+ return Math.min(PAGE_CALL_MAX_TIMEOUT_MS, Math.max(PAGE_CALL_MIN_TIMEOUT_MS, n));
25
+ }
26
+ /** 除 op/target/timeoutMs 外的扁平参数名(保持扩展侧原名:what/selector/…)。
27
+ * 列表即 schema 里的可选字段——改 schema 忘改这里,单测会炸(见
28
+ * tests/unit/browser-page-tool.test.ts)。 */
29
+ const BROWSER_PAGE_ARG_KEYS = ["what", "selector", "text", "url", "code", "all", "index", "maxEdge"];
30
+ /** 只收模型**确实传了**的参数:undefined 不入包,否则扩展拿到一堆
31
+ * `"selector": undefined` 会覆盖自己的默认值。 */
32
+ export function collectBrowserPageArgs(params) {
33
+ const args = {};
34
+ for (const k of BROWSER_PAGE_ARG_KEYS) {
35
+ if (params[k] !== undefined)
36
+ args[k] = params[k];
37
+ }
38
+ return args;
39
+ }
40
+ /** 页面调用结果 → 给模型的文本:字符串原样(read 的正文就是这样,别再加引号),
41
+ * 其余 JSON 缩进;空结果给一句说明,免得模型以为工具没输出。 */
42
+ export function formatPageCallResult(result) {
43
+ if (typeof result === "string")
44
+ return result.length > 0 ? result : "(empty)";
45
+ if (result === undefined || result === null)
46
+ return "(no result)";
47
+ try {
48
+ return JSON.stringify(result, null, 2) ?? String(result);
49
+ }
50
+ catch {
51
+ // 循环引用/含大整数等不可序列化结果:别让格式化把工具调用炸掉。
52
+ return String(result);
53
+ }
54
+ }
55
+ /** 失败文本:带上 op 与原因,再补一句**可执行的**下一步(模型只有知道该让
56
+ * 用户干什么,才不会再盲目重试同一个调用)。 */
57
+ export function formatBrowserPageError(op, error) {
58
+ return [
59
+ `browser_page "${op}" failed: ${error}`,
60
+ `browser_page "${op}" 失败:${error}`,
61
+ 'Next: make sure a pi-web-ui page is open with the page-picker extension enabled and paired, then try op:"pages" to see which pages are available. If the target page is not allowed yet, ask the user to allow it in the extension.',
62
+ '下一步:确认 pi-web-ui 页面已打开、page-picker 扩展已启用并与该页面配对,再用 op:"pages" 看有哪些可操作页面;若目标页面尚未授权,请让用户先在扩展里授权。',
63
+ ].join("\n");
64
+ }
65
+ /**
66
+ * 标准 pi 引擎的 browser_page 工具:模型调用时把请求桥到用户浏览器里的
67
+ * pi-web-ui 页面(page_request/page_response 协议),由 page-picker 扩展真正
68
+ * 操作用户授权的页面。
69
+ *
70
+ * 与 ask_user_question 同样以 customTool 注册(标准 SDK 没有这个工具;DSH 引擎
71
+ * 走自己的运行时,也不经此)。写法严格比照 makeAskUserQuestionTool。
72
+ *
73
+ * pageCall 签名同样带 {aborted} 快照而非完整 AbortSignal(customTool 的 execute
74
+ * 信号服务于整个 agent 生命周期,这里只要「已中止即失败」的最小语义)。
75
+ */
76
+ export function makeBrowserPageTool(clientSession,
77
+ /** 本 runtime 所属会话(语义与 ask_user_question 的 ownerId 一致)。 */
78
+ ownerId) {
79
+ return {
80
+ name: BROWSER_PAGE_TOOL_NAME,
81
+ label: "Browser page",
82
+ description: [
83
+ "Read or act on a page in the USER'S OWN browser via the pi-web-ui page-picker extension (the server only forwards).",
84
+ "Only the parameters below exist — an op option that is not a field here (e.g. type's submit) is unavailable.",
85
+ "ops: pages | read (what? selector? all?) | click (selector? index?) | type (selector text) | scroll (selector?) | goto (url) | wait (selector? text? timeoutMs?) | eval (code) | shot (maxEdge?)",
86
+ ].join("\n"),
87
+ promptSnippet: "operate a page in the user's browser (page-picker extension)",
88
+ promptGuidelines: [
89
+ "Only use browser_page when the user asked you to read or act on a page in their browser; " +
90
+ "never click or type on their pages on your own initiative",
91
+ 'Start with op:"pages"; the target page must already be allowed in the page-picker extension — ' +
92
+ "if it fails, tell the user what to enable instead of retrying.",
93
+ ],
94
+ parameters: Type.Object({
95
+ op: Type.String({
96
+ description: "Action to perform (extension-side).",
97
+ }),
98
+ target: Type.Optional(Type.String({
99
+ description: "Target page origin (e.g. https://example.com). Only needed when several pages are allowed.",
100
+ })),
101
+ what: Type.Optional(Type.String({ description: 'For op:read — "text" | "html" | "title" | "url" | "query" (default: text).' })),
102
+ selector: Type.Optional(Type.String({ description: "CSS selector, for op:read / click / type / scroll / wait." })),
103
+ text: Type.Optional(Type.String({ description: "For op:type — the text to enter; for op:wait — the text to wait for." })),
104
+ url: Type.Optional(Type.String({ description: "For op:goto — the absolute URL to navigate to." })),
105
+ code: Type.Optional(Type.String({
106
+ description: "For op:eval — JS to run in the page (extension-side switch, disabled by default).",
107
+ })),
108
+ all: Type.Optional(Type.Boolean({ description: "For op:read — return every match instead of only the first one." })),
109
+ index: Type.Optional(Type.Number({ description: "For op:click — which match to click (default: 0)." })),
110
+ maxEdge: Type.Optional(Type.Number({
111
+ description: "For op:shot — max px of the longer side (320-1568, default 1280).",
112
+ })),
113
+ timeoutMs: Type.Optional(Type.Number({
114
+ description: "How long the server waits for the browser (1000-120000 ms, default 30000).",
115
+ })),
116
+ }),
117
+ execute: async (_id, params, signal) => {
118
+ const p = (params ?? {});
119
+ const op = typeof p.op === "string" ? p.op.trim() : "";
120
+ if (!op) {
121
+ throw new Error('browser_page requires a non-empty `op` (e.g. "pages", "read", "click").\nbrowser_page 需要非空的 op(如 pages/read/click)。');
122
+ }
123
+ const resolved = await clientSession.pageCall({
124
+ op,
125
+ args: collectBrowserPageArgs(p),
126
+ target: typeof p.target === "string" && p.target.length > 0 ? p.target : undefined,
127
+ timeoutMs: normalizePageCallTimeoutMs(p.timeoutMs),
128
+ }, {
129
+ aborted: signal?.aborted,
130
+ }, ownerId);
131
+ if (!resolved.ok) {
132
+ // 抛 Error 而不是回一段失败文本:模型需要看到「工具失败」才会改策略。
133
+ throw new Error(formatBrowserPageError(op, resolved.error));
134
+ }
135
+ const shot = extractShotImage(resolved.result);
136
+ if (!shot) {
137
+ // 工具结果:read 的正文原样给模型,结构化结果 JSON 缩进;details 留 UI/轨迹。
138
+ return {
139
+ content: [{ type: "text", text: formatPageCallResult(resolved.result) }],
140
+ details: { op, args: collectBrowserPageArgs(p), target: p.target, result: resolved.result },
141
+ };
142
+ }
143
+ // 截图:**主模型能看图就直接把图给回去**(当轮就能看到,不用等下一轮);
144
+ // 看不到图(纯文本模型)就交给视觉桥转写成文字证据 —— 与用户粘贴图片走同一套
145
+ // 选择逻辑与提示词,设置里开着就自动生效,模型侧不需要任何额外配置。
146
+ const where = `${p.target ?? "the page"}${shot.selector ? ` (element ${shot.selector})` : ""}`;
147
+ const caption = [
148
+ `Screenshot of ${where} — ${shot.width ?? "?"}×${shot.height ?? "?"} px.`,
149
+ `页面截图:${where} — ${shot.width ?? "?"}×${shot.height ?? "?"} px。`,
150
+ ].join("\n");
151
+ const details = {
152
+ op,
153
+ args: collectBrowserPageArgs(p),
154
+ target: p.target,
155
+ result: { ...resolved.result, image: "[image]" },
156
+ };
157
+ if (clientSession.canSeeImages?.() === true) {
158
+ return {
159
+ content: [
160
+ { type: "text", text: caption },
161
+ { type: "image", data: shot.data, mimeType: shot.mimeType },
162
+ ],
163
+ details,
164
+ };
165
+ }
166
+ const bridged = await clientSession.transcribeToolImage?.(shot, signal);
167
+ const note = bridged?.text
168
+ ? `\n\n<vision-bridge>\n${bridged.text}\n</vision-bridge>`
169
+ : [
170
+ `\n\n(当前模型看不到图片:${bridged?.reason ?? "视觉桥不可用"} —— 可让用户改用支持识图的模型,或在模型配置里加一个支持图片的模型)`,
171
+ `(The current model cannot see images: ${bridged?.reason ?? "vision bridge unavailable"})`,
172
+ ].join("\n");
173
+ return {
174
+ content: [{ type: "text", text: caption + note }],
175
+ details,
176
+ };
177
+ },
178
+ };
179
+ }
180
+ /**
181
+ * 从扩展的截图结果里取出图片。
182
+ *
183
+ * 扩展回的是 `{ image: { dataUrl, mimeType, width, height }, selector?, rect?, viewport? }`;
184
+ * dataUrl 带 `data:image/jpeg;base64,` 前缀,而模型 API 要的是**纯 base64** —— 剥前缀这一步
185
+ * 很容易忘(忘了就是「图片解析失败」)。
186
+ */
187
+ export function extractShotImage(result) {
188
+ if (!result || typeof result !== "object")
189
+ return undefined;
190
+ const image = result.image;
191
+ if (!image || typeof image !== "object")
192
+ return undefined;
193
+ const src = image;
194
+ if (typeof src.dataUrl !== "string")
195
+ return undefined;
196
+ const match = /^data:([^;,]+);base64,(.+)$/s.exec(src.dataUrl);
197
+ if (!match)
198
+ return undefined;
199
+ const selector = result.selector;
200
+ return {
201
+ data: match[2],
202
+ mimeType: typeof src.mimeType === "string" && src.mimeType ? src.mimeType : match[1],
203
+ ...(typeof src.width === "number" ? { width: src.width } : {}),
204
+ ...(typeof src.height === "number" ? { height: src.height } : {}),
205
+ ...(typeof selector === "string" && selector ? { selector } : {}),
206
+ };
207
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * client-id-utils — 伪客户端 ID 判断与插件调用工作区校验。
3
+ *
4
+ * 负责:
5
+ * - isPseudoClientId: 判断是否为插件或定时任务的无头伪客户端(sink 常驻)
6
+ * - checkPluginCwd: 校验插件指定的工作目录合法性(防止 Windows SystemRoot 误操作)
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ import { statSync } from "node:fs";
11
+ import { resolve, sep } from "node:path";
12
+ /** issue #226:插件无头调用的工作目录校验(纯函数,可单测)。
13
+ * 存在性语义与定时任务一致(须存在且为目录,不默默跑错目录);另在
14
+ * Windows 下拒绝 SystemRoot 及其子树(如 C:\Windows\System32)——后台服务/
15
+ * 快捷方式启动时宿主 cwd 常飘到 system32,直接跑就是高危误操作。 */
16
+ export function checkPluginCwd(cwd) {
17
+ const trimmed = String(cwd ?? "").trim();
18
+ if (!trimmed)
19
+ return { ok: false, error: "工作目录为空" };
20
+ let abs;
21
+ try {
22
+ abs =
23
+ process.platform === "win32" && /^[A-Za-z]:$/.test(trimmed) ? `${trimmed.toUpperCase()}${sep}` : resolve(trimmed);
24
+ }
25
+ catch {
26
+ return { ok: false, error: `工作目录非法:${trimmed}` };
27
+ }
28
+ try {
29
+ if (!statSync(abs).isDirectory())
30
+ throw new Error("not-a-dir");
31
+ }
32
+ catch {
33
+ return { ok: false, error: `目标项目不存在或不是目录:${trimmed}` };
34
+ }
35
+ if (process.platform === "win32") {
36
+ const sysRoot = (process.env.SystemRoot || process.env.windir || "C:\\Windows")
37
+ .replace(/\//g, "\\")
38
+ .replace(/\\+$/, "");
39
+ const norm = abs.replace(/\//g, "\\").replace(/\\+$/, "");
40
+ const low = norm.toLowerCase();
41
+ const rootLow = sysRoot.toLowerCase();
42
+ if (low === rootLow || low.startsWith(`${rootLow}\\`)) {
43
+ return { ok: false, error: `拒绝在系统目录执行:${abs}(请在插件设置里指定项目工作目录)` };
44
+ }
45
+ }
46
+ return { ok: true, abs };
47
+ }
48
+ /** 插件/调度伪客户端:sink 常驻(fire-and-forget 的空函数),不能按浏览器存活判断。 */
49
+ export function isPseudoClientId(id) {
50
+ return id.startsWith("plugin:") || id.startsWith("scheduler:");
51
+ }
@@ -12,8 +12,8 @@ import { dirname, isAbsolute, resolve } from "node:path";
12
12
  import { writeJsonAtomicSync } from "./atomic-file.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
15
- import { UI_SLOTS } from "./plugins.js";
16
15
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
16
+ import { UI_SLOTS } from "./plugin-ui-slots.js";
17
17
  /** 大模型 API 出错自动重试次数的默认值(SDK 默认 3)。 */
18
18
  export const DEFAULT_RETRY_MAX_ATTEMPTS = 6;
19
19
  /** 工具执行看门狗超时的默认值(默认 20 分钟;环境变量 PI_WEB_TOOL_TIMEOUT_MS 覆盖)。 */
@@ -21,6 +21,25 @@ export const DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS = (() => {
21
21
  const v = Number(process.env.PI_WEB_TOOL_TIMEOUT_MS);
22
22
  return Number.isFinite(v) && v >= 0 ? v : 20 * 60_000;
23
23
  })();
24
+ /** 消息列表尾部「常驻渲染」消息条数的默认值:更早的消息折叠为摘要行
25
+ * (见 web/src/components/MessageList.tsx 的 recentStart)。默认与原硬编码
26
+ * KEEP_RECENT 一致(15),想要更大窗口在设置面板「常驻渲染消息数」里开。纯 UI 偏好。 */
27
+ export const DEFAULT_KEEP_RECENT_MESSAGES = 15;
28
+ export const KEEP_RECENT_MESSAGES_MIN = 5;
29
+ export const KEEP_RECENT_MESSAGES_MAX = 100;
30
+ /** 归一化常驻渲染消息数:缺省/非数值回落默认值;有效整数钳到 [5, 100]。 */
31
+ export function normalizeKeepRecentMessages(v) {
32
+ if (v === null || v === undefined || v === "")
33
+ return DEFAULT_KEEP_RECENT_MESSAGES;
34
+ const n = Math.floor(Number(v));
35
+ if (!Number.isFinite(n))
36
+ return DEFAULT_KEEP_RECENT_MESSAGES;
37
+ if (n < KEEP_RECENT_MESSAGES_MIN)
38
+ return KEEP_RECENT_MESSAGES_MIN;
39
+ if (n > KEEP_RECENT_MESSAGES_MAX)
40
+ return KEEP_RECENT_MESSAGES_MAX;
41
+ return n;
42
+ }
24
43
  /** 归一化工具看门狗超时(毫秒):0 = 禁用;非数值、负数或空值回落默认值,非负整数保留。 */
25
44
  export function normalizeToolWatchdogTimeoutMs(v) {
26
45
  if (v === null || v === undefined || v === "")
@@ -237,6 +256,17 @@ export const DEFAULT_TOOL_LAZY_LOADING = (() => {
237
256
  const v = (process.env.PI_WEB_TOOL_LAZY_LOADING ?? "").trim().toLowerCase();
238
257
  return !(v === "0" || v === "false" || v === "off" || v === "no");
239
258
  })();
259
+ export const DEFAULT_CODEMODE_MODE = "on";
260
+ export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
261
+ export function normalizeCodemodeMode(v) {
262
+ return v === "only" ? "only" : "on";
263
+ }
264
+ export function normalizeCodemodeInlineBudget(v) {
265
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) {
266
+ return Math.floor(v);
267
+ }
268
+ return DEFAULT_CODEMODE_INLINE_BUDGET;
269
+ }
240
270
  /** 预设 → 设置面板列表用的 UI 形状(协议要求字段完整:旧/部分预设用默认值补齐)。 */
241
271
  export function settingsPresetToUi(p) {
242
272
  return {
@@ -244,7 +274,7 @@ export function settingsPresetToUi(p) {
244
274
  promptMode: p.promptMode === "replace" ? "replace" : "append",
245
275
  customSystemPrompt: p.customSystemPrompt ?? "",
246
276
  promptTemplate: p.promptTemplate ?? "",
247
- promptOverrides: { ...(p.promptOverrides ?? {}) },
277
+ promptOverrides: { ...p.promptOverrides },
248
278
  disabledSkills: [...(p.disabledSkills ?? [])],
249
279
  disabledExtensions: [...(p.disabledExtensions ?? [])],
250
280
  reviewPrompt: p.reviewPrompt ?? "",
@@ -772,6 +802,8 @@ export class ClientStateStore {
772
802
  readDirEnabled: stored?.readDirEnabled ?? true,
773
803
  bgAutoCleanupMin: normalizeBgCleanupMinutes(stored?.bgAutoCleanupMin),
774
804
  toolLazyLoading: stored?.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
805
+ codemodeMode: normalizeCodemodeMode(stored?.codemodeMode),
806
+ codemodeInlineBudget: normalizeCodemodeInlineBudget(stored?.codemodeInlineBudget),
775
807
  toolApprovalEnabled: stored?.toolApprovalEnabled ?? true,
776
808
  editSoftEnabled: stored?.disabledAgentTools !== undefined
777
809
  ? deriveLegacy(legacyToDisabled(stored)).editSoftEnabled
@@ -786,6 +818,7 @@ export class ClientStateStore {
786
818
  autoReload: stored?.autoReload,
787
819
  toolsWrap: stored?.toolsWrap ?? true,
788
820
  toolImagesEnabled: stored?.toolImagesEnabled ?? true,
821
+ keepRecentMessages: normalizeKeepRecentMessages(stored?.keepRecentMessages),
789
822
  skillsFullText: normalizeSkillList(stored?.skillsFullText),
790
823
  visionBridgeEnabled: stored?.visionBridgeEnabled ?? true,
791
824
  visionBridgeModel: stored?.visionBridgeModel ?? null,
@@ -836,6 +869,8 @@ export class ClientStateStore {
836
869
  readDirEnabled: settings.readDirEnabled ?? cur.readDirEnabled ?? true,
837
870
  bgAutoCleanupMin: normalizeBgCleanupMinutes(settings.bgAutoCleanupMin ?? cur.bgAutoCleanupMin),
838
871
  toolLazyLoading: settings.toolLazyLoading ?? cur.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
872
+ codemodeMode: normalizeCodemodeMode(settings.codemodeMode ?? cur.codemodeMode ?? DEFAULT_CODEMODE_MODE),
873
+ codemodeInlineBudget: normalizeCodemodeInlineBudget(settings.codemodeInlineBudget ?? cur.codemodeInlineBudget ?? DEFAULT_CODEMODE_INLINE_BUDGET),
839
874
  toolApprovalEnabled: settings.toolApprovalEnabled ?? cur.toolApprovalEnabled ?? true,
840
875
  editSoftEnabled: settings.editSoftEnabled ?? cur.editSoftEnabled ?? false,
841
876
  questionnaireEnabled: settings.questionnaireEnabled ?? cur.questionnaireEnabled ?? true,
@@ -846,6 +881,7 @@ export class ClientStateStore {
846
881
  autoReload: settings.autoReload ?? cur.autoReload,
847
882
  toolsWrap: settings.toolsWrap ?? cur.toolsWrap ?? true,
848
883
  toolImagesEnabled: settings.toolImagesEnabled ?? cur.toolImagesEnabled ?? true,
884
+ keepRecentMessages: normalizeKeepRecentMessages(settings.keepRecentMessages ?? cur.keepRecentMessages ?? DEFAULT_KEEP_RECENT_MESSAGES),
849
885
  skillsFullText: normalizeSkillList(settings.skillsFullText ?? cur.skillsFullText),
850
886
  visionBridgeEnabled: settings.visionBridgeEnabled ?? cur.visionBridgeEnabled ?? true,
851
887
  // 按键存在性合并:null 是合法值(清除语义),`null ?? cur` 会把旧值
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import { randomUUID } from "node:crypto";
21
21
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
22
+ import { reorderEntriesForMainBranch } from "./session-branch.js";
22
23
  export const COMPACTION_PENDING_TYPE = "pi-web-ui/compaction-pending";
23
24
  export const COMPACTION_DONE_TYPE = "pi-web-ui/compaction-done";
24
25
  /** 0.90.x 写死的 id——repair 用来识别存量坏标记。 */
@@ -240,7 +241,39 @@ export function repairSessionTranscript(raw) {
240
241
  }
241
242
  }
242
243
  }
243
- const anyChange = result.removedPending > 0 || result.renamedIds > 0 || result.rewiredParents > 0 || result.cyclesBroken > 0;
244
+ // 第 4 步:分支拓扑归置(issue #567)。
245
+ // 当物理文件尾部是由于旧节点上追加的 custom/metadata 导致的侧枝(导致主对话分支
246
+ // 被 SDK 的 SessionManager 读成旧历史)时,按拓扑顺序重排,确保包含完整对话的
247
+ // 主分支叶子位于物理文件的末行,同时保留全部 custom 条目及其 parentId。
248
+ const liveEntries = slots.filter((s) => !s.removed && s.entry !== null).map((s) => s.entry);
249
+ if (liveEntries.length > 1) {
250
+ const reorderResult = reorderEntriesForMainBranch(liveEntries);
251
+ if (reorderResult.changed) {
252
+ result.reorderedBranches = true;
253
+ result.reorderedReason = reorderResult.reason;
254
+ const slotByEntry = new Map();
255
+ for (const s of slots) {
256
+ if (!s.removed && s.entry)
257
+ slotByEntry.set(s.entry, s);
258
+ }
259
+ const reorderedSlots = [];
260
+ for (const e of reorderResult.entries) {
261
+ const s = slotByEntry.get(e);
262
+ if (s) {
263
+ s.dirty = true;
264
+ reorderedSlots.push(s);
265
+ }
266
+ }
267
+ const prefixSlots = slots.filter((s) => !s.removed && s.entry === null);
268
+ slots.length = 0;
269
+ slots.push(...prefixSlots, ...reorderedSlots);
270
+ }
271
+ }
272
+ const anyChange = result.removedPending > 0 ||
273
+ result.renamedIds > 0 ||
274
+ result.rewiredParents > 0 ||
275
+ result.cyclesBroken > 0 ||
276
+ Boolean(result.reorderedBranches);
244
277
  if (!anyChange)
245
278
  return result;
246
279
  result.changed = true;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * context-budget-runner — 多级分层上下文预算裁剪执行器。
3
+ *
4
+ * 当上下文达到预警水位(例如 70%)时,自动执行第一级(远期工具输出裁剪)和
5
+ * 第二级(已完成步骤折叠),推迟触发全量 LLM 压缩,保留近期关键代码的细节。
6
+ *
7
+ * 从 agent-service.ts 抽出为独立模块。
8
+ */
9
+ import { contextWindowOf, modelKeyOf } from "./agent-formatters.js";
10
+ import { effectiveSoftCap, softCapToReserve, DEFAULT_COMPACTION_RESERVE_TOKENS } from "./soft-cap.js";
11
+ import { pruneContextHierarchically } from "./context-budget.js";
12
+ /**
13
+ * 对指定对话执行分层上下文预算裁剪评估与就地修剪。
14
+ */
15
+ export function executeContextBudgetPruning(conv, settings) {
16
+ if (!conv?.session)
17
+ return { pruned: false, tokensSaved: 0 };
18
+ try {
19
+ const contextWindow = contextWindowOf(conv.session);
20
+ if (!contextWindow || contextWindow <= 0)
21
+ return { pruned: false, tokensSaved: 0 };
22
+ const modelId = modelKeyOf(conv.session);
23
+ const cap = effectiveSoftCap(settings.softCapTokens ?? 0, settings.softCapByModel, modelId);
24
+ const reserve = softCapToReserve(contextWindow, cap) ?? DEFAULT_COMPACTION_RESERVE_TOKENS;
25
+ const messages = conv.session.agent.state.messages;
26
+ if (!messages || messages.length === 0)
27
+ return { pruned: false, tokensSaved: 0 };
28
+ const result = pruneContextHierarchically(messages, {
29
+ contextWindow,
30
+ reserveTokens: reserve,
31
+ softCap: cap > 0 ? cap : null,
32
+ });
33
+ if (result.tier1.trimmedCount > 0 || result.tier2.foldedCount > 0) {
34
+ conv.session.agent.state.messages = result.messages;
35
+ const tokensSaved = result.tokensBefore - result.tokensAfter;
36
+ return { pruned: true, tokensSaved };
37
+ }
38
+ return { pruned: false, tokensSaved: 0 };
39
+ }
40
+ catch {
41
+ return { pruned: false, tokensSaved: 0 };
42
+ }
43
+ }
@@ -21,12 +21,25 @@
21
21
  * - findDanglingToolCalls:纯函数,消息/条目数组里找「有调用、无后继结果」的 toolCall;
22
22
  * - tailAssistantToolCallIds:沿当前分支回溯,定位尾部会上线的 assistant 的 toolCallId 集合;
23
23
  * - healDanglingToolCallFile:落盘版,仅针对当前分支尾部生效的悬空调用追加合成 toolResult;
24
- * - 合成结果文案:DANGLING_TOOL_RESULT_TEXT(中英各一,toolResult content 只带一条文本)。
24
+ * - 合成结果文案:danglingToolResultText(cause)(按成因归因,中英各一,toolResult content 只带一条文本)。
25
25
  */
26
26
  import { appendFileSync, existsSync, readFileSync } from "node:fs";
27
27
  import { randomUUID } from "node:crypto";
28
- export const DANGLING_TOOL_RESULT_TEXT = "(系统:上一次运行被强制终止(工具执行超时/模型流卡死),该工具调用没有返回结果。为避免对话记录损坏,已自动填入一条合成结果。请根据需要重新执行该工具或继续对话。)";
29
- export const DANGLING_TOOL_RESULT_TEXT_EN = "(System: the previous run was force-terminated (tool timeout / hung model stream) and this tool call never returned. A synthetic result was inserted automatically to keep the transcript valid. Re-run the tool or continue as needed.)";
28
+ const DANGLING_TEXT = {
29
+ generic: {
30
+ zh: "(系统:上一次运行未正常结束(可能是工具执行超时、模型流卡死或服务中断),该工具调用没有返回结果。为避免对话记录损坏,已自动填入一条合成结果。该命令可能已部分或全部执行,若需重跑请先确认是否会产生重复副作用。)",
31
+ en: "(System: the previous run did not finish cleanly (possibly a tool timeout, a hung model stream, or a service interruption) and this tool call never returned. A synthetic result was inserted automatically to keep the transcript valid. The command may have partly or fully run; confirm before re-running anything with side effects.)",
32
+ },
33
+ restart: {
34
+ zh: "(系统:上一次运行因服务重启被中断,该工具调用没有返回结果——它可能已经执行过。为避免对话记录损坏,已自动填入一条合成结果。重跑前请先确认是否会产生重复副作用(如删除、部署、推送)。)",
35
+ en: "(System: the previous run was interrupted by a service restart and this tool call never returned — it may already have executed. A synthetic result was inserted automatically to keep the transcript valid. Confirm before re-running anything with side effects such as deletes, deploys or pushes.)",
36
+ },
37
+ };
38
+ /** 合成 toolResult 的文本(中英各一,content 只带一条文本)。 */
39
+ export function danglingToolResultText(cause = "generic") {
40
+ const t = DANGLING_TEXT[cause];
41
+ return `${t.zh}\n${t.en}`;
42
+ }
30
43
  function toolCallsOfMessage(msg) {
31
44
  if (typeof msg !== "object" || msg === null)
32
45
  return [];
@@ -164,7 +177,7 @@ export function tailAssistantToolCallIds(entries, lastId) {
164
177
  * parentId 链式接在当前尾行之后。append-only——历史字节不动,无需备份。
165
178
  * 返回追加条数(0 = 健康,无需处理;-1 = 文件不可读/不可写)。
166
179
  */
167
- export function healDanglingToolCallFile(filePath) {
180
+ export function healDanglingToolCallFile(filePath, cause = "generic") {
168
181
  let raw;
169
182
  try {
170
183
  raw = readFileSync(filePath, "utf8");
@@ -210,7 +223,7 @@ export function healDanglingToolCallFile(filePath) {
210
223
  role: "toolResult",
211
224
  toolCallId: d.toolCallId,
212
225
  toolName: d.toolName,
213
- content: [{ type: "text", text: `${DANGLING_TOOL_RESULT_TEXT}\n${DANGLING_TOOL_RESULT_TEXT_EN}` }],
226
+ content: [{ type: "text", text: danglingToolResultText(cause) }],
214
227
  isError: true,
215
228
  timestamp: Date.now(),
216
229
  },
@@ -49,6 +49,7 @@ const BLOCKED_TOOLS = new Set([
49
49
  "git",
50
50
  // 代码求值(eval 沙箱可写真实文件系统 —— 主对话只审阅不施工,#436)
51
51
  "eval",
52
+ "codemode",
52
53
  "format",
53
54
  "prettier",
54
55
  "lint_fix",