pi-web-ui 0.99.0 → 0.101.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  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 +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -14,15 +14,17 @@
14
14
  * MCP 服务器,照常应用。
15
15
  */
16
16
  import { readFileSync, watch } from "node:fs";
17
- import { join } from "node:path";
18
- import { mcpServerSnapshot, parseMcpConfig } from "./mcp-bridge.js";
17
+ import { dirname, join } from "node:path";
18
+ import { getGlobalMcpPath, getProjectMcpPath, mcpServerSnapshot, parseMcpConfig, } from "./mcp-bridge.js";
19
19
  /** 规范化指纹:只含影响行为的字段、服务器顺序无关 —— 「内容变了吗」的判据。 */
20
20
  function fingerprint(servers) {
21
21
  const names = Object.keys(servers).sort();
22
22
  return JSON.stringify(names.map((n) => [n, mcpServerSnapshot(servers[n])]));
23
23
  }
24
24
  export function createMcpHotReload(deps) {
25
- const file = join(deps.dataDir, "mcp.json");
25
+ const globalFile = getGlobalMcpPath(deps.agentDir, deps.dataDir);
26
+ const projectFile = deps.cwd ? getProjectMcpPath(deps.cwd) : undefined;
27
+ const legacyFile = join(deps.dataDir, "mcp.json");
26
28
  const log = deps.log ?? (() => { });
27
29
  const debounceMs = deps.debounceMs ?? 300;
28
30
  const pollIntervalMs = deps.pollIntervalMs ?? 2000;
@@ -30,22 +32,17 @@ export function createMcpHotReload(deps) {
30
32
  let applied = null;
31
33
  let debounce = null;
32
34
  let poller = null;
33
- let watcher = null;
34
- /** 读一次磁盘:指纹 + 清单(`servers` 为 null = 坏配置/读失败)。文件不在按「没有服务器」算。 */
35
- function readOnce() {
35
+ let watchers = [];
36
+ function readOneFile(file) {
36
37
  let raw;
37
38
  try {
38
39
  raw = readFileSync(file, "utf8");
39
40
  }
40
41
  catch (err) {
41
- // 不变量 3 只覆盖「文件不在」:删掉 mcp.json = 关掉全部 MCP 服务器。
42
- // #497:EBUSY/EACCES 等临时读失败(OneDrive/杀毒独占、权限误改)既不是
43
- // 坏配置也不是删除意图——按坏配置口径走(servers: null → 保留在跑的
44
- // 服务器 + 一次性提示),否则会把在跑的 MCP 服务器全杀还报「成功 0 个」。
45
42
  const code = err?.code;
46
43
  if (code === "ENOENT")
47
44
  return { fp: "empty", servers: {} };
48
- log(`[mcp] mcp.json 读取失败(${code ?? String(err)}),按坏配置处理:保留在跑的 MCP 服务器`);
45
+ log(`[mcp] ${file} 读取失败(${code ?? String(err)}),按坏配置处理:保留在跑的 MCP 服务器`);
49
46
  return { fp: `unreadable:${code ?? "unknown"}`, servers: null };
50
47
  }
51
48
  const parsed = parseMcpConfig(raw);
@@ -53,6 +50,48 @@ export function createMcpHotReload(deps) {
53
50
  return { fp: `invalid:${raw}`, servers: null };
54
51
  return { fp: `ok:${fingerprint(parsed.servers)}`, servers: parsed.servers };
55
52
  }
53
+ /** 读全部配置文件(全局 + 项目)并合并指纹 */
54
+ function readOnce() {
55
+ const g = readOneFile(globalFile);
56
+ let globalServers = g.servers;
57
+ let gFp = g.fp;
58
+ if (g.fp === "empty" && legacyFile !== globalFile) {
59
+ const leg = readOneFile(legacyFile);
60
+ if (leg.servers) {
61
+ globalServers = leg.servers;
62
+ gFp = leg.fp;
63
+ }
64
+ else if (leg.fp.startsWith("unreadable:") || leg.fp.startsWith("invalid:")) {
65
+ return leg;
66
+ }
67
+ }
68
+ else if (!g.servers && (g.fp.startsWith("unreadable:") || g.fp.startsWith("invalid:"))) {
69
+ return g;
70
+ }
71
+ let pFp = "none";
72
+ let projServers = {};
73
+ if (projectFile) {
74
+ const p = readOneFile(projectFile);
75
+ if (!p.servers && (p.fp.startsWith("unreadable:") || p.fp.startsWith("invalid:"))) {
76
+ return p;
77
+ }
78
+ projServers = p.servers;
79
+ pFp = p.fp;
80
+ }
81
+ const merged = { ...globalServers };
82
+ for (const [name, ps] of Object.entries(projServers || {})) {
83
+ if (!ps.command && !ps.url && ps.enabled !== undefined && merged[name]) {
84
+ merged[name] = { ...merged[name], enabled: ps.enabled };
85
+ }
86
+ else {
87
+ merged[name] = ps;
88
+ }
89
+ }
90
+ return {
91
+ fp: `g:${gFp}|p:${pFp}`,
92
+ servers: merged,
93
+ };
94
+ }
56
95
  async function apply() {
57
96
  const { fp, servers } = readOnce();
58
97
  if (fp === applied)
@@ -84,8 +123,13 @@ export function createMcpHotReload(deps) {
84
123
  }
85
124
  /** fs.watch 用不了(目录还不存在、网络盘、容器)→ 回落到轮询:单文件不值得上更重的机制。 */
86
125
  function fallBackToPolling() {
87
- watcher?.close();
88
- watcher = null;
126
+ for (const w of watchers) {
127
+ try {
128
+ w.close();
129
+ }
130
+ catch { }
131
+ }
132
+ watchers = [];
89
133
  if (poller)
90
134
  return;
91
135
  log(`[mcp] 目录监视不可用,mcp.json 热加载回落到 ${pollIntervalMs}ms 轮询`);
@@ -93,21 +137,29 @@ export function createMcpHotReload(deps) {
93
137
  poller.unref();
94
138
  }
95
139
  function start() {
96
- if (watcher || poller)
140
+ if (watchers.length > 0 || poller)
97
141
  return;
98
142
  // 播种:启动时 load() 已按同一份文件启动过服务器,别在第一个事件里白重载一次。
99
143
  applied = readOnce().fp;
100
- try {
101
- watcher = watch(deps.dataDir, { persistent: false }, (_event, filename) => {
102
- // 有些平台/编辑器(保存 = 临时文件 + rename)给不出文件名,拿不到就当命中。
103
- if (typeof filename === "string" && filename && filename !== "mcp.json")
104
- return;
105
- schedule();
106
- });
107
- watcher.on("error", () => fallBackToPolling());
108
- }
109
- catch {
110
- fallBackToPolling();
144
+ const dirsToWatch = new Set();
145
+ dirsToWatch.add(deps.dataDir);
146
+ if (globalFile)
147
+ dirsToWatch.add(dirname(globalFile));
148
+ if (projectFile)
149
+ dirsToWatch.add(dirname(projectFile));
150
+ for (const dir of dirsToWatch) {
151
+ try {
152
+ const w = watch(dir, { persistent: false }, (_event, filename) => {
153
+ if (typeof filename === "string" && filename && filename !== "mcp.json")
154
+ return;
155
+ schedule();
156
+ });
157
+ w.on("error", () => fallBackToPolling());
158
+ watchers.push(w);
159
+ }
160
+ catch {
161
+ fallBackToPolling();
162
+ }
111
163
  }
112
164
  }
113
165
  function dispose() {
@@ -117,8 +169,13 @@ export function createMcpHotReload(deps) {
117
169
  if (poller)
118
170
  clearInterval(poller);
119
171
  poller = null;
120
- watcher?.close();
121
- watcher = null;
172
+ for (const w of watchers) {
173
+ try {
174
+ w.close();
175
+ }
176
+ catch { }
177
+ }
178
+ watchers = [];
122
179
  }
123
180
  return { apply, start, dispose };
124
181
  }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * MCP 服务器管理服务
3
+ *
4
+ * 负责 Pi 全局 (~/.pi/agent/mcp.json 或兼容 ~/.pi-web/mcp.json)
5
+ * 与工作区项目级 (.pi/mcp.json) MCP 服务器配置的读写、合并与生命周期。
6
+ */
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { dirname } from "node:path";
9
+ import { getGlobalMcpPath, getProjectMcpPath, parseMcpConfig, } from "./mcp-bridge.js";
10
+ export { getGlobalMcpPath, getProjectMcpPath };
11
+ /** 读取指定文件的 MCP 服务器配置 */
12
+ export function readMcpConfigFile(filePath) {
13
+ if (!existsSync(filePath)) {
14
+ return { servers: {}, raw: null, legacy: false, exists: false };
15
+ }
16
+ try {
17
+ const text = readFileSync(filePath, "utf8");
18
+ let raw = null;
19
+ try {
20
+ const parsed = JSON.parse(text);
21
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
22
+ raw = parsed;
23
+ }
24
+ }
25
+ catch {
26
+ /* invalid json */
27
+ }
28
+ const legacy = !!raw && raw.servers !== undefined && raw.mcpServers === undefined;
29
+ const parsedConfig = parseMcpConfig(text);
30
+ return {
31
+ servers: parsedConfig ? parsedConfig.servers : {},
32
+ raw,
33
+ legacy,
34
+ exists: true,
35
+ };
36
+ }
37
+ catch {
38
+ return { servers: {}, raw: null, legacy: false, exists: true };
39
+ }
40
+ }
41
+ /** 写入指定文件的 MCP 服务器配置(保留除服务器清单以外的其它字段) */
42
+ export function writeMcpConfigFile(filePath, servers, preferLegacy = false) {
43
+ mkdirSync(dirname(filePath), { recursive: true });
44
+ let raw = {};
45
+ if (existsSync(filePath)) {
46
+ try {
47
+ const text = readFileSync(filePath, "utf8");
48
+ const parsed = JSON.parse(text);
49
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
50
+ raw = parsed;
51
+ }
52
+ }
53
+ catch {
54
+ /* ignore corrupt file, rewrite cleanly */
55
+ }
56
+ }
57
+ const legacy = raw.servers !== undefined && raw.mcpServers === undefined ? true : preferLegacy;
58
+ const next = { ...raw };
59
+ if (legacy) {
60
+ delete next.mcpServers;
61
+ next.servers = servers;
62
+ }
63
+ else {
64
+ delete next.servers;
65
+ next.mcpServers = servers;
66
+ }
67
+ writeFileSync(filePath, JSON.stringify(next, null, 2) + "\n", "utf8");
68
+ }
69
+ /** 校验 MCP 服务器名称合法性(字母、数字、下划线、短横线) */
70
+ export function isValidMcpServerName(name) {
71
+ return /^[a-zA-Z0-9_-]+$/.test(name.trim());
72
+ }
73
+ /** 汇总查询全局与项目级配置列表,并结合 McpBridge 运行时状态组装 UiMcpServer 数组 */
74
+ export function listAllMcpServers(opts) {
75
+ const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
76
+ const projectPath = getProjectMcpPath(opts.cwd);
77
+ const globalCfg = readMcpConfigFile(globalPath);
78
+ const projectCfg = readMcpConfigFile(projectPath);
79
+ const result = [];
80
+ // 全局服务器
81
+ for (const [name, spec] of Object.entries(globalCfg.servers)) {
82
+ const status = getRuntimeStatus(name, spec, opts.bridge);
83
+ result.push({
84
+ name,
85
+ scope: "global",
86
+ command: spec.command,
87
+ args: spec.args,
88
+ cwd: spec.cwd,
89
+ env: spec.env,
90
+ url: spec.url,
91
+ headers: spec.headers,
92
+ type: spec.type,
93
+ timeout: spec.timeout,
94
+ protocolVersion: spec.protocolVersion,
95
+ enabled: spec.enabled !== false,
96
+ description: spec.description,
97
+ status: status.status,
98
+ error: status.error,
99
+ tools: status.tools,
100
+ });
101
+ }
102
+ // 项目级服务器
103
+ for (const [name, spec] of Object.entries(projectCfg.servers)) {
104
+ const status = getRuntimeStatus(name, spec, opts.bridge);
105
+ result.push({
106
+ name,
107
+ scope: "project",
108
+ command: spec.command,
109
+ args: spec.args,
110
+ cwd: spec.cwd,
111
+ env: spec.env,
112
+ url: spec.url,
113
+ headers: spec.headers,
114
+ type: spec.type,
115
+ timeout: spec.timeout,
116
+ protocolVersion: spec.protocolVersion,
117
+ enabled: spec.enabled !== false,
118
+ description: spec.description,
119
+ status: status.status,
120
+ error: status.error,
121
+ tools: status.tools,
122
+ });
123
+ }
124
+ return { servers: result, globalPath, projectPath };
125
+ }
126
+ function getRuntimeStatus(name, spec, bridge) {
127
+ if (spec.enabled === false) {
128
+ return { status: "stopped", tools: [] };
129
+ }
130
+ if (!bridge) {
131
+ return { status: "stopped", tools: [] };
132
+ }
133
+ return bridge.getServerStatus(name);
134
+ }
135
+ /** 保存或更新 MCP 服务器 */
136
+ export function saveMcpServer(opts) {
137
+ const name = opts.server.name.trim();
138
+ if (!isValidMcpServerName(name)) {
139
+ return { ok: false, error: "服务器名称仅允许包含英文字母、数字、下划线及中划线" };
140
+ }
141
+ const targetScope = opts.server.scope;
142
+ const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
143
+ const projectPath = getProjectMcpPath(opts.cwd);
144
+ const targetPath = targetScope === "global" ? globalPath : projectPath;
145
+ // 若存在旧名称或作用域移动,从原作用域文件中移除
146
+ if (opts.prevName && opts.prevScope) {
147
+ const prevCleanName = opts.prevName.trim();
148
+ if (prevCleanName !== name || opts.prevScope !== targetScope) {
149
+ const oldPath = opts.prevScope === "global" ? globalPath : projectPath;
150
+ const oldCfg = readMcpConfigFile(oldPath);
151
+ if (oldCfg.servers[prevCleanName]) {
152
+ delete oldCfg.servers[prevCleanName];
153
+ writeMcpConfigFile(oldPath, oldCfg.servers, oldCfg.legacy);
154
+ }
155
+ }
156
+ }
157
+ const targetCfg = readMcpConfigFile(targetPath);
158
+ const spec = {
159
+ command: opts.server.command?.trim() || undefined,
160
+ args: Array.isArray(opts.server.args) && opts.server.args.length > 0 ? opts.server.args.map(String) : undefined,
161
+ cwd: opts.server.cwd?.trim() || undefined,
162
+ env: opts.server.env && Object.keys(opts.server.env).length > 0
163
+ ? opts.server.env
164
+ : undefined,
165
+ url: opts.server.url?.trim() || undefined,
166
+ headers: opts.server.headers && Object.keys(opts.server.headers).length > 0
167
+ ? opts.server.headers
168
+ : undefined,
169
+ type: opts.server.type,
170
+ timeout: typeof opts.server.timeout === "number" ? opts.server.timeout : undefined,
171
+ protocolVersion: opts.server.protocolVersion?.trim() || undefined,
172
+ enabled: opts.server.enabled !== false,
173
+ description: opts.server.description?.trim() || undefined,
174
+ };
175
+ targetCfg.servers[name] = spec;
176
+ writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
177
+ return { ok: true };
178
+ }
179
+ /** 删除指定作用域下的 MCP 服务器 */
180
+ export function deleteMcpServer(opts) {
181
+ const name = opts.name.trim();
182
+ const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
183
+ const projectPath = getProjectMcpPath(opts.cwd);
184
+ const targetPath = opts.scope === "global" ? globalPath : projectPath;
185
+ const targetCfg = readMcpConfigFile(targetPath);
186
+ if (!targetCfg.servers[name]) {
187
+ return { ok: false, error: `服务器 ${name} 在 ${opts.scope === "global" ? "全局" : "项目"} 配置中不存在` };
188
+ }
189
+ delete targetCfg.servers[name];
190
+ writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
191
+ return { ok: true };
192
+ }
193
+ /** 切换指定作用域下的 MCP 服务器启用/停用状态 */
194
+ export function toggleMcpServer(opts) {
195
+ const name = opts.name.trim();
196
+ const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
197
+ const projectPath = getProjectMcpPath(opts.cwd);
198
+ const targetPath = opts.scope === "global" ? globalPath : projectPath;
199
+ const targetCfg = readMcpConfigFile(targetPath);
200
+ if (targetCfg.servers[name]) {
201
+ targetCfg.servers[name].enabled = opts.enabled;
202
+ writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
203
+ return { ok: true };
204
+ }
205
+ // 若在项目级切换全局服务器的启用状态(项目级覆盖):写入仅带 enabled 的配置项
206
+ if (opts.scope === "project") {
207
+ const globalCfg = readMcpConfigFile(globalPath);
208
+ if (globalCfg.servers[name]) {
209
+ targetCfg.servers[name] = { enabled: opts.enabled };
210
+ writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
211
+ return { ok: true };
212
+ }
213
+ }
214
+ return { ok: false, error: `服务器 ${name} 不存在` };
215
+ }
@@ -0,0 +1,32 @@
1
+ import { findEntryByUiId } from "./serialize.js";
2
+ /**
3
+ * 将前端渲染的用户消息 ID(u-<timestamp>-<seq>)解析为底层 SessionEntry 的唯一 ID。
4
+ * seq 用于解决同一毫秒内发出的多条用户消息(例如附件 aside 消息)。
5
+ */
6
+ export function resolveUserMessageEntryId(contextEntries, messageId) {
7
+ const m = /^u-(\d+)(?:-(\d+))?$/.exec(messageId);
8
+ if (!m)
9
+ return null;
10
+ const ts = Number(m[1]);
11
+ const seq = m[2] ? Number(m[2]) : 1;
12
+ let count = 0;
13
+ for (const entry of contextEntries) {
14
+ if (entry.type !== "message")
15
+ continue;
16
+ const msg = entry.message;
17
+ if (!msg || msg.role !== "user" || msg.timestamp !== ts)
18
+ continue;
19
+ count += 1;
20
+ if (count === seq)
21
+ return entry.id;
22
+ }
23
+ return null;
24
+ }
25
+ /**
26
+ * 将任意渲染的消息 ID 解析为当前会话分支的 SessionEntry 节点。
27
+ * 优先在上下文条目中比对 UI ID,未命中时通过 fallback 查整棵历史树。
28
+ */
29
+ export function resolveConversationMessageEntry(contextEntries, messageId, seqOf, fallbackGetEntry) {
30
+ const found = findEntryByUiId(contextEntries, messageId, seqOf);
31
+ return found ?? fallbackGetEntry?.(messageId) ?? null;
32
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * orphan-manager — 残留会话认领与同工作区比对工具。
3
+ *
4
+ * 负责:
5
+ * - pickAdoptableOrphan: 选一个断开连接的残留会话给新标签页认领(纯函数)
6
+ * - sameCwd: 跨平台工作区路径一致性比对(纯函数)
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ import { normalizePathKey } from "./client-state.js";
11
+ /**
12
+ * 选一个断开的残留会话给新标签认领(纯函数):
13
+ * - 还有别的在线浏览器(非伪客户端且 live)→ 不认领(新标签是第二块屏,
14
+ * issue #10 的隔离必须保留,跑着的对话继续走 elsewhere 只读感知)。
15
+ * - 否则在断开 + 非伪 + 有内容的候选中按(streaming 多 → 最近活跃)取最优;
16
+ * 没有返回 null(调用方走正常新建流程)。
17
+ */
18
+ export function pickAdoptableOrphan(cands) {
19
+ if (cands.some((c) => !c.pseudo && c.live))
20
+ return null;
21
+ let best = null;
22
+ for (const c of cands) {
23
+ if (c.pseudo || c.live || !c.adoptable)
24
+ continue;
25
+ if (!best || c.streaming > best.streaming || (c.streaming === best.streaming && c.activity > best.activity)) {
26
+ best = c;
27
+ }
28
+ }
29
+ return best?.id ?? null;
30
+ }
31
+ /** 同项目判定(纯函数):调度视口回退与 id 唤醒的 cwd 护栏用。
32
+ * Windows 大小写/分隔符差异归一,空串永不相等。 */
33
+ export function sameCwd(a, b) {
34
+ const x = String(a ?? "").trim();
35
+ const y = String(b ?? "").trim();
36
+ if (!x || !y)
37
+ return false;
38
+ try {
39
+ return normalizePathKey(x) === normalizePathKey(y);
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
@@ -24,10 +24,23 @@
24
24
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { dirname, join } from "node:path";
27
- /** Old fragment that performs the union merge (single occurrence in the file). */
28
- const OLD = "getModels: () => mergeModels(provider.getModels(), dynamicModels),";
29
- /** Replacement: whole-replace with the remote catalog when available. */
30
- const NEW = "getModels: () => (dynamicModels.length > 0 ? dynamicModels : provider.getModels()),";
27
+ /** Supported patch pairs across SDK versions (0.87.x, 1.1.0+). */
28
+ const PATCH_PAIRS = [
29
+ // SDK 0.87.x
30
+ {
31
+ old: "getModels: () => mergeModels(provider.getModels(), dynamicModels),",
32
+ new: "getModels: () => (dynamicModels.length > 0 ? dynamicModels : provider.getModels()),",
33
+ },
34
+ // SDK 1.1.0+ (typed model shards: chat, image, classifier)
35
+ {
36
+ old: 'getModels: () => mergeModels(provider.getModels(), dynamicModels.filter((model) => isModelType(model, "chat"))),',
37
+ new: 'getModels: () => (dynamicModels.length > 0 ? dynamicModels.filter((model) => isModelType(model, "chat")) : provider.getModels()),',
38
+ },
39
+ {
40
+ old: "getAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),",
41
+ new: "getAllModels: () => (dynamicModels.length > 0 ? dynamicModels : (provider.getAllModels?.() ?? provider.getModels())),",
42
+ },
43
+ ];
31
44
  /** Absolute path of the installed remote-catalog-provider.js, or null. */
32
45
  function remoteCatalogFile() {
33
46
  try {
@@ -45,12 +58,17 @@ function applyPatch() {
45
58
  const file = remoteCatalogFile();
46
59
  if (!file || !existsSync(file))
47
60
  return;
48
- const src = readFileSync(file, "utf8");
49
- if (src.includes(NEW))
50
- return; // already patched
51
- if (!src.includes(OLD))
52
- return; // unexpected SDK content — leave alone
53
- writeFileSync(file, src.replace(OLD, NEW), "utf8");
61
+ let src = readFileSync(file, "utf8");
62
+ let changed = false;
63
+ for (const { old: oldPattern, new: newPattern } of PATCH_PAIRS) {
64
+ if (src.includes(oldPattern) && !src.includes(newPattern)) {
65
+ src = src.replace(oldPattern, newPattern);
66
+ changed = true;
67
+ }
68
+ }
69
+ if (changed) {
70
+ writeFileSync(file, src, "utf8");
71
+ }
54
72
  }
55
73
  catch {
56
74
  // best-effort — without the patch the SDK keeps its default union merge
@@ -20,17 +20,18 @@ export function makePatchTool(options) {
20
20
  const getLang = options.lang ?? (() => "en");
21
21
  return defineTool({
22
22
  name: PATCH_TOOL_NAME,
23
- promptSnippet: "apply content-hashed, line-anchored patches to workspace files (prevents stale edits, line drift, and indentation hallucination)",
23
+ promptSnippet: "apply content-hashed, line-anchored patches to files",
24
24
  label: "Apply Hashline patch",
25
25
  description: `Apply content-hashed, line-anchored patches to workspace files — prevents stale edits, line drift, and indentation hallucination.
26
26
  Each file section starts with \`[path#TAG]\` (or \`[path]\` if the hash is unknown yet). Operations:
27
27
  - \`PUT N.=M:\` replace lines N..M (inclusive) with the following \`+TEXT\` lines.
28
- - \`PUT N*:\` replace the whole syntactic block starting at line N (closing brace/indent auto-resolved).
29
- - \`PUT <N:\` insert before line N (\`<1\` = head of file); \`PUT >N:\` insert after (\`>$\` = end).
30
- - \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines and save to register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
31
- - \`REM\` delete file; \`MV dest/path\` move/rename file.
32
- - Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line).
33
- On divergence the engine attempts a 3-way merge. After success the tool returns the next anchor tag and live LSP diagnostics.`,
28
+ - \`PUT N*:\` replace the syntactic block starting at line N (closing brace/indent auto-resolved).
29
+ - \`PUT <N:\` / \`PUT >N:\` insert before / after line N (\`<1\` = head, \`>$\` = end).
30
+ - \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines into a register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
31
+ - \`REM\` delete file; \`MV dest/path\` move/rename.
32
+ - Create a file: bare \`[path]\` header (no tag) on a nonexistent path + \`PUT <1:\` / \`PUT >$:\` \`+TEXT\` content.
33
+ - Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line). Divergence triggers a 3-way merge.
34
+ Success returns the next anchor tag and live LSP diagnostics.`,
34
35
  parameters: Type.Object({
35
36
  patch: Type.String({
36
37
  description: "The complete Hashline patch text containing one or more [path#TAG] sections with PUT/CUT/REM/MV operations.",
@@ -38,7 +39,7 @@ On divergence the engine attempts a 3-way merge. After success the tool returns
38
39
  timeout: Type.Optional(Type.Number({
39
40
  minimum: 1,
40
41
  maximum: 300,
41
- description: "Optional execution timeout in seconds (1-300).",
42
+ description: "Optional execution timeout in seconds.",
42
43
  })),
43
44
  }),
44
45
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * persona-chain — 内联人设注入、扩展提示词包裹剥离与平台人设补丁。
3
+ *
4
+ * 负责:
5
+ * - INLINE_PERSONA_EXT: 自家内联扩展名标识
6
+ * - splitAgentStartPrompt: 剥离先前扩展对 SDK 原始系统提示词的首尾增补
7
+ * - PI_DOC_PATHS: 本地 pi SDK 文档路径发现
8
+ * - WINDOWS_PERSONA: Windows 平台特有人设补丁(超时/非交互 TTY/GBK 编码)
9
+ *
10
+ * 从 agent-service.ts 抽出为独立模块。
11
+ */
12
+ import { createRequire } from "node:module";
13
+ import { dirname, join } from "node:path";
14
+ import { splitExtensionWrap } from "./prompt-composer.js";
15
+ /** 自家内联扩展名(组合模板渲染,见 prompt-composer.ts)。SDK 以其
16
+ * "<inline:<name>>" 作为 path;扩展白名单/禁用过滤必须放行它。 */
17
+ export const INLINE_PERSONA_EXT = "<inline:pi-webui-persona>";
18
+ /** 本次 run 的 SDK 原始提示词 + 早前扩展的首尾增补(见 splitExtensionWrap)。
19
+ * 导出仅为单测(tests/unit/persona-prompt-chain.test.ts)可达。
20
+ * systemPromptOptions 就是 runner 里那个共享可变对象,forceSystemPrompt 有值即
21
+ * 说明前面有扩展替换过提示词;临时清掉再读 event.systemPrompt 就拿到原始基线
22
+ * (公开字段,不碰 SDK 内部)。没人动过时零开销,直接返回当前文本。 */
23
+ export function splitAgentStartPrompt(event) {
24
+ const current = event.systemPrompt;
25
+ const opts = event.systemPromptOptions;
26
+ const forced = opts?.forceSystemPrompt;
27
+ if (!opts || typeof forced !== "string")
28
+ return { pre: "", core: current, post: "" };
29
+ try {
30
+ opts.forceSystemPrompt = undefined;
31
+ return splitExtensionWrap(event.systemPrompt, current);
32
+ }
33
+ finally {
34
+ opts.forceSystemPrompt = forced;
35
+ }
36
+ }
37
+ /** Pi 包文档路径(composer 的 {{pi_docs}} 自动内容用)。随安装位置解析一次。 */
38
+ export const PI_DOC_PATHS = (() => {
39
+ try {
40
+ const requireLocal = createRequire(import.meta.url);
41
+ const root = dirname(requireLocal.resolve("@earendil-works/pi-coding-agent/package.json"));
42
+ return { readme: join(root, "README.md"), docs: join(root, "docs"), examples: join(root, "examples") };
43
+ }
44
+ catch {
45
+ return { readme: "", docs: "", examples: "" };
46
+ }
47
+ })();
48
+ /** Windows persona appendix — appended to the SDK system prompt on win32 only.
49
+ * Two failure modes it guards against: (1) the SDK bash tool has NO default
50
+ * timeout, so a long-running command hangs the whole conversation forever;
51
+ * (2) the in-app terminal is an interactive TTY where heredocs / interactive
52
+ * programs wait for input that never comes. Legacy Chinese files are often
53
+ * GBK/GB2312 — read them with the right encoding, never paste mojibake into
54
+ * reasoning/answers. */
55
+ export const WINDOWS_PERSONA = `You are a coding agent running on Windows. The bash tool runs Git Bash (bash.exe), not PowerShell. Follow these rules to avoid hanging the session:
56
+
57
+
58
+
59
+ - ALWAYS pass a timeout parameter to the bash tool (in seconds). There is NO default timeout — a command that never finishes (servers, watchers, infinite loops, slow downloads/installs) will hang the entire conversation indefinitely. Pick a generous timeout for long-running work, but never omit it.
60
+ - NEVER run interactive or foreground long-running commands through the bash tool (vi, less, top, python -, node -, npm run dev, sleep 10000). For servers/daemons use background execution with output redirected to a log file, then poll the log; stop them when done.
61
+ - In the interactive terminal (TTY) — which is Git Bash too, not PowerShell — NEVER use heredocs (<<'EOF' ... EOF) or here-strings, and NEVER start interactive programs (vi, less, python -, node -, npm init): they wait for keyboard input that never arrives and hang the terminal forever. Prefer writing a temp script file (e.g. .pi-tmp.sh) and running it non-interactively. ALWAYS pass a timeout to long-running commands (e.g. \`timeout 120 npm run dev\`).
62
+
63
+ Many legacy Chinese text files (.html/.txt/.md/.log, exported documents) are GBK/GB2312 encoded: the read tool decodes UTF-8 only and will show mojibake (乱码) for them. If a file's content looks garbled, read it through the terminal instead: in Git Bash use \`cat file | iconv -f GBK -t UTF-8\` (or \`iconv -f GBK -t UTF-8 file\`); in cmd use \`chcp 65001 && type file\`; in PowerShell use \`Get-Content -Encoding Default file\`. Never paste mojibake into your reasoning or answer — describe the decoded content instead.`;
@@ -49,6 +49,8 @@ const BLOCKED_TOOLS = new Set([
49
49
  // 代码求值(eval 沙箱的 execute 直接 kernel.execute,可写真实文件系统;
50
50
  // 默认关但用户可开,开了就是一条写路径 —— #436)
51
51
  "eval",
52
+ // QuickJS 沙箱代码执行(可嵌套调用写工具/命令,计划模式禁止任意代码执行)
53
+ "codemode",
52
54
  // 形态变换(会重写整个文件树)
53
55
  "format",
54
56
  "prettier",
@@ -67,18 +69,19 @@ const BLOCKED_TOOLS = new Set([
67
69
  const TERMINAL_WRITE_TOOLS = new Set(["terminal_input", "terminal_key"]);
68
70
  /**
69
71
  * 三个只读闸门(计划 / 审查者 / 目标审查)共用的「派发类」工具名:它们会把活
70
- * 派到**别的会话**执行(delegate_task 走子代理 spawn 通道;schedule_task 到期
72
+ * 派到**别的会话**执行(delegate_task 走子代理 spawn 通道;schedule 到期
71
73
  * 唤醒对话跑 prompt),而这三道闸门都是会话级的 —— 放行即绕过。
72
74
  *
73
75
  * 名单以 server/tool-manager.ts 实际注册的工具名为事实源(#436):历史名单里的
74
76
  * spawn / spawn_agent / subagent_spawn / schedule_agent / host_schedule /
75
77
  * create_goal / set_goal / start_goal_wizard / create_conversation /
76
- * fork_conversation / schedule / set_plan_mode 等都是协议消息名或从未注册的
77
- * 幽灵名,一个真实工具都没拦住,反而掩盖了 schedule_task 这类真实旁路工具
78
- * 完全可用的事实。subagent 是单 action 工具,由各闸门按 action 细分(只读
79
- * action 放行,见各闸门的判定函数)。
78
+ * fork_conversation / set_plan_mode 等都是协议消息名或从未注册的幽灵名,一个
79
+ * 真实工具都没拦住,反而掩盖了 schedule 这类真实旁路工具完全可用的事实。
80
+ * subagent 是单 action 工具,由各闸门按 action 细分(只读 action 放行,见各闸门
81
+ * 的判定函数);schedule(create/list/cancel)则整工具拒——调度面在计划/审查
82
+ * 回合都不需要,宁可保守。
80
83
  */
81
- export const SESSION_DISPATCH_TOOLS = new Set(["delegate_task", "schedule_task"]);
84
+ export const SESSION_DISPATCH_TOOLS = new Set(["delegate_task", "schedule"]);
82
85
  /**
83
86
  * 计划模式下也禁掉的「旁路工具」(真实派发类,见 SESSION_DISPATCH_TOOLS):
84
87
  * 它们能在**别的会话**里干活,而闸门是会话级的 —— 子代理/排程对话的