@keyou007/agent-bot 0.1.17-alpha.0 → 0.1.17-alpha.2

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 (51) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +3 -1
  3. package/README.zh.md +3 -1
  4. package/config.example.yaml +12 -0
  5. package/dist/codex/CodexProcessManager.js +2 -1
  6. package/dist/codex/CodexProcessManager.js.map +1 -1
  7. package/dist/codex/CodexRuntime.js +22 -2
  8. package/dist/codex/CodexRuntime.js.map +1 -1
  9. package/dist/config/loadConfig.js +10 -0
  10. package/dist/config/loadConfig.js.map +1 -1
  11. package/dist/config/schema.js +6 -0
  12. package/dist/config/schema.js.map +1 -1
  13. package/dist/feishu/FeishuConnector.js +61 -5
  14. package/dist/feishu/FeishuConnector.js.map +1 -1
  15. package/dist/feishu/FeishuMarkdown.js +42 -13
  16. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  17. package/dist/feishu/FeishuTurnPresenter.js +35 -12
  18. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  19. package/dist/feishu/LocalImageMarkdown.js +16 -2
  20. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  21. package/dist/index.js +33 -5
  22. package/dist/index.js.map +1 -1
  23. package/dist/local-files/LocalFileViewerServer.js +706 -0
  24. package/dist/local-files/LocalFileViewerServer.js.map +1 -0
  25. package/dist/local-files/NetworkAddressSelector.js +97 -0
  26. package/dist/local-files/NetworkAddressSelector.js.map +1 -0
  27. package/dist/proxy/ProxySessionController.js +43 -29
  28. package/dist/proxy/ProxySessionController.js.map +1 -1
  29. package/dist/supervision/SafeRestartScheduler.js +15 -2
  30. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  31. package/dist/utils/spawnCommand.js +2 -1
  32. package/dist/utils/spawnCommand.js.map +1 -1
  33. package/docs/technical-reference.md +8 -0
  34. package/docs/technical-reference.zh.md +8 -0
  35. package/npm-shrinkwrap.json +9 -9
  36. package/package.json +2 -2
  37. package/skills/agent-bot/SKILL.md +1 -1
  38. package/src/codex/CodexProcessManager.ts +3 -1
  39. package/src/codex/CodexRuntime.ts +25 -2
  40. package/src/config/loadConfig.ts +10 -0
  41. package/src/config/schema.ts +9 -0
  42. package/src/feishu/FeishuConnector.ts +70 -5
  43. package/src/feishu/FeishuMarkdown.ts +51 -12
  44. package/src/feishu/FeishuTurnPresenter.ts +43 -13
  45. package/src/feishu/LocalImageMarkdown.ts +23 -2
  46. package/src/index.ts +33 -4
  47. package/src/local-files/LocalFileViewerServer.ts +774 -0
  48. package/src/local-files/NetworkAddressSelector.ts +111 -0
  49. package/src/proxy/ProxySessionController.ts +33 -20
  50. package/src/supervision/SafeRestartScheduler.ts +23 -2
  51. package/src/utils/spawnCommand.ts +2 -0
@@ -0,0 +1,706 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import http from "node:http";
4
+ import path from "node:path";
5
+ import { selectPreferredNetworkAddress, } from "./NetworkAddressSelector.js";
6
+ const SECRET_FILE = "secret";
7
+ const PORT_FILE = "port";
8
+ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
9
+ const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
10
+ const DIRECTORY_PAGE_SIZE = 100;
11
+ export class LocalFileViewerServer {
12
+ options;
13
+ server;
14
+ secret;
15
+ address;
16
+ basePath = "";
17
+ constructor(options) {
18
+ this.options = options;
19
+ }
20
+ async start() {
21
+ if (this.address)
22
+ return this.address;
23
+ fs.mkdirSync(this.options.stateDirectory, { recursive: true });
24
+ this.secret = readOrCreateSecret(path.join(this.options.stateDirectory, SECRET_FILE));
25
+ const configuredPublicBaseUrl = this.options.publicBaseUrl
26
+ ? normalizePublicBaseUrl(this.options.publicBaseUrl)
27
+ : undefined;
28
+ const configuredPort = this.options.port;
29
+ const persistedPort = configuredPort === 0
30
+ ? readPersistedPort(path.join(this.options.stateDirectory, PORT_FILE))
31
+ : undefined;
32
+ const preferredPort = configuredPort || persistedPort || 0;
33
+ const server = http.createServer((request, response) => {
34
+ void this.handleRequest(request, response).catch((error) => {
35
+ if (response.headersSent) {
36
+ response.destroy(error instanceof Error ? error : new Error(String(error)));
37
+ return;
38
+ }
39
+ this.sendHtml(response, 500, errorPage("无法读取文件", "本地文件查看服务处理请求时发生错误。"));
40
+ });
41
+ });
42
+ server.on("clientError", (_error, socket) => socket.end("HTTP/1.1 400 Bad Request\r\n\r\n"));
43
+ let selectedPort = preferredPort;
44
+ try {
45
+ await listen(server, this.options.host, selectedPort);
46
+ }
47
+ catch (error) {
48
+ if (configuredPort !== 0 || preferredPort === 0 || !isAddressInUse(error))
49
+ throw error;
50
+ selectedPort = 0;
51
+ await listen(server, this.options.host, selectedPort);
52
+ }
53
+ const boundAddress = server.address();
54
+ if (!boundAddress || typeof boundAddress === "string") {
55
+ await closeServer(server);
56
+ throw new Error("Local file viewer did not bind to a TCP port.");
57
+ }
58
+ try {
59
+ const selectedNetwork = configuredPublicBaseUrl || !isWildcardHost(this.options.host)
60
+ ? undefined
61
+ : selectPreferredNetworkAddress();
62
+ const publicHost = selectedNetwork?.address ?? urlHost(this.options.host);
63
+ const publicBaseUrl = configuredPublicBaseUrl
64
+ ?? normalizePublicBaseUrl(`http://${urlHost(publicHost)}:${boundAddress.port}`);
65
+ this.basePath = normalizeBasePath(new URL(publicBaseUrl).pathname);
66
+ if (configuredPort === 0 && persistedPort !== boundAddress.port) {
67
+ fs.writeFileSync(path.join(this.options.stateDirectory, PORT_FILE), `${boundAddress.port}\n`, {
68
+ encoding: "utf8",
69
+ mode: 0o600,
70
+ });
71
+ }
72
+ this.server = server;
73
+ this.address = {
74
+ host: this.options.host,
75
+ port: boundAddress.port,
76
+ publicBaseUrl,
77
+ publicInterface: selectedNetwork?.interfaceName,
78
+ publicConnectionKind: selectedNetwork?.kind,
79
+ };
80
+ }
81
+ catch (error) {
82
+ await closeServer(server);
83
+ throw error;
84
+ }
85
+ return this.address;
86
+ }
87
+ async close() {
88
+ const server = this.server;
89
+ this.server = undefined;
90
+ this.address = undefined;
91
+ if (server)
92
+ await closeServer(server);
93
+ }
94
+ createFileUrl(filePath, reference) {
95
+ if (!this.address || !this.secret)
96
+ return undefined;
97
+ const absolutePath = normalizeAbsolutePath(filePath);
98
+ if (!absolutePath)
99
+ return undefined;
100
+ try {
101
+ const stat = fs.statSync(absolutePath);
102
+ if (!stat.isFile() && !stat.isDirectory())
103
+ return undefined;
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ const token = Buffer.from(absolutePath, "utf8").toString("base64url");
109
+ const url = this.createSignedUrl("view", token);
110
+ const line = parseLineReference(reference);
111
+ if (line !== undefined)
112
+ url.hash = `L${line}`;
113
+ return url.toString();
114
+ }
115
+ async handleRequest(request, response) {
116
+ if (request.method !== "GET" && request.method !== "HEAD") {
117
+ response.setHeader("Allow", "GET, HEAD");
118
+ this.sendHtml(response, 405, errorPage("不支持的请求", "该服务只接受只读请求。"), request.method === "HEAD");
119
+ return;
120
+ }
121
+ const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
122
+ const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
123
+ const match = /^\/(view|raw)\/([A-Za-z0-9_-]+)$/u.exec(route);
124
+ if (!match?.[1] || !match[2]) {
125
+ this.sendHtml(response, 404, errorPage("文件链接无效", "请从 Agent Bot 的回答中重新打开文件链接。"), request.method === "HEAD");
126
+ return;
127
+ }
128
+ const token = match[2];
129
+ const signature = requestUrl.searchParams.get("sig") ?? "";
130
+ const filePath = this.verifyToken(token, signature);
131
+ if (!filePath) {
132
+ this.sendHtml(response, 403, errorPage("文件链接无效", "签名校验失败,Agent Bot 已拒绝该请求。"), request.method === "HEAD");
133
+ return;
134
+ }
135
+ let stat;
136
+ try {
137
+ stat = fs.statSync(filePath);
138
+ if (!stat.isFile() && !stat.isDirectory())
139
+ throw new Error("Unsupported path type");
140
+ }
141
+ catch {
142
+ this.sendHtml(response, 404, errorPage("文件不存在", "文件可能已被移动、重命名或删除。"), request.method === "HEAD");
143
+ return;
144
+ }
145
+ if (match[1] === "raw") {
146
+ if (stat.isDirectory()) {
147
+ this.sendHtml(response, 400, errorPage("无法打开目录", "目录只能通过文件列表页面浏览。"), request.method === "HEAD");
148
+ return;
149
+ }
150
+ this.serveRawFile(request, response, filePath, stat, requestUrl.searchParams.get("download") === "1");
151
+ return;
152
+ }
153
+ const html = stat.isDirectory()
154
+ ? this.renderDirectoryViewer(filePath, stat, token, parseDirectoryPage(requestUrl.searchParams.get("page")))
155
+ : this.renderViewer(filePath, stat, token, signature);
156
+ this.sendHtml(response, 200, html, request.method === "HEAD");
157
+ }
158
+ verifyToken(token, signature) {
159
+ if (!this.secret || !/^[a-f0-9]{64}$/u.test(signature))
160
+ return undefined;
161
+ const expected = this.sign(token);
162
+ const actualBuffer = Buffer.from(signature, "hex");
163
+ const expectedBuffer = Buffer.from(expected, "hex");
164
+ if (actualBuffer.length !== expectedBuffer.length || !timingSafeEqual(actualBuffer, expectedBuffer))
165
+ return undefined;
166
+ let decoded;
167
+ try {
168
+ decoded = Buffer.from(token, "base64url").toString("utf8");
169
+ }
170
+ catch {
171
+ return undefined;
172
+ }
173
+ if (!decoded || decoded.includes("\0") || Buffer.from(decoded, "utf8").toString("base64url") !== token)
174
+ return undefined;
175
+ return normalizeAbsolutePath(decoded);
176
+ }
177
+ sign(token) {
178
+ return createHmac("sha256", this.secret).update(token).digest("hex");
179
+ }
180
+ createSignedUrl(route, token) {
181
+ const url = new URL(this.address.publicBaseUrl);
182
+ url.pathname = `${this.basePath}/${route}/${token}`.replace(/\/{2,}/gu, "/");
183
+ url.search = "";
184
+ url.hash = "";
185
+ url.searchParams.set("sig", this.sign(token));
186
+ return url;
187
+ }
188
+ renderViewer(filePath, stat, token, signature) {
189
+ const fileName = path.basename(filePath);
190
+ const extension = path.extname(filePath).toLowerCase();
191
+ const classification = classifyFileContent(filePath, stat.size);
192
+ const contentType = binaryContentTypeFor(extension);
193
+ const rawUrl = this.createSignedUrl("raw", token);
194
+ rawUrl.searchParams.set("sig", signature);
195
+ const downloadUrl = new URL(rawUrl);
196
+ downloadUrl.searchParams.set("download", "1");
197
+ let content;
198
+ if (classification.kind === "text") {
199
+ const preview = readTextPreview(filePath, stat.size, classification.encoding);
200
+ content = `${preview.truncated ? '<div class="notice">文件较大,仅显示开头 2 MiB。可使用下方按钮查看或下载完整文件。</div>' : ""}${renderText(preview.text)}`;
201
+ }
202
+ else if (contentType.startsWith("image/")) {
203
+ content = `<div class="media"><img src="${escapeAttribute(rawUrl.toString())}" alt="${escapeAttribute(fileName)}"></div>`;
204
+ }
205
+ else if (contentType === "application/pdf") {
206
+ content = `<object class="document" data="${escapeAttribute(rawUrl.toString())}" type="application/pdf"><p>浏览器无法内嵌该 PDF,请打开原始文件。</p></object>`;
207
+ }
208
+ else if (contentType.startsWith("audio/")) {
209
+ content = `<div class="media"><audio controls src="${escapeAttribute(rawUrl.toString())}"></audio></div>`;
210
+ }
211
+ else if (contentType.startsWith("video/")) {
212
+ content = `<div class="media"><video controls src="${escapeAttribute(rawUrl.toString())}"></video></div>`;
213
+ }
214
+ else {
215
+ content = '<div class="unsupported">该文件是二进制格式,无法直接预览。可以打开原始文件或下载到本地。</div>';
216
+ }
217
+ return renderViewerPage({
218
+ title: fileName,
219
+ filePath,
220
+ metadata: [formatFileSize(stat.size), stat.mtime.toLocaleString()],
221
+ actions: [
222
+ { href: rawUrl.toString(), label: "打开原始文件" },
223
+ { href: downloadUrl.toString(), label: "下载" },
224
+ ],
225
+ content,
226
+ });
227
+ }
228
+ renderDirectoryViewer(directory, stat, token, requestedPage) {
229
+ const entries = fs.readdirSync(directory, { withFileTypes: true })
230
+ .flatMap((entry) => {
231
+ const entryPath = path.join(directory, entry.name);
232
+ try {
233
+ const entryStat = fs.statSync(entryPath);
234
+ if (!entryStat.isDirectory() && !entryStat.isFile())
235
+ return [];
236
+ return [{
237
+ name: entry.name,
238
+ path: entryPath,
239
+ stat: entryStat,
240
+ kind: directoryViewerEntryKind(entryPath, entryStat),
241
+ }];
242
+ }
243
+ catch {
244
+ return [];
245
+ }
246
+ })
247
+ .sort((left, right) => Number(right.kind === "directory") - Number(left.kind === "directory")
248
+ || left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" }));
249
+ const totalPages = Math.max(1, Math.ceil(entries.length / DIRECTORY_PAGE_SIZE));
250
+ const page = Math.min(requestedPage, totalPages - 1);
251
+ const visibleEntries = entries.slice(page * DIRECTORY_PAGE_SIZE, (page + 1) * DIRECTORY_PAGE_SIZE);
252
+ const rows = visibleEntries.length > 0
253
+ ? visibleEntries.map((entry) => renderDirectoryEntry(entry, this.createFileUrl(entry.path))).join("")
254
+ : '<div class="empty-directory">这个目录是空的。</div>';
255
+ const pagination = totalPages > 1
256
+ ? renderDirectoryPagination(page, totalPages, (targetPage) => {
257
+ const url = this.createSignedUrl("view", token);
258
+ url.searchParams.set("page", String(targetPage));
259
+ return url.toString();
260
+ })
261
+ : "";
262
+ const title = path.basename(directory) || directory;
263
+ return renderViewerPage({
264
+ title,
265
+ filePath: directory,
266
+ metadata: [`${entries.length} 项`, stat.mtime.toLocaleString()],
267
+ actions: [],
268
+ content: `<div class="directory-list">${rows}</div>${pagination}`,
269
+ });
270
+ }
271
+ serveRawFile(request, response, filePath, stat, download) {
272
+ const extension = path.extname(filePath).toLowerCase();
273
+ const classification = classifyFileContent(filePath, stat.size);
274
+ const contentType = classification.kind === "text"
275
+ ? textContentTypeFor(extension, classification.encoding)
276
+ : binaryContentTypeFor(extension);
277
+ const range = parseRange(request.headers.range, stat.size);
278
+ const fileName = path.basename(filePath);
279
+ const disposition = download ? "attachment" : "inline";
280
+ setSecurityHeaders(response);
281
+ response.setHeader("Accept-Ranges", "bytes");
282
+ response.setHeader("Cache-Control", "no-store");
283
+ response.setHeader("Content-Type", contentType);
284
+ response.setHeader("Content-Disposition", `${disposition}; filename*=UTF-8''${encodeURIComponent(fileName)}`);
285
+ if (range === "invalid") {
286
+ response.statusCode = 416;
287
+ response.setHeader("Content-Range", `bytes */${stat.size}`);
288
+ response.end();
289
+ return;
290
+ }
291
+ const start = range?.start ?? 0;
292
+ const end = range?.end ?? Math.max(0, stat.size - 1);
293
+ const contentLength = stat.size === 0 ? 0 : end - start + 1;
294
+ response.statusCode = range ? 206 : 200;
295
+ response.setHeader("Content-Length", contentLength);
296
+ if (range)
297
+ response.setHeader("Content-Range", `bytes ${start}-${end}/${stat.size}`);
298
+ if (request.method === "HEAD" || stat.size === 0) {
299
+ response.end();
300
+ return;
301
+ }
302
+ const stream = fs.createReadStream(filePath, { start, end });
303
+ stream.on("error", (error) => response.destroy(error));
304
+ stream.pipe(response);
305
+ }
306
+ sendHtml(response, status, html, headOnly = false) {
307
+ const body = Buffer.from(html, "utf8");
308
+ setSecurityHeaders(response);
309
+ response.statusCode = status;
310
+ response.setHeader("Cache-Control", "no-store");
311
+ response.setHeader("Content-Type", "text/html; charset=utf-8");
312
+ response.setHeader("Content-Length", body.length);
313
+ response.end(headOnly ? undefined : body);
314
+ }
315
+ }
316
+ function renderViewerPage(input) {
317
+ const metadata = input.metadata.map((item) => `<span>${escapeHtml(item)}</span>`).join("");
318
+ const actions = input.actions.length > 0
319
+ ? `<nav class="actions">${input.actions.map((action) => `<a href="${escapeAttribute(action.href)}">${escapeHtml(action.label)}</a>`).join("")}</nav>`
320
+ : "";
321
+ return `<!doctype html>
322
+ <html lang="zh-CN">
323
+ <head>
324
+ <meta charset="utf-8">
325
+ <meta name="viewport" content="width=device-width, initial-scale=1">
326
+ <title>${escapeHtml(input.title)} · Agent Bot</title>
327
+ <style>
328
+ :root { color-scheme: light dark; font-family: Inter, "Segoe UI", system-ui, sans-serif; }
329
+ * { box-sizing: border-box; }
330
+ body { margin: 0; background: #f5f7fa; color: #1f2329; }
331
+ header { position: sticky; top: 0; z-index: 2; padding: 14px 22px; background: rgba(255,255,255,.96); border-bottom: 1px solid #dfe3e8; }
332
+ h1 { margin: 0; font-size: 18px; font-weight: 650; overflow-wrap: anywhere; }
333
+ .path { margin-top: 5px; color: #646a73; font: 12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; overflow-wrap: anywhere; }
334
+ .meta { display: flex; gap: 12px; align-items: center; margin-top: 10px; color: #646a73; font-size: 12px; }
335
+ .actions { margin-left: auto; display: flex; gap: 8px; }
336
+ .actions a { color: #1456f0; text-decoration: none; padding: 5px 9px; border: 1px solid #c9d0db; border-radius: 5px; background: #fff; }
337
+ main { padding: 18px 22px 30px; }
338
+ .notice, .unsupported { margin-bottom: 12px; padding: 12px 14px; border: 1px solid #f3cf8f; background: #fff7e6; border-radius: 6px; }
339
+ .code { margin: 0; padding: 12px 0; overflow: auto; border: 1px solid #dfe3e8; border-radius: 6px; background: #fff; color: #1f2329; font: 13px/1.55 ui-monospace, SFMono-Regular, Consolas, monospace; tab-size: 2; }
340
+ .line { display: block; min-height: 1.55em; padding-right: 16px; }
341
+ .line:target { background: #fff1b8; }
342
+ .line-number { display: inline-block; width: 4.5em; margin-right: 12px; padding-right: 12px; text-align: right; color: #8f959e; border-right: 1px solid #eceff3; text-decoration: none; user-select: none; }
343
+ .media { display: grid; place-items: center; min-height: 220px; }
344
+ .media img, .media video { max-width: 100%; max-height: calc(100vh - 180px); }
345
+ .media audio { width: min(720px, 100%); }
346
+ .document { width: 100%; height: calc(100vh - 150px); border: 1px solid #dfe3e8; border-radius: 6px; background: #fff; }
347
+ .directory-list { overflow: hidden; border: 1px solid #dfe3e8; border-radius: 6px; background: #fff; }
348
+ .directory-entry { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 18px; align-items: center; min-height: 44px; padding: 8px 14px; color: inherit; text-decoration: none; border-bottom: 1px solid #eceff3; }
349
+ .directory-entry:last-child { border-bottom: 0; }
350
+ .directory-entry:hover { background: #f0f4ff; }
351
+ .entry-name { min-width: 0; overflow-wrap: anywhere; }
352
+ .entry-kind, .entry-detail { color: #8f959e; font-size: 12px; white-space: nowrap; }
353
+ .empty-directory { padding: 36px 18px; color: #8f959e; text-align: center; }
354
+ .pagination { display: flex; justify-content: center; align-items: center; gap: 14px; margin-top: 16px; color: #646a73; font-size: 13px; }
355
+ .pagination a { color: #1456f0; text-decoration: none; }
356
+ @media (max-width: 640px) {
357
+ .directory-entry { grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; }
358
+ .entry-detail { grid-column: 1 / -1; padding-left: 28px; }
359
+ }
360
+ @media (prefers-color-scheme: dark) {
361
+ body { background: #17181a; color: #e5e6eb; }
362
+ header { background: rgba(32,33,36,.96); border-color: #3a3b3d; }
363
+ .path, .meta, .pagination { color: #a6a9ad; }
364
+ .actions a, .pagination a { color: #8ab4ff; }
365
+ .actions a { border-color: #55585c; background: #292a2d; }
366
+ .code, .directory-list { background: #202124; color: #e8eaed; border-color: #3a3b3d; }
367
+ .directory-entry { border-color: #3a3b3d; }
368
+ .directory-entry:hover { background: #292f3d; }
369
+ .line-number { color: #8b9098; border-color: #3a3b3d; }
370
+ .line:target { background: #594c20; }
371
+ .notice, .unsupported { color: #f5d58a; background: #3b321c; border-color: #705b28; }
372
+ }
373
+ </style>
374
+ </head>
375
+ <body>
376
+ <header>
377
+ <h1>${escapeHtml(input.title)}</h1>
378
+ <div class="path">${escapeHtml(input.filePath)}</div>
379
+ <div class="meta">${metadata}${actions}</div>
380
+ </header>
381
+ <main>${input.content}</main>
382
+ </body>
383
+ </html>`;
384
+ }
385
+ function directoryViewerEntryKind(filePath, stat) {
386
+ if (stat.isDirectory())
387
+ return "directory";
388
+ if (classifyFileContent(filePath, stat.size).kind === "text")
389
+ return "text";
390
+ const contentType = binaryContentTypeFor(path.extname(filePath).toLowerCase());
391
+ if (contentType.startsWith("image/"))
392
+ return "image";
393
+ if (contentType === "application/pdf")
394
+ return "pdf";
395
+ if (contentType.startsWith("audio/") || contentType.startsWith("video/"))
396
+ return "media";
397
+ return "binary";
398
+ }
399
+ function renderDirectoryEntry(entry, viewerUrl) {
400
+ const labels = {
401
+ directory: { icon: "📁", label: "目录" },
402
+ text: { icon: "📄", label: "文本" },
403
+ image: { icon: "🖼️", label: "图片" },
404
+ pdf: { icon: "📕", label: "PDF" },
405
+ media: { icon: "🎞️", label: "媒体" },
406
+ binary: { icon: "📦", label: "二进制" },
407
+ };
408
+ const display = labels[entry.kind];
409
+ const detail = entry.kind === "directory"
410
+ ? entry.stat.mtime.toLocaleString()
411
+ : `${formatFileSize(entry.stat.size)} · ${entry.stat.mtime.toLocaleString()}`;
412
+ return `<a class="directory-entry" href="${escapeAttribute(viewerUrl)}"><span class="entry-name">${display.icon} ${escapeHtml(entry.name)}</span><span class="entry-kind">${display.label}</span><span class="entry-detail">${escapeHtml(detail)}</span></a>`;
413
+ }
414
+ function renderDirectoryPagination(page, totalPages, pageUrl) {
415
+ const previous = page > 0
416
+ ? `<a href="${escapeAttribute(pageUrl(page - 1))}">上一页</a>`
417
+ : "";
418
+ const next = page + 1 < totalPages
419
+ ? `<a href="${escapeAttribute(pageUrl(page + 1))}">下一页</a>`
420
+ : "";
421
+ return `<nav class="pagination">${previous}<span>第 ${page + 1}/${totalPages} 页</span>${next}</nav>`;
422
+ }
423
+ function readOrCreateSecret(filePath) {
424
+ try {
425
+ const existing = fs.readFileSync(filePath, "utf8").trim();
426
+ if (/^[a-f0-9]{64}$/u.test(existing))
427
+ return Buffer.from(existing, "hex");
428
+ throw new Error(`Invalid local file viewer secret: ${filePath}`);
429
+ }
430
+ catch (error) {
431
+ if (error.code !== "ENOENT")
432
+ throw error;
433
+ }
434
+ const secret = randomBytes(32);
435
+ try {
436
+ fs.writeFileSync(filePath, `${secret.toString("hex")}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
437
+ return secret;
438
+ }
439
+ catch (error) {
440
+ if (error.code !== "EEXIST")
441
+ throw error;
442
+ const existing = fs.readFileSync(filePath, "utf8").trim();
443
+ if (!/^[a-f0-9]{64}$/u.test(existing))
444
+ throw new Error(`Invalid local file viewer secret: ${filePath}`);
445
+ return Buffer.from(existing, "hex");
446
+ }
447
+ }
448
+ function readPersistedPort(filePath) {
449
+ try {
450
+ const port = Number.parseInt(fs.readFileSync(filePath, "utf8").trim(), 10);
451
+ return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : undefined;
452
+ }
453
+ catch {
454
+ return undefined;
455
+ }
456
+ }
457
+ function normalizeAbsolutePath(filePath) {
458
+ const normalized = /^\/[a-z]:[\\/]/iu.test(filePath) ? filePath.slice(1) : filePath;
459
+ if (!path.isAbsolute(normalized))
460
+ return undefined;
461
+ return path.resolve(normalized);
462
+ }
463
+ function normalizePublicBaseUrl(value) {
464
+ const url = new URL(value);
465
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
466
+ throw new Error("Local file viewer publicBaseUrl must use http or https.");
467
+ }
468
+ url.search = "";
469
+ url.hash = "";
470
+ url.pathname = url.pathname.replace(/\/+$/u, "") || "/";
471
+ return url.toString().replace(/\/$/u, "");
472
+ }
473
+ function normalizeBasePath(value) {
474
+ const pathName = value.replace(/\/+$/u, "");
475
+ return pathName === "/" ? "" : pathName;
476
+ }
477
+ function routeWithinBasePath(pathName, basePath) {
478
+ if (!basePath)
479
+ return pathName;
480
+ if (!pathName.startsWith(`${basePath}/`))
481
+ return "";
482
+ return pathName.slice(basePath.length);
483
+ }
484
+ function urlHost(host) {
485
+ if (host === "0.0.0.0")
486
+ return "127.0.0.1";
487
+ if (host === "::")
488
+ return "[::1]";
489
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
490
+ }
491
+ function isWildcardHost(host) {
492
+ return host === "0.0.0.0" || host === "::";
493
+ }
494
+ function parseLineReference(reference) {
495
+ if (!reference)
496
+ return undefined;
497
+ const match = /^:(\d+)(?::\d+)?$/u.exec(reference);
498
+ if (!match?.[1])
499
+ return undefined;
500
+ const line = Number.parseInt(match[1], 10);
501
+ return Number.isSafeInteger(line) && line > 0 ? line : undefined;
502
+ }
503
+ function parseDirectoryPage(value) {
504
+ if (!value || !/^\d+$/u.test(value))
505
+ return 0;
506
+ const page = Number.parseInt(value, 10);
507
+ return Number.isSafeInteger(page) && page >= 0 ? page : 0;
508
+ }
509
+ function readTextPreview(filePath, size, encoding) {
510
+ const length = Math.min(size, MAX_TEXT_PREVIEW_BYTES);
511
+ const buffer = Buffer.alloc(length);
512
+ const descriptor = fs.openSync(filePath, "r");
513
+ try {
514
+ const bytesRead = fs.readSync(descriptor, buffer, 0, length, 0);
515
+ const truncated = size > bytesRead;
516
+ return {
517
+ text: decodeText(buffer.subarray(0, bytesRead), encoding, !truncated),
518
+ truncated,
519
+ };
520
+ }
521
+ finally {
522
+ fs.closeSync(descriptor);
523
+ }
524
+ }
525
+ export function classifyFileContent(filePath, size = fs.statSync(filePath).size) {
526
+ const length = Math.min(size, MAX_CONTENT_SAMPLE_BYTES);
527
+ if (length === 0)
528
+ return { kind: "text", encoding: "utf-8" };
529
+ const sample = Buffer.alloc(length);
530
+ const descriptor = fs.openSync(filePath, "r");
531
+ try {
532
+ const bytesRead = fs.readSync(descriptor, sample, 0, length, 0);
533
+ return classifyContentSample(sample.subarray(0, bytesRead), bytesRead >= size);
534
+ }
535
+ finally {
536
+ fs.closeSync(descriptor);
537
+ }
538
+ }
539
+ function classifyContentSample(sample, complete) {
540
+ if (sample.length === 0)
541
+ return { kind: "text", encoding: "utf-8" };
542
+ if (sample.length >= 4 && (sample.subarray(0, 4).equals(Buffer.from([0xff, 0xfe, 0x00, 0x00]))
543
+ || sample.subarray(0, 4).equals(Buffer.from([0x00, 0x00, 0xfe, 0xff])))) {
544
+ return { kind: "binary" };
545
+ }
546
+ const bomEncoding = sample[0] === 0xff && sample[1] === 0xfe
547
+ ? "utf-16le"
548
+ : sample[0] === 0xfe && sample[1] === 0xff
549
+ ? "utf-16be"
550
+ : undefined;
551
+ if (bomEncoding) {
552
+ return isTextForEncoding(sample, bomEncoding, complete)
553
+ ? { kind: "text", encoding: bomEncoding }
554
+ : { kind: "binary" };
555
+ }
556
+ if (sample.includes(0))
557
+ return { kind: "binary" };
558
+ for (const encoding of ["utf-8", "gb18030"]) {
559
+ if (isTextForEncoding(sample, encoding, complete))
560
+ return { kind: "text", encoding };
561
+ }
562
+ return { kind: "binary" };
563
+ }
564
+ function isTextForEncoding(sample, encoding, complete) {
565
+ try {
566
+ return hasTextLikeCharacters(decodeText(sample, encoding, complete, true));
567
+ }
568
+ catch {
569
+ return false;
570
+ }
571
+ }
572
+ function decodeText(value, encoding, complete, fatal = false) {
573
+ const decoder = new TextDecoder(encoding, { fatal });
574
+ return decoder.decode(value, { stream: !complete });
575
+ }
576
+ function hasTextLikeCharacters(value) {
577
+ let controls = 0;
578
+ let characters = 0;
579
+ for (const character of value) {
580
+ const codePoint = character.codePointAt(0);
581
+ characters += 1;
582
+ if ((codePoint < 0x20 && ![0x08, 0x09, 0x0a, 0x0c, 0x0d, 0x1b].includes(codePoint))
583
+ || (codePoint >= 0x7f && codePoint <= 0x9f)) {
584
+ controls += 1;
585
+ }
586
+ }
587
+ return controls <= 2 || controls / Math.max(1, characters) <= 0.02;
588
+ }
589
+ function renderText(value) {
590
+ const lines = value.split(/\r?\n/u);
591
+ return `<pre class="code"><code>${lines.map((line, index) => {
592
+ const lineNumber = index + 1;
593
+ return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a>${escapeHtml(line)}</span>`;
594
+ }).join("")}</code></pre>`;
595
+ }
596
+ function contentTypeFor(extension) {
597
+ const known = {
598
+ ".aac": "audio/aac", ".avi": "video/x-msvideo", ".bmp": "image/bmp", ".css": "text/css; charset=utf-8",
599
+ ".csv": "text/csv; charset=utf-8", ".gif": "image/gif", ".htm": "text/html; charset=utf-8",
600
+ ".html": "text/html; charset=utf-8", ".ico": "image/x-icon", ".jpeg": "image/jpeg", ".jpg": "image/jpeg",
601
+ ".js": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".m4a": "audio/mp4",
602
+ ".md": "text/markdown; charset=utf-8", ".mov": "video/quicktime", ".mp3": "audio/mpeg", ".mp4": "video/mp4",
603
+ ".mpeg": "video/mpeg", ".oga": "audio/ogg", ".ogg": "audio/ogg", ".ogv": "video/ogg", ".pdf": "application/pdf",
604
+ ".png": "image/png", ".svg": "image/svg+xml", ".tif": "image/tiff", ".tiff": "image/tiff",
605
+ ".ts": "text/plain; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".wav": "audio/wav",
606
+ ".webm": "video/webm", ".webp": "image/webp", ".xml": "application/xml; charset=utf-8",
607
+ ".yaml": "text/yaml; charset=utf-8", ".yml": "text/yaml; charset=utf-8",
608
+ };
609
+ return known[extension] ?? "application/octet-stream";
610
+ }
611
+ function binaryContentTypeFor(extension) {
612
+ const contentType = contentTypeFor(extension);
613
+ return isTextContentType(contentType) ? "application/octet-stream" : contentType;
614
+ }
615
+ function textContentTypeFor(extension, encoding) {
616
+ const contentType = contentTypeFor(extension);
617
+ if (!isTextContentType(contentType))
618
+ return `text/plain; charset=${encoding}`;
619
+ return contentType.replace(/;\s*charset=[^;]+/iu, `; charset=${encoding}`);
620
+ }
621
+ function isTextContentType(contentType) {
622
+ return contentType.startsWith("text/")
623
+ || contentType.includes("json")
624
+ || contentType.includes("xml")
625
+ || contentType.includes("yaml")
626
+ || contentType === "image/svg+xml";
627
+ }
628
+ function parseRange(value, size) {
629
+ if (!value)
630
+ return undefined;
631
+ const match = /^bytes=(\d*)-(\d*)$/u.exec(value.trim());
632
+ if (!match)
633
+ return "invalid";
634
+ const startText = match[1] ?? "";
635
+ const endText = match[2] ?? "";
636
+ if (!startText && !endText)
637
+ return "invalid";
638
+ let start;
639
+ let end;
640
+ if (!startText) {
641
+ const suffix = Number.parseInt(endText, 10);
642
+ if (!Number.isSafeInteger(suffix) || suffix <= 0 || size === 0)
643
+ return "invalid";
644
+ start = Math.max(0, size - suffix);
645
+ end = size - 1;
646
+ }
647
+ else {
648
+ start = Number.parseInt(startText, 10);
649
+ end = endText ? Number.parseInt(endText, 10) : size - 1;
650
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || start >= size) {
651
+ return "invalid";
652
+ }
653
+ end = Math.min(end, size - 1);
654
+ }
655
+ return { start, end };
656
+ }
657
+ function formatFileSize(size) {
658
+ if (size < 1024)
659
+ return `${size} B`;
660
+ if (size < 1024 * 1024)
661
+ return `${(size / 1024).toFixed(1)} KiB`;
662
+ if (size < 1024 * 1024 * 1024)
663
+ return `${(size / 1024 / 1024).toFixed(1)} MiB`;
664
+ return `${(size / 1024 / 1024 / 1024).toFixed(1)} GiB`;
665
+ }
666
+ function setSecurityHeaders(response) {
667
+ response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'");
668
+ response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
669
+ response.setHeader("Referrer-Policy", "no-referrer");
670
+ response.setHeader("X-Content-Type-Options", "nosniff");
671
+ response.setHeader("X-Frame-Options", "SAMEORIGIN");
672
+ }
673
+ function escapeHtml(value) {
674
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
675
+ }
676
+ function escapeAttribute(value) {
677
+ return escapeHtml(value);
678
+ }
679
+ function errorPage(title, message) {
680
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)} · Agent Bot</title><style>body{font-family:system-ui,sans-serif;max-width:720px;margin:12vh auto;padding:0 24px;color:#1f2329}h1{font-size:24px}p{color:#646a73}</style></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p></body></html>`;
681
+ }
682
+ function listen(server, host, port) {
683
+ return new Promise((resolve, reject) => {
684
+ const onError = (error) => {
685
+ server.off("listening", onListening);
686
+ reject(error);
687
+ };
688
+ const onListening = () => {
689
+ server.off("error", onError);
690
+ resolve();
691
+ };
692
+ server.once("error", onError);
693
+ server.once("listening", onListening);
694
+ server.listen({ host, port });
695
+ });
696
+ }
697
+ function closeServer(server) {
698
+ return new Promise((resolve, reject) => {
699
+ server.close((error) => error ? reject(error) : resolve());
700
+ server.closeAllConnections();
701
+ });
702
+ }
703
+ function isAddressInUse(error) {
704
+ return error.code === "EADDRINUSE";
705
+ }
706
+ //# sourceMappingURL=LocalFileViewerServer.js.map