@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.5

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 (159) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +102 -18
  3. package/README.zh.md +102 -18
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +2676 -243
  9. package/assets/workspace.css +553 -44
  10. package/assets/workspace.js +3429 -327
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +51 -22
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +106 -14
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +141 -122
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +53 -276
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +43 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +24 -6
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +1153 -104
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +129 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +15 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +31 -22
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +335 -113
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +53 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +19 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +213 -23
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +157 -39
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +22 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/promptQuotes.js +47 -0
  103. package/dist/utils/promptQuotes.js.map +1 -0
  104. package/dist/utils/toolTimestamp.js +6 -0
  105. package/dist/utils/toolTimestamp.js.map +1 -0
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +1 -1
  108. package/skills/agent-bot/SKILL.md +23 -2
  109. package/src/cli/SelfUpdateObserver.ts +111 -0
  110. package/src/cli/SelfUpdateRunner.ts +271 -85
  111. package/src/cli/SelfUpdater.ts +53 -16
  112. package/src/cli/controlProtocol.ts +1 -0
  113. package/src/cli/help.ts +6 -0
  114. package/src/cli.ts +71 -5
  115. package/src/codex/CodexEventMapper.ts +25 -5
  116. package/src/codex/CodexRuntime.ts +4 -0
  117. package/src/feishu/CardRenderer.ts +48 -13
  118. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  119. package/src/feishu/FeishuMarkdown.ts +2 -14
  120. package/src/feishu/FeishuMessageClient.ts +10 -0
  121. package/src/feishu/FeishuTurnPresenter.ts +49 -16
  122. package/src/feishu/types.ts +1 -0
  123. package/src/index.ts +47 -12
  124. package/src/local-files/DiagramPreview.ts +11 -6
  125. package/src/local-files/GitDiffPreview.ts +107 -15
  126. package/src/local-files/LiveMarkup.ts +103 -0
  127. package/src/local-files/LocalFileViewerServer.ts +128 -125
  128. package/src/local-files/MarkdownExport.ts +54 -0
  129. package/src/local-files/PreviewCodeFont.ts +12 -0
  130. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  131. package/src/local-files/ToolCommandDisplay.ts +104 -0
  132. package/src/local-files/TurnPreviewPage.ts +58 -261
  133. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  134. package/src/local-files/WorkspaceFiles.ts +72 -5
  135. package/src/local-files/WorkspaceImages.ts +35 -0
  136. package/src/local-files/WorkspacePage.ts +24 -6
  137. package/src/local-files/WorkspaceSessions.ts +1057 -111
  138. package/src/local-files/WorkspaceTimeline.ts +135 -0
  139. package/src/presentation/OutboundRouter.ts +18 -4
  140. package/src/presentation/TurnStateReducer.ts +30 -19
  141. package/src/presentation/turnViewTypes.ts +3 -1
  142. package/src/proxy/ProxySessionController.ts +336 -96
  143. package/src/proxy/TaskMetadata.ts +81 -0
  144. package/src/runtime/types.ts +2 -1
  145. package/src/scheduling/ScheduleCards.ts +10 -4
  146. package/src/scheduling/ScheduleCommand.ts +4 -0
  147. package/src/scheduling/ScheduledTaskStore.ts +56 -9
  148. package/src/scheduling/types.ts +27 -4
  149. package/src/state/StateStore.ts +227 -24
  150. package/src/state/TurnPreviewJournal.ts +155 -38
  151. package/src/state/TurnToolText.ts +156 -0
  152. package/src/state/migrations.ts +4 -0
  153. package/src/supervision/SafeRestartNotifier.ts +9 -6
  154. package/src/terminal/TerminalPage.ts +5 -0
  155. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  156. package/src/updates/ManualUpdateController.ts +8 -3
  157. package/src/utils/promptAttachments.ts +27 -0
  158. package/src/utils/promptQuotes.ts +48 -0
  159. package/src/utils/toolTimestamp.ts +5 -0
