@keyou007/agent-bot 0.1.27-alpha.2 → 0.1.27-alpha.4
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.
- package/CHANGELOG.md +22 -0
- package/README.md +78 -13
- package/README.zh.md +78 -13
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +26 -14
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +40 -10
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +219 -129
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +23 -269
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +20 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +22 -8
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +207 -132
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +24 -0
- 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
|
-
|
|
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:
|
|
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,10 @@
|
|
|
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
|
+
}
|
|
@@ -1,21 +1,36 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
1
2
|
import fs from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { readPackageVersion } from "../cli/packageVersion.js";
|
|
3
5
|
import { GIT_DIFF_PREVIEW_CSS } 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";
|
|
5
10
|
|
|
6
|
-
export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT
|
|
11
|
+
export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + MARKDOWN_EXPORT_CLIENT_SCRIPT + LIVE_MARKUP_CLIENT_SCRIPT
|
|
12
|
+
+ fs.readFileSync(new URL("../../assets/workspace-drafts.js", import.meta.url), "utf8")
|
|
7
13
|
+ fs.readFileSync(new URL("../../assets/workspace-sessions.js", import.meta.url), "utf8")
|
|
8
14
|
+ fs.readFileSync(new URL("../../assets/workspace.js", import.meta.url), "utf8");
|
|
15
|
+
export const WORKSPACE_ICON_NAME = "agent-bot.ico";
|
|
16
|
+
export const WORKSPACE_ICON = fs.readFileSync(new URL("../../assets/" + WORKSPACE_ICON_NAME, import.meta.url));
|
|
9
17
|
const WORKSPACE_CSS = fs.readFileSync(new URL("../../assets/workspace.css", import.meta.url), "utf8") + GIT_DIFF_PREVIEW_CSS + DIAGRAM_PREVIEW_CSS;
|
|
18
|
+
export const WORKSPACE_REVISION_HEADER = "X-AgentBot-Workspace-Revision";
|
|
19
|
+
export const WORKSPACE_INSTANCE_HEADER = "X-AgentBot-Workspace-Instance";
|
|
20
|
+
export const WORKSPACE_INSTANCE = randomBytes(16).toString("hex");
|
|
21
|
+
export const WORKSPACE_REVISION = createHash("sha256").update(readPackageVersion()).update("\0")
|
|
22
|
+
.update(WORKSPACE_SCRIPT).update("\0").update(WORKSPACE_CSS).digest("hex");
|
|
10
23
|
|
|
11
24
|
function escapeHtml(value: string): string {
|
|
12
25
|
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
13
26
|
}
|
|
14
27
|
|
|
15
|
-
export function renderWorkspacePage(root: string, workspaceUrl: string, scriptUrl: string, appBase?: string): string {
|
|
28
|
+
export function renderWorkspacePage(root: string, workspaceUrl: string, scriptUrl: string, appBase?: string, embedded = false): string {
|
|
16
29
|
const project = path.basename(root) || root;
|
|
17
30
|
return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
18
|
-
+ '<
|
|
19
|
-
+ '<
|
|
20
|
-
+ (
|
|
31
|
+
+ '<link rel="icon" type="image/x-icon" href="' + escapeHtml(scriptUrl.replace(/workspace\.js$/u, WORKSPACE_ICON_NAME)) + '">'
|
|
32
|
+
+ '<title>' + (project ? escapeHtml(project) + ' · ' : '') + 'AgentBot Workspace</title><style>' + previewCodeFontCss(scriptUrl) + WORKSPACE_CSS + '</style>'
|
|
33
|
+
+ '<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") + '"'
|
|
34
|
+
+ (appBase ? ' data-workspace-app="' + escapeHtml(appBase) + '"' : '')
|
|
35
|
+
+ (embedded ? ' data-workspace-embedded' : '') + '><agentbot-workspace></agentbot-workspace></body></html>';
|
|
21
36
|
}
|