pi-web-ui 0.104.4 → 0.105.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 (52) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +2 -2
  4. package/bin/pi-web-ui.mjs +9 -3
  5. package/dist/server/agent-service-daemon.js +7 -7
  6. package/dist/server/agent-service.js +497 -109
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +29 -0
  9. package/dist/server/dispatch-domain-handlers.js +35 -7
  10. package/dist/server/dsh/dsh-agent-service.js +88 -33
  11. package/dist/server/dsh/dsh-serialize.js +16 -1
  12. package/dist/server/ensure-bash.js +7 -2
  13. package/dist/server/file-transfer-routes.js +114 -1
  14. package/dist/server/index.js +347 -68
  15. package/dist/server/load-tools-tool.js +2 -1
  16. package/dist/server/locales.js +5 -0
  17. package/dist/server/markers/marker.js +28 -0
  18. package/dist/server/mcp-bridge.js +20 -6
  19. package/dist/server/pkg-info.js +69 -0
  20. package/dist/server/plugin-facilities.js +18 -9
  21. package/dist/server/plugin-manifest-validate.js +3 -0
  22. package/dist/server/plugin-updater.js +11 -5
  23. package/dist/server/plugins.js +3 -12
  24. package/dist/server/present-files-tool.js +47 -1
  25. package/dist/server/preset-fields.js +14 -0
  26. package/dist/server/preset-share.js +5 -12
  27. package/dist/server/prompt-composer.js +1 -1
  28. package/dist/server/remote-ssh-service.js +158 -5
  29. package/dist/server/serialize.js +15 -4
  30. package/dist/server/session-parser.js +138 -2
  31. package/dist/server/settings-service.js +19 -0
  32. package/dist/server/terminals.js +7 -1
  33. package/dist/server/text-quote.js +64 -2
  34. package/dist/server/tool-manager.js +10 -0
  35. package/dist/server/tool-prompts.js +1 -0
  36. package/dist/server/update-check.js +98 -24
  37. package/dist/server/workspace-snapshot.js +251 -13
  38. package/dist/server/worktree-service.js +262 -0
  39. package/dist/server/worktree-tool.js +173 -0
  40. package/package.json +3 -1
  41. package/plugin-sdk/index.d.ts +14 -1
  42. package/themes/zhujian-dark.css +16 -4
  43. package/themes/zhujian.css +16 -4
  44. package/themes/zhupi-dark.css +16 -4
  45. package/themes/zhupi.css +16 -4
  46. package/web/dist/assets/{TerminalPanel-B7x99tkg.js → TerminalPanel-B9exeXrl.js} +1 -1
  47. package/web/dist/assets/index-BQC6lADz.css +1 -0
  48. package/web/dist/assets/index-D79IKG33.js +690 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-DOrLcjLY.js +0 -680
  52. package/web/dist/assets/index-_H2BS7OX.css +0 -1
@@ -19,13 +19,27 @@ import { homedir } from "node:os";
19
19
  import { join } from "node:path";
20
20
  /** 获取全局 MCP 配置文件路径 */
21
21
  export function getGlobalMcpPath(agentDir, dataDir) {
22
- const defaultAgentDir = agentDir || process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
23
- const agentPath = join(defaultAgentDir, "mcp.json");
24
- if (existsSync(agentPath))
22
+ if (agentDir) {
23
+ const agentPath = join(agentDir, "mcp.json");
24
+ if (existsSync(agentPath))
25
+ return agentPath;
26
+ if (dataDir && existsSync(join(dataDir, "mcp.json")))
27
+ return join(dataDir, "mcp.json");
25
28
  return agentPath;
26
- if (dataDir && existsSync(join(dataDir, "mcp.json")))
27
- return join(dataDir, "mcp.json");
28
- return agentPath;
29
+ }
30
+ if (process.env.PI_CODING_AGENT_DIR) {
31
+ const envPath = join(process.env.PI_CODING_AGENT_DIR, "mcp.json");
32
+ if (existsSync(envPath))
33
+ return envPath;
34
+ }
35
+ if (dataDir) {
36
+ const dataPath = join(dataDir, "mcp.json");
37
+ if (existsSync(dataPath))
38
+ return dataPath;
39
+ return dataPath;
40
+ }
41
+ const defaultAgentDir = join(homedir(), ".pi", "agent");
42
+ return join(defaultAgentDir, "mcp.json");
29
43
  }
30
44
  /** 获取项目级 MCP 配置文件路径 */
31
45
  export function getProjectMcpPath(cwd) {
@@ -0,0 +1,69 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ let cachedPkgRoot = null;
5
+ let cachedAppVersion = null;
6
+ /**
7
+ * 解析 pi-web-ui 包的根目录。
8
+ * 兼容:
9
+ * - 源码开发模式:server/ (tsx)
10
+ * - 源码子模块:server/dsh/ (tsx)
11
+ * - 生产构建模式:dist/server/
12
+ * - 生产构建子模块:dist/server/dsh/
13
+ * - 环境变量显式指定:process.env.PI_WEB_PKG_ROOT
14
+ */
15
+ export function getPkgRoot(fromUrl = import.meta.url) {
16
+ if (process.env.PI_WEB_PKG_ROOT && existsSync(join(process.env.PI_WEB_PKG_ROOT, "package.json"))) {
17
+ return process.env.PI_WEB_PKG_ROOT;
18
+ }
19
+ if (cachedPkgRoot)
20
+ return cachedPkgRoot;
21
+ let dir = dirname(fileURLToPath(fromUrl));
22
+ for (let i = 0; i < 5; i++) {
23
+ const pkgPath = join(dir, "package.json");
24
+ if (existsSync(pkgPath)) {
25
+ try {
26
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
27
+ if (pkg.name === "pi-web-ui") {
28
+ cachedPkgRoot = dir;
29
+ return dir;
30
+ }
31
+ }
32
+ catch {
33
+ /* ignore */
34
+ }
35
+ }
36
+ const parent = dirname(dir);
37
+ if (parent === dir)
38
+ break;
39
+ dir = parent;
40
+ }
41
+ // Fallback 策略:尝试向上找任意 package.json
42
+ dir = dirname(fileURLToPath(fromUrl));
43
+ const candidates = [resolve(dir, ".."), resolve(dir, "..", ".."), resolve(dir, "..", "..", "..")];
44
+ for (const c of candidates) {
45
+ if (existsSync(join(c, "package.json"))) {
46
+ cachedPkgRoot = c;
47
+ return c;
48
+ }
49
+ }
50
+ cachedPkgRoot = candidates[0] ?? dir;
51
+ return cachedPkgRoot;
52
+ }
53
+ /**
54
+ * 获取 pi-web-ui 宿主运行时的真实版本号。
55
+ * 若读取失败则 fallback 为 ""。
56
+ */
57
+ export function getAppVersion(fromUrl = import.meta.url) {
58
+ if (cachedAppVersion !== null)
59
+ return cachedAppVersion;
60
+ try {
61
+ const root = getPkgRoot(fromUrl);
62
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
63
+ cachedAppVersion = pkg.version ?? "";
64
+ }
65
+ catch {
66
+ cachedAppVersion = "";
67
+ }
68
+ return cachedAppVersion;
69
+ }
@@ -383,15 +383,24 @@ export function ensurePluginDeps(pluginDir, specs, onProgress) {
383
383
  // 规避 DEP0190 与命令行注入,posix 不用 shell(路径不含空格假设成立,与宿主其它 spawn 一致)。
384
384
  const isWin = process.platform === "win32";
385
385
  const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : "npm";
386
- const spawnArgs = isWin
387
- ? ["/d", "/s", "/c", "npm.cmd", "install", "--no-audit", "--no-fund", ...missing]
388
- : ["install", "--no-audit", "--no-fund", ...missing];
389
- const res = spawnSync(spawnCmd, spawnArgs, {
390
- cwd: pluginDir,
391
- timeout: DEP_TIMEOUT_MS,
392
- windowsHide: true,
393
- encoding: "utf8",
394
- });
386
+ const runNpmInstall = (extraFlags) => {
387
+ const spawnArgs = isWin
388
+ ? ["/d", "/s", "/c", "npm.cmd", "install", "--no-audit", "--no-fund", ...extraFlags, ...missing]
389
+ : ["install", "--no-audit", "--no-fund", ...extraFlags, ...missing];
390
+ return spawnSync(spawnCmd, spawnArgs, {
391
+ cwd: pluginDir,
392
+ timeout: DEP_TIMEOUT_MS,
393
+ windowsHide: true,
394
+ encoding: "utf8",
395
+ });
396
+ };
397
+ let res = runNpmInstall([]);
398
+ // 传递依赖(如 @xenova/transformers 拉进来的 sharp@0.32)在无编译环境或连不上
399
+ // GitHub Release 拉 libvips 时,install 脚本会以非 0 退出拖垮整轮安装;
400
+ // 用 --ignore-scripts 重试一次,让预打包二进制(如 onnxruntime-node)与纯 JS 包先落盘。
401
+ if (res.error || res.status !== 0) {
402
+ res = runNpmInstall(["--ignore-scripts"]);
403
+ }
395
404
  if (res.error || res.status !== 0) {
396
405
  console.error(`[plugin-deps] ${join(pluginDir)} npm install 失败:`, res.error ?? res.stderr?.slice(0, 500));
397
406
  return false;
@@ -26,6 +26,9 @@ export const KNOWN_PERMISSION_FAMILIES = new Set([
26
26
  "llm",
27
27
  "dom",
28
28
  "dom:anchor",
29
+ "notify",
30
+ "storage",
31
+ "secrets",
29
32
  ]);
30
33
  function isRecord(v) {
31
34
  return Boolean(v) && typeof v === "object" && !Array.isArray(v);
@@ -56,8 +56,8 @@ export function ensureBackup(dataDir, id, opts) {
56
56
  mkdirSync(dirnameOf(dest), { recursive: true });
57
57
  cpSync(target, dest, {
58
58
  recursive: true,
59
- // 与安装一致:不备份 .git/node_modules(纯运行目录),config.json 等保留。
60
- filter: (s) => !/(^|[\\/])(\.git|node_modules)([\\/]|$)/.test(s),
59
+ // 与安装一致:不备份 .git/node_modules/whisper-cache(纯运行/大体量模型缓存),config.json 等保留。
60
+ filter: (s) => !/(^|[\\/])(\.git|node_modules|whisper-cache)([\\/]|$)/.test(s),
61
61
  });
62
62
  writeFileSync(join(dest, ".pi-backup.json"), JSON.stringify({ id, ts, source: opts?.source }, null, 2) + "\n");
63
63
  pruneBackups(dataDir, id);
@@ -103,9 +103,15 @@ export function restoreBackup(dataDir, id) {
103
103
  const src = join(dataDir, "plugin-backups", backups[0]);
104
104
  const target = join(dataDir, "plugins", id);
105
105
  try {
106
- if (existsSync(target))
107
- rmSync(target, { recursive: true, force: true });
108
- mkdirSync(join(dataDir, "plugins"), { recursive: true });
106
+ if (existsSync(target)) {
107
+ const keepDirs = new Set(["node_modules", "whisper-cache"]);
108
+ for (const entry of readdirSync(target)) {
109
+ if (keepDirs.has(entry))
110
+ continue;
111
+ rmSync(join(target, entry), { recursive: true, force: true });
112
+ }
113
+ }
114
+ mkdirSync(target, { recursive: true });
109
115
  cpSync(src, target, { recursive: true });
110
116
  rmSync(src, { recursive: true, force: true });
111
117
  return backups[0];
@@ -27,6 +27,7 @@ import { pick } from "./i18n.js";
27
27
  import { PluginStorage, PluginSecrets, ensurePluginDeps, WorkspaceFS, withFileRmwLock } from "./plugin-facilities.js";
28
28
  import { parseCronSpec, armDelay, nextCronFire, loadScheduleRecords, saveScheduleRecords, } from "./plugin-schedule.js";
29
29
  import { PluginPermissionStore } from "./plugin-permissions.js";
30
+ import { getAppVersion } from "./pkg-info.js";
30
31
  import { readCatalog, addCustomEntry, removeCustomEntry } from "./plugin-catalog.js";
31
32
  import { PluginGrantsStore, normalizeGrantPath } from "./plugin-grants.js";
32
33
  import { normalizeIconSvg } from "./icon-svg.js";
@@ -252,19 +253,9 @@ export function satisfiesEnginesConstraint(constraint, current) {
252
253
  return cur[0] === r[0] && cmpVerTuple(cur, r) >= 0; // ^:同主版本且不低于
253
254
  }
254
255
  /** 宿主自身版本(package.json version,读一次缓存;读不到回 null——调用方放行)。 */
255
- let cachedHostVersion;
256
256
  export function readHostVersion() {
257
- if (cachedHostVersion !== undefined)
258
- return cachedHostVersion;
259
- try {
260
- const here = dirname(fileURLToPath(import.meta.url));
261
- const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
262
- cachedHostVersion = typeof pkg.version === "string" ? pkg.version : null;
263
- }
264
- catch {
265
- cachedHostVersion = null;
266
- }
267
- return cachedHostVersion;
257
+ const ver = getAppVersion();
258
+ return ver ? ver : null;
268
259
  }
269
260
  // ---------------------------------------------------------------------------
270
261
  // 声明式设置 schema(manifest "settings")
@@ -25,11 +25,12 @@
25
25
  * DSH 引擎无 customTool 注册面(工具来自 shipped preset),本工具只服务 pi 引擎。
26
26
  */
27
27
  import { open, stat } from "node:fs/promises";
28
- import { basename, extname, sep } from "node:path";
28
+ import { basename, extname, posix, sep } from "node:path";
29
29
  import { defineTool } from "@earendil-works/pi-coding-agent";
30
30
  import { Type } from "typebox";
31
31
  import { pick } from "./i18n.js";
32
32
  import { resolvePathForDirCheck } from "./read-tool.js";
33
+ import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, restoreWorkspaceUriFromSessionDir, } from "./remote-ssh-service.js";
33
34
  import { decodeText, isAudioFile, looksLikeText, previewKind } from "./text-sniff.js";
34
35
  import { PRESENT_FILES_TOOL_NAME } from "./tool-manager.js";
35
36
  /** 展示文件工具名(唯一登记见 tool-manager.ts;此处导出供 import 方沿用)。 */
@@ -185,6 +186,51 @@ async function attachExcerpt(item, budget, native) {
185
186
  }
186
187
  /** 逐条探测:stat → 判类 → (未知扩展)嗅探 → 摘录。 */
187
188
  export async function probePresentItem(raw, cwd, budget) {
189
+ const effCwd = restoreWorkspaceUriFromSessionDir(cwd);
190
+ if (isRemoteWorkspaceUri(effCwd)) {
191
+ const parsed = parseRemoteWorkspaceUri(effCwd);
192
+ const sshSvc = getGlobalRemoteSshService();
193
+ const cleaned = String(raw.path ?? "")
194
+ .trim()
195
+ .replace(/^@/, "")
196
+ .replace(/\\/g, "/");
197
+ const remoteAbs = cleaned.startsWith("/")
198
+ ? posix.normalize(cleaned)
199
+ : posix.resolve(parsed?.remotePath || "/", cleaned);
200
+ const name = posix.basename(remoteAbs) || raw.path;
201
+ const base = { ...raw, name, abs: remoteAbs, kind: "missing" };
202
+ if (!sshSvc || !parsed)
203
+ return base;
204
+ const st = await sshSvc.sftpStat(effCwd, remoteAbs).catch(() => null);
205
+ if (!st)
206
+ return base;
207
+ if (st.isDirectory)
208
+ return { ...base, kind: "dir", mtime: st.mtime };
209
+ if (!st.isFile)
210
+ return base;
211
+ let kind = classifyPresentKind(name);
212
+ if (shouldSniff(kind) && st.size > 0 && st.size <= MAX_SNIFFABLE_BYTES) {
213
+ const headRes = await sshSvc.sftpReadFile(effCwd, remoteAbs, SNIFF_BYTES).catch(() => null);
214
+ if (headRes && headRes.data.length > 0 && looksLikeText(headRes.data))
215
+ kind = "text";
216
+ }
217
+ const item = { ...base, kind, size: st.size, mtime: st.mtime };
218
+ if (hasExcerpt(item.kind) && st.size > 0 && st.size <= MAX_SNIFFABLE_BYTES && budget.left > 0) {
219
+ const headRes = await sshSvc.sftpReadFile(effCwd, remoteAbs, EXCERPT_READ_BYTES).catch(() => null);
220
+ if (headRes && headRes.data.length > 0) {
221
+ const text = decodeText(headRes.data).replace(/\u0000+$/, "");
222
+ if (text) {
223
+ const cap = Math.min(MAX_EXCERPT_CHARS, budget.left);
224
+ const clipped = text.length > cap;
225
+ const excerpt = clipped ? text.slice(0, cap) : text;
226
+ item.excerpt = excerpt;
227
+ item.excerptTruncated = clipped || st.size > headRes.data.length;
228
+ budget.left -= excerpt.length;
229
+ }
230
+ }
231
+ }
232
+ return item;
233
+ }
188
234
  const native = resolvePathForDirCheck(raw.path, cwd);
189
235
  const abs = toWirePath(native);
190
236
  const name = basename(native) || raw.path;
@@ -77,6 +77,8 @@ export const PRESET_FIELD_GROUPS = {
77
77
  "toolsWrap",
78
78
  "toolImagesEnabled",
79
79
  "keepRecentMessages",
80
+ "showForkedParentSessions",
81
+ "retainFinishedConversations",
80
82
  "bgAutoCleanupMin",
81
83
  "quickPhrases",
82
84
  "quickPhrasesEnabled",
@@ -399,6 +401,18 @@ export const PRESET_FIELD_META = {
399
401
  hintZh: "消息列表尾部保持完整渲染的消息条数;更早的折叠为摘要行",
400
402
  hintEn: "Recent messages rendered in full; older ones collapse to summary rows",
401
403
  },
404
+ showForkedParentSessions: {
405
+ labelZh: "显示已分支的父会话",
406
+ labelEn: "Show Forked Parent Sessions",
407
+ hintZh: "编辑历史提问或派生分支后,在历史对话列表中同时保留原父会话",
408
+ hintEn: "Keep original parent sessions visible in the history list after editing a message or forking",
409
+ },
410
+ retainFinishedConversations: {
411
+ labelZh: "保留已结束的运行对话",
412
+ labelEn: "Retain Finished Running Conversations",
413
+ hintZh: "切换对话或新建对话时,已结束(空闲)的对话依然保留在运行列表中,直到手动移出",
414
+ hintEn: "Keep finished (idle) conversations in the Running Chats list when switching away until manually removed",
415
+ },
402
416
  quickPhrases: {
403
417
  labelZh: "快捷短语列表",
404
418
  labelEn: "Quick Phrases List",
@@ -26,6 +26,7 @@ import { tmpdir } from "node:os";
26
26
  import { dirname, join } from "node:path";
27
27
  import { fileURLToPath } from "node:url";
28
28
  import { promisify } from "node:util";
29
+ import { getAppVersion } from "./pkg-info.js";
29
30
  import { normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeSkillList, normalizeUiLayout, } from "./client-state.js";
30
31
  import { pick } from "./i18n.js";
31
32
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
@@ -67,19 +68,9 @@ const TAG_COUNT_MAX = 8;
67
68
  /* ------------------------------------------------------------------ */
68
69
  /* 配置(env 在调用时读取,便于测试与热改) */
69
70
  /* ------------------------------------------------------------------ */
70
- /** 本包版本(写进交换文档的 appVersion;读不到就空串)。首次调用时读一次。 */
71
- let cachedPackageVersion = null;
71
+ /** 本包版本(写进交换文档的 appVersion;读不到就空串)。 */
72
72
  export function packageVersion() {
73
- if (cachedPackageVersion === null) {
74
- try {
75
- const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
76
- cachedPackageVersion = pkg.version ?? "";
77
- }
78
- catch {
79
- cachedPackageVersion = "";
80
- }
81
- }
82
- return cachedPackageVersion;
73
+ return getAppVersion();
83
74
  }
84
75
  /** 真实网络的抓取器(与 update-check 的 defaultFetcher 同一个实现)。 */
85
76
  export const defaultTextFetcher = defaultFetcher;
@@ -282,6 +273,8 @@ const PRESET_FIELD_KINDS = {
282
273
  toolsWrap: "bool",
283
274
  toolImagesEnabled: "bool",
284
275
  keepRecentMessages: "number",
276
+ showForkedParentSessions: "bool",
277
+ retainFinishedConversations: "bool",
285
278
  quickPhrases: "list",
286
279
  quickPhrasesEnabled: "bool",
287
280
  devNoCache: "bool",
@@ -202,7 +202,7 @@ function buildToolsText(inputs, lang) {
202
202
  : "(none)";
203
203
  const parts = [`Available tools:\n${toolsList}`];
204
204
  if (inputs.lazy) {
205
- parts.push(pick(lang, "上表里有一部分工具的**参数 schema 尚未附加**;调用前先用 `load_tools` 把它们的名字传进来,即可拿到完整参数(本对话后续轮次都能继续用)。尚不在你工具列表里的,一律先 load_tools。", "Some tools above do NOT have their parameter schema attached yet. Before calling one, pass its name to `load_tools` to attach the full schema for the rest of this conversation. Anything not in your function list must be loaded first.", "prompt.tools.lazy"));
205
+ parts.push(pick(lang, "核心工具(bash, read, edit, write)及 `load_tools` 始终常驻可用,无需加载。上表中其他尚未附加参数 schema 的工具,调用前先用 `load_tools` 附加上完整参数(本对话后续轮次持续有效)。", "Core tools (bash, read, edit, write) and `load_tools` are always active and ready to use. Other tools above do NOT have their parameter schema attached yet: pass their names to `load_tools` before calling them to attach full schemas for the rest of this conversation.", "prompt.tools.lazy"));
206
206
  }
207
207
  parts.push("In addition to the tools above, you may have access to other custom tools depending on the project.");
208
208
  return parts.join("\n\n");
@@ -14,6 +14,8 @@ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID }
14
14
  import { existsSync, mkdirSync, readFileSync, writeFileSync, promises as fs } from "node:fs";
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
+ import { Readable } from "node:stream";
18
+ import { isAudioFile, previewKind } from "./text-sniff.js";
17
19
  const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 连接空闲 30 分钟自动断开
18
20
  const PROBE_TIMEOUT_MS = 25_000;
19
21
  const DEFAULT_KEY_CANDIDATES = ["~/.ssh/id_ed25519", "~/.ssh/id_ecdsa", "~/.ssh/id_rsa", "~/.ssh/id_dsa"];
@@ -917,9 +919,18 @@ done
917
919
  }
918
920
  try {
919
921
  const sftp = await this.getSftp(conn);
920
- const targetPath = (reqPath && reqPath.trim()) || conn.system?.homeDir || "/";
922
+ const homeDir = conn.system?.homeDir || "/";
923
+ let rawTarget = (reqPath && reqPath.trim()) || homeDir;
924
+ if (rawTarget === "~") {
925
+ rawTarget = homeDir;
926
+ }
927
+ else if (rawTarget.startsWith("~/") || rawTarget.startsWith("~\\")) {
928
+ rawTarget = path.posix.join(homeDir, rawTarget.slice(2).replace(/\\/g, "/"));
929
+ }
930
+ const normTarget = path.posix.normalize(rawTarget.replace(/\\/g, "/"));
931
+ const targetPath = normTarget !== "/" ? normTarget.replace(/\/+$/, "") || "/" : "/";
921
932
  return await new Promise((resolve) => {
922
- sftp.readdir(targetPath, (err, list) => {
933
+ sftp.readdir(targetPath, async (err, list) => {
923
934
  if (err) {
924
935
  return resolve({
925
936
  ok: false,
@@ -933,8 +944,22 @@ done
933
944
  for (const item of list) {
934
945
  if (item.filename === "." || item.filename === "..")
935
946
  continue;
936
- const isDir = Boolean(item.attrs.isDirectory());
937
947
  const fullPath = targetPath === "/" ? `/${item.filename}` : `${targetPath.replace(/\/+$/, "")}/${item.filename}`;
948
+ let isDir = Boolean(item.attrs.isDirectory?.());
949
+ const isSymlink = typeof item.attrs.isSymbolicLink === "function"
950
+ ? Boolean(item.attrs.isSymbolicLink())
951
+ : ((item.attrs.mode ?? 0) & 0o170000) === 0o120000;
952
+ if (!isDir && isSymlink && typeof sftp.stat === "function") {
953
+ try {
954
+ const st = await new Promise((resStat, rejStat) => {
955
+ sftp.stat(fullPath, (stErr, stats) => (stErr ? rejStat(stErr) : resStat(stats)));
956
+ });
957
+ isDir = Boolean(st?.isDirectory?.());
958
+ }
959
+ catch {
960
+ isDir = false;
961
+ }
962
+ }
938
963
  items.push({
939
964
  name: item.filename,
940
965
  path: fullPath,
@@ -1129,8 +1154,11 @@ fi
1129
1154
  for (const item of list) {
1130
1155
  if (item.filename === "." || item.filename === "..")
1131
1156
  continue;
1132
- let isDir = Boolean(item.attrs.isDirectory());
1133
- if (item.attrs.isSymbolicLink()) {
1157
+ let isDir = Boolean(item.attrs.isDirectory?.());
1158
+ const isSymlink = typeof item.attrs.isSymbolicLink === "function"
1159
+ ? Boolean(item.attrs.isSymbolicLink())
1160
+ : ((item.attrs.mode ?? 0) & 0o170000) === 0o120000;
1161
+ if (!isDir && isSymlink) {
1134
1162
  try {
1135
1163
  const target = path.posix.join(remoteAbsPath, item.filename);
1136
1164
  const st = await this.sftpStat(uri, target);
@@ -1149,6 +1177,18 @@ fi
1149
1177
  }
1150
1178
  return out;
1151
1179
  }
1180
+ /** SFTP 创建远程文件读取流(供 HTTP 下载与媒体流式预览使用) */
1181
+ async sftpCreateReadStream(uri, remoteAbsPath, opts) {
1182
+ const { sftp } = await this.getOrConnectByUri(uri);
1183
+ if (typeof sftp.createReadStream === "function") {
1184
+ return sftp.createReadStream(remoteAbsPath, opts);
1185
+ }
1186
+ const { data } = await this.sftpReadFile(uri, remoteAbsPath);
1187
+ const slice = opts?.start !== undefined || opts?.end !== undefined
1188
+ ? data.subarray(opts?.start ?? 0, opts?.end !== undefined ? opts.end + 1 : undefined)
1189
+ : data;
1190
+ return Readable.from(slice);
1191
+ }
1152
1192
  /** SFTP 读取远程文件 Buffer(可选限制最大读取字节数) */
1153
1193
  async sftpReadFile(uri, remoteAbsPath, maxBytes) {
1154
1194
  const { sftp } = await this.getOrConnectByUri(uri);
@@ -1377,3 +1417,116 @@ fi
1377
1417
  return virtualPty;
1378
1418
  }
1379
1419
  }
1420
+ /**
1421
+ * 通过 SFTP 流式响应远程工作区文件的 HTTP 下载与媒体/HTML 预览请求(/api/file 与 /api/preview)。
1422
+ */
1423
+ export async function serveRemoteWorkspaceFile(req, res, root, rawPath, opts, sshServiceOverride) {
1424
+ const parsed = parseRemoteWorkspaceUri(root);
1425
+ const sshSvc = sshServiceOverride ?? getGlobalRemoteSshService();
1426
+ if (!parsed || !sshSvc) {
1427
+ res.status(404).end("not found");
1428
+ return;
1429
+ }
1430
+ const trimmed = rawPath.trim();
1431
+ let remoteAbs;
1432
+ if (trimmed.startsWith("/")) {
1433
+ remoteAbs = path.posix.normalize(trimmed);
1434
+ if (remoteAbs === "/") {
1435
+ res.status(400).end("not a file");
1436
+ return;
1437
+ }
1438
+ }
1439
+ else {
1440
+ const w = resolveRemoteWorkspacePath(parsed.remotePath, trimmed);
1441
+ if (!w || w.rel === "") {
1442
+ res.status(400).end("path outside workspace");
1443
+ return;
1444
+ }
1445
+ remoteAbs = w.abs;
1446
+ }
1447
+ const name = path.posix.basename(remoteAbs);
1448
+ const kind = previewKind(name);
1449
+ const lower = name.toLowerCase();
1450
+ const isHtmlPreview = lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml");
1451
+ const isAudioPreview = isAudioFile(name);
1452
+ if (!opts.isDownload &&
1453
+ !opts.allowAllTypes &&
1454
+ kind !== "image" &&
1455
+ kind !== "video" &&
1456
+ !isHtmlPreview &&
1457
+ !isAudioPreview) {
1458
+ res.status(400).end("not a previewable media file");
1459
+ return;
1460
+ }
1461
+ const st = await sshSvc.sftpStat(root, remoteAbs);
1462
+ if (!st.isFile) {
1463
+ res.status(400).end("not a file");
1464
+ return;
1465
+ }
1466
+ res.type?.(name);
1467
+ if (opts.isDownload) {
1468
+ const asciiFallback = name.replace(/[^\x20-\x7e]|["\\]/g, "_");
1469
+ const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
1470
+ res.setHeader("Content-Disposition", `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encoded}`);
1471
+ }
1472
+ else {
1473
+ res.setHeader("X-Content-Type-Options", "nosniff");
1474
+ if (isHtmlPreview) {
1475
+ const allowJs = req.query?.allowJs === "1";
1476
+ res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
1477
+ }
1478
+ else if (lower.endsWith(".svg")) {
1479
+ res.setHeader("Content-Security-Policy", "sandbox");
1480
+ }
1481
+ }
1482
+ const rangeHeader = typeof req.headers?.range === "string" ? req.headers.range : "";
1483
+ let streamOpts;
1484
+ if (!opts.isDownload && rangeHeader && st.size > 0 && /^bytes=\d*-\d*$/.test(rangeHeader)) {
1485
+ const [startStr, endStr] = rangeHeader.slice(6).split("-");
1486
+ let start = startStr ? parseInt(startStr, 10) : 0;
1487
+ let end = endStr ? parseInt(endStr, 10) : st.size - 1;
1488
+ if (!startStr && endStr) {
1489
+ start = Math.max(0, st.size - parseInt(endStr, 10));
1490
+ end = st.size - 1;
1491
+ }
1492
+ if (start >= st.size || start > end || start < 0) {
1493
+ res.status(416);
1494
+ res.setHeader("Content-Range", `bytes */${st.size}`);
1495
+ res.end();
1496
+ return;
1497
+ }
1498
+ end = Math.min(end, st.size - 1);
1499
+ res.status(206);
1500
+ res.setHeader("Accept-Ranges", "bytes");
1501
+ res.setHeader("Content-Range", `bytes ${start}-${end}/${st.size}`);
1502
+ res.setHeader("Content-Length", String(end - start + 1));
1503
+ streamOpts = { start, end };
1504
+ }
1505
+ else {
1506
+ res.setHeader("Accept-Ranges", "bytes");
1507
+ res.setHeader("Content-Length", String(st.size));
1508
+ if (st.size === 0) {
1509
+ res.end();
1510
+ return;
1511
+ }
1512
+ }
1513
+ const stream = await sshSvc.sftpCreateReadStream(root, remoteAbs, streamOpts);
1514
+ await new Promise((resolveStream) => {
1515
+ stream.on("error", () => {
1516
+ if (!res.headersSent)
1517
+ res.status(404).end("not found");
1518
+ else
1519
+ res.destroy?.();
1520
+ resolveStream();
1521
+ });
1522
+ res.on("finish", () => resolveStream());
1523
+ res.on("close", () => resolveStream());
1524
+ req.on?.("close", () => {
1525
+ if ("destroy" in stream && typeof stream.destroy === "function") {
1526
+ stream.destroy();
1527
+ }
1528
+ resolveStream();
1529
+ });
1530
+ stream.pipe(res);
1531
+ });
1532
+ }
@@ -1,5 +1,6 @@
1
1
  import { splitQuotedPrompt } from "./text-quote.js";
2
2
  import { saveAttachmentSync } from "./attachment-store.js";
3
+ import { stripMarkers } from "./markers/index.js";
3
4
  export const TEXT_CAP = 200_000;
4
5
  export const TOOL_OUTPUT_CAP = 100_000;
5
6
  export const ARGS_CAP = 20_000;
@@ -143,10 +144,11 @@ function serializeUserContent(content) {
143
144
  return { type: "text", text: String(b.text ?? "") };
144
145
  });
145
146
  }
146
- function serializeAssistantContent(content) {
147
+ function serializeAssistantContent(content, streaming = false) {
147
148
  return content.map((b) => {
148
149
  if (b.type === "text") {
149
- const { text, truncated } = truncate(b.text, TEXT_CAP);
150
+ const cleaned = stripMarkers(b.text, { stripTrailingIncomplete: streaming });
151
+ const { text, truncated } = truncate(cleaned, TEXT_CAP);
150
152
  return { type: "text", text, truncated };
151
153
  }
152
154
  if (b.type === "thinking") {
@@ -291,19 +293,27 @@ export function serializeMessage(m, seq) {
291
293
  switch (m.role) {
292
294
  case "user": {
293
295
  const quotes = [];
296
+ const attachments = [];
294
297
  const raw = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content;
295
298
  const content = raw.map((block) => {
296
299
  if (block.type !== "text")
297
300
  return block;
298
301
  const parsed = splitQuotedPrompt(block.text);
299
302
  quotes.push(...parsed.quotes);
303
+ if (parsed.attachments?.length)
304
+ attachments.push(...parsed.attachments);
300
305
  return { ...block, text: parsed.text };
301
306
  });
307
+ const details = {};
308
+ if (quotes.length)
309
+ details.quotes = quotes;
310
+ if (attachments.length)
311
+ details.attachments = attachments;
302
312
  return {
303
313
  id,
304
314
  role: "user",
305
315
  content: serializeUserContent(content),
306
- ...(quotes.length ? { details: { quotes } } : {}),
316
+ ...(Object.keys(details).length ? { details } : {}),
307
317
  timestamp: m.timestamp,
308
318
  };
309
319
  }
@@ -460,5 +470,6 @@ export function serializeStreamingMessage(m) {
460
470
  const msg = serializeMessage(m, 0);
461
471
  if (!msg)
462
472
  return null;
463
- return { ...msg, id: `stream-${m.timestamp ?? 0}` };
473
+ const content = m.role === "assistant" ? serializeAssistantContent(m.content, true) : msg.content;
474
+ return { ...msg, id: `stream-${m.timestamp ?? 0}`, content };
464
475
  }