@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-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 (118) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +54 -4
  3. package/README.zh.md +54 -4
  4. package/SECURITY.md +14 -0
  5. package/assets/workspace-sessions.js +648 -0
  6. package/assets/workspace.css +160 -0
  7. package/assets/workspace.js +1795 -0
  8. package/config.example.yaml +3 -2
  9. package/dist/codex/CodexEventMapper.js +35 -0
  10. package/dist/codex/CodexEventMapper.js.map +1 -1
  11. package/dist/codex/CodexRuntime.js +50 -4
  12. package/dist/codex/CodexRuntime.js.map +1 -1
  13. package/dist/codex/TraeTaskNotification.js +44 -0
  14. package/dist/codex/TraeTaskNotification.js.map +1 -0
  15. package/dist/config/SettingsStore.js +1 -1
  16. package/dist/config/SettingsStore.js.map +1 -1
  17. package/dist/config/loadConfig.js +3 -2
  18. package/dist/config/loadConfig.js.map +1 -1
  19. package/dist/config/paths.js +3 -0
  20. package/dist/config/paths.js.map +1 -1
  21. package/dist/feishu/CardRenderer.js +54 -10
  22. package/dist/feishu/CardRenderer.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +2 -2
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +103 -16
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/index.js +61 -17
  28. package/dist/index.js.map +1 -1
  29. package/dist/local-files/DiagramPreview.js +1 -1
  30. package/dist/local-files/GitDiffPreview.js +11 -7
  31. package/dist/local-files/GitDiffPreview.js.map +1 -1
  32. package/dist/local-files/LocalFileViewerServer.js +273 -25
  33. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  34. package/dist/local-files/MarkdownFileLinks.js +5 -4
  35. package/dist/local-files/MarkdownFileLinks.js.map +1 -1
  36. package/dist/local-files/TurnPreviewPage.js +32 -10
  37. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  38. package/dist/local-files/WebPageTitle.js +85 -0
  39. package/dist/local-files/WebPageTitle.js.map +1 -0
  40. package/dist/local-files/WorkspaceFiles.js +553 -0
  41. package/dist/local-files/WorkspaceFiles.js.map +1 -0
  42. package/dist/local-files/WorkspaceOrigin.js +38 -0
  43. package/dist/local-files/WorkspaceOrigin.js.map +1 -0
  44. package/dist/local-files/WorkspacePage.js +19 -0
  45. package/dist/local-files/WorkspacePage.js.map +1 -0
  46. package/dist/local-files/WorkspaceSessions.js +689 -0
  47. package/dist/local-files/WorkspaceSessions.js.map +1 -0
  48. package/dist/presentation/TurnStateReducer.js +74 -13
  49. package/dist/presentation/TurnStateReducer.js.map +1 -1
  50. package/dist/presentation/turnActivity.js +41 -0
  51. package/dist/presentation/turnActivity.js.map +1 -0
  52. package/dist/presentation/turnStatus.js +11 -0
  53. package/dist/presentation/turnStatus.js.map +1 -1
  54. package/dist/presentation/visibleTurnActivities.js +4 -2
  55. package/dist/presentation/visibleTurnActivities.js.map +1 -1
  56. package/dist/proxy/ProxySessionController.js +150 -14
  57. package/dist/proxy/ProxySessionController.js.map +1 -1
  58. package/dist/runtime/types.js +1 -1
  59. package/dist/runtime/types.js.map +1 -1
  60. package/dist/state/InboundMessageStore.js +54 -0
  61. package/dist/state/InboundMessageStore.js.map +1 -0
  62. package/dist/state/StateStore.js +71 -1
  63. package/dist/state/StateStore.js.map +1 -1
  64. package/dist/state/TurnPreviewJournal.js +4 -2
  65. package/dist/state/TurnPreviewJournal.js.map +1 -1
  66. package/dist/state/migrations.js +20 -0
  67. package/dist/state/migrations.js.map +1 -1
  68. package/dist/supervision/SafeRestartNotifier.js +1 -0
  69. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  70. package/dist/supervision/SafeRestartScheduler.js +33 -16
  71. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  72. package/dist/terminal/TerminalLinks.js +32 -0
  73. package/dist/terminal/TerminalLinks.js.map +1 -1
  74. package/dist/terminal/TerminalPage.js +44 -24
  75. package/dist/terminal/TerminalPage.js.map +1 -1
  76. package/dist/terminal/TerminalServer.js +103 -39
  77. package/dist/terminal/TerminalServer.js.map +1 -1
  78. package/docs/technical-reference.md +1 -1
  79. package/docs/technical-reference.zh.md +2 -2
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
  82. package/skills/agent-bot/SKILL.md +3 -1
  83. package/src/codex/CodexEventMapper.ts +39 -1
  84. package/src/codex/CodexRuntime.ts +54 -4
  85. package/src/codex/TraeTaskNotification.ts +49 -0
  86. package/src/config/SettingsStore.ts +1 -1
  87. package/src/config/loadConfig.ts +3 -2
  88. package/src/config/paths.ts +4 -0
  89. package/src/feishu/CardRenderer.ts +45 -11
  90. package/src/feishu/FeishuMessageClient.ts +2 -2
  91. package/src/feishu/FeishuTurnPresenter.ts +110 -20
  92. package/src/index.ts +62 -17
  93. package/src/local-files/DiagramPreview.ts +1 -1
  94. package/src/local-files/GitDiffPreview.ts +10 -7
  95. package/src/local-files/LocalFileViewerServer.ts +243 -25
  96. package/src/local-files/MarkdownFileLinks.ts +5 -3
  97. package/src/local-files/TurnPreviewPage.ts +35 -9
  98. package/src/local-files/WebPageTitle.ts +59 -0
  99. package/src/local-files/WorkspaceFiles.ts +468 -0
  100. package/src/local-files/WorkspaceOrigin.ts +31 -0
  101. package/src/local-files/WorkspacePage.ts +21 -0
  102. package/src/local-files/WorkspaceSessions.ts +587 -0
  103. package/src/presentation/TurnStateReducer.ts +76 -14
  104. package/src/presentation/turnActivity.ts +43 -0
  105. package/src/presentation/turnStatus.ts +14 -0
  106. package/src/presentation/turnViewTypes.ts +10 -1
  107. package/src/presentation/visibleTurnActivities.ts +4 -2
  108. package/src/proxy/ProxySessionController.ts +149 -13
  109. package/src/runtime/types.ts +17 -0
  110. package/src/state/InboundMessageStore.ts +72 -0
  111. package/src/state/StateStore.ts +80 -1
  112. package/src/state/TurnPreviewJournal.ts +4 -2
  113. package/src/state/migrations.ts +20 -0
  114. package/src/supervision/SafeRestartNotifier.ts +1 -0
  115. package/src/supervision/SafeRestartScheduler.ts +42 -18
  116. package/src/terminal/TerminalLinks.ts +26 -0
  117. package/src/terminal/TerminalPage.ts +44 -24
  118. package/src/terminal/TerminalServer.ts +98 -36
@@ -0,0 +1,59 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import http, { type IncomingMessage } from "node:http";
3
+ import https from "node:https";
4
+ import { BlockList, isIP } from "node:net";
5
+ import MarkdownIt from "markdown-it";
6
+ import { WorkspaceError } from "./WorkspaceFiles.js";
7
+
8
+ const blocked = new BlockList(), globalV6 = new BlockList();
9
+ for (const [address, prefix] of [["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]] as const) blocked.addSubnet(address, prefix, "ipv4");
10
+ globalV6.addSubnet("2000::", 3, "ipv6");
11
+ for (const [address, prefix] of [["2001::",23],["2001:db8::",32],["2002::",16],["3fff::",20]] as const) blocked.addSubnet(address, prefix, "ipv6");
12
+ const unescape = new MarkdownIt().utils.unescapeAll;
13
+ const MAX_BYTES = 64 * 1024;
14
+
15
+ function publicAddress(address: string): boolean {
16
+ const family = isIP(address);
17
+ return family === 4 ? !blocked.check(address, "ipv4") : family === 6 && globalV6.check(address, "ipv6") && !blocked.check(address, "ipv6");
18
+ }
19
+
20
+ export async function readWebPageTitle(input: string): Promise<{ title?: string }> {
21
+ if (input.length > 4096) throw new WorkspaceError("网页地址过长。");
22
+ let url: URL;
23
+ try { url = new URL(input); } catch { throw new WorkspaceError("网页地址无效。"); }
24
+ const signal = AbortSignal.timeout(5000);
25
+ for (let redirects = 0; redirects <= 3; redirects++) {
26
+ if (!["http:","https:"].includes(url.protocol) || url.username || url.password || url.port) throw new WorkspaceError("标题读取仅支持不含账号密码、使用标准端口的公开 HTTP / HTTPS 网页。", 403);
27
+ const hostname = url.hostname.replace(/^\[|\]$/gu, "");
28
+ let abort!: () => void;
29
+ const addresses = await Promise.race([lookup(hostname, { all: true, verbatim: true }), new Promise<never>((_, reject) => { abort = () => reject(new WorkspaceError("读取网页标题超时。", 504)); signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); })]).finally(() => signal.removeEventListener("abort", abort));
30
+ if (!addresses.length || addresses.some(item => !publicAddress(item.address))) throw new WorkspaceError("为保护本机和内网,不能从这个地址读取网页标题。", 403);
31
+ const address = addresses.find(item => item.family === 4) ?? addresses[0]!;
32
+ // Pin the validated DNS result so a second lookup cannot reach a private address.
33
+ const response = await new Promise<IncomingMessage>((resolve, reject) => {
34
+ const request = (url.protocol === "https:" ? https : http).get(url, { signal, family: address.family, lookup: (_host, _options, done) => done(null, address.address, address.family), headers: { Accept: "text/html,application/xhtml+xml" } }, resolve);
35
+ request.on("error", reject);
36
+ });
37
+ if (response.statusCode! >= 300 && response.statusCode! < 400 && response.headers.location) {
38
+ response.destroy();
39
+ if (redirects === 3) throw new WorkspaceError("网页重定向次数过多。", 502);
40
+ url = new URL(response.headers.location, url); continue;
41
+ }
42
+ if (response.statusCode! < 200 || response.statusCode! >= 300) { response.destroy(); throw new WorkspaceError("读取网页标题失败(HTTP " + response.statusCode + ")。", 502); }
43
+ const contentType = response.headers["content-type"] ?? "";
44
+ if (!/^(?:text\/html|application\/xhtml\+xml)(?:;|$)/iu.test(contentType)) { response.destroy(); return {}; }
45
+ const chunks: Buffer[] = []; let size = 0;
46
+ for await (const chunk of response) {
47
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array), remaining = MAX_BYTES - size;
48
+ chunks.push(data.subarray(0, remaining)); size += Math.min(data.length, remaining);
49
+ if (size === MAX_BYTES || /<\/title\s*>|<\/head\s*>/iu.test(Buffer.concat(chunks).toString("latin1"))) break;
50
+ }
51
+ const buffer = Buffer.concat(chunks), prefix = buffer.subarray(0, 1024).toString("latin1");
52
+ const encoding = /charset\s*=\s*["']?([^\s;"'>]+)/iu.exec(contentType)?.[1] ?? /<meta\b[^>]*charset\s*=\s*["']?([^\s;"'>]+)/iu.exec(prefix)?.[1] ?? "utf-8";
53
+ let decoder: TextDecoder; try { decoder = new TextDecoder(encoding); } catch { decoder = new TextDecoder("utf-8"); }
54
+ const html = decoder.decode(buffer).replace(/<!--[\s\S]*?-->|<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/giu, ""), text = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/iu.exec(html)?.[1];
55
+ const title = text && unescape(text.replaceAll("\\", "&#92;")).replace(/[\u0000-\u001f\u007f]/gu, " " ).replace(/\s+/gu, " ").trim().slice(0, 200);
56
+ return title ? { title } : {};
57
+ }
58
+ return {};
59
+ }
@@ -0,0 +1,468 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { renderGitFileDiff } from "./GitDiffPreview.js";
7
+
8
+ const runFile = promisify(execFile);
9
+ const PAGE_SIZE = 100;
10
+ const PRELOAD_LIMIT = 300;
11
+ const SEARCH_SCAN_LIMIT = 20_000;
12
+ const MAX_GIT_BYTES = 4 * 1024 * 1024;
13
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
14
+ export type WorkspaceDiffMode = "all" | "staged" | "unstaged";
15
+ export class WorkspaceError extends Error {
16
+ constructor(message: string, readonly status = 400) { super(message); }
17
+ }
18
+
19
+ function within(root: string, target: string): boolean {
20
+ const relative = path.relative(root, target);
21
+ return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(".." + path.sep));
22
+ }
23
+
24
+ function gitInternal(root: string, target: string): boolean {
25
+ return path.relative(root, target).split(path.sep).some((part) => (process.platform === "win32" ? part.toLowerCase() : part) === ".git");
26
+ }
27
+
28
+ export function resolveWorkspacePath(root: string, entry = "", allowMissing = false): string {
29
+ if (entry.includes("\0") || path.isAbsolute(entry) || (process.platform === "win32" && entry.includes(":")))
30
+ throw new WorkspaceError("文件路径无效。", 403);
31
+ const target = path.resolve(root, entry);
32
+ if (!within(root, target) || gitInternal(root, target))
33
+ throw new WorkspaceError("不能访问项目范围之外或 Git 内部的文件。", 403);
34
+ if (path.resolve(fs.realpathSync(root)) !== path.resolve(root))
35
+ throw new WorkspaceError("项目根目录已改变,请重新打开工作台链接。", 403);
36
+ let ancestor = target;
37
+ while (!fs.existsSync(ancestor)) {
38
+ if (!allowMissing || ancestor === root) throw new WorkspaceError("文件不存在,可能已被移动或删除。", 404);
39
+ ancestor = path.dirname(ancestor);
40
+ }
41
+ const physical = path.resolve(fs.realpathSync(ancestor), path.relative(ancestor, target));
42
+ if (!within(root, physical) || gitInternal(root, physical))
43
+ throw new WorkspaceError("这个链接指向项目范围之外或 Git 内部,未读取文件。", 403);
44
+ return target;
45
+ }
46
+
47
+ function paginate<T>(entries: T[], requestedPage: number) {
48
+ const totalPages = Math.max(1, Math.ceil(entries.length / PAGE_SIZE));
49
+ const page = Math.min(requestedPage, totalPages - 1);
50
+ return { entries: entries.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE), total: entries.length, page, totalPages };
51
+ }
52
+
53
+ function directoryNode(root: string, directory: string, name: string) {
54
+ const absolute = path.join(directory, name), relative = path.relative(root, absolute).split(path.sep).join("/");
55
+ try {
56
+ resolveWorkspacePath(root, relative);
57
+ const stat = fs.statSync(absolute);
58
+ return { name, path: relative, directory: stat.isDirectory(), blocked: !stat.isDirectory() && !stat.isFile() };
59
+ } catch (error) {
60
+ return { name, path: relative, directory: false, blocked: true, error: error instanceof Error ? error.message : String(error) };
61
+ }
62
+ }
63
+
64
+ export function readWorkspaceDirectory(root: string, entry: string, page: number) {
65
+ const directory = resolveWorkspacePath(root, entry);
66
+ if (!fs.statSync(directory).isDirectory()) throw new WorkspaceError("这不是目录。");
67
+ const entries = fs.readdirSync(directory, { withFileTypes: true }).filter((item) => item.name !== ".git")
68
+ .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name, undefined, { numeric: true }));
69
+ const result = paginate(entries, page);
70
+ return { ...result, entries: result.entries.map((item) => directoryNode(root, directory, item.name)) };
71
+ }
72
+
73
+ export async function readWorkspaceTree(root: string, query = "") {
74
+ resolveWorkspacePath(root);
75
+ const entries: ReturnType<typeof directoryNode>[] = [], pending = [root];
76
+ const normalized = query.trim().replaceAll("\\", "/").toLowerCase();
77
+ const limit = normalized ? SEARCH_SCAN_LIMIT : PRELOAD_LIMIT + 1, deadline = Date.now() + 1000;
78
+ let scanned = 0, truncated = false;
79
+ if (normalized.includes("/")) {
80
+ const prefix = query.trim().replaceAll("\\", "/").slice(0, query.trim().replaceAll("\\", "/").lastIndexOf("/"));
81
+ const directory = resolveWorkspacePath(root, prefix, true);
82
+ if (fs.statSync(directory, { throwIfNoEntry: false })?.isDirectory()) pending[0] = directory;
83
+ }
84
+ scan: while (pending.length) {
85
+ const directory = pending.shift()!;
86
+ resolveWorkspacePath(root, path.relative(root, directory));
87
+ let handle: fs.Dir;
88
+ try { handle = await fs.promises.opendir(directory); }
89
+ catch (error) {
90
+ if (!normalized && ["EACCES", "EPERM"].includes((error as NodeJS.ErrnoException).code ?? "")) { truncated = true; break; }
91
+ throw error;
92
+ }
93
+ for await (const item of handle) {
94
+ if (item.name.toLowerCase() === ".git") continue;
95
+ if (++scanned > limit || Date.now() > deadline) { truncated = true; break scan; }
96
+ const node = directoryNode(root, directory, item.name);
97
+ if (!normalized && node.directory && item.isSymbolicLink()) { truncated = true; break scan; }
98
+ if (!normalized || node.path.toLowerCase().includes(normalized)) entries.push(node);
99
+ if (normalized && entries.length >= PRELOAD_LIMIT) { truncated = true; break scan; }
100
+ if (node.directory && !node.blocked && !item.isSymbolicLink()) pending.push(path.join(directory, item.name));
101
+ }
102
+ }
103
+ return normalized ? { entries, truncated, scanned } : { preloaded: truncated || entries.length > PRELOAD_LIMIT ? undefined : entries };
104
+ }
105
+
106
+ export async function readWorkspaceAddress(root: string, entry: string, query?: string) {
107
+ if (entry.length > 4096) throw new WorkspaceError("文件路径过长。");
108
+ entry = entry.replaceAll("\\", "/");
109
+ let exact: string | undefined;
110
+ try {
111
+ const file = resolveWorkspacePath(root, entry);
112
+ if (fs.statSync(file).isFile()) exact = path.relative(root, file).split(path.sep).join("/");
113
+ } catch (error) {
114
+ if (!(error instanceof WorkspaceError && error.status === 404)) throw error;
115
+ }
116
+ const data = query ? await readWorkspaceTree(root, query) : { entries: [], truncated: false };
117
+ const matches = (data.entries ?? []).filter(item => !item.directory && !item.blocked).sort((a,b) => a.path.localeCompare(b.path,undefined,{numeric:true})), entries = matches.slice(0, 20);
118
+ if (exact) {
119
+ const requested = exact, existing = entries.find(item => process.platform === "win32" ? item.path.toLowerCase() === requested.toLowerCase() : item.path === requested);
120
+ if (existing) exact = existing.path;
121
+ else entries.unshift(directoryNode(root, path.dirname(path.join(root, exact)), path.basename(exact)));
122
+ }
123
+ return { exact, entries: entries.slice(0, 20), truncated: data.truncated || matches.length > 20 };
124
+ }
125
+
126
+ async function readOnlyGit(cwd: string) {
127
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" };
128
+ for (const name of Object.keys(env)) {
129
+ if (/^GIT_(?:DIR|WORK_TREE|COMMON_DIR|INDEX_FILE|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|CONFIG.*)$/u.test(name)) delete env[name];
130
+ }
131
+ const args = ["--no-pager", "--literal-pathspecs", "-c", "core.fsmonitor=false", "-c", "core.quotepath=false"];
132
+ const signal = AbortSignal.timeout(10_000);
133
+ const git = async (command: string[], input?: string): Promise<{ stdout: Buffer; stderr: string; code: number }> => {
134
+ resolveWorkspacePath(cwd);
135
+ try {
136
+ const pending = runFile("git", [...args, ...command], { cwd, env, signal, windowsHide: true,
137
+ maxBuffer: MAX_GIT_BYTES, encoding: "buffer" });
138
+ // execFile reports child failures, including a closed input pipe.
139
+ pending.child.stdin?.on("error", () => {});
140
+ pending.child.stdin?.end(input);
141
+ const result = await pending;
142
+ return { stdout: result.stdout, stderr: "", code: 0 };
143
+ } catch (error) {
144
+ const failure = error as { code?: unknown; stdout?: Buffer; stderr?: Buffer };
145
+ if (typeof failure.code === "number") return { stdout: failure.stdout ?? Buffer.alloc(0),
146
+ stderr: failure.stderr?.toString("utf8") ?? "", code: failure.code };
147
+ if (failure.code === "ENOENT") throw new WorkspaceError("未找到 Git,请在主机安装 Git 后重试。", 503);
148
+ throw new WorkspaceError("Git 读取失败:" + (error instanceof Error ? error.message : String(error)), 502);
149
+ }
150
+ };
151
+ const filters = await git(["config", "--null", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|process|required)$"]);
152
+ if (filters.code !== 0 && filters.code !== 1) throw new WorkspaceError("读取 Git 配置失败:" + filters.stderr, 502);
153
+ const names = gitText(filters.stdout).split("\0").filter(Boolean);
154
+ if (names.length > 128 || names.some((name) => !/^filter\.[^\r\n]+\.(?:clean|process|required)$/u.test(name)))
155
+ throw new WorkspaceError("Git filter 配置过多或无效,未执行仓库配置的外部程序。", 502);
156
+ for (const name of names) args.push("-c", name + "=" + (name.endsWith(".required") ? "false" : ""));
157
+ return git;
158
+ }
159
+
160
+ function gitText(value: Buffer): string { return new TextDecoder("utf-8", { fatal: true }).decode(value); }
161
+
162
+ interface WorkspaceLineStats {
163
+ additions?: number;
164
+ deletions?: number;
165
+ }
166
+
167
+ export interface WorkspaceChange extends WorkspaceLineStats {
168
+ path: string;
169
+ originalPath?: string;
170
+ index: string;
171
+ worktree: string;
172
+ untracked: boolean;
173
+ conflict: boolean;
174
+ }
175
+
176
+ export function parseWorkspaceStatus(output: string): WorkspaceChange[] {
177
+ const records = output.split("\0");
178
+ const entries: WorkspaceChange[] = [];
179
+ for (let i = 0; i < records.length; i++) {
180
+ const record = records[i]!;
181
+ if (!record) continue;
182
+ if (record.length < 4 || record[2] !== " ") throw new WorkspaceError("Git 状态格式无效。", 502);
183
+ const index = record[0]!, worktree = record[1]!;
184
+ const originalPath = /[RC]/u.test(index + worktree) ? records[++i] : undefined;
185
+ if (/[RC]/u.test(index + worktree) && !originalPath) throw new WorkspaceError("Git 重命名状态不完整。", 502);
186
+ entries.push({ path: record.slice(3), ...(originalPath ? { originalPath } : {}), index, worktree,
187
+ untracked: index === "?", conflict: index === "U" || worktree === "U" || index + worktree === "AA" || index + worktree === "DD" });
188
+ }
189
+ return entries;
190
+ }
191
+
192
+ export function parseWorkspaceNumstat(output: string): Map<string, WorkspaceLineStats> {
193
+ const records = output.split("\0"), entries = new Map<string, WorkspaceLineStats>();
194
+ for (let i = 0; i < records.length; i++) {
195
+ const record = records[i]!;
196
+ if (!record) continue;
197
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/u.exec(record);
198
+ if (!match) throw new WorkspaceError("Git 行数统计格式无效。", 502);
199
+ let entry = match[3]!;
200
+ if (!entry) {
201
+ if (!records[++i] || !(entry = records[++i]!)) throw new WorkspaceError("Git 重命名行数统计不完整。", 502);
202
+ }
203
+ if (match[1] === "-" && match[2] === "-") entries.set(entry, {});
204
+ else {
205
+ const additions = Number(match[1]), deletions = Number(match[2]);
206
+ if (!Number.isSafeInteger(additions) || !Number.isSafeInteger(deletions) || additions < 0 || deletions < 0)
207
+ throw new WorkspaceError("Git 行数统计无效。", 502);
208
+ entries.set(entry, { additions, deletions });
209
+ }
210
+ }
211
+ return entries;
212
+ }
213
+
214
+ async function readUntrackedLineStats(root: string, entry: string): Promise<WorkspaceLineStats> {
215
+ try {
216
+ const file = resolveWorkspacePath(root, entry), stat = await fs.promises.lstat(file);
217
+ if (stat.isSymbolicLink()) return { additions: 1, deletions: 0 };
218
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return {};
219
+ const handle = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
220
+ try {
221
+ const snapshot = await handle.stat();
222
+ if (!snapshot.isFile() || snapshot.size > MAX_FILE_BYTES) return {};
223
+ const buffer = Buffer.alloc(snapshot.size + 1), { bytesRead } = await handle.read(buffer, 0, buffer.length, 0), completed = await handle.stat();
224
+ resolveWorkspacePath(root, entry);
225
+ if (bytesRead !== snapshot.size || snapshot.size !== completed.size || snapshot.mtimeMs !== completed.mtimeMs || snapshot.ctimeMs !== completed.ctimeMs) return {};
226
+ const content = buffer.subarray(0, bytesRead);
227
+ if (content.subarray(0, 8000).includes(0)) return {};
228
+ let additions = content.length && content[content.length - 1] !== 10 ? 1 : 0;
229
+ for (const byte of content) if (byte === 10) additions++;
230
+ return { additions, deletions: 0 };
231
+ } finally { await handle.close(); }
232
+ } catch { return {}; }
233
+ }
234
+
235
+ interface WorkspaceDirectoryChanges { changes: number; additions: number; deletions: number; lineStatsIncomplete?: boolean }
236
+
237
+ function workspaceDirectoryChanges(changes: WorkspaceChange[], includeOriginal = false): Map<string, WorkspaceDirectoryChanges> {
238
+ const folders = new Map<string, WorkspaceDirectoryChanges>();
239
+ for (const item of changes) {
240
+ const parents = new Set<string>();
241
+ for (const entry of [item.path, ...(includeOriginal && /R/u.test(item.index + item.worktree) && item.originalPath ? [item.originalPath] : [])])
242
+ for (let folder = path.posix.dirname(entry); folder !== "."; folder = path.posix.dirname(folder))
243
+ parents.add(process.platform === "win32" ? folder.toLowerCase() : folder);
244
+ for (const folder of parents) {
245
+ const previous = folders.get(folder) ?? { changes: 0, additions: 0, deletions: 0 };
246
+ previous.changes++; previous.additions += item.additions ?? 0; previous.deletions += item.deletions ?? 0;
247
+ if (item.additions === undefined || item.deletions === undefined) previous.lineStatsIncomplete = true;
248
+ folders.set(folder, previous);
249
+ }
250
+ }
251
+ return folders;
252
+ }
253
+
254
+ type WorkspaceChangeNode = (WorkspaceChange & { name: string; directory: false })
255
+ | (WorkspaceDirectoryChanges & { path: string; name: string; directory: true });
256
+
257
+ export async function readWorkspaceGitStatus(root: string, options: { lineStats?: boolean } = {}): Promise<{ changes: WorkspaceChange[]; repository: boolean; branch?: string; notice?: string; lineStatsError?: string }> {
258
+ const git = await readOnlyGit(root);
259
+ const repository = await git(["rev-parse", "--show-toplevel"]);
260
+ if (repository.code !== 0) {
261
+ if (/not a git repository/iu.test(repository.stderr))
262
+ return { changes: [], repository: false, notice: "这个项目不是 Git 仓库,仍可浏览文件。" };
263
+ throw new WorkspaceError("读取 Git 仓库失败:" + repository.stderr.trim(), 502);
264
+ }
265
+ const repoRoot = fs.realpathSync.native(gitText(repository.stdout).trimEnd());
266
+ const physicalRoot = fs.realpathSync.native(root);
267
+ const status = await git(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", "."]);
268
+ if (status.code !== 0) throw new WorkspaceError("读取未提交改动失败:" + status.stderr.trim(), 502);
269
+ const changes = parseWorkspaceStatus(gitText(status.stdout)).flatMap((item) => {
270
+ const absolute = path.resolve(repoRoot, item.path);
271
+ const original = item.originalPath ? path.resolve(repoRoot, item.originalPath) : undefined;
272
+ if (!within(physicalRoot, absolute)) {
273
+ if (!original || !within(physicalRoot, original)) return [];
274
+ return [{ ...item, path: path.relative(physicalRoot, original).split(path.sep).join("/"), originalPath: undefined, index: "D" }];
275
+ }
276
+ return [{ ...item, path: path.relative(physicalRoot, absolute).split(path.sep).join("/"),
277
+ originalPath: original && within(physicalRoot, original) ? path.relative(physicalRoot, original).split(path.sep).join("/") : undefined }];
278
+ });
279
+ const branch = await git(["symbolic-ref", "--quiet", "--short", "HEAD"]);
280
+ let lineStatsError: string | undefined;
281
+ if (options.lineStats && changes.length) {
282
+ try {
283
+ const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"]);
284
+ if (head.code !== 0 && head.code !== 1) throw new WorkspaceError("读取 Git HEAD 失败:" + head.stderr.trim(), 502);
285
+ const empty = head.code === 1 ? await git(["hash-object", "-t", "tree", "--stdin"], "") : undefined;
286
+ if (empty && empty.code !== 0) throw new WorkspaceError("读取 Git 空树失败:" + empty.stderr.trim(), 502);
287
+ const baseline = gitText((empty ?? head).stdout).trim();
288
+ const result = await git(["diff", "--numstat", "-z", "--relative", "--no-ext-diff", "--no-textconv", "--no-color", "--find-renames", baseline, "--", "."]);
289
+ if (result.code !== 0) throw new WorkspaceError("读取 Git 增删行数失败:" + result.stderr.trim(), 502);
290
+ const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
291
+ const stats = new Map([...parseWorkspaceNumstat(gitText(result.stdout))].map(([entry,counts]) => [normalize(entry),counts]));
292
+ for (const item of changes) if (!item.untracked) {
293
+ const current = stats.get(normalize(item.path)) ?? { additions: 0, deletions: 0 };
294
+ const previous = item.originalPath && /R/u.test(item.index + item.worktree) ? stats.get(normalize(item.originalPath)) : undefined;
295
+ Object.assign(item, previous?.additions === 0 && previous.deletions && current.deletions === 0
296
+ ? { additions: current.additions, deletions: previous.deletions } : current);
297
+ }
298
+ const untracked = changes.filter(item => item.untracked), deadline = Date.now() + 5000;
299
+ let next = 0;
300
+ await Promise.all(Array.from({ length: Math.min(8, untracked.length) }, async () => {
301
+ while (next < untracked.length && Date.now() < deadline) {
302
+ const item = untracked[next++]!; Object.assign(item, await readUntrackedLineStats(root, item.path));
303
+ }
304
+ }));
305
+ } catch (error) { lineStatsError = error instanceof Error ? error.message : String(error); }
306
+ }
307
+ return { changes, repository: true, branch: branch.code === 0 ? gitText(branch.stdout).trimEnd() : "分离 HEAD", ...(lineStatsError ? { lineStatsError } : {}) };
308
+ }
309
+
310
+ export async function readWorkspaceEntries(root: string, entry: string, page: number, options: { prefetch?: boolean; query?: string } = {}) {
311
+ const data = options.query ? await readWorkspaceTree(root, options.query) : { ...readWorkspaceDirectory(root, entry, page), ...(options.prefetch && !entry && page === 0 ? await readWorkspaceTree(root) : {}) };
312
+ let status: Awaited<ReturnType<typeof readWorkspaceGitStatus>>;
313
+ try { status = await readWorkspaceGitStatus(root, { lineStats: true }); }
314
+ catch (error) { return { ...data, gitError: error instanceof Error ? error.message : String(error) }; }
315
+ const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
316
+ const ignored = new Set<string>();
317
+ let gitError: string | undefined = status.lineStatsError;
318
+ const paths = new Set([...("entries" in data ? data.entries ?? [] : []), ...("preloaded" in data ? data.preloaded ?? [] : [])].filter(item => !item.blocked).map(item => item.path));
319
+ if (options.query) for (const entry of [...paths])
320
+ for (let folder = path.posix.dirname(entry); folder !== "."; folder = path.posix.dirname(folder)) paths.add(folder);
321
+ if (status.repository && paths.size) {
322
+ try {
323
+ const git = await readOnlyGit(root);
324
+ // check-ignore treats stdin as literal paths and rejects pathspec magic.
325
+ const result = await git(["--no-literal-pathspecs", "check-ignore", "--stdin", "-z"], [...paths].join("\0") + "\0");
326
+ if (result.code !== 0 && result.code !== 1) throw new WorkspaceError("读取 Git 忽略状态失败:" + result.stderr.trim(), 502);
327
+ for (const entry of gitText(result.stdout).split("\0").filter(Boolean)) ignored.add(normalize(entry));
328
+ } catch (error) { gitError = error instanceof Error ? error.message : String(error); }
329
+ }
330
+ const files = new Map(status.changes.map(item => [normalize(item.path),item])), folders = workspaceDirectoryChanges(status.changes, true);
331
+ const decorate = (item: ReturnType<typeof directoryNode>) => ({ ...item, ...(ignored.has(normalize(item.path)) ? { ignored: true } : {}),
332
+ ...(item.directory ? folders.get(normalize(item.path)) : files.get(normalize(item.path))) });
333
+ const directoryChanges = options.query ? [...paths].flatMap(entry => { const counts = folders.get(normalize(entry)); return counts ? [{path:entry,...counts}] : []; }) : undefined;
334
+ return { ...data, ...(gitError ? { gitError } : {}), ...(options.query ? { ignoredPaths: [...ignored], directoryChanges } : {}), ...("entries" in data && data.entries ? { entries: data.entries.map(decorate) } : {}), ...("preloaded" in data && data.preloaded ? { preloaded: data.preloaded.map(decorate) } : {}) };
335
+ }
336
+
337
+ export async function readWorkspaceChanges(root: string, entry: string, page: number, options: { prefetch?: boolean; query?: string } = {}) {
338
+ const directory = resolveWorkspacePath(root, entry, true), stat = fs.statSync(directory, { throwIfNoEntry: false });
339
+ if (stat && !stat.isDirectory()) throw new WorkspaceError("这不是目录。");
340
+ const directoryEntry = path.relative(root, directory).split(path.sep).join("/");
341
+ const status = await readWorkspaceGitStatus(root, { lineStats: true }), changes = status.changes;
342
+ if (!status.repository) return { ...paginate<WorkspaceChangeNode>([], page), ...(options.prefetch ? { preloaded: [] as WorkspaceChangeNode[] } : {}), totalChanges: 0, repository: false, notice: status.notice };
343
+ const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
344
+ const counts = workspaceDirectoryChanges(changes);
345
+ const prefix = directoryEntry ? directoryEntry + "/" : "", folders = new Map<string, WorkspaceChangeNode>();
346
+ const files: WorkspaceChangeNode[] = [];
347
+ for (const item of changes) {
348
+ if (!item.path.startsWith(prefix)) continue;
349
+ const relative = item.path.slice(prefix.length), separator = relative.indexOf("/");
350
+ if (separator < 0) files.push({ ...item, name: relative, directory: false });
351
+ else {
352
+ const name = relative.slice(0, separator);
353
+ if (!folders.has(name)) folders.set(name, { path: prefix + name, name, directory: true, ...counts.get(normalize(prefix + name))! });
354
+ }
355
+ }
356
+ if (!stat && !folders.size && !files.length) throw new WorkspaceError("目录不存在,可能已被移动或删除。", 404);
357
+ const entries = [...folders.values(), ...files].sort((a, b) => Number(b.directory) - Number(a.directory) || a.name.localeCompare(b.name, undefined, { numeric: true }));
358
+ const result = paginate(entries, page);
359
+ const visible = result.entries.map((item) => {
360
+ try { resolveWorkspacePath(root, item.path, true); return { ...item, blocked: false }; }
361
+ catch (error) { return { ...item, blocked: true, error: error instanceof Error ? error.message : String(error) }; }
362
+ });
363
+ const metadata = { totalChanges: changes.length, repository: true, branch: status.branch, ...(status.lineStatsError ? { gitError: status.lineStatsError } : {}) };
364
+ const checked = (item: WorkspaceChangeNode) => {
365
+ try { resolveWorkspacePath(root, item.path, true); return { ...item, blocked: false }; }
366
+ catch (error) { return { ...item, blocked: true, error: error instanceof Error ? error.message : String(error) }; }
367
+ };
368
+ if (options.query) {
369
+ const matches = changes.filter(item => item.path.toLowerCase().includes(options.query!.trim().replaceAll("\\", "/").toLowerCase()));
370
+ const entries = matches.slice(0, PRELOAD_LIMIT).map(item => checked({ ...item, name: path.posix.basename(item.path), directory: false }));
371
+ const parents = new Set<string>();
372
+ for (const item of entries) for (let folder = path.posix.dirname(item.path); folder !== "."; folder = path.posix.dirname(folder)) parents.add(normalize(folder));
373
+ return { ...metadata, total: matches.length, page: 0, totalPages: 1, entries, directoryChanges:[...parents].map(path => ({path,...counts.get(path)!})), truncated: matches.length > PRELOAD_LIMIT };
374
+ }
375
+ const flat = new Map<string, WorkspaceChangeNode>();
376
+ if (options.prefetch) for (const item of changes) {
377
+ flat.set(item.path, { ...item, name: path.posix.basename(item.path), directory: false });
378
+ for (let folder = path.posix.dirname(item.path); folder !== "."; folder = path.posix.dirname(folder)) {
379
+ flat.set(folder, { path: folder, name: path.posix.basename(folder), directory: true, ...counts.get(normalize(folder))! });
380
+ }
381
+ if (flat.size > PRELOAD_LIMIT) break;
382
+ }
383
+ return { ...result, entries: visible, ...metadata, ...(options.prefetch && flat.size <= PRELOAD_LIMIT ? { preloaded: [...flat.values()].map(checked) } : {}) };
384
+ }
385
+
386
+ export async function readWorkspaceFileVersions(root: string, entry: string, mode: WorkspaceDiffMode, originalEntry?: string): Promise<{ before: Buffer; after: Buffer; beforeExists: boolean; canViewFile: boolean }> {
387
+ const file = resolveWorkspacePath(root, entry, true);
388
+ const original = originalEntry ? resolveWorkspacePath(root, originalEntry, true) : file;
389
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
390
+ if (stat && !stat.isFile() && !stat.isSymbolicLink()) throw new WorkspaceError("目录或子模块不支持文本 Diff。", 400);
391
+ if (mode !== "staged" && stat && stat.size > MAX_FILE_BYTES) throw new WorkspaceError("文件超过 2 MiB,暂不生成 Diff;可以查看文件内容或下载。", 413);
392
+ const git = await readOnlyGit(root);
393
+ const [repository, head] = await Promise.all([git(["rev-parse", "--show-toplevel"]), git(["rev-parse", "--verify", "--quiet", "HEAD"])]);
394
+ if (repository.code !== 0) throw new WorkspaceError("读取 Git 仓库失败:" + repository.stderr.trim(), 502);
395
+ if (head.code !== 0 && head.code !== 1) throw new WorkspaceError("读取 Git HEAD 失败:" + head.stderr.trim(), 502);
396
+ const repoRoot = fs.realpathSync.native(gitText(repository.stdout).trimEnd());
397
+ const physicalRoot = fs.realpathSync.native(root);
398
+ const previousPath = path.relative(repoRoot, path.resolve(physicalRoot, path.relative(root, original))).split(path.sep).join("/");
399
+ const currentPath = path.relative(root, file).split(path.sep).join("/");
400
+ const [tree, index] = await Promise.all([
401
+ head.code === 0 ? git(["ls-tree", "--full-tree", "-z", gitText(head.stdout).trim(), "--", previousPath]) : Promise.resolve({ stdout: Buffer.alloc(0), stderr: "", code: 0 }),
402
+ git(["ls-files", "--stage", "-z", "--", currentPath]),
403
+ ]);
404
+ if (tree.code !== 0 || index.code !== 0) throw new WorkspaceError("读取文件版本失败:" + (tree.stderr || index.stderr).trim(), 502);
405
+ const headBlob = /^\d{6} blob ([a-f\d]+)\t/u.exec(gitText(tree.stdout))?.[1];
406
+ if (tree.stdout.length && !headBlob) throw new WorkspaceError("目录或子模块不支持文本 Diff。", 400);
407
+ const stages = gitText(index.stdout).split("\0").flatMap((record) => {
408
+ const match = /^(\d{6}) ([a-f\d]+) ([0-3])\t/u.exec(record);
409
+ return match ? [{ mode: match[1]!, id: match[2]!, stage: match[3]! }] : [];
410
+ });
411
+ if (stages.some((item) => item.mode === "160000")) throw new WorkspaceError("子模块不支持文本 Diff。", 400);
412
+ const staged = stages.find((item) => item.stage === "0");
413
+ if (!staged && stages.length && mode === "staged") throw new WorkspaceError("文件存在合并冲突,暂存区没有合并版本;请切换全部或未暂存范围。", 409);
414
+ const beforeId = mode === "unstaged" ? (staged ?? stages.find((item) => item.stage === "2"))?.id : headBlob;
415
+ const readBlob = async (id: string | undefined): Promise<Buffer> => {
416
+ if (!id) return Buffer.alloc(0);
417
+ const result = await git(["cat-file", "blob", id]);
418
+ if (result.code !== 0) throw new WorkspaceError("读取文件版本失败:" + result.stderr.trim(), 502);
419
+ if (result.stdout.length > MAX_FILE_BYTES) throw new WorkspaceError("文件版本超过 2 MiB,暂不生成完整 Diff。", 413);
420
+ return result.stdout;
421
+ };
422
+ const [before, indexed] = await Promise.all([readBlob(beforeId), mode === "staged" ? readBlob(staged?.id) : Promise.resolve(Buffer.alloc(0))]);
423
+ let after = indexed;
424
+ resolveWorkspacePath(root, entry, true);
425
+ if (mode !== "staged") {
426
+ const current = fs.lstatSync(file, { throwIfNoEntry: false });
427
+ if (current?.isSymbolicLink()) after = Buffer.from(fs.readlinkSync(file));
428
+ else if (current?.isFile()) {
429
+ const descriptor = fs.openSync(file, "r");
430
+ try {
431
+ const snapshot = fs.fstatSync(descriptor);
432
+ if (snapshot.size > MAX_FILE_BYTES) throw new WorkspaceError("文件超过 2 MiB,暂不生成完整 Diff。", 413);
433
+ const buffer = Buffer.alloc(snapshot.size + 1), bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, 0), completed = fs.fstatSync(descriptor);
434
+ if (bytesRead > MAX_FILE_BYTES || completed.size > MAX_FILE_BYTES) throw new WorkspaceError("文件超过 2 MiB,暂不生成完整 Diff。", 413);
435
+ if (bytesRead !== snapshot.size || snapshot.size !== completed.size || snapshot.mtimeMs !== completed.mtimeMs || snapshot.ctimeMs !== completed.ctimeMs)
436
+ throw new WorkspaceError("文件在读取期间发生变化,未生成不完整 Diff;请刷新后重试。", 409);
437
+ after = buffer.subarray(0, bytesRead);
438
+ } finally { fs.closeSync(descriptor); }
439
+ }
440
+ }
441
+ if (after.length > MAX_FILE_BYTES) throw new WorkspaceError("文件超过 2 MiB,暂不生成完整 Diff。", 413);
442
+ return { before, after, beforeExists: beforeId !== undefined, canViewFile: fs.statSync(file, { throwIfNoEntry: false })?.isFile() ?? false };
443
+ }
444
+
445
+ export async function createWorkspaceDiff(root: string, before: string, after: string): Promise<string> {
446
+ const sources = [before, after].map((text) => text.replace(/\r\n?/gu, "\n"));
447
+ if (sources.some((text) => Buffer.byteLength(text, "utf8") > MAX_FILE_BYTES || (text ? text.replace(/\n$/u, "").split("\n").length : 0) > 10_000))
448
+ throw new WorkspaceError("完整文件超过 Diff 预览上限(2 MiB 或 10000 行),请在本地 Git 工具中查看。", 413);
449
+ if (sources[0] === sources[1]) return "";
450
+ const git = await readOnlyGit(root);
451
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "agentbot-workspace-diff-"));
452
+ try {
453
+ const files = [path.join(temporary, "before.txt"), path.join(temporary, "after.txt")];
454
+ files.forEach((file, index) => fs.writeFileSync(file, sources[index]!));
455
+ const result = await git(["-c", "core.autocrlf=false", "diff", "--no-index", "--text", "--no-ext-diff", "--no-textconv", "--no-color", "--unified=3", "--", ...files]);
456
+ if (result.code > 1) throw new WorkspaceError("读取 Diff 失败:" + result.stderr.trim(), 502);
457
+ const diff = gitText(result.stdout);
458
+ if (Buffer.byteLength(diff, "utf8") > 1024 * 1024 || diff.split("\n").length > 10_000)
459
+ throw new WorkspaceError("改动超过 Diff 预览上限(1 MiB 或 10000 行),请在本地 Git 工具中查看。", 413);
460
+ return diff;
461
+ } finally { fs.rmSync(temporary, { recursive: true, force: true }); }
462
+ }
463
+
464
+ export function renderWorkspaceDiff(diff: string, currentText: string, highlight?: (text: string) => string[]): string {
465
+ const html = renderGitFileDiff(diff || "diff --git a/file b/file\n", currentText, highlight);
466
+ if (!html) throw new WorkspaceError("无法合并完整文件与改动,请刷新后重试。", 409);
467
+ return (diff ? "" : '<div class="workspace-notice">这个范围内没有内容差异。暂存和未暂存改动可能互相抵消,请切换范围查看。</div>') + html;
468
+ }
@@ -0,0 +1,31 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import { isIP } from "node:net";
3
+
4
+ function ipAddress(address: string | undefined): string | undefined {
5
+ const ip = address?.split("%")[0] ?? "";
6
+ const family = isIP(ip);
7
+ if (!family) return;
8
+ const normalized = family === 6 ? new URL(`http://[${ip}]`).hostname.slice(1, -1) : ip;
9
+ const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u.exec(normalized);
10
+ if (!mapped) return normalized;
11
+ const high = parseInt(mapped[1]!, 16), low = parseInt(mapped[2]!, 16);
12
+ return [high >>> 8, high & 255, low >>> 8, low & 255].join(".");
13
+ }
14
+
15
+ /** Allow a literal listener address as an alternative to the configured public origin. */
16
+ export function directWorkspaceOrigin(request: IncomingMessage): string | undefined {
17
+ const { host } = request.headers;
18
+ if (!host || !/^(?:localhost|[\d.]+|\[[a-f0-9:.]+\])(?::\d{1,5})?$/iu.test(host)) return;
19
+ if (Object.keys(request.headers).some((name) => name === "forwarded" || name.startsWith("x-forwarded-")
20
+ || name === "via" || name === "x-real-ip" || name === "cf-connecting-ip" || name === "true-client-ip")) return;
21
+ const local = ipAddress(request.socket.localAddress);
22
+ if (!local) return;
23
+ try {
24
+ const origin = new URL(`http://${host}`);
25
+ if (Number(origin.port || 80) !== request.socket.localPort) return;
26
+ const hostname = origin.hostname;
27
+ if (ipAddress(hostname.replace(/^\[|\]$/gu, "")) === local) return origin.origin;
28
+ if (hostname === "localhost" && (local === "::1" || local.startsWith("127."))) return origin.origin;
29
+ } catch { /* A malformed authority is not a direct listener address. */ }
30
+ return undefined;
31
+ }
@@ -0,0 +1,21 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { GIT_DIFF_PREVIEW_CSS } from "./GitDiffPreview.js";
4
+ import { DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
5
+
6
+ export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT
7
+ + fs.readFileSync(new URL("../../assets/workspace-sessions.js", import.meta.url), "utf8")
8
+ + fs.readFileSync(new URL("../../assets/workspace.js", import.meta.url), "utf8");
9
+ const WORKSPACE_CSS = fs.readFileSync(new URL("../../assets/workspace.css", import.meta.url), "utf8") + GIT_DIFF_PREVIEW_CSS + DIAGRAM_PREVIEW_CSS;
10
+
11
+ function escapeHtml(value: string): string {
12
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
13
+ }
14
+
15
+ export function renderWorkspacePage(root: string, workspaceUrl: string, scriptUrl: string, appBase?: string): string {
16
+ const project = path.basename(root) || root;
17
+ return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
18
+ + '<title>' + (project ? escapeHtml(project) + ' · ' : '') + 'AgentBot Workspace</title><style>' + WORKSPACE_CSS + '</style>'
19
+ + '<script defer src="' + escapeHtml(scriptUrl) + '"></script></head><body data-workspace-url="' + escapeHtml(workspaceUrl) + '" data-diagram-script="' + escapeHtml(scriptUrl.replace(/workspace\.js$/u, "mermaid.js")) + '" data-root="' + escapeHtml(root) + '" data-project="' + escapeHtml(project || "Agent Bot") + '"'
20
+ + (appBase ? ' data-workspace-app="' + escapeHtml(appBase) + '"' : '') + '><agentbot-workspace></agentbot-workspace></body></html>';
21
+ }