@@ -0,0 +1,186 @@
1
+ import fs from "node:fs";
2
+ import type { ServerResponse } from "node:http";
3
+ import path from "node:path";
4
+ import { readWorkspaceGitDirectories, readWorkspaceGitStatus, resolveWorkspacePath, WorkspaceError } from "./WorkspaceFiles.js";
5
+
6
+ const MAX_PROJECTS = 12;
7
+ const MAX_STREAMS = 48;
8
+ const MAX_PATHS = 64;
9
+ const CHANGE_BATCH_MS = 250;
10
+ const HEARTBEAT_MS = 15_000;
11
+ const GIT_CACHE_MS = 1_000;
12
+ const nativeRecursive = process.platform === "win32" || process.platform === "darwin";
13
+ const MAX_DIRECTORY_WATCHERS = 64;
14
+
15
+ type GitStatus = ReturnType<typeof readWorkspaceGitStatus>;
16
+ interface Project {
17
+ root: string;
18
+ responses: Set<ServerResponse>;
19
+ watchers: fs.FSWatcher[];
20
+ paths: Set<string>;
21
+ git: boolean;
22
+ reset: boolean;
23
+ batch?: NodeJS.Timeout;
24
+ heartbeat?: NodeJS.Timeout;
25
+ gitRevision: number;
26
+ directories: Map<string, fs.FSWatcher>;
27
+ status?: { expires: number; revision: number; pending: GitStatus };
28
+ }
29
+
30
+ function gitMetadata(entry: string): boolean {
31
+ return /^(?:HEAD|index|config(?:\.worktree)?|packed-refs|commondir|info(?:\/exclude)?|refs(?:\/.*)?)$/u.test(entry);
32
+ }
33
+
34
+ /** Shares one project watcher and one Git read across that project's browser views. */
35
+ export class WorkspaceFileEvents {
36
+ private readonly projects = new Map<string, Project>();
37
+ private streams = 0;
38
+
39
+ subscribe(root: string, response: ServerResponse): void {
40
+ let project = this.projects.get(root);
41
+ if (this.streams >= MAX_STREAMS || !project && this.projects.size >= MAX_PROJECTS) {
42
+ throw new WorkspaceError("项目实时连接较多,请稍后重试。", 429);
43
+ }
44
+ if (!project) {
45
+ project = { root, responses: new Set(), watchers: [], paths: new Set(), git: false, reset: false, gitRevision: 0, directories: new Map() };
46
+ this.projects.set(root, project);
47
+ this.startWatching(project);
48
+ }
49
+ const current = project;
50
+ this.streams++;
51
+ current.responses.add(response);
52
+ response.once("close", () => {
53
+ if (current.responses.delete(response)) this.streams--;
54
+ if (!current.responses.size) this.release(current);
55
+ });
56
+ response.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store, no-transform", "X-Accel-Buffering": "no", "Cross-Origin-Resource-Policy": "same-origin" });
57
+ response.write("retry: 2500\nevent: ready\ndata: {}\n\n");
58
+ }
59
+
60
+ gitStatus(root: string): GitStatus {
61
+ const project = this.projects.get(root);
62
+ if (!project) return readWorkspaceGitStatus(root, { lineStats: true });
63
+ if (project.status) {
64
+ const { expires, pending, revision } = project.status;
65
+ if (revision === project.gitRevision && expires > Date.now()) return pending;
66
+ if (expires === Infinity) return pending.then(() => this.gitStatus(root), () => this.gitStatus(root));
67
+ }
68
+ const pending = readWorkspaceGitStatus(root, { lineStats: true });
69
+ const item = project.status = { expires: Infinity, revision: project.gitRevision, pending };
70
+ void pending.then(() => { item.expires = Date.now() + GIT_CACHE_MS; }, () => { if (project.status === item) project.status = undefined; });
71
+ return pending;
72
+ }
73
+
74
+ invalidateGit(root: string): void {
75
+ const project = this.projects.get(root);
76
+ if (project) project.gitRevision++;
77
+ }
78
+
79
+ watchDirectory(root: string, entry: string): void {
80
+ if (nativeRecursive || !entry) return;
81
+ const project = this.projects.get(root);
82
+ if (!project) return;
83
+ const existing = project.directories.get(entry);
84
+ if (existing) { project.directories.delete(entry); project.directories.set(entry, existing); return; }
85
+ try {
86
+ const directory = resolveWorkspacePath(root, entry);
87
+ if (!fs.lstatSync(directory).isDirectory() || fs.realpathSync(directory) !== directory) return;
88
+ const watcher = this.watch(project, directory, false, (name) => {
89
+ this.worktreeChange(project, name ? path.join(entry, name) : null);
90
+ });
91
+ if (!watcher) return;
92
+ project.directories.set(entry, watcher);
93
+ watcher.once("close", () => { if (project.directories.get(entry) === watcher) project.directories.delete(entry); });
94
+ if (project.directories.size > MAX_DIRECTORY_WATCHERS) {
95
+ const first = project.directories.keys().next().value!;
96
+ project.directories.get(first)!.close(); project.directories.delete(first);
97
+ }
98
+ } catch { /* A directory may disappear between the request and subscription. */ }
99
+ }
100
+
101
+ close(): void {
102
+ for (const project of this.projects.values()) {
103
+ this.release(project);
104
+ for (const response of project.responses) response.end();
105
+ }
106
+ }
107
+
108
+ private startWatching(project: Project): void {
109
+ this.watch(project, project.root, nativeRecursive, (filename) => this.worktreeChange(project, filename));
110
+ void readWorkspaceGitDirectories(project.root).then((directories) => {
111
+ if (this.projects.get(project.root) !== project) return;
112
+ for (const directory of directories) {
113
+ this.watch(project, directory, false, (filename) => {
114
+ if (!filename || gitMetadata(filename)) this.changed(project, undefined, true);
115
+ });
116
+ for (const folder of ["refs", "info"]) {
117
+ const target = path.join(directory, folder);
118
+ if (fs.existsSync(target)) this.watch(project, target, nativeRecursive, () => this.changed(project, undefined, true));
119
+ }
120
+ }
121
+ }).catch(() => { /* The periodic reconciliation also covers non-Git and unavailable Git. */ });
122
+ let pulses = 0;
123
+ project.heartbeat = setInterval(() => {
124
+ for (const response of project.responses) this.write(response, ": heartbeat\n\n");
125
+ if (++pulses % (nativeRecursive && project.watchers.length ? 8 : 4) === 0) this.changed(project, undefined, true, true);
126
+ }, HEARTBEAT_MS);
127
+ project.heartbeat.unref();
128
+ }
129
+
130
+ private worktreeChange(project: Project, filename: string | null): void {
131
+ if (!filename) { this.changed(project, undefined, true, true); return; }
132
+ const entry = filename.split(path.sep).join("/");
133
+ if (path.isAbsolute(filename) || entry.split("/").some((part) => part === "..") || entry.length > 4096) return;
134
+ const segments = entry.split("/");
135
+ const git = segments.findIndex((part) => part.toLowerCase() === ".git");
136
+ if (git >= 0) {
137
+ if (git === 0 && (segments.length === 1 || gitMetadata(segments.slice(1).join("/")))) this.changed(project, undefined, true);
138
+ } else this.changed(project, entry, /(?:^|\/)\.(?:gitignore|gitattributes)$/u.test(entry));
139
+ }
140
+
141
+ private watch(project: Project, directory: string, recursive: boolean, receive: (filename: string | null) => void): fs.FSWatcher | undefined {
142
+ try {
143
+ const watcher = fs.watch(directory, { recursive, persistent: false }, (_event, filename) => receive(filename));
144
+ project.watchers.push(watcher);
145
+ watcher.on("error", () => { watcher.close(); this.changed(project, undefined, true, true); });
146
+ watcher.once("close", () => { project.watchers = project.watchers.filter((value) => value !== watcher); });
147
+ return watcher;
148
+ } catch { return undefined; }
149
+ }
150
+
151
+ private changed(project: Project, entry?: string, git = false, reset = false): void {
152
+ if (this.projects.get(project.root) !== project) return;
153
+ project.git ||= git;
154
+ if (entry && !project.reset) project.paths.add(entry);
155
+ project.reset ||= reset || project.paths.size > MAX_PATHS;
156
+ if (project.reset) project.paths.clear();
157
+ if (project.batch) return;
158
+ project.batch = setTimeout(() => {
159
+ project.batch = undefined;
160
+ try { resolveWorkspacePath(project.root); } catch {
161
+ this.release(project);
162
+ for (const response of project.responses) response.end();
163
+ return;
164
+ }
165
+ project.gitRevision++;
166
+ const data = JSON.stringify({ paths: [...project.paths], git: project.git, reset: project.reset });
167
+ project.paths.clear(); project.git = project.reset = false;
168
+ for (const response of project.responses) this.write(response, `event: change\ndata: ${data}\n\n`);
169
+ }, CHANGE_BATCH_MS);
170
+ project.batch.unref();
171
+ }
172
+
173
+ private write(response: ServerResponse, value: string): void {
174
+ if (response.writableEnded || response.destroyed) return;
175
+ if (response.writableLength > 64 * 1024) response.destroy();
176
+ else response.write(value);
177
+ }
178
+
179
+ private release(project: Project): void {
180
+ if (this.projects.get(project.root) !== project) return;
181
+ this.projects.delete(project.root);
182
+ clearInterval(project.heartbeat);
183
+ clearTimeout(project.batch);
184
+ for (const watcher of project.watchers) watcher.close();
185
+ }
186
+ }
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
+ import { fileURLToPath } from "node:url";
6
7
  import { renderGitFileDiff } from "./GitDiffPreview.js";
7
8
 
8
9
  const runFile = promisify(execFile);
@@ -123,7 +124,7 @@ export async function readWorkspaceAddress(root: string, entry: string, query?:
123
124
  return { exact, entries: entries.slice(0, 20), truncated: data.truncated || matches.length > 20 };
124
125
  }
125
126
 
126
- async function readOnlyGit(cwd: string) {
127
+ async function readOnlyGit(cwd: string, configureFilters = true) {
127
128
  const env: NodeJS.ProcessEnv = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" };
128
129
  for (const name of Object.keys(env)) {
129
130
  if (/^GIT_(?:DIR|WORK_TREE|COMMON_DIR|INDEX_FILE|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|CONFIG.*)$/u.test(name)) delete env[name];
@@ -148,6 +149,7 @@ async function readOnlyGit(cwd: string) {
148
149
  throw new WorkspaceError("Git 读取失败:" + (error instanceof Error ? error.message : String(error)), 502);
149
150
  }
150
151
  };
152
+ if (!configureFilters) return git;
151
153
  const filters = await git(["config", "--null", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|process|required)$"]);
152
154
  if (filters.code !== 0 && filters.code !== 1) throw new WorkspaceError("读取 Git 配置失败:" + filters.stderr, 502);
153
155
  const names = gitText(filters.stdout).split("\0").filter(Boolean);
@@ -159,6 +161,65 @@ async function readOnlyGit(cwd: string) {
159
161
 
160
162
  function gitText(value: Buffer): string { return new TextDecoder("utf-8", { fatal: true }).decode(value); }
161
163
 
164
+ export async function resolveWorkspaceDirectoryAddress(input: string, { directoryOnly = false } = {}): Promise<{ root: string; entry?: string }> {
165
+ let requested = input;
166
+ if (/^file:/iu.test(requested)) {
167
+ try { requested = fileURLToPath(requested); }
168
+ catch { throw new WorkspaceError("本地文件网址无效。"); }
169
+ }
170
+ if (!path.isAbsolute(requested)
171
+ || (process.platform === "win32" && !/^(?:[a-z]:[\\/]|[\\/]{2}[^.?\\/])/iu.test(requested))) {
172
+ throw new WorkspaceError(directoryOnly ? "请输入主机上的绝对目录路径。" : "请输入主机上的绝对文件或目录路径。");
173
+ }
174
+ const check = (value: string) => {
175
+ if (gitInternal(path.parse(value).root, value)) throw new WorkspaceError("不能打开 Git 内部文件或目录。", 403);
176
+ if (process.platform === "win32" && value.slice(path.parse(value).root.length).includes(":")) {
177
+ throw new WorkspaceError("本地路径无效。");
178
+ }
179
+ };
180
+ check(requested);
181
+ let directory: string, file: string | undefined;
182
+ try {
183
+ const physical = await fs.promises.realpath(requested);
184
+ check(physical);
185
+ const stat = await fs.promises.stat(physical);
186
+ if (!stat.isFile() && !stat.isDirectory()) throw new WorkspaceError("该路径不是普通文件或目录。");
187
+ if (directoryOnly && !stat.isDirectory()) throw new WorkspaceError("请输入目录路径。");
188
+ directory = stat.isDirectory() ? physical : path.dirname(physical);
189
+ if (stat.isFile()) file = physical;
190
+ } catch (error) {
191
+ const code = (error as NodeJS.ErrnoException).code;
192
+ if (code === "ENOENT" || code === "ENOTDIR") throw new WorkspaceError("文件或目录不存在。", 404);
193
+ if (code === "EACCES" || code === "EPERM") throw new WorkspaceError("没有读取该路径的权限。", 403);
194
+ throw error;
195
+ }
196
+ if (directoryOnly) return { root: directory };
197
+ let root = directory;
198
+ // An ordinary folder can still be opened on a host without Git installed.
199
+ for (let ancestor = directory;; ancestor = path.dirname(ancestor)) {
200
+ if (fs.existsSync(path.join(ancestor, ".git"))) {
201
+ const git = await readOnlyGit(directory, false);
202
+ const result = await git(["rev-parse", "--show-toplevel"]);
203
+ if (result.code === 0) {
204
+ const top = await fs.promises.realpath(gitText(result.stdout).replace(/\r?\n$/u, ""));
205
+ if (within(top, directory)) root = top;
206
+ } else if (!result.stderr.includes("not a git repository")) {
207
+ throw new WorkspaceError("无法确定 Git 仓库根目录:" + result.stderr.trim(), 502);
208
+ }
209
+ break;
210
+ }
211
+ if (path.dirname(ancestor) === ancestor) break;
212
+ }
213
+ return { root, ...(file ? { entry: path.relative(root, file).split(path.sep).join("/") } : {}) };
214
+ }
215
+
216
+ export async function readWorkspaceGitDirectories(root: string): Promise<string[]> {
217
+ const git = await readOnlyGit(root);
218
+ const resolved = await git(["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"]);
219
+ if (resolved.code !== 0) return [];
220
+ return [...new Set(gitText(resolved.stdout).trimEnd().split(/\r?\n/u).slice(0, 2).filter((value) => path.isAbsolute(value)))];
221
+ }
222
+
162
223
  interface WorkspaceLineStats {
163
224
  additions?: number;
164
225
  deletions?: number;
@@ -307,10 +368,16 @@ export async function readWorkspaceGitStatus(root: string, options: { lineStats?
307
368
  return { changes, repository: true, branch: branch.code === 0 ? gitText(branch.stdout).trimEnd() : "分离 HEAD", ...(lineStatsError ? { lineStatsError } : {}) };
308
369
  }
309
370
 
310
- export async function readWorkspaceEntries(root: string, entry: string, page: number, options: { prefetch?: boolean; query?: string } = {}) {
371
+ interface WorkspaceTreeOptions {
372
+ prefetch?: boolean;
373
+ query?: string;
374
+ readGitStatus?: () => ReturnType<typeof readWorkspaceGitStatus>;
375
+ }
376
+
377
+ export async function readWorkspaceEntries(root: string, entry: string, page: number, options: WorkspaceTreeOptions = {}) {
311
378
  const data = options.query ? await readWorkspaceTree(root, options.query) : { ...readWorkspaceDirectory(root, entry, page), ...(options.prefetch && !entry && page === 0 ? await readWorkspaceTree(root) : {}) };
312
379
  let status: Awaited<ReturnType<typeof readWorkspaceGitStatus>>;
313
- try { status = await readWorkspaceGitStatus(root, { lineStats: true }); }
380
+ try { status = await (options.readGitStatus?.() ?? readWorkspaceGitStatus(root, { lineStats: true })); }
314
381
  catch (error) { return { ...data, gitError: error instanceof Error ? error.message : String(error) }; }
315
382
  const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
316
383
  const ignored = new Set<string>();
@@ -334,11 +401,11 @@ export async function readWorkspaceEntries(root: string, entry: string, page: nu
334
401
  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
402
  }
336
403
 
337
- export async function readWorkspaceChanges(root: string, entry: string, page: number, options: { prefetch?: boolean; query?: string } = {}) {
404
+ export async function readWorkspaceChanges(root: string, entry: string, page: number, options: WorkspaceTreeOptions = {}) {
338
405
  const directory = resolveWorkspacePath(root, entry, true), stat = fs.statSync(directory, { throwIfNoEntry: false });
339
406
  if (stat && !stat.isDirectory()) throw new WorkspaceError("这不是目录。");
340
407
  const directoryEntry = path.relative(root, directory).split(path.sep).join("/");
341
- const status = await readWorkspaceGitStatus(root, { lineStats: true }), changes = status.changes;
408
+ const status = await (options.readGitStatus?.() ?? readWorkspaceGitStatus(root, { lineStats: true })), changes = status.changes;
342
409
  if (!status.repository) return { ...paginate<WorkspaceChangeNode>([], page), ...(options.prefetch ? { preloaded: [] as WorkspaceChangeNode[] } : {}), totalChanges: 0, repository: false, notice: status.notice };
343
410
  const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
344
411
  const counts = workspaceDirectoryChanges(changes);
@@ -0,0 +1,35 @@
1
+ // These are passive raster formats supported by both Workspace and App Server.
2
+ export function workspaceImageExtension(bytes: Buffer): string | undefined {
3
+ if (bytes.length >= 33 && bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))
4
+ && bytes.toString("ascii", 12, 16) === "IHDR") return ".png";
5
+ if (bytes.length >= 12 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
6
+ && bytes.lastIndexOf(Buffer.from([0xff, 0xd9])) > 2) return ".jpg";
7
+ if (bytes.length >= 14 && /^(?:GIF87a|GIF89a)$/u.test(bytes.toString("ascii", 0, 6))) return ".gif";
8
+ if (bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP"
9
+ && ["VP8 ", "VP8L", "VP8X"].includes(bytes.toString("ascii", 12, 16))) return ".webp";
10
+ }
11
+
12
+ export const WORKSPACE_PNG_HEADER_BYTES = 64 * 1024;
13
+
14
+ export function workspacePngDisplaySize(view: DataView): [number, number] | undefined {
15
+ if (view.byteLength < 33 || view.getUint32(0) !== 0x89504e47 || view.getUint32(4) !== 0x0d0a1a0a
16
+ || view.getUint32(8) !== 13 || view.getUint32(12) !== 0x49484452) return;
17
+ const width = view.getUint32(16), height = view.getUint32(20);
18
+ if (!width || !height || Math.max(width, height) > 1_000_000) return;
19
+ for (let offset = 33; offset + 12 <= view.byteLength;) {
20
+ const length = view.getUint32(offset), type = view.getUint32(offset + 4), data = offset + 8;
21
+ if (type === 0x49444154 || type === 0x49454e44 || data + length + 4 > view.byteLength) return;
22
+ if (type === 0x70485973) { // pHYs specifies physical density when its unit is meters.
23
+ if (length !== 9 || view.getUint8(data + 8) !== 1) return;
24
+ const pixelsPerMeter = view.getUint32(data);
25
+ if (pixelsPerMeter !== view.getUint32(data + 4)) return;
26
+ const dpi = Math.round(pixelsPerMeter * 0.0254);
27
+ if (dpi <= 96) return;
28
+ return [Math.max(1, Math.round(width * 96 / dpi)), Math.max(1, Math.round(height * 96 / dpi))];
29
+ }
30
+ offset = data + length + 4;
31
+ }
32
+ }
33
+
34
+ export const WORKSPACE_IMAGE_CLIENT_SCRIPT = `const workspacePngHeaderBytes = ${WORKSPACE_PNG_HEADER_BYTES};
35
+ const workspacePngDisplaySize = ${workspacePngDisplaySize.toString()};\n`;
@@ -1,21 +1,39 @@
1
+ import { createHash, randomBytes } from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
- import { GIT_DIFF_PREVIEW_CSS } from "./GitDiffPreview.js";
4
+ import { readPackageVersion } from "../cli/packageVersion.js";
5
+ import { GIT_DIFF_PREVIEW_CSS, PATCH_HUNK_HEADER } from "./GitDiffPreview.js";
4
6
  import { DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
7
+ import { previewCodeFontCss } from "./PreviewCodeFont.js";
8
+ import { MARKDOWN_EXPORT_CLIENT_SCRIPT } from "./MarkdownExport.js";
9
+ import { LIVE_MARKUP_CLIENT_SCRIPT } from "./LiveMarkup.js";
10
+ import { WORKSPACE_IMAGE_CLIENT_SCRIPT } from "./WorkspaceImages.js";
11
+ import { splitHighlightedLines } from "./PreviewSyntaxHighlight.js";
5
12
 
6
- export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT
13
+ export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + MARKDOWN_EXPORT_CLIENT_SCRIPT + LIVE_MARKUP_CLIENT_SCRIPT + WORKSPACE_IMAGE_CLIENT_SCRIPT
14
+ + `const workspaceHighlightedLines = ${splitHighlightedLines.toString()};\nconst workspacePatchHunkHeader = ${PATCH_HUNK_HEADER};\n`
15
+ + fs.readFileSync(new URL("../../assets/workspace-drafts.js", import.meta.url), "utf8")
7
16
  + fs.readFileSync(new URL("../../assets/workspace-sessions.js", import.meta.url), "utf8")
8
17
  + fs.readFileSync(new URL("../../assets/workspace.js", import.meta.url), "utf8");
18
+ export const WORKSPACE_ICON_NAME = "agent-bot.ico";
19
+ export const WORKSPACE_ICON = fs.readFileSync(new URL("../../assets/" + WORKSPACE_ICON_NAME, import.meta.url));
9
20
  const WORKSPACE_CSS = fs.readFileSync(new URL("../../assets/workspace.css", import.meta.url), "utf8") + GIT_DIFF_PREVIEW_CSS + DIAGRAM_PREVIEW_CSS;
21
+ export const WORKSPACE_REVISION_HEADER = "X-AgentBot-Workspace-Revision";
22
+ export const WORKSPACE_INSTANCE_HEADER = "X-AgentBot-Workspace-Instance";
23
+ export const WORKSPACE_INSTANCE = randomBytes(16).toString("hex");
24
+ export const WORKSPACE_REVISION = createHash("sha256").update(readPackageVersion()).update("\0")
25
+ .update(WORKSPACE_SCRIPT).update("\0").update(WORKSPACE_CSS).digest("hex");
10
26
 
11
27
  function escapeHtml(value: string): string {
12
28
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
13
29
  }
14
30
 
15
- export function renderWorkspacePage(root: string, workspaceUrl: string, scriptUrl: string, appBase?: string): string {
31
+ export function renderWorkspacePage(root: string, workspaceUrl: string, scriptUrl: string, appBase?: string, embedded = false): string {
16
32
  const project = path.basename(root) || root;
17
33
  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>';
34
+ + '<link rel="icon" type="image/x-icon" href="' + escapeHtml(scriptUrl.replace(/workspace\.js$/u, WORKSPACE_ICON_NAME)) + '">'
35
+ + '<title>' + (project ? escapeHtml(project) + ' · ' : '') + 'AgentBot Workspace</title><style>' + previewCodeFontCss(scriptUrl) + WORKSPACE_CSS + '</style>'
36
+ + '<script id="workspace-script" defer src="' + escapeHtml(scriptUrl) + '"></script></head><body data-workspace-revision="' + WORKSPACE_REVISION + '" data-workspace-instance="' + WORKSPACE_INSTANCE + '" 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") + '"'
37
+ + (appBase ? ' data-workspace-app="' + escapeHtml(appBase) + '"' : '')
38
+ + (embedded ? ' data-workspace-embedded' : '') + '><agentbot-workspace></agentbot-workspace></body></html>';
21
39
  }