@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.3
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 +28 -0
- package/README.md +55 -5
- package/README.zh.md +55 -5
- package/SECURITY.md +14 -0
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +54 -10
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +359 -37
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +32 -10
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +45 -11
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +10 -7
- package/src/local-files/LocalFileViewerServer.ts +330 -37
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
+
import { statSync } from "node:fs";
|
|
4
|
+
import type { Duplex } from "node:stream";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import MarkdownIt from "markdown-it";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { detectProjectlessWorkspace } from "../codex/ProjectlessWorkspace.js";
|
|
9
|
+
import { DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema } from "../config/schema.js";
|
|
10
|
+
import type { Logger } from "pino";
|
|
11
|
+
import type { ProxySessionController } from "../proxy/ProxySessionController.js";
|
|
12
|
+
import { displayRuntimeError } from "../runtime/responseErrors.js";
|
|
13
|
+
import type { SessionRecord, StateStore } from "../state/StateStore.js";
|
|
14
|
+
import type { TurnViewState } from "../presentation/turnViewTypes.js";
|
|
15
|
+
import type { LocalFileViewerServer, LocalFileViewerService } from "./LocalFileViewerServer.js";
|
|
16
|
+
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
17
|
+
import { highlightPreviewCode } from "./PreviewSyntaxHighlight.js";
|
|
18
|
+
import { resolveWorkspacePath, WorkspaceError } from "./WorkspaceFiles.js";
|
|
19
|
+
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
20
|
+
import type { TerminalWorkspaceAccess } from "../terminal/TerminalServer.js";
|
|
21
|
+
|
|
22
|
+
const TTL = 8 * 60 * 60_000;
|
|
23
|
+
const MAX_HISTORY = 20;
|
|
24
|
+
const HISTORY_BYTES = 512 * 1024;
|
|
25
|
+
const MAX_TOOL_CHARS = 32_000;
|
|
26
|
+
const MAX_TOOL_JOURNAL_BYTES = 4 * 1024 * 1024;
|
|
27
|
+
const id = z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u);
|
|
28
|
+
const key = z.uuid();
|
|
29
|
+
const imageEntry = z.string().min(1).max(4096).regex(/^[^\x00-\x1f\x7f]+$/u);
|
|
30
|
+
const imageQuery = z.object({ task: id.optional(), entry: imageEntry, proof: z.string().regex(/^[A-Za-z0-9_-]{43}$/u) });
|
|
31
|
+
const selection = z.object({ page: key, task: id.optional(), generation: z.int().nonnegative(), anchor: id.optional() }).strict();
|
|
32
|
+
const instruction = z.discriminatedUnion("action", [
|
|
33
|
+
z.object({ action: z.enum(["send", "queue"]), task: id, request: key, text: z.string().trim().min(1).max(24_000) }).strict(),
|
|
34
|
+
z.object({ action: z.literal("stop"), task: id, request: key, turn: id }).strict(),
|
|
35
|
+
]);
|
|
36
|
+
const markdown = new MarkdownIt({ html: false, breaks: true, linkify: true, highlight: highlightPreviewCode });
|
|
37
|
+
markdown.renderer.rules.table_open = (tokens, index, options, _env, renderer) =>
|
|
38
|
+
'<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0">' + renderer.renderToken(tokens, index, options);
|
|
39
|
+
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
|
40
|
+
const validLink = markdown.validateLink.bind(markdown);
|
|
41
|
+
markdown.validateLink = (value) => isFileUrl(value) || /^\/?[a-z]:[\\/]/iu.test(value) || validLink(value);
|
|
42
|
+
const token = () => randomBytes(32).toString("base64url");
|
|
43
|
+
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
44
|
+
|
|
45
|
+
interface Credentials { owner: string; secret?: string }
|
|
46
|
+
type WorkspaceAccess =
|
|
47
|
+
| { mode: "password"; credentials: Credentials & { secret: string }; hint?: never }
|
|
48
|
+
| { mode: "automatic"; credentials: Credentials; hint?: never }
|
|
49
|
+
| { mode: "disabled"; credentials?: never; hint: string };
|
|
50
|
+
interface Grant extends TerminalWorkspaceAccess { secret?: string; origin: string; csrf: string; abort: AbortController }
|
|
51
|
+
interface Stream {
|
|
52
|
+
grant: Grant; response: ServerResponse; version: number; generation: number;
|
|
53
|
+
task?: string; tail?: string; catalogue: number; heartbeat: number;
|
|
54
|
+
}
|
|
55
|
+
interface WorkspaceSessionOptions {
|
|
56
|
+
store: StateStore;
|
|
57
|
+
inboundImageDirectory: string;
|
|
58
|
+
owner(): string | undefined;
|
|
59
|
+
password(): string | undefined;
|
|
60
|
+
controller: Pick<ProxySessionController, "controlSendTaskPrompt" | "controlQueueTaskPrompt" | "controlStopTask">;
|
|
61
|
+
canSubmit(): boolean;
|
|
62
|
+
isAppServer?(agentName: string): boolean;
|
|
63
|
+
logger: Pick<Logger, "warn">;
|
|
64
|
+
}
|
|
65
|
+
class RequestError extends Error {
|
|
66
|
+
constructor(readonly status: number, message: string) { super(message); }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class WorkspaceSessions implements LocalFileViewerService {
|
|
70
|
+
private base!: URL;
|
|
71
|
+
private readonly grants = new Map<string, Grant>();
|
|
72
|
+
private readonly streams = new Map<string, Stream>();
|
|
73
|
+
private readonly running = new Set<string>();
|
|
74
|
+
private readonly imageSecret = randomBytes(32);
|
|
75
|
+
private readonly failures: { address: string; at: number }[] = [];
|
|
76
|
+
private readonly rendered = new Map<string, { html: string; truncated: boolean }>();
|
|
77
|
+
private catalogue = 0;
|
|
78
|
+
private catalogueHash = "";
|
|
79
|
+
private nextCatalogue = 0;
|
|
80
|
+
private timer?: NodeJS.Timeout;
|
|
81
|
+
private nextPrune = 0;
|
|
82
|
+
private get cookieName(): string { return "agentbot_workspace_" + hash(`services:${this.base.href}`).slice(0, 16); }
|
|
83
|
+
|
|
84
|
+
constructor(private readonly viewer: LocalFileViewerServer, private readonly options: WorkspaceSessionOptions) {}
|
|
85
|
+
get preparingActions(): number { return this.running.size; }
|
|
86
|
+
start(): string {
|
|
87
|
+
this.base = new URL(this.viewer.mountService("workspace-app", this).publicBaseUrl);
|
|
88
|
+
this.timer = setInterval(() => this.poll(), 800);
|
|
89
|
+
this.timer.unref();
|
|
90
|
+
return this.base.pathname;
|
|
91
|
+
}
|
|
92
|
+
async close(): Promise<void> {
|
|
93
|
+
clearInterval(this.timer);
|
|
94
|
+
for (const stream of this.streams.values()) stream.response.end();
|
|
95
|
+
this.streams.clear();
|
|
96
|
+
for (const id of this.grants.keys()) this.revoke(id);
|
|
97
|
+
this.rendered.clear();
|
|
98
|
+
}
|
|
99
|
+
terminalAccess(request: IncomingMessage, origin: string): TerminalWorkspaceAccess | undefined {
|
|
100
|
+
const site = request.headers["sec-fetch-site"];
|
|
101
|
+
if (!this.base || (site && site !== "same-origin" && site !== "none") || (request.headers.origin && request.headers.origin !== origin)) return;
|
|
102
|
+
return this.grant(request, origin);
|
|
103
|
+
}
|
|
104
|
+
handleUpgrade(_request: IncomingMessage, socket: Duplex): void { socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"); }
|
|
105
|
+
handleRequest(request: IncomingMessage, response: ServerResponse): void {
|
|
106
|
+
void this.serve(request, response).catch((error: unknown) => {
|
|
107
|
+
if (response.destroyed || response.writableEnded) return;
|
|
108
|
+
if (response.headersSent) { response.destroy(); return; }
|
|
109
|
+
if (!(error instanceof RequestError)) this.options.logger.warn({ error }, "Workspace request failed.");
|
|
110
|
+
this.json(response, error instanceof RequestError ? error.status : 500,
|
|
111
|
+
{ error: error instanceof RequestError ? error.message : "工作台暂时无法处理请求,请重试。" });
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private async serve(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
116
|
+
const url = new URL(request.url ?? "/", this.base.origin);
|
|
117
|
+
const route = url.pathname.slice(this.base.pathname.length);
|
|
118
|
+
const origin = request.headers.host === this.base.host ? this.base.origin : directWorkspaceOrigin(request);
|
|
119
|
+
if ((request.method === "GET" || request.method === "HEAD") && route === "") {
|
|
120
|
+
this.viewer.serveWorkspaceAppPage(response, new URL(this.base.pathname, origin ?? this.base.origin), request.method === "HEAD"); return;
|
|
121
|
+
}
|
|
122
|
+
if (!origin || request.headers["sec-fetch-site"] === "cross-site") {
|
|
123
|
+
throw new RequestError(403, "工作台请求来源不受信任。");
|
|
124
|
+
}
|
|
125
|
+
if (request.method === "POST" && (request.headers.origin !== origin
|
|
126
|
+
|| request.headers["content-type"]?.split(";")[0] !== "application/json")) throw new RequestError(403, "工作台请求来源或格式无效。");
|
|
127
|
+
const imageRequest = route === "/image" && (request.method === "GET" || request.method === "HEAD");
|
|
128
|
+
if (request.method !== "GET" && request.method !== "POST" && !imageRequest) throw new RequestError(405, "工作台请求方法无效。");
|
|
129
|
+
const grant = this.grant(request, origin);
|
|
130
|
+
if (route === "/session" && request.method === "GET") {
|
|
131
|
+
const access = this.access();
|
|
132
|
+
this.json(response, 200, { available: access.mode !== "disabled", auth: access.mode, hint: access.hint, csrf: grant?.csrf }); return;
|
|
133
|
+
}
|
|
134
|
+
if (route === "/login" && request.method === "POST") {
|
|
135
|
+
const body = await this.body(request);
|
|
136
|
+
const access = this.access();
|
|
137
|
+
if (access.mode === "disabled") throw new RequestError(503, access.hint);
|
|
138
|
+
const at = Date.now();
|
|
139
|
+
if (access.mode === "password") {
|
|
140
|
+
const { password } = parse(z.object({ password: z.string().min(1).max(256) }).strict(), body);
|
|
141
|
+
this.checkPassword(request, password, access.credentials.secret, at);
|
|
142
|
+
} else {
|
|
143
|
+
parse(z.object({}).strict(), body);
|
|
144
|
+
const existing = this.grant(request, origin);
|
|
145
|
+
if (existing) { this.json(response, 200, { csrf: existing.csrf, auth: access.mode }); return; }
|
|
146
|
+
}
|
|
147
|
+
this.pruneGrants();
|
|
148
|
+
const session = token(), csrf = token();
|
|
149
|
+
// Forget the oldest idle grant first so public, passwordless visitors cannot fill the session map for eight hours.
|
|
150
|
+
if (this.grants.size >= 64) {
|
|
151
|
+
const connected = new Set([...this.streams.values()].map((stream) => stream.grant));
|
|
152
|
+
const idle = [...this.grants].find(([, entry]) => !connected.has(entry));
|
|
153
|
+
if (!idle) throw new RequestError(429, "已达到工作台会话上限,请稍后再试。");
|
|
154
|
+
this.revoke(idle[0]);
|
|
155
|
+
}
|
|
156
|
+
const abort = new AbortController();
|
|
157
|
+
this.grants.set(session, { ...access.credentials, origin, csrf, expires: at + TTL, abort, signal: abort.signal });
|
|
158
|
+
response.setHeader("Set-Cookie", this.cookie(session, TTL / 1000, origin));
|
|
159
|
+
this.json(response, 200, { csrf, auth: access.mode }); return;
|
|
160
|
+
}
|
|
161
|
+
if (!grant) throw new RequestError(401, "请登录工作台后继续。");
|
|
162
|
+
if (imageRequest) { this.serveImage(request, response, url.searchParams); return; }
|
|
163
|
+
if (request.method === "POST" && request.headers["x-workspace-csrf"] !== grant.csrf) throw new RequestError(403, "工作台会话已变更,请刷新页面。");
|
|
164
|
+
if (route === "/logout" && request.method === "POST") {
|
|
165
|
+
this.revoke(this.sessionId(request));
|
|
166
|
+
this.pruneGrants();
|
|
167
|
+
response.setHeader("Set-Cookie", this.cookie("", 0, origin)); this.json(response, 200, {}); return;
|
|
168
|
+
}
|
|
169
|
+
if (route === "/events" && request.method === "GET") {
|
|
170
|
+
this.connect(grant, parse(key, url.searchParams.get("page")), response); return;
|
|
171
|
+
}
|
|
172
|
+
if (route === "/tasks" && request.method === "GET") {
|
|
173
|
+
this.json(response, 200, this.list(url.searchParams)); return;
|
|
174
|
+
}
|
|
175
|
+
if (route === "/task" && request.method === "GET") {
|
|
176
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
177
|
+
const before = parse(id.optional(), url.searchParams.get("before") ?? undefined);
|
|
178
|
+
const anchor = parse(id.optional(), url.searchParams.get("anchor") ?? undefined);
|
|
179
|
+
this.json(response, 200, this.history(task, origin, before, anchor)); return;
|
|
180
|
+
}
|
|
181
|
+
if (route === "/focus" && request.method === "POST") {
|
|
182
|
+
const input = parse(selection, await this.body(request));
|
|
183
|
+
const stream = this.streams.get(input.page);
|
|
184
|
+
if (!stream || stream.grant !== grant) throw new RequestError(409, "实时连接尚未就绪。");
|
|
185
|
+
if (input.generation < stream.generation) throw new RequestError(409, "所选任务已变更。");
|
|
186
|
+
const task = input.task ? this.task(input.task) : undefined;
|
|
187
|
+
stream.task = task?.localSessionId; stream.generation = input.generation; stream.tail = undefined;
|
|
188
|
+
this.json(response, 200, { ...(task && this.history(task, origin, undefined, input.anchor)), version: stream.version, generation: stream.generation }); return;
|
|
189
|
+
}
|
|
190
|
+
if ((route === "/detail" || route === "/tool") && request.method === "GET") {
|
|
191
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
192
|
+
const turn = parse(id, url.searchParams.get("turn"));
|
|
193
|
+
const head = this.head(task);
|
|
194
|
+
if (turn !== head && this.options.store.workspaceTurnPage(task.localSessionId, head, turn, 1).beforeMissing) {
|
|
195
|
+
throw new RequestError(404, "当前对话分支中没有该轮次。");
|
|
196
|
+
}
|
|
197
|
+
const state = this.options.store.getTurnSnapshot(turn) as TurnViewState | undefined;
|
|
198
|
+
if (!state) throw new RequestError(404, "执行记录已不可用。");
|
|
199
|
+
const tools = (state.activities ?? []).filter((item) => item.kind === "tool");
|
|
200
|
+
if (route === "/tool") {
|
|
201
|
+
const toolId = parse(id, url.searchParams.get("tool"));
|
|
202
|
+
const tool = tools.find((item) => item.id === toolId)?.tool;
|
|
203
|
+
if (!tool) throw new RequestError(404, "该工具的执行记录已不可用。");
|
|
204
|
+
const journal = this.options.store.previews, journalId = state.previewTurnId ?? turn;
|
|
205
|
+
const journalSize = statSync(journal.file(journalId), { throwIfNoEntry: false })?.size ?? 0;
|
|
206
|
+
// Do not replay a very large journal inside a browser request.
|
|
207
|
+
const full = journalSize && journalSize <= MAX_TOOL_JOURNAL_BYTES ? journal.load(journalId, `tool:${toolId}`) : undefined;
|
|
208
|
+
const detail = full?.activities.find((item) => item.kind === "tool" && item.id === toolId);
|
|
209
|
+
const output = full?.fullToolOutputs?.[toolId] || (detail?.kind === "tool" ? detail.tool.output : tool.output) || "";
|
|
210
|
+
const error = full?.fullToolErrors?.[toolId] || (detail?.kind === "tool" ? detail.tool.error : tool.error) || "";
|
|
211
|
+
this.json(response, 200, { output: output.slice(0, MAX_TOOL_CHARS), error: error.slice(0, MAX_TOOL_CHARS),
|
|
212
|
+
truncated: output.length > MAX_TOOL_CHARS || error.length > MAX_TOOL_CHARS || Boolean(state.previewJournal && !full) });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.json(response, 200, {
|
|
216
|
+
plan: (state.plan ?? []).slice(0, 30),
|
|
217
|
+
tools: tools.slice(-30).map(({ id, tool }) => ({ id,
|
|
218
|
+
title: tool.title?.slice(0, 300), status: tool.status, command: tool.command?.slice(0, 2000),
|
|
219
|
+
hasOutput: Boolean(tool.output || tool.error || state.previewJournal),
|
|
220
|
+
})),
|
|
221
|
+
changes: (state.fileSummary ?? []).slice(0, 30).map((file) => ({
|
|
222
|
+
name: file.path, entry: this.fileEntry(task, path.resolve(task.cwd, file.path)),
|
|
223
|
+
})),
|
|
224
|
+
compact: Boolean(state.previewJournal || state.activitiesTruncated || state.historyDetail === "summary"),
|
|
225
|
+
}); return;
|
|
226
|
+
}
|
|
227
|
+
if (route === "/operation" && request.method === "GET") {
|
|
228
|
+
const requestId = parse(key, url.searchParams.get("request"));
|
|
229
|
+
const record = this.options.store.workspaceRequest(requestId);
|
|
230
|
+
if (!record) throw new RequestError(404, "未找到这次提交的记录。");
|
|
231
|
+
this.task(record.localSessionId);
|
|
232
|
+
this.json(response, 200, this.operation(requestId, record)); return;
|
|
233
|
+
}
|
|
234
|
+
if (route === "/operation" && request.method === "POST") {
|
|
235
|
+
const input = parse(instruction, await this.body(request));
|
|
236
|
+
this.json(response, 200, await this.submit(input)); return;
|
|
237
|
+
}
|
|
238
|
+
throw new RequestError(404, "工作台接口不存在。");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private eligible(task: SessionRecord): boolean {
|
|
242
|
+
return task.runtimeKind === "codex" || (task.runtimeKind === undefined && this.options.isAppServer?.(task.agentName) === true);
|
|
243
|
+
}
|
|
244
|
+
private task(key: string): SessionRecord {
|
|
245
|
+
const task = this.options.store.getSession(key);
|
|
246
|
+
if (!task || !this.eligible(task)) throw new RequestError(404, "任务不存在或不是 App Server 任务。");
|
|
247
|
+
return task;
|
|
248
|
+
}
|
|
249
|
+
private project(task: SessionRecord) {
|
|
250
|
+
const root = detectProjectlessWorkspace(task.cwd) ? undefined : path.resolve(task.cwd);
|
|
251
|
+
return { id: root ? (process.platform === "win32" ? root.toLowerCase() : root) : "", name: root ? path.basename(root) || root : "无项目", root };
|
|
252
|
+
}
|
|
253
|
+
private describe(task: SessionRecord, fileOrigin?: string) {
|
|
254
|
+
const project = this.project(task);
|
|
255
|
+
return { id: task.localSessionId, title: task.title?.slice(0, 200) || "未命名任务", agent: task.agentName,
|
|
256
|
+
provider: task.modelProvider, model: task.model, project, updatedAt: task.updatedAt,
|
|
257
|
+
status: task.status === "closed" ? "closed" : task.status === "running" || task.status === "starting"
|
|
258
|
+
? (task.lastTurnStatus === "waiting_for_approval" ? task.lastTurnStatus : task.status)
|
|
259
|
+
: task.lastTurnStatus ?? task.status,
|
|
260
|
+
...(fileOrigin ? { workspace: project.root && this.viewer.createWorkspaceUrl(project.root, fileOrigin),
|
|
261
|
+
queued: this.options.store.countQueuedPrompts(task.localSessionId) } : {}),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
private list(params: URLSearchParams) {
|
|
265
|
+
const search = (params.get("q") ?? "").slice(0, 160).trim().toLowerCase();
|
|
266
|
+
const all = this.options.store.listAllSessions().filter((task) => this.eligible(task)
|
|
267
|
+
&& (params.get("archived") === "1" ? task.status === "closed" : task.status !== "closed"));
|
|
268
|
+
const groups = new Map<string, ReturnType<WorkspaceSessions["project"]> & { count: number }>();
|
|
269
|
+
for (const task of all) {
|
|
270
|
+
const project = this.project(task);
|
|
271
|
+
if (search && !`${task.title ?? "未命名任务"}\n${project.name}\n${project.root ?? ""}\n${task.agentName}`.toLowerCase().includes(search)) continue;
|
|
272
|
+
const current = groups.get(project.id);
|
|
273
|
+
if (current) current.count++;
|
|
274
|
+
else groups.set(project.id, { ...project, count: 1 });
|
|
275
|
+
}
|
|
276
|
+
const project = params.get("project");
|
|
277
|
+
const cursor = params.get("after");
|
|
278
|
+
if (project !== null) {
|
|
279
|
+
const matches = all.filter((task) => this.project(task).id === project && (!search
|
|
280
|
+
|| `${task.title ?? "未命名任务"}\n${this.project(task).name}\n${task.cwd}\n${task.agentName}`.toLowerCase().includes(search)));
|
|
281
|
+
const index = cursor ? matches.findIndex((task) => task.localSessionId === cursor) + 1 : 0;
|
|
282
|
+
return { items: matches.slice(index, index + 20).map((task) => this.describe(task)), more: matches.length > index + 20 };
|
|
283
|
+
}
|
|
284
|
+
const values = [...groups.values()];
|
|
285
|
+
const index = cursor === null ? 0 : values.findIndex((group) => group.id === cursor) + 1;
|
|
286
|
+
return { groups: values.slice(index, index + 30), more: values.length > index + 30 };
|
|
287
|
+
}
|
|
288
|
+
private head(task: SessionRecord): string | undefined {
|
|
289
|
+
return this.options.store.workspaceTurnHead(task);
|
|
290
|
+
}
|
|
291
|
+
private history(task: SessionRecord, origin: string, before?: string, anchor?: string) {
|
|
292
|
+
const head = this.head(task);
|
|
293
|
+
const around = anchor && anchor !== head ? this.options.store.workspaceTurnPage(task.localSessionId, head, anchor, 1) : undefined;
|
|
294
|
+
const page = this.options.store.workspaceTurnPage(task.localSessionId, around && !around.beforeMissing ? anchor : head, before, MAX_HISTORY);
|
|
295
|
+
if (page.beforeMissing) throw new RequestError(409, "对话分支已有变更,请重新加载历史。");
|
|
296
|
+
const turns: NonNullable<ReturnType<WorkspaceSessions["turn"]>>[] = [];
|
|
297
|
+
let bytes = 0;
|
|
298
|
+
for (const turnId of page.ids) {
|
|
299
|
+
const turn = this.turn(task, turnId);
|
|
300
|
+
if (!turn) continue;
|
|
301
|
+
const cost = Buffer.byteLength(JSON.stringify(turn));
|
|
302
|
+
if (turns.length && bytes + cost > HISTORY_BYTES) break;
|
|
303
|
+
turns.push(turn); bytes += cost;
|
|
304
|
+
}
|
|
305
|
+
return { task: this.describe(task, origin), head, headStatus: head ? this.options.store.getTurnPromptSummary(head)?.status : undefined,
|
|
306
|
+
turns: turns.reverse(), more: page.more || turns.length < page.ids.length, anchored: Boolean(around && !around.beforeMissing) };
|
|
307
|
+
}
|
|
308
|
+
private turn(task: SessionRecord, turnId: string) {
|
|
309
|
+
const row = this.options.store.workspaceTurnText(turnId);
|
|
310
|
+
if (!row) return undefined;
|
|
311
|
+
const dialogue = JSON.parse(row.dialogue) as { kind: "assistant" | "user"; id: string; text: string | null; images: unknown }[];
|
|
312
|
+
const answer = row.answer || (row.status === "completed" || !dialogue.some((item) => item.kind === "assistant") ? row.live : undefined);
|
|
313
|
+
return { id: turnId, status: row.status, startedAt: row.startedAt, prompt: row.prompt?.slice(0, 24_000),
|
|
314
|
+
promptImages: this.attachments(task, row.promptImages ? JSON.parse(row.promptImages) : undefined),
|
|
315
|
+
answer: answer ? this.render(task, answer) : undefined,
|
|
316
|
+
messages: dialogue.flatMap((item) => {
|
|
317
|
+
const images = item.kind === "user" ? this.attachments(task, item.images) : undefined;
|
|
318
|
+
if ((!item.text && !images?.length) || (item.kind === "assistant" && item.text === answer)) return [];
|
|
319
|
+
const rich = item.kind === "assistant" && item.text?.includes("![") ? this.render(task, item.text, true) : undefined;
|
|
320
|
+
return [{ id: item.id, role: item.kind, text: rich ? undefined : item.text, images, rich }];
|
|
321
|
+
}),
|
|
322
|
+
error: row.error || row.notice ? displayRuntimeError(row.error || row.notice!) : undefined, summary: row.detail === "summary",
|
|
323
|
+
delivered: row.status === "completed" && row.answer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
private fileEntry(task: SessionRecord, file: string): string | undefined {
|
|
327
|
+
const { root } = this.project(task);
|
|
328
|
+
if (!root) return;
|
|
329
|
+
const relative = path.relative(root, file);
|
|
330
|
+
if (!relative || path.isAbsolute(relative) || relative === ".." || relative.startsWith(`..${path.sep}`)) return;
|
|
331
|
+
const entry = relative.split(path.sep).join("/");
|
|
332
|
+
try { resolveWorkspacePath(root, entry, true); return entry; } catch { return; }
|
|
333
|
+
}
|
|
334
|
+
private imageRoot(task?: SessionRecord): string {
|
|
335
|
+
return task ? path.resolve(task.cwd) : this.options.inboundImageDirectory;
|
|
336
|
+
}
|
|
337
|
+
private imageProof(root: string, entry: string, task?: SessionRecord): string {
|
|
338
|
+
return createHmac("sha256", this.imageSecret).update(JSON.stringify([root, entry, task?.localSessionId])).digest("base64url");
|
|
339
|
+
}
|
|
340
|
+
private imageUrl(file: string, task?: SessionRecord): URL | undefined {
|
|
341
|
+
const root = this.imageRoot(task);
|
|
342
|
+
if (!path.isAbsolute(file)) return;
|
|
343
|
+
const entry = path.relative(root, file).split(path.sep).join("/");
|
|
344
|
+
if (entry === ".." || entry.startsWith("../") || path.isAbsolute(entry) || !imageEntry.safeParse(entry).success) return;
|
|
345
|
+
const url = new URL(this.base); url.pathname += "/image";
|
|
346
|
+
url.searchParams.set("entry", entry);
|
|
347
|
+
if (task) url.searchParams.set("task", task.localSessionId);
|
|
348
|
+
url.searchParams.set("proof", this.imageProof(root, entry, task));
|
|
349
|
+
return url;
|
|
350
|
+
}
|
|
351
|
+
private attachments(task: SessionRecord, paths: unknown): (string | null)[] | undefined {
|
|
352
|
+
if (!Array.isArray(paths) || !paths.length) return;
|
|
353
|
+
const files = new Set(paths.filter((file): file is string => typeof file === "string" && !!file));
|
|
354
|
+
return [...files].slice(0, 20).map((file) => {
|
|
355
|
+
const url = this.imageUrl(file) ?? this.imageUrl(file, task);
|
|
356
|
+
return url ? url.pathname + url.search : null;
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
private serveImage(request: IncomingMessage, response: ServerResponse, params: URLSearchParams): void {
|
|
360
|
+
const { task: taskId, entry, proof } = parse(imageQuery, Object.fromEntries(params));
|
|
361
|
+
const task = taskId ? this.task(taskId) : undefined;
|
|
362
|
+
const root = this.imageRoot(task);
|
|
363
|
+
if (!timingSafeEqual(Buffer.from(proof), Buffer.from(this.imageProof(root, entry, task)))) {
|
|
364
|
+
throw new RequestError(403, "聊天图片链接无效。");
|
|
365
|
+
}
|
|
366
|
+
this.headers(response);
|
|
367
|
+
try { this.viewer.serveWorkspaceChatImage(request, response, root, entry); }
|
|
368
|
+
catch (error) {
|
|
369
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
370
|
+
if (error instanceof WorkspaceError || code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM") {
|
|
371
|
+
throw new RequestError(error instanceof WorkspaceError ? error.status : code === "EACCES" || code === "EPERM" ? 403 : 404, "聊天图片无法读取。");
|
|
372
|
+
}
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
private render(task: SessionRecord, text: string, short = false) {
|
|
377
|
+
const cacheKey = hash(`${task.localSessionId}\0${task.cwd}\0${short}\0${text}`), cached = this.rendered.get(cacheKey);
|
|
378
|
+
if (cached) return cached;
|
|
379
|
+
const truncated = text.length > 48_000;
|
|
380
|
+
const env = {}, tokens = markdown.parse(text.slice(0, 48_000), env);
|
|
381
|
+
const imagePrefix = this.base.origin + this.base.pathname + "/image?";
|
|
382
|
+
const visit = (items: typeof tokens): void => {
|
|
383
|
+
for (const item of items) {
|
|
384
|
+
if (item.type === "link_open") {
|
|
385
|
+
item.attrSet("rel", "noreferrer noopener"); item.attrSet("target", "_blank");
|
|
386
|
+
const href = item.attrGet("href");
|
|
387
|
+
if (typeof href === "string" && href.startsWith(this.base.origin + this.base.pathname + "/?file=")) {
|
|
388
|
+
const url = new URL(href); const entry = url.searchParams.get("file");
|
|
389
|
+
if (entry) item.attrSet("data-chat-file", entry);
|
|
390
|
+
item.attrSet("href", url.hash || "#");
|
|
391
|
+
}
|
|
392
|
+
} else if (item.type === "image") {
|
|
393
|
+
const src = item.attrGet("src");
|
|
394
|
+
if (typeof src === "string" && src.startsWith(imagePrefix)) item.attrSet("src", src.slice(this.base.origin.length));
|
|
395
|
+
else if (typeof src !== "string" || !/^data:image\/(?:gif|png|jpeg|webp);base64,/iu.test(src)) {
|
|
396
|
+
item.type = "text"; item.content = item.content ? `[图片不可用:${item.content}]` : "[图片不可用]";
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
item.attrSet("loading", "lazy"); item.attrSet("decoding", "async");
|
|
400
|
+
}
|
|
401
|
+
if (item.children) visit(item.children);
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
rewriteMarkdownFileLinks(tokens, path.join(task.cwd, "reply.md"), (file) => {
|
|
405
|
+
const entry = this.fileEntry(task, file);
|
|
406
|
+
if (!entry) return;
|
|
407
|
+
const url = new URL(this.base); url.pathname += "/"; url.searchParams.set("file", entry); return url;
|
|
408
|
+
}, (file) => this.imageUrl(file, task));
|
|
409
|
+
visit(tokens);
|
|
410
|
+
const html = markdown.renderer.render(tokens, markdown.options, env);
|
|
411
|
+
const result = html.length <= (short ? 12_000 : 220_000)
|
|
412
|
+
? { html, truncated }
|
|
413
|
+
: { html: `<p>${markdown.utils.escapeHtml(text.slice(0, short ? 4_000 : 24_000))}</p>`, truncated: true };
|
|
414
|
+
if (this.rendered.size >= 48) this.rendered.delete(this.rendered.keys().next().value!);
|
|
415
|
+
this.rendered.set(cacheKey, result); return result;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
private connect(grant: Grant, page: string, response: ServerResponse): void {
|
|
419
|
+
const current = this.streams.get(page);
|
|
420
|
+
if (current && current.grant !== grant) throw new RequestError(409, "请重新打开工作台页面。");
|
|
421
|
+
if (!current && this.streams.size >= 32) throw new RequestError(429, "实时连接已达到上限。");
|
|
422
|
+
current?.response.end();
|
|
423
|
+
this.headers(response);
|
|
424
|
+
response.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
425
|
+
response.setHeader("X-Accel-Buffering", "no");
|
|
426
|
+
response.flushHeaders();
|
|
427
|
+
const stream: Stream = { grant, response, version: 0, generation: 0, catalogue: this.catalogue, heartbeat: Date.now() };
|
|
428
|
+
this.streams.set(page, stream);
|
|
429
|
+
response.once("close", () => { if (this.streams.get(page) === stream) this.streams.delete(page); });
|
|
430
|
+
// Reconnects always reconcile with an authoritative snapshot; no per-token replay is needed.
|
|
431
|
+
this.event(stream, "sync", {});
|
|
432
|
+
}
|
|
433
|
+
private poll(): void {
|
|
434
|
+
if (!this.streams.size && !this.grants.size) return;
|
|
435
|
+
try {
|
|
436
|
+
const at = Date.now();
|
|
437
|
+
if (at >= this.nextPrune) { this.nextPrune = at + 5_000; this.pruneGrants(); }
|
|
438
|
+
if (!this.streams.size) return;
|
|
439
|
+
if (at >= this.nextCatalogue) {
|
|
440
|
+
this.nextCatalogue = at + 2_000;
|
|
441
|
+
const next = hash(JSON.stringify(this.options.store.listAllSessions().filter((task) => this.eligible(task)).map((task) => this.describe(task))));
|
|
442
|
+
if (this.catalogueHash !== next) { this.catalogueHash = next; this.catalogue++; }
|
|
443
|
+
}
|
|
444
|
+
const tails = new Map<string, unknown>();
|
|
445
|
+
for (const stream of this.streams.values()) {
|
|
446
|
+
if (stream.catalogue !== this.catalogue) {
|
|
447
|
+
stream.catalogue = this.catalogue; this.event(stream, "tasks", {});
|
|
448
|
+
}
|
|
449
|
+
if (stream.task) {
|
|
450
|
+
if (!tails.has(stream.task)) {
|
|
451
|
+
const task = this.options.store.getSession(stream.task), head = task && this.eligible(task) ? this.head(task) : undefined;
|
|
452
|
+
tails.set(stream.task, task && this.eligible(task) ? { task: this.describe(task), queued: this.options.store.countQueuedPrompts(task.localSessionId),
|
|
453
|
+
turn: head ? this.turn(task, head) : null } : null);
|
|
454
|
+
}
|
|
455
|
+
const next = JSON.stringify(tails.get(stream.task));
|
|
456
|
+
if (next !== stream.tail) {
|
|
457
|
+
stream.tail = next;
|
|
458
|
+
this.event(stream, "tail", { taskId: stream.task, generation: stream.generation, value: tails.get(stream.task) });
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (at - stream.heartbeat > 15_000) {
|
|
462
|
+
stream.heartbeat = at;
|
|
463
|
+
this.event(stream, "heartbeat", {});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
} catch (error) { this.options.logger.warn({ error }, "Failed to refresh Workspace events."); }
|
|
467
|
+
}
|
|
468
|
+
private event(stream: Stream, kind: string, payload: object): void {
|
|
469
|
+
if (stream.response.writableEnded) return;
|
|
470
|
+
const packet = `id: ${++stream.version}\nevent: ${kind}\ndata: ${JSON.stringify(payload)}\n\n`;
|
|
471
|
+
if (stream.response.writableLength > 256 * 1024) { stream.response.destroy(); return; }
|
|
472
|
+
stream.response.write(packet);
|
|
473
|
+
}
|
|
474
|
+
private async submit(input: z.infer<typeof instruction>) {
|
|
475
|
+
const task = this.task(input.task);
|
|
476
|
+
const store = this.options.store;
|
|
477
|
+
const fingerprint = hash(JSON.stringify(input));
|
|
478
|
+
const previous = store.workspaceRequest(input.request);
|
|
479
|
+
if (previous) {
|
|
480
|
+
if (previous.fingerprint !== fingerprint) throw new RequestError(409, "该请求标识已用于另一项操作。");
|
|
481
|
+
return this.operation(input.request, previous);
|
|
482
|
+
}
|
|
483
|
+
if (task.status === "closed") throw new RequestError(409, "任务已归档,不能发送或停止。");
|
|
484
|
+
if (!this.options.canSubmit()) throw new RequestError(503, "服务正在启动或重启,未提交此操作。");
|
|
485
|
+
if (this.running.size >= 16) throw new RequestError(429, "当前请求较多,未提交此操作。");
|
|
486
|
+
store.beginWorkspaceRequest(input.request, task.localSessionId, fingerprint);
|
|
487
|
+
this.running.add(input.request);
|
|
488
|
+
let ambiguous = input.action !== "send";
|
|
489
|
+
try {
|
|
490
|
+
if (input.action === "stop") {
|
|
491
|
+
const result = await this.options.controller.controlStopTask(task.localSessionId, input.turn);
|
|
492
|
+
store.updateWorkspaceRequest(input.request, result === "stale" ? "stale" : "accepted");
|
|
493
|
+
} else if (input.action === "queue") {
|
|
494
|
+
await this.options.controller.controlQueueTaskPrompt(task.localSessionId, input.text);
|
|
495
|
+
store.updateWorkspaceRequest(input.request, "accepted");
|
|
496
|
+
} else {
|
|
497
|
+
await this.options.controller.controlSendTaskPrompt(task.localSessionId, input.text, {
|
|
498
|
+
requestId: input.request,
|
|
499
|
+
onPosting: () => { ambiguous = true; },
|
|
500
|
+
onPosted: () => { store.updateWorkspaceRequest(input.request, "pending", true); },
|
|
501
|
+
});
|
|
502
|
+
store.updateWorkspaceRequest(input.request, "accepted");
|
|
503
|
+
}
|
|
504
|
+
} catch (error) {
|
|
505
|
+
const message = displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "操作未完成。");
|
|
506
|
+
store.updateWorkspaceRequest(input.request, ambiguous ? "unknown" : "failed", false, message);
|
|
507
|
+
} finally { this.running.delete(input.request); }
|
|
508
|
+
return this.operation(input.request, store.workspaceRequest(input.request)!);
|
|
509
|
+
}
|
|
510
|
+
private operation(request: string, record: NonNullable<ReturnType<StateStore["workspaceRequest"]>>) {
|
|
511
|
+
return { status: record.status === "pending" && !this.running.has(request) ? "unknown" : record.status,
|
|
512
|
+
posted: Boolean(record.posted), message: record.message ?? undefined };
|
|
513
|
+
}
|
|
514
|
+
private access(): WorkspaceAccess {
|
|
515
|
+
const password = this.options.password(), owner = this.options.owner();
|
|
516
|
+
if (!owner) return { mode: "disabled", hint: "尚未配置飞书所有者。" };
|
|
517
|
+
if (password === undefined || password === DEFAULT_TERMINAL_PASSWORD) return { mode: "automatic", credentials: { owner } };
|
|
518
|
+
if (!terminalPasswordSchema.safeParse(password).success) {
|
|
519
|
+
return { mode: "disabled", hint: "工作台 / 终端密码配置无效,请在飞书 /settings → 高级中修改后安全重启。" };
|
|
520
|
+
}
|
|
521
|
+
return { mode: "password", credentials: { owner, secret: hash(password) } };
|
|
522
|
+
}
|
|
523
|
+
private checkPassword(request: IncomingMessage, password: string, secret: string, at: number): void {
|
|
524
|
+
const address = request.socket.remoteAddress ?? "";
|
|
525
|
+
while (this.failures.length && at - this.failures[0]!.at > 60_000) this.failures.shift();
|
|
526
|
+
if (this.failures.length >= 60 || this.failures.filter((failure) => failure.address === address).length >= 6) {
|
|
527
|
+
throw new RequestError(429, "尝试次数过多,请稍后再试。");
|
|
528
|
+
}
|
|
529
|
+
if (!timingSafeEqual(Buffer.from(hash(password)), Buffer.from(secret))) {
|
|
530
|
+
this.failures.push({ address, at }); throw new RequestError(401, "工作台密码不正确。");
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
private valid(grant: Grant | undefined): grant is Grant {
|
|
534
|
+
if (!grant || grant.expires <= Date.now()) return false;
|
|
535
|
+
const credentials = this.access().credentials;
|
|
536
|
+
return credentials?.owner === grant.owner && credentials.secret === grant.secret;
|
|
537
|
+
}
|
|
538
|
+
private revoke(id: string): void {
|
|
539
|
+
const grant = this.grants.get(id);
|
|
540
|
+
this.grants.delete(id);
|
|
541
|
+
grant?.abort.abort();
|
|
542
|
+
}
|
|
543
|
+
private pruneGrants(): void {
|
|
544
|
+
for (const [id, grant] of this.grants) if (!this.valid(grant)) this.revoke(id);
|
|
545
|
+
for (const stream of this.streams.values()) if (stream.grant.signal.aborted) {
|
|
546
|
+
this.event(stream, "expired", {}); stream.response.end();
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
private sessionId(request: IncomingMessage): string {
|
|
550
|
+
return request.headers.cookie?.split(/;\s*/u).find((part) => part.startsWith(`${this.cookieName}=`))?.slice(this.cookieName.length + 1) ?? "";
|
|
551
|
+
}
|
|
552
|
+
private grant(request: IncomingMessage, origin: string): Grant | undefined {
|
|
553
|
+
const grant = this.grants.get(this.sessionId(request));
|
|
554
|
+
return this.valid(grant) && grant.origin === origin ? grant : undefined;
|
|
555
|
+
}
|
|
556
|
+
private cookie(value: string, age: number, origin: string): string {
|
|
557
|
+
const servicePath = new URL(".", this.base).pathname;
|
|
558
|
+
return `${this.cookieName}=${value}; Path=${servicePath}; HttpOnly; SameSite=Strict; Max-Age=${age}${origin.startsWith("https:") ? "; Secure" : ""}`;
|
|
559
|
+
}
|
|
560
|
+
private async body(request: IncomingMessage): Promise<unknown> {
|
|
561
|
+
if (Number(request.headers["content-length"]) > 150_000) throw new RequestError(413, "请求内容过大。");
|
|
562
|
+
const chunks: Buffer[] = [];
|
|
563
|
+
let bytes = 0;
|
|
564
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
565
|
+
const buffer = Buffer.from(chunk as Uint8Array); bytes += buffer.length;
|
|
566
|
+
if (bytes > 150_000) { request.resume(); throw new RequestError(413, "请求内容过大。"); }
|
|
567
|
+
chunks.push(buffer);
|
|
568
|
+
}
|
|
569
|
+
try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); }
|
|
570
|
+
catch { throw new RequestError(400, "请求内容不是有效的 JSON。"); }
|
|
571
|
+
}
|
|
572
|
+
private headers(response: ServerResponse): void {
|
|
573
|
+
response.setHeader("Cache-Control", "no-store");
|
|
574
|
+
response.setHeader("Referrer-Policy", "no-referrer");
|
|
575
|
+
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
576
|
+
response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
577
|
+
}
|
|
578
|
+
private json(response: ServerResponse, status: number, body: unknown): void {
|
|
579
|
+
this.headers(response); response.statusCode = status;
|
|
580
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8"); response.end(JSON.stringify(body));
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
function parse<T>(schema: z.ZodType<T>, value: unknown): T {
|
|
584
|
+
const parsed = schema.safeParse(value);
|
|
585
|
+
if (!parsed.success) throw new RequestError(400, "工作台参数无效,请检查输入。");
|
|
586
|
+
return parsed.data;
|
|
587
|
+
}
|