agent-loft 0.2.90 → 0.2.94

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.
@@ -0,0 +1,315 @@
1
+ // 工作区面板的文件部分:列出会话工作目录里的文件,解析出能给前端看的路径,以及编辑、新建、重命名、删除、上传。
2
+ //
3
+ // 和 core/reply-files.ts 的区别:回复里的文件只认 agent 写过的路径;这里是用户主动浏览,
4
+ // 范围换成「会话的工作目录之内」,接口只收相对路径。能不能用面板由 users.ts 的 canUseFiles 决定。
5
+ //
6
+ // 三道关:
7
+ // 1. 写法上不能跳出工作目录(../、绝对路径);
8
+ // 2. 解析符号链接后不能跳出工作区根目录(链接到同一工作区的别的项目可以);
9
+ // 3. 解析前后都不能是敏感文件(isSensitivePath)或 .git 目录里的东西 ——
10
+ // .git/config 的远程地址里可能带着令牌。
11
+ // 写操作走同样的规矩,敏感文件和 .git 里的东西也写不了。
12
+ import crypto from "node:crypto";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { config, resolveWorkspacePath } from "./config.js";
16
+ import { isSensitivePath } from "./reply-files.js";
17
+
18
+ /** 一个目录最多列这么多项:node_modules 这种没人会一项项翻 */
19
+ const LIST_MAX = 2000;
20
+
21
+ export type WorkspaceEntry = {
22
+ name: string;
23
+ /** 相对工作目录 */
24
+ path: string;
25
+ type: "dir" | "file";
26
+ /** 目录没有大小 */
27
+ size?: number;
28
+ mtime: number;
29
+ /** 符号链接:显示时标一下,指向的类型算在 type 里 */
30
+ link?: boolean;
31
+ };
32
+
33
+ export type WorkspaceListing = {
34
+ /** 相对工作目录,根目录是 "" */
35
+ path: string;
36
+ entries: WorkspaceEntry[];
37
+ /** 项太多,只列了前一部分 */
38
+ truncated: boolean;
39
+ };
40
+
41
+ function inside(dir: string, target: string): boolean {
42
+ return target === dir || target.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
43
+ }
44
+
45
+ /** 不分大小写的文件系统(macOS、Windows)上 .GIT 就是 .git */
46
+ function blocked(file: string): boolean {
47
+ return file.split(path.sep).some((part) => part.toLowerCase() === ".git") || isSensitivePath(file);
48
+ }
49
+
50
+ /** 给页面的相对路径一律用斜杠,Windows 上也一样 */
51
+ const toPosix = (rel: string): string => (path.sep === "/" ? rel : rel.split(path.sep).join("/"));
52
+
53
+ /** 会话的工作目录。目录没了、配置改过后不在工作区之内:undefined */
54
+ export function workspaceDir(cwd: string): string | undefined {
55
+ return resolveWorkspacePath(cwd) ?? undefined;
56
+ }
57
+
58
+ /** 相对路径 → 绝对路径和解析符号链接后的路径。不合规矩返回 undefined */
59
+ function resolveEntry(cwd: string, rel: string): { abs: string; real: string; stat: fs.Stats } | undefined {
60
+ if (rel.includes("\0") || path.isAbsolute(rel)) return undefined;
61
+ const abs = path.resolve(cwd, rel);
62
+ if (!inside(cwd, abs) || blocked(abs)) return undefined;
63
+ try {
64
+ const real = fs.realpathSync(abs);
65
+ if (!inside(fs.realpathSync(config().workspaceRoot), real) || blocked(real)) return undefined;
66
+ return { abs, real, stat: fs.statSync(real) };
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ }
71
+
72
+ /** 解析成可以给前端看的真实文件路径。不存在、不是普通文件、不能看:undefined */
73
+ export function resolveWorkspaceFile(cwd: string, rel: string): string | undefined {
74
+ const entry = rel ? resolveEntry(cwd, rel) : undefined;
75
+ return entry?.stat.isFile() ? entry.real : undefined;
76
+ }
77
+
78
+ /** 列一层目录:目录在前,按名字自然排序。不能看的(敏感文件、跳出工作区的链接)直接不出现 */
79
+ export function listWorkspaceEntries(cwd: string, rel: string): WorkspaceListing | undefined {
80
+ const dir = resolveEntry(cwd, rel);
81
+ if (!dir?.stat.isDirectory()) return undefined;
82
+ const base = toPosix(path.relative(cwd, dir.abs));
83
+ let names: fs.Dirent[];
84
+ try {
85
+ names = fs.readdirSync(dir.real, { withFileTypes: true });
86
+ } catch {
87
+ return undefined;
88
+ }
89
+ const collator = new Intl.Collator("zh-CN", { numeric: true, sensitivity: "base" });
90
+ // 目录排前面再截断:项太多时不至于把目录截掉(指向目录的符号链接到后面才知道,最后再排一次)
91
+ names.sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || collator.compare(a.name, b.name));
92
+ const entries: WorkspaceEntry[] = [];
93
+ let truncated = false;
94
+ for (const item of names) {
95
+ if (entries.length >= LIST_MAX) {
96
+ truncated = true;
97
+ break;
98
+ }
99
+ const child = base ? `${base}/${item.name}` : item.name;
100
+ const found = resolveEntry(cwd, child);
101
+ if (!found) continue;
102
+ const isDir = found.stat.isDirectory();
103
+ // 管道、设备文件之类的打开了也看不了
104
+ if (!isDir && !found.stat.isFile()) continue;
105
+ entries.push({
106
+ name: item.name,
107
+ path: child,
108
+ type: isDir ? "dir" : "file",
109
+ ...(isDir ? {} : { size: found.stat.size }),
110
+ mtime: found.stat.mtimeMs,
111
+ ...(item.isSymbolicLink() ? { link: true } : {}),
112
+ });
113
+ }
114
+ entries.sort((a, b) => Number(b.type === "dir") - Number(a.type === "dir"));
115
+ return { path: base, entries, truncated };
116
+ }
117
+
118
+ // ---------- 编辑 ----------
119
+
120
+ /** 能在网页里编辑的文件大小上限(和预览时读的上限一致:超过的只读得到开头,保存会把文件截断) */
121
+ export const EDIT_MAX_BYTES = 1024 * 1024;
122
+ /** 保存时收的内容上限:编辑时可能粘贴进更多内容 */
123
+ export const SAVE_MAX_BYTES = 8 * 1024 * 1024;
124
+ /** 上传到工作目录的文件上限(和对话附件一致) */
125
+ export const UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
126
+
127
+ /** 带 HTTP 状态的错误:接口层照着回 */
128
+ export class WorkspaceError extends Error {
129
+ constructor(
130
+ readonly status: number,
131
+ message: string,
132
+ readonly extra: Record<string, unknown> = {},
133
+ ) {
134
+ super(message);
135
+ }
136
+ }
137
+
138
+ const hashOf = (data: Buffer | string) => crypto.createHash("sha256").update(data).digest("hex");
139
+
140
+ export type WorkspaceText = { path: string; name: string; content: string; hash: string; size: number; mtime: number };
141
+
142
+ /** 读出来编辑。太大、不是文本、不是 UTF-8 的不给编辑 —— 改完存回去内容会坏 */
143
+ export function readWorkspaceText(cwd: string, rel: string): WorkspaceText {
144
+ const file = resolveWorkspaceFile(cwd, rel);
145
+ if (!file) throw new WorkspaceError(404, "文件不存在,或者不能查看");
146
+ const st = fs.statSync(file);
147
+ if (st.size > EDIT_MAX_BYTES) throw new WorkspaceError(413, "文件超过 1 MB,不能在网页里编辑");
148
+ const data = fs.readFileSync(file);
149
+ if (data.includes(0)) throw new WorkspaceError(415, "这个文件不是文本,不能编辑");
150
+ const content = data.toString("utf8");
151
+ if (!Buffer.from(content, "utf8").equals(data)) throw new WorkspaceError(415, "这个文件不是 UTF-8 编码,保存会损坏内容,不能编辑");
152
+ return { path: rel, name: path.basename(file), content, hash: hashOf(data), size: st.size, mtime: st.mtimeMs };
153
+ }
154
+
155
+ function isErrno(err: unknown, ...codes: string[]): boolean {
156
+ return codes.includes((err as NodeJS.ErrnoException).code ?? "");
157
+ }
158
+
159
+ function writeError(err: unknown, action: string): WorkspaceError {
160
+ if (err instanceof WorkspaceError) return err;
161
+ if (isErrno(err, "EACCES", "EPERM", "EROFS")) return new WorkspaceError(403, `没有权限${action}`);
162
+ if (isErrno(err, "ENOSPC", "EDQUOT")) return new WorkspaceError(507, "磁盘空间不足");
163
+ return new WorkspaceError(500, `${action}失败:${err instanceof Error ? err.message : String(err)}`);
164
+ }
165
+
166
+ /** 先写到同目录的临时文件再改名:写到一半出错、断电,原文件都还是完整的。保留原来的权限 */
167
+ function writeAtomic(file: string, data: Buffer, mode?: number): void {
168
+ const temp = path.join(path.dirname(file), `.${path.basename(file).slice(0, 100)}.${crypto.randomBytes(4).toString("hex")}.aloft-tmp`);
169
+ try {
170
+ fs.writeFileSync(temp, data, { flag: "wx", ...(mode !== undefined ? { mode } : {}) });
171
+ // writeFile 的 mode 会被 umask 削掉
172
+ if (mode !== undefined) fs.chmodSync(temp, mode);
173
+ fs.renameSync(temp, file);
174
+ } catch (err) {
175
+ fs.rmSync(temp, { force: true });
176
+ throw err;
177
+ }
178
+ }
179
+
180
+ /**
181
+ * 保存。baseHash 是读出来时的内容 hash:文件这期间被 agent 或别人改过就返回 409,不覆盖;
182
+ * force 明确要覆盖时不看 hash。文件已经被删掉:一样算冲突,force 时重新创建。
183
+ */
184
+ export function saveWorkspaceText(cwd: string, rel: string, content: string, opts: { baseHash?: string; force?: boolean }): { hash: string; size: number; mtime: number } {
185
+ const data = Buffer.from(content, "utf8");
186
+ const existing = rel ? resolveEntry(cwd, rel) : undefined;
187
+ let target: string;
188
+ let mode: number | undefined;
189
+ if (existing) {
190
+ if (!existing.stat.isFile()) throw new WorkspaceError(400, "这不是文件,不能保存");
191
+ target = existing.real;
192
+ mode = existing.stat.mode & 0o7777;
193
+ if (!opts.force && hashOf(fs.readFileSync(target)) !== opts.baseHash) {
194
+ throw new WorkspaceError(409, "文件已经被改过了", { conflict: "changed" });
195
+ }
196
+ // 改名替换不看文件本身的权限,只读文件得在这里挡住
197
+ try {
198
+ fs.accessSync(target, fs.constants.W_OK);
199
+ } catch {
200
+ throw new WorkspaceError(403, "这个文件是只读的");
201
+ }
202
+ } else {
203
+ target = resolveNewEntry(cwd, path.dirname(rel) === "." ? "" : path.dirname(rel), path.basename(rel));
204
+ // 路径上有东西但看不了(比如跳出工作区的链接):不能把它换成一个文件
205
+ if (fs.lstatSync(target, { throwIfNoEntry: false })) throw new WorkspaceError(404, "文件不存在,或者不能查看");
206
+ if (!opts.force) throw new WorkspaceError(409, "文件已经被删掉了", { conflict: "deleted" });
207
+ }
208
+ try {
209
+ writeAtomic(target, data, mode);
210
+ } catch (err) {
211
+ throw writeError(err, "保存");
212
+ }
213
+ const st = fs.statSync(target);
214
+ return { hash: hashOf(data), size: st.size, mtime: st.mtimeMs };
215
+ }
216
+
217
+ // ---------- 新建、重命名、删除、上传 ----------
218
+
219
+ function checkName(name: unknown): string {
220
+ const n = typeof name === "string" ? name.trim() : "";
221
+ if (!n || n === "." || n === ".." || /[\\/\x00-\x1f\x7f]/.test(n) || Buffer.byteLength(n) > 255) {
222
+ throw new WorkspaceError(400, "请输入有效的名称,不能包含斜杠或控制字符");
223
+ }
224
+ return n;
225
+ }
226
+
227
+ /** 要在 dir(相对工作目录)里新建的东西的绝对路径:目录要存在且能看,新名字不能是敏感文件 */
228
+ function resolveNewEntry(cwd: string, dir: string, name: unknown): string {
229
+ const n = checkName(name);
230
+ const parent = resolveEntry(cwd, dir);
231
+ if (!parent?.stat.isDirectory()) throw new WorkspaceError(404, "目录不存在,或者不能查看");
232
+ const target = path.join(parent.real, n);
233
+ if (blocked(target) || blocked(path.join(parent.abs, n))) throw new WorkspaceError(403, "敏感文件和 .git 里的东西不能在这里操作");
234
+ return target;
235
+ }
236
+
237
+ function assertFree(target: string): void {
238
+ if (fs.lstatSync(target, { throwIfNoEntry: false })) throw new WorkspaceError(409, "同名文件或文件夹已存在");
239
+ }
240
+
241
+ export function createWorkspaceEntry(cwd: string, dir: string, name: unknown, type: unknown): { path: string; type: "file" | "dir" } {
242
+ const target = resolveNewEntry(cwd, dir, name);
243
+ assertFree(target);
244
+ const kind = type === "dir" ? "dir" : "file";
245
+ try {
246
+ if (kind === "dir") fs.mkdirSync(target);
247
+ else fs.writeFileSync(target, "", { flag: "wx" });
248
+ } catch (err) {
249
+ if (isErrno(err, "EEXIST")) throw new WorkspaceError(409, "同名文件或文件夹已存在");
250
+ throw writeError(err, "新建");
251
+ }
252
+ return { path: toPosix(path.join(dir, path.basename(target))), type: kind };
253
+ }
254
+
255
+ /**
256
+ * 要改名、删除的东西本身(不跟符号链接:删链接不能变成删它指向的内容)。
257
+ * 工作目录本身不行;目录里有别的会话的工作目录也不行,那些会话要从项目菜单里处理。
258
+ */
259
+ function resolveExisting(cwd: string, rel: string, conversationDirs: string[]): { target: string; isDir: boolean } {
260
+ if (!rel || rel.includes("\0") || path.isAbsolute(rel)) throw new WorkspaceError(404, "文件不存在,或者不能操作");
261
+ const abs = path.resolve(cwd, rel);
262
+ if (abs === cwd || !inside(cwd, abs)) throw new WorkspaceError(403, "不能操作工作目录本身");
263
+ const parent = resolveEntry(cwd, path.relative(cwd, path.dirname(abs)));
264
+ if (!parent?.stat.isDirectory()) throw new WorkspaceError(404, "文件不存在,或者不能操作");
265
+ const target = path.join(parent.real, path.basename(abs));
266
+ if (blocked(target) || blocked(abs)) throw new WorkspaceError(404, "文件不存在,或者不能操作");
267
+ const st = fs.lstatSync(target, { throwIfNoEntry: false });
268
+ if (!st) throw new WorkspaceError(404, "文件不存在,或者不能操作");
269
+ if (st.isDirectory() && conversationDirs.some((dir) => inside(target, dir))) {
270
+ throw new WorkspaceError(409, "这个目录是其他会话的工作目录,或者包含其他会话的工作目录,不能在这里操作");
271
+ }
272
+ return { target, isDir: st.isDirectory() };
273
+ }
274
+
275
+ export function renameWorkspaceEntry(cwd: string, rel: string, name: unknown, conversationDirs: string[]): { path: string } {
276
+ const { target } = resolveExisting(cwd, rel, conversationDirs);
277
+ const relDir = path.dirname(rel) === "." ? "" : path.dirname(rel);
278
+ const next = resolveNewEntry(cwd, relDir, name);
279
+ if (next === target) return { path: rel };
280
+ // 不分大小写的文件系统上,只改大小写时新旧名字是同一个文件,不算重名
281
+ const from = fs.lstatSync(target);
282
+ const to = fs.lstatSync(next, { throwIfNoEntry: false });
283
+ if (to && (to.ino !== from.ino || to.dev !== from.dev)) throw new WorkspaceError(409, "同名文件或文件夹已存在");
284
+ try {
285
+ fs.renameSync(target, next);
286
+ } catch (err) {
287
+ if (isErrno(err, "EEXIST", "ENOTEMPTY")) throw new WorkspaceError(409, "同名文件或文件夹已存在");
288
+ throw writeError(err, "重命名");
289
+ }
290
+ return { path: toPosix(path.join(relDir, path.basename(next))) };
291
+ }
292
+
293
+ export function deleteWorkspaceEntry(cwd: string, rel: string, conversationDirs: string[]): void {
294
+ const { target, isDir } = resolveExisting(cwd, rel, conversationDirs);
295
+ try {
296
+ if (isDir) fs.rmSync(target, { recursive: true });
297
+ else fs.unlinkSync(target);
298
+ } catch (err) {
299
+ throw writeError(err, "删除");
300
+ }
301
+ }
302
+
303
+ export function uploadWorkspaceFile(cwd: string, dir: string, name: unknown, data: Buffer, overwrite: boolean): { path: string } {
304
+ const target = resolveNewEntry(cwd, dir, name);
305
+ const st = fs.lstatSync(target, { throwIfNoEntry: false });
306
+ if (st && !overwrite) throw new WorkspaceError(409, "同名文件已存在", { conflict: "exists" });
307
+ // 不替换目录,也不替换符号链接:把链接换成文件多半不是想要的结果
308
+ if (st && !st.isFile()) throw new WorkspaceError(409, "同名的文件夹或链接已存在,不能覆盖");
309
+ try {
310
+ writeAtomic(target, data, st ? st.mode & 0o7777 : undefined);
311
+ } catch (err) {
312
+ throw writeError(err, "上传");
313
+ }
314
+ return { path: toPosix(path.join(dir, path.basename(target))) };
315
+ }
@@ -23,11 +23,13 @@
23
23
  min-width: 0;
24
24
  }
25
25
 
26
- .tool-check-item > input {
26
+ .tool-check-item > input,
27
+ .perm-list > .check-item > input {
27
28
  flex-shrink: 0;
28
29
  }
29
30
 
30
- .tool-check-item > span {
31
+ .tool-check-item > span,
32
+ .perm-list > .check-item > span {
31
33
  flex: 0 0 auto;
32
34
  max-width: calc(100% - 28px);
33
35
  white-space: nowrap;
@@ -35,7 +37,8 @@
35
37
  text-overflow: ellipsis;
36
38
  }
37
39
 
38
- .tool-check-item > small {
40
+ .tool-check-item > small,
41
+ .perm-list > .check-item > small {
39
42
  flex: 1;
40
43
  }
41
44
 
@@ -1,5 +1,36 @@
1
1
  /* ---------- 设置 ---------- */
2
2
 
3
+ /* 设置和从设置打开的弹层共用黑白主题,覆盖原生控件的系统强调色。 */
4
+ .settings,
5
+ body:has(.settings) > :is(.overlay, .menu) {
6
+ --accent: var(--fg);
7
+ --accent-fg: var(--bg);
8
+ --link: var(--fg);
9
+ accent-color: var(--accent);
10
+ }
11
+
12
+ :is(.settings, body:has(.settings) > .overlay, body:has(.settings) > .menu) a:not(.btn) {
13
+ color: var(--link);
14
+ }
15
+
16
+ :is(.settings, body:has(.settings) > .overlay, body:has(.settings) > .menu) .switch input:checked + .slider::before {
17
+ background: var(--accent-fg);
18
+ }
19
+
20
+ :is(.settings, body:has(.settings) > .overlay, body:has(.settings) > .menu) .btn.accent:hover:not(:disabled) {
21
+ opacity: 0.85;
22
+ }
23
+
24
+ :is(.settings, body:has(.settings) > .overlay, body:has(.settings) > .menu) .btn:disabled {
25
+ opacity: 0.5;
26
+ }
27
+
28
+ :is(.settings, body:has(.settings) > .overlay, body:has(.settings) > .menu)
29
+ :is(button, a, summary, input[type="checkbox"], input[type="radio"]):focus-visible {
30
+ outline: 2px solid var(--accent);
31
+ outline-offset: 2px;
32
+ }
33
+
3
34
  .settings {
4
35
  display: flex;
5
36
  min-height: 0;
@@ -407,9 +407,12 @@ button.conv-group:hover {
407
407
  height: 14px;
408
408
  }
409
409
 
410
- /* 尾部图标共用右侧空间,状态始终排在最后。 */
411
- .conv-item > .task-mark ~ .dot,
412
- .conv-item > .task-mark ~ .conv-spin {
410
+ /* 进行中只显示转圈;待处理状态仍排在任务图标后面。 */
411
+ .conv-item:has(> .conv-spin) > .task-mark {
412
+ display: none;
413
+ }
414
+
415
+ .conv-item > .task-mark ~ .dot {
413
416
  margin-left: 0;
414
417
  }
415
418
 
@@ -431,12 +434,12 @@ button.conv-group:hover {
431
434
  display: inline-grid;
432
435
  }
433
436
 
434
- .conv-item:hover > .expert-mark ~ .dot,
435
- .conv-item:hover > .expert-mark ~ .conv-spin {
437
+ .conv-item:hover > .expert-mark ~ .dot {
436
438
  margin-left: 0;
437
439
  }
438
440
 
439
441
  .conv-item:hover .task-mark,
442
+ .conv-item:hover > .expert-mark ~ .conv-spin,
440
443
  .conv-item:hover .expert-mark ~ .feishu-mark {
441
444
  display: none;
442
445
  }
@@ -390,6 +390,10 @@
390
390
  color: inherit;
391
391
  }
392
392
 
393
+ .top-file-stat[hidden] {
394
+ display: none;
395
+ }
396
+
393
397
  /* 分布的四种颜色:固定顺序(输入、缓存写入、缓存读取、输出),深色模式用为深色底挑的那一档 */
394
398
  .usage {
395
399
  --usage-input: #2a78d6;