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