pi-web-ui 0.110.0 → 0.112.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -0,0 +1,119 @@
1
+ /**
2
+ * server/approval-audit.ts
3
+ *
4
+ * 审批决策与安全拦截审计日志(Append-Only Structured Audit Trail,Issue #722)。
5
+ *
6
+ * 记录每一个高危操作与自定义规则的安全事件:
7
+ * - 规则直接阻断(rule_denied)
8
+ * - 弹窗审批答复(user_approved / user_denied / user_edited)
9
+ * - 策略静默放行(suppressed_category / suppressed_all / suppressed_disabled)
10
+ * - 批量自动放行(batch_approved_policy / batch_approved_disabled)
11
+ *
12
+ * 存储路径:<dataDir>/audit/approvals.jsonl
13
+ * 轮转规则:单文件达到 10MB 自动轮转,最多保留 3 份归档。
14
+ */
15
+ import { existsSync, mkdirSync, statSync, renameSync, unlinkSync, appendFileSync, readFileSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+ const MAX_AUDIT_FILE_SIZE = 10 * 1024 * 1024; // 10MB
18
+ const MAX_BACKUP_FILES = 3;
19
+ /** 参数摘录与截断(单个字段最长 1024 字符,防止长文本撑爆审计日志)。 */
20
+ export function sanitizeAuditParams(params) {
21
+ if (params === null || params === undefined)
22
+ return params;
23
+ if (typeof params === "string") {
24
+ return params.length > 1024 ? `${params.slice(0, 1024)}... [truncated ${params.length} chars]` : params;
25
+ }
26
+ if (typeof params !== "object")
27
+ return params;
28
+ if (Array.isArray(params)) {
29
+ return params.slice(0, 20).map(sanitizeAuditParams);
30
+ }
31
+ const obj = params;
32
+ const out = {};
33
+ for (const [k, v] of Object.entries(obj)) {
34
+ out[k] = sanitizeAuditParams(v);
35
+ }
36
+ return out;
37
+ }
38
+ export class ApprovalAuditLogger {
39
+ logPath;
40
+ seq = 0;
41
+ constructor(dataDir) {
42
+ this.logPath = join(dataDir, "audit", "approvals.jsonl");
43
+ }
44
+ getFilePath() {
45
+ return this.logPath;
46
+ }
47
+ /** 记录一条审批/安全决策。 */
48
+ record(entry) {
49
+ try {
50
+ const now = Date.now();
51
+ const fullEntry = {
52
+ id: `audit-${now}-${++this.seq}`,
53
+ timestamp: now,
54
+ isoTime: new Date(now).toISOString(),
55
+ ...entry,
56
+ params: sanitizeAuditParams(entry.params),
57
+ };
58
+ this.rotateIfNeeded();
59
+ const dir = dirname(this.logPath);
60
+ if (!existsSync(dir)) {
61
+ mkdirSync(dir, { recursive: true });
62
+ }
63
+ appendFileSync(this.logPath, JSON.stringify(fullEntry) + "\n", "utf8");
64
+ }
65
+ catch (err) {
66
+ // 审计日志写入为旁路监控,绝不中断正常业务流,仅记录调试警告
67
+ console.warn("[approval-audit] Failed to write audit log:", err);
68
+ }
69
+ }
70
+ /** 检查文件大小并按需轮转。 */
71
+ rotateIfNeeded() {
72
+ if (!existsSync(this.logPath))
73
+ return;
74
+ try {
75
+ const stat = statSync(this.logPath);
76
+ if (stat.size < MAX_AUDIT_FILE_SIZE)
77
+ return;
78
+ for (let i = MAX_BACKUP_FILES - 1; i >= 1; i--) {
79
+ const src = this.logPath.replace(/\.jsonl$/, `.${i}.jsonl`);
80
+ const dst = this.logPath.replace(/\.jsonl$/, `.${i + 1}.jsonl`);
81
+ if (existsSync(src)) {
82
+ if (i === MAX_BACKUP_FILES - 1 && existsSync(dst)) {
83
+ unlinkSync(dst);
84
+ }
85
+ renameSync(src, dst);
86
+ }
87
+ }
88
+ const firstBackup = this.logPath.replace(/\.jsonl$/, ".1.jsonl");
89
+ if (existsSync(firstBackup))
90
+ unlinkSync(firstBackup);
91
+ renameSync(this.logPath, firstBackup);
92
+ }
93
+ catch (err) {
94
+ console.warn("[approval-audit] Log rotation failed:", err);
95
+ }
96
+ }
97
+ /** 读取最近 N 条审计记录(主要供单测和审计查看)。 */
98
+ readRecentEntries(limit = 100) {
99
+ if (!existsSync(this.logPath))
100
+ return [];
101
+ try {
102
+ const content = readFileSync(this.logPath, "utf8");
103
+ const lines = content.trim().split("\n").filter(Boolean);
104
+ const out = [];
105
+ for (let i = Math.max(0, lines.length - limit); i < lines.length; i++) {
106
+ try {
107
+ out.push(JSON.parse(lines[i]));
108
+ }
109
+ catch {
110
+ // 忽略单行解析异常
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ }
119
+ }
@@ -113,7 +113,7 @@ export const DEFAULT_APPROVAL_RULES = [
113
113
  {
114
114
  id: "builtin.file.sensitive.env",
115
115
  enabled: true,
116
- tools: ["write", "edit", "edit_soft"],
116
+ tools: ["write", "edit", "edit_soft", "patch"],
117
117
  field: "path",
118
118
  match: "regex",
119
119
  value: "(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$",
@@ -128,7 +128,7 @@ export const DEFAULT_APPROVAL_RULES = [
128
128
  {
129
129
  id: "builtin.file.sensitive.ssh",
130
130
  enabled: true,
131
- tools: ["write", "edit", "edit_soft"],
131
+ tools: ["write", "edit", "edit_soft", "patch"],
132
132
  field: "path",
133
133
  match: "regex",
134
134
  value: "(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$",
@@ -143,7 +143,7 @@ export const DEFAULT_APPROVAL_RULES = [
143
143
  {
144
144
  id: "builtin.file.sensitive.shell",
145
145
  enabled: true,
146
- tools: ["write", "edit", "edit_soft"],
146
+ tools: ["write", "edit", "edit_soft", "patch"],
147
147
  field: "path",
148
148
  match: "regex",
149
149
  value: "(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$",
@@ -158,7 +158,7 @@ export const DEFAULT_APPROVAL_RULES = [
158
158
  {
159
159
  id: "builtin.file.outside-workspace",
160
160
  enabled: true,
161
- tools: ["write", "edit", "edit_soft"],
161
+ tools: ["write", "edit", "edit_soft", "patch"],
162
162
  field: "path",
163
163
  match: "outside_workspace",
164
164
  value: "",
@@ -30,23 +30,30 @@
30
30
  * - 内存缓存 + 文件 mtime 感知,支持直接编辑 JSON 文件热生效。
31
31
  */
32
32
  import { existsSync, readFileSync, statSync } from "node:fs";
33
- import { resolve, sep } from "node:path";
33
+ import { isAbsolute, relative, resolve, sep } from "node:path";
34
34
  import { writeJsonAtomicSync } from "./atomic-file.js";
35
35
  import { DEFAULT_APPROVAL_RULES } from "./approval-default-rules.js";
36
36
  export { DEFAULT_APPROVAL_RULES };
37
+ /**
38
+ * 检测命令字符串中是否包含 Shell 复合操作符或子命令执行结构(分号、逻辑与/或、管道、反引号、换行、$())。
39
+ * 用于白名单(allow)规则防止借由安全前缀在复合命令中夹带高危操作(Issue #722)。
40
+ */
41
+ export const SHELL_COMPOUND_OPERATOR_RE = /(?:[;&|`\n]|\$\()/;
42
+ export function hasShellCompoundOperator(command) {
43
+ return SHELL_COMPOUND_OPERATOR_RE.test(command);
44
+ }
37
45
  /**
38
46
  * 跨平台判定 target 路径是否严格位于 root 目录内部或就是 root 本身。
39
47
  * 针对 Windows 盘符大小写不敏感及正反斜杠统一进行规范化,防止 .. 路径穿越逃逸。
40
48
  */
41
49
  export function isPathInsideRoot(target, root) {
42
- const normTarget = resolve(target);
43
- const normRoot = resolve(root);
44
- if (process.platform === "win32") {
45
- const lowerTarget = normTarget.toLowerCase();
46
- const lowerRoot = normRoot.toLowerCase();
47
- return (lowerTarget === lowerRoot || lowerTarget.startsWith(lowerRoot + sep) || lowerTarget.startsWith(lowerRoot + "/"));
48
- }
49
- return normTarget === normRoot || normTarget.startsWith(normRoot + sep);
50
+ const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
51
+ const rel = relative(fold(resolve(root)), fold(resolve(target)));
52
+ if (rel === "")
53
+ return true;
54
+ if (isAbsolute(rel))
55
+ return false;
56
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !rel.startsWith("../");
50
57
  }
51
58
  /**
52
59
  * 极简 glob 转 RegExp(只支持 * 单段、? 单字符、** 跨段)。
@@ -139,6 +146,10 @@ export function matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceR
139
146
  const fieldValue = extractRuleFieldValue(rule.field, toolName, params);
140
147
  if (!fieldValue)
141
148
  return [];
149
+ if (rule.action === "allow" && rule.field === "command" && hasShellCompoundOperator(fieldValue)) {
150
+ const single = matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots);
151
+ return single ? [single] : [];
152
+ }
142
153
  let re;
143
154
  try {
144
155
  re = new RegExp(rule.value, "gi");
@@ -186,61 +197,75 @@ export function matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRo
186
197
  if (!fieldValue)
187
198
  return null;
188
199
  // 4. 按 match kind 进行文本判定并提取命中区间
200
+ let matched = null;
189
201
  switch (rule.match) {
190
202
  case "regex": {
191
203
  try {
192
204
  const re = new RegExp(rule.value, "i");
193
205
  const m = re.exec(fieldValue);
194
206
  if (m) {
195
- return {
207
+ matched = {
196
208
  index: m.index,
197
209
  length: m[0].length,
198
210
  text: m[0],
199
211
  };
200
212
  }
201
- return null;
202
213
  }
203
214
  catch {
204
215
  return null;
205
216
  }
217
+ break;
206
218
  }
207
219
  case "glob": {
208
220
  try {
209
221
  const re = globToRegex(rule.value);
210
222
  const normalized = fieldValue.replace(/\\/g, "/");
211
223
  if (re.test(normalized)) {
212
- return { index: 0, length: fieldValue.length, text: fieldValue };
224
+ matched = { index: 0, length: fieldValue.length, text: fieldValue };
213
225
  }
214
- return null;
215
226
  }
216
227
  catch {
217
228
  return null;
218
229
  }
230
+ break;
219
231
  }
220
232
  case "contains": {
221
233
  const idx = fieldValue.toLowerCase().indexOf(rule.value.toLowerCase());
222
234
  if (idx >= 0) {
223
- return {
235
+ matched = {
224
236
  index: idx,
225
237
  length: rule.value.length,
226
238
  text: fieldValue.slice(idx, idx + rule.value.length),
227
239
  };
228
240
  }
229
- return null;
241
+ break;
230
242
  }
231
243
  case "prefix": {
232
244
  if (fieldValue.toLowerCase().startsWith(rule.value.toLowerCase())) {
233
- return {
245
+ matched = {
234
246
  index: 0,
235
247
  length: rule.value.length,
236
248
  text: fieldValue.slice(0, rule.value.length),
237
249
  };
238
250
  }
239
- return null;
251
+ break;
240
252
  }
241
253
  default:
242
254
  return null;
243
255
  }
256
+ if (!matched)
257
+ return null;
258
+ // 复合命令白名单防逃逸(Issue #722):
259
+ // 当动作为 allow(免审放行)且字段为 command 时,如果整段命令包含复合操作符(; && || | \n $() `),
260
+ // 且该白名单匹配未完全覆盖整条命令输入,禁止仅凭前缀、子串或通配符放行整条复合命令,
261
+ // 防止如 `git status && rm -rf /` 借由安全前缀绕过后续的高危规则拦截。
262
+ if (rule.action === "allow" &&
263
+ rule.field === "command" &&
264
+ hasShellCompoundOperator(fieldValue) &&
265
+ matched.text.trim().length < fieldValue.trim().length) {
266
+ return null;
267
+ }
268
+ return matched;
244
269
  }
245
270
  /**
246
271
  * 单条规则针对具体工具调用的匹配判定(纯函数)。
@@ -8,9 +8,10 @@
8
8
  * - 避免快照和消息列表随会话进行出现数兆字节 base64 的膨胀。
9
9
  */
10
10
  import { createHash, randomUUID } from "node:crypto";
11
- import { mkdirSync, existsSync, readdirSync, writeFileSync, renameSync, rmSync } from "node:fs";
11
+ import { mkdirSync, existsSync, readdirSync } from "node:fs";
12
12
  import { readFile, rename, rm, writeFile, stat } from "node:fs/promises";
13
13
  import { join, extname } from "node:path";
14
+ import { writeAtomicSync } from "./atomic-file.js";
14
15
  let storeDir = "";
15
16
  /** 初始化附件存储目录(服务启动时调用)。 */
16
17
  export function initAttachmentStore(dataDir) {
@@ -92,16 +93,10 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
92
93
  const fileName = `${hash}${ext}`;
93
94
  const filePath = join(storeDir, fileName);
94
95
  if (!existsSync(filePath)) {
95
- const tmpPath = `${filePath}.${randomUUID()}.tmp`;
96
96
  try {
97
- writeFileSync(tmpPath, buffer);
98
- renameSync(tmpPath, filePath);
97
+ writeAtomicSync(filePath, buffer);
99
98
  }
100
99
  catch (err) {
101
- try {
102
- rmSync(tmpPath, { force: true });
103
- }
104
- catch { }
105
100
  const code = err.code;
106
101
  if (code === "EEXIST") {
107
102
  // 并发写同哈希:目标已在,按「已存在」成功路径返回
@@ -115,6 +110,11 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
115
110
  throw err;
116
111
  }
117
112
  }
113
+ if (!existsSync(filePath)) {
114
+ const err = new Error(`EPERM: target file does not exist after write ${filePath}`);
115
+ err.code = "EPERM";
116
+ throw err;
117
+ }
118
118
  }
119
119
  return {
120
120
  hash,
@@ -4,6 +4,7 @@ import { saveUpload, uploadsRoot } from "./uploads.js";
4
4
  import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
5
5
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
6
6
  import { saveAttachment } from "./attachment-store.js";
7
+ import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, } from "./remote-ssh-service.js";
7
8
  /** 跨快照的视觉转写缓存:批次 hash(名称 + base64 头 + 提示词)→ 转写文本。
8
9
  * 编辑重问重发相同图片不再重复耗视觉 token。进程级共享即可。
9
10
  * 长驻进程下无界 Map 会随图片种类缓慢吃内存(单条转写可达数十 KB),
@@ -36,8 +37,38 @@ export async function buildAttachmentMessages(ctx, attachments) {
36
37
  if (!attachments || attachments.length === 0)
37
38
  return [];
38
39
  const fs = await import("node:fs/promises");
39
- const { resolve, sep, relative, extname, basename } = await import("node:path");
40
- const root = resolve(ctx.cwd);
40
+ const { resolve, sep, relative, extname, basename, posix } = await import("node:path");
41
+ const isRemote = isRemoteWorkspaceUri(ctx.cwd);
42
+ const remoteParsed = isRemote ? parseRemoteWorkspaceUri(ctx.cwd) : null;
43
+ const remoteRoot = remoteParsed ? remoteParsed.remotePath : "/";
44
+ const sshSvc = isRemote ? getGlobalRemoteSshService() : null;
45
+ const root = isRemote ? "" : resolve(ctx.cwd);
46
+ const resolveTarget = (attPath) => {
47
+ if (isRemote) {
48
+ let clean = attPath.trim();
49
+ if (isRemoteWorkspaceUri(clean)) {
50
+ const p = parseRemoteWorkspaceUri(clean);
51
+ if (p)
52
+ clean = p.remotePath;
53
+ }
54
+ if (clean.startsWith("/")) {
55
+ const abs = posix.normalize(clean);
56
+ const rawRel = posix.relative(remoteRoot, abs);
57
+ const isOutside = rawRel.startsWith("..") || rawRel.includes("/..");
58
+ return { abs, rel: isOutside ? abs : rawRel || ".", isOutside: false };
59
+ }
60
+ const w = resolveRemoteWorkspacePath(remoteRoot, clean);
61
+ if (!w)
62
+ return null;
63
+ return { abs: w.abs, rel: w.rel || ".", isOutside: false };
64
+ }
65
+ const absPath = isAbsoluteWirePath(attPath);
66
+ const abs = absPath ? wireToAbs(attPath) : resolve(root, attPath);
67
+ const rawRel = absPath ? null : relative(root, abs);
68
+ const isOutside = !absPath && (rawRel.startsWith("..") || rawRel.includes(`${sep}..`));
69
+ const rel = absPath ? abs.split(sep).join("/") : rawRel.split(sep).join("/");
70
+ return { abs, rel, isOutside };
71
+ };
41
72
  const MAX_ATTACHMENT_BYTES = 200 * 1024;
42
73
  const IMAGE_EXT = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"]);
43
74
  const MIME = {
@@ -111,23 +142,42 @@ export async function buildAttachmentMessages(ctx, attachments) {
111
142
  const ext = extname(att.path).toLowerCase();
112
143
  if (!IMAGE_EXT.has(ext) || ext === ".svg")
113
144
  continue;
114
- // 机器浏览的绝对路径(盘符 / posix "/")允许在工作区之外。
115
- const absPath = isAbsoluteWirePath(att.path);
116
- const abs = absPath ? wireToAbs(att.path) : resolve(root, att.path);
117
- const rawRel = absPath ? null : relative(root, abs);
118
- if (!absPath && (rawRel.startsWith("..") || rawRel.includes(`${sep}..`)))
145
+ const target = resolveTarget(att.path);
146
+ if (!target || target.isOutside)
119
147
  continue;
120
148
  let st;
121
- try {
122
- st = await fs.stat(abs);
149
+ if (isRemote) {
150
+ if (!sshSvc)
151
+ continue;
152
+ try {
153
+ const s = await sshSvc.sftpStat(ctx.cwd, target.abs);
154
+ st = { size: s.size, isFile: s.isFile };
155
+ }
156
+ catch {
157
+ continue;
158
+ }
123
159
  }
124
- catch {
160
+ else {
161
+ try {
162
+ const s = await fs.stat(target.abs);
163
+ st = { size: s.size, isFile: s.isFile() };
164
+ }
165
+ catch {
166
+ continue;
167
+ }
168
+ }
169
+ if (!st.isFile || st.size === 0 || st.size > MAX_PATH_IMAGE_BYTES) {
125
170
  continue;
126
171
  }
127
- if (!st.isFile() || st.size === 0 || st.size > MAX_PATH_IMAGE_BYTES) {
172
+ let buf;
173
+ try {
174
+ buf = isRemote
175
+ ? (await sshSvc.sftpReadFile(ctx.cwd, target.abs, MAX_PATH_IMAGE_BYTES)).data
176
+ : await fs.readFile(target.abs);
177
+ }
178
+ catch {
128
179
  continue;
129
180
  }
130
- const buf = await fs.readFile(abs);
131
181
  const mime = sniffImageMime(buf, ext);
132
182
  if (!mime)
133
183
  continue;
@@ -508,10 +558,8 @@ export async function buildAttachmentMessages(ctx, attachments) {
508
558
  pushUploadAside(att.name ?? basename(abs), abs.split(sep).join("/"), buf);
509
559
  continue;
510
560
  }
511
- const absPath = isAbsoluteWirePath(att.path);
512
- const abs = absPath ? wireToAbs(att.path) : resolve(root, att.path);
513
- const rawRel = absPath ? null : relative(root, abs);
514
- if (!absPath && (rawRel.startsWith("..") || rawRel.includes(`${sep}..`))) {
561
+ const target = resolveTarget(att.path);
562
+ if (!target || target.isOutside) {
515
563
  ctx.emit({
516
564
  type: "notice",
517
565
  level: "warning",
@@ -520,22 +568,49 @@ export async function buildAttachmentMessages(ctx, attachments) {
520
568
  });
521
569
  continue;
522
570
  }
523
- // Normalize to forward slashes (relative() returns "\\" on Windows);
524
- // <file path> and details.path must use the wire format. 机器浏览的绝对
525
- // 路径直接按绝对路径引用(SDK 读文件工具接受绝对路径,与上传文件一致)。
526
- const rel = absPath ? abs.split(sep).join("/") : rawRel.split(sep).join("/");
571
+ const { abs, rel } = target;
527
572
  let stat;
528
- try {
529
- stat = await fs.stat(abs);
573
+ if (isRemote) {
574
+ if (!sshSvc) {
575
+ ctx.emit({
576
+ type: "notice",
577
+ level: "error",
578
+ text: `远程 SSH 服务不可用:${att.path}`,
579
+ textEn: `Remote SSH service not available: ${att.path}`,
580
+ });
581
+ continue;
582
+ }
583
+ try {
584
+ const s = await sshSvc.sftpStat(ctx.cwd, abs);
585
+ stat = {
586
+ size: s.size,
587
+ isFile: () => s.isFile,
588
+ isDirectory: () => s.isDirectory,
589
+ };
590
+ }
591
+ catch {
592
+ ctx.emit({
593
+ type: "notice",
594
+ level: "error",
595
+ text: `附件不存在:${att.path}`,
596
+ textEn: `Attachment does not exist: ${att.path}`,
597
+ });
598
+ continue;
599
+ }
530
600
  }
531
- catch {
532
- ctx.emit({
533
- type: "notice",
534
- level: "error",
535
- text: `附件不存在:${att.path}`,
536
- textEn: `Attachment does not exist: ${att.path}`,
537
- });
538
- continue;
601
+ else {
602
+ try {
603
+ stat = await fs.stat(abs);
604
+ }
605
+ catch {
606
+ ctx.emit({
607
+ type: "notice",
608
+ level: "error",
609
+ text: `附件不存在:${att.path}`,
610
+ textEn: `Attachment does not exist: ${att.path}`,
611
+ });
612
+ continue;
613
+ }
539
614
  }
540
615
  const name = att.path.split(/[\\/]/).pop() ?? att.path;
541
616
  // Folders can't be inlined — always a path reference the model browses
@@ -634,7 +709,15 @@ ${transcript}
634
709
  });
635
710
  continue;
636
711
  }
637
- const data = await fs.readFile(abs, "base64");
712
+ let data;
713
+ try {
714
+ data = isRemote
715
+ ? (await sshSvc.sftpReadFile(ctx.cwd, abs, MAX_ATTACHMENT_BYTES)).data.toString("base64")
716
+ : await fs.readFile(abs, "base64");
717
+ }
718
+ catch {
719
+ continue;
720
+ }
638
721
  out.push({
639
722
  message: {
640
723
  customType: "file",