@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
|
@@ -1,29 +1,85 @@
|
|
|
1
1
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import MarkdownIt from "markdown-it";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { detectProjectlessWorkspace } from "../codex/ProjectlessWorkspace.js";
|
|
7
7
|
import { DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema } from "../config/schema.js";
|
|
8
|
+
import { listTaskDirectories, TASK_DIRECTORY_KIND, taskDirectoryId } from "../proxy/TaskMetadata.js";
|
|
8
9
|
import { displayRuntimeError } from "../runtime/responseErrors.js";
|
|
10
|
+
import { TurnNotSubmittedError } from "../runtime/submissionErrors.js";
|
|
11
|
+
import { scheduleDisplayPrompt, scheduleInputSchema } from "../scheduling/types.js";
|
|
12
|
+
import { toolTextFields } from "../state/TurnToolText.js";
|
|
13
|
+
import { formatPreviewToolCommand, normalizeToolOutput } from "./ToolCommandDisplay.js";
|
|
14
|
+
import { workspaceTimeline } from "./WorkspaceTimeline.js";
|
|
15
|
+
import { workspaceImageExtension } from "./WorkspaceImages.js";
|
|
9
16
|
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
10
17
|
import { highlightPreviewCode } from "./PreviewSyntaxHighlight.js";
|
|
11
|
-
import {
|
|
18
|
+
import { highlightRecordedPatch } from "./GitDiffPreview.js";
|
|
19
|
+
import { WORKSPACE_INSTANCE, WORKSPACE_INSTANCE_HEADER, WORKSPACE_REVISION, WORKSPACE_REVISION_HEADER } from "./WorkspacePage.js";
|
|
20
|
+
import { resolveWorkspaceDirectoryAddress, resolveWorkspacePath, WorkspaceError } from "./WorkspaceFiles.js";
|
|
12
21
|
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
22
|
+
import { turnAnswerFilename } from "./MarkdownExport.js";
|
|
23
|
+
import { toolTimestamp } from "../utils/toolTimestamp.js";
|
|
24
|
+
import { formatStorageSize } from "../utils/formatStorageSize.js";
|
|
25
|
+
import { defaultResourcePromptFromCounts, queuedPromptContent } from "../utils/promptAttachments.js";
|
|
13
26
|
const TTL = 8 * 60 * 60_000;
|
|
14
27
|
const MAX_HISTORY = 20;
|
|
28
|
+
const TASK_PAGE_SIZE = 20;
|
|
15
29
|
const HISTORY_BYTES = 512 * 1024;
|
|
16
|
-
const
|
|
17
|
-
const
|
|
30
|
+
const MAX_EXECUTION_CHARS = 32_000;
|
|
31
|
+
const MAX_TOOL_FILE_ENTRIES = 200;
|
|
32
|
+
const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
|
|
33
|
+
const MAX_ATTACHMENT_TOTAL = 12 * 1024 * 1024;
|
|
34
|
+
const MAX_OPERATION_BYTES = Math.ceil(MAX_ATTACHMENT_TOTAL / 3) * 4 + 150_000;
|
|
35
|
+
const attachmentData = z.string().max(Math.ceil(MAX_ATTACHMENT_BYTES / 3) * 4);
|
|
36
|
+
const attachmentKind = "workspace-prompt-files";
|
|
18
37
|
const id = z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u);
|
|
19
38
|
const key = z.uuid();
|
|
20
39
|
const imageEntry = z.string().min(1).max(4096).regex(/^[^\x00-\x1f\x7f]+$/u);
|
|
40
|
+
const directoryPanelKind = "workspace-directory-panel";
|
|
41
|
+
const directoryPanelKey = "state";
|
|
42
|
+
const maxDirectoryTabs = 24;
|
|
43
|
+
const directoryPanelState = z.object({
|
|
44
|
+
roots: z.record(taskDirectoryId, imageEntry),
|
|
45
|
+
tabs: z.array(taskDirectoryId),
|
|
46
|
+
active: taskDirectoryId.nullable(),
|
|
47
|
+
}).refine(({ active, roots, tabs }) => tabs.every((directory) => Object.hasOwn(roots, directory)) && (!active || tabs.includes(active)));
|
|
48
|
+
const directoryPanelCommand = z.discriminatedUnion("action", [
|
|
49
|
+
z.object({ task: id, action: z.literal("open-path"), address: imageEntry }).strict(),
|
|
50
|
+
z.object({ task: id, action: z.literal("open-recorded"), directory: taskDirectoryId }).strict(),
|
|
51
|
+
z.object({ task: id, action: z.literal("activate"), directory: taskDirectoryId.nullable() }).strict(),
|
|
52
|
+
z.object({ task: id, action: z.literal("close"), directory: taskDirectoryId }).strict(),
|
|
53
|
+
]);
|
|
21
54
|
const imageQuery = z.object({ task: id.optional(), entry: imageEntry, proof: z.string().regex(/^[A-Za-z0-9_-]{43}$/u) });
|
|
22
55
|
const selection = z.object({ page: key, task: id.optional(), generation: z.int().nonnegative(), anchor: id.optional() }).strict();
|
|
56
|
+
const newTask = z.object({ request: key, title: z.string().trim().max(200), agent: id,
|
|
57
|
+
directory: imageEntry.optional(), model: id.optional(), thinking: id.optional() }).strict();
|
|
58
|
+
const taskSetting = z.object({ task: id, setting: z.enum(["model", "thinking"]), value: id }).strict();
|
|
59
|
+
const turnAction = z.object({ task: id, turn: id, action: z.enum(["reset", "fork"]) }).strict();
|
|
60
|
+
const queueRevision = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
61
|
+
const queueCancel = z.object({ task: id, prompt: id, request: key, revision: queueRevision.optional() }).strict();
|
|
62
|
+
const queueEdit = z.object({ task: id, prompt: id, revision: queueRevision, text: z.string().trim().max(24_000) }).strict();
|
|
63
|
+
const attachmentEntry = z.object({ name: z.string().min(1).max(255), entry: imageEntry });
|
|
64
|
+
const uploadFields = {
|
|
65
|
+
images: z.array(attachmentData.min(1)).max(4).optional(),
|
|
66
|
+
files: z.array(z.object({ name: attachmentEntry.shape.name, data: attachmentData }).strict()).max(4).optional()
|
|
67
|
+
};
|
|
68
|
+
const scheduleCreate = z.object({ task: id, request: key, schedule: scheduleInputSchema, ...uploadFields }).strict()
|
|
69
|
+
.refine(input => Boolean(input.schedule.prompt || input.images?.length || input.files?.length)
|
|
70
|
+
&& (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4, "请输入 Prompt 或添加至多 4 个附件。");
|
|
71
|
+
const scheduleActionFields = { task: id, job: id, revision: z.int().positive() };
|
|
72
|
+
const scheduleAction = z.discriminatedUnion("action", [
|
|
73
|
+
z.object({ ...scheduleActionFields, action: z.literal("edit"), schedule: scheduleInputSchema }).strict(),
|
|
74
|
+
z.object({ ...scheduleActionFields, action: z.enum(["confirm", "pause", "resume", "delete", "run"]) }).strict(),
|
|
75
|
+
]);
|
|
76
|
+
const promptFields = { task: id, request: key, text: z.string().trim().max(24_000), ...uploadFields };
|
|
23
77
|
const instruction = z.discriminatedUnion("action", [
|
|
24
|
-
z.object({ action: z.enum(["send", "queue"]),
|
|
78
|
+
z.object({ action: z.enum(["send", "queue"]), ...promptFields }).strict(),
|
|
79
|
+
z.object({ action: z.literal("steer"), turn: id, ...promptFields }).strict(),
|
|
25
80
|
z.object({ action: z.literal("stop"), task: id, request: key, turn: id }).strict(),
|
|
26
|
-
])
|
|
81
|
+
]).refine((input) => input.action === "stop" || (Boolean(input.text || input.images?.length || input.files?.length)
|
|
82
|
+
&& (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4));
|
|
27
83
|
const markdown = new MarkdownIt({ html: false, breaks: true, linkify: true, highlight: highlightPreviewCode });
|
|
28
84
|
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
85
|
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
|
@@ -31,6 +87,49 @@ const validLink = markdown.validateLink.bind(markdown);
|
|
|
31
87
|
markdown.validateLink = (value) => isFileUrl(value) || /^\/?[a-z]:[\\/]/iu.test(value) || validLink(value);
|
|
32
88
|
const token = () => randomBytes(32).toString("base64url");
|
|
33
89
|
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
90
|
+
const activeTaskStatuses = new Set(["starting", "running", "tool_running", "waiting_for_approval"]);
|
|
91
|
+
function workspacePromptPreview(prompt) {
|
|
92
|
+
const text = prompt?.replace(/\s+/gu, " ").trim();
|
|
93
|
+
if (!text)
|
|
94
|
+
return null;
|
|
95
|
+
const start = /^.{1,48}/u.exec(text)[0];
|
|
96
|
+
return start === text ? text : `${start.trimEnd()}…`;
|
|
97
|
+
}
|
|
98
|
+
function queuePromptRevision(prompt) {
|
|
99
|
+
return hash(JSON.stringify([prompt.text, prompt.displayPrompt]));
|
|
100
|
+
}
|
|
101
|
+
function workspaceFileSummary(state, cwd) {
|
|
102
|
+
const key = (file) => {
|
|
103
|
+
const resolved = path.resolve(cwd, file);
|
|
104
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
105
|
+
};
|
|
106
|
+
const summaries = new Map((state.fileSummary ?? []).map((file) => [key(file.path), file]));
|
|
107
|
+
if (state.activitiesTruncated)
|
|
108
|
+
return [...summaries.values()];
|
|
109
|
+
const edits = new Map();
|
|
110
|
+
for (const activity of state.activities ?? []) {
|
|
111
|
+
if (activity.kind !== "tool")
|
|
112
|
+
continue;
|
|
113
|
+
for (const { path: name, additions, deletions, moveTo } of activity.tool.files ?? []) {
|
|
114
|
+
const id = key(name), previous = edits.get(id) ?? { path: name };
|
|
115
|
+
edits.set(id, { path: name, moveTo: moveTo ?? previous.moveTo,
|
|
116
|
+
additions: additions === undefined ? previous.additions : (previous.additions ?? 0) + additions,
|
|
117
|
+
deletions: deletions === undefined ? previous.deletions : (previous.deletions ?? 0) + deletions });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return [...summaries].map(([id, file]) => edits.get(id) ?? file);
|
|
121
|
+
}
|
|
122
|
+
function formatWorkspaceToolPage(page, offset, toolKind) {
|
|
123
|
+
if (offset !== 0)
|
|
124
|
+
return page;
|
|
125
|
+
// Formatting needs the whole command; page offsets always refer to the original text.
|
|
126
|
+
const command = toolKind === "command" && page.command && !page.remaining.includes("command")
|
|
127
|
+
? formatPreviewToolCommand(page.command) : undefined;
|
|
128
|
+
const sameError = page.output && page.error && !page.remaining.includes("output") && !page.remaining.includes("error")
|
|
129
|
+
&& normalizeToolOutput(page.output) === normalizeToolOutput(page.error);
|
|
130
|
+
return { ...page, ...(command && command !== page.command ? { displayCommand: command } : {}),
|
|
131
|
+
...(sameError ? { error: "", outputIsError: true } : {}) };
|
|
132
|
+
}
|
|
34
133
|
class RequestError extends Error {
|
|
35
134
|
status;
|
|
36
135
|
constructor(status, message) {
|
|
@@ -44,24 +143,32 @@ export class WorkspaceSessions {
|
|
|
44
143
|
base;
|
|
45
144
|
grants = new Map();
|
|
46
145
|
streams = new Map();
|
|
146
|
+
directoryStreams = new Map();
|
|
47
147
|
running = new Set();
|
|
148
|
+
turnActions = new Set();
|
|
48
149
|
imageSecret = randomBytes(32);
|
|
49
150
|
failures = [];
|
|
50
151
|
rendered = new Map();
|
|
152
|
+
metricsCache = new Map();
|
|
51
153
|
catalogue = 0;
|
|
52
154
|
catalogueHash = "";
|
|
53
155
|
nextCatalogue = 0;
|
|
54
156
|
timer;
|
|
55
157
|
nextPrune = 0;
|
|
158
|
+
operationBodies = 0;
|
|
159
|
+
lastSubmissionAt;
|
|
56
160
|
get cookieName() { return "agentbot_workspace_" + hash(`services:${this.base.href}`).slice(0, 16); }
|
|
57
161
|
constructor(viewer, options) {
|
|
58
162
|
this.viewer = viewer;
|
|
59
163
|
this.options = options;
|
|
60
164
|
}
|
|
61
|
-
get preparingActions() { return this.
|
|
165
|
+
get preparingActions() { return this.operationBodies; }
|
|
166
|
+
get latestInboundAt() {
|
|
167
|
+
return this.lastSubmissionAt === undefined ? undefined : new Date(this.lastSubmissionAt).toISOString();
|
|
168
|
+
}
|
|
62
169
|
start() {
|
|
63
170
|
this.base = new URL(this.viewer.mountService("workspace-app", this).publicBaseUrl);
|
|
64
|
-
this.timer = setInterval(() => this.poll(),
|
|
171
|
+
this.timer = setInterval(() => this.poll(), 400);
|
|
65
172
|
this.timer.unref();
|
|
66
173
|
return this.base.pathname;
|
|
67
174
|
}
|
|
@@ -70,9 +177,13 @@ export class WorkspaceSessions {
|
|
|
70
177
|
for (const stream of this.streams.values())
|
|
71
178
|
stream.response.end();
|
|
72
179
|
this.streams.clear();
|
|
180
|
+
for (const response of this.directoryStreams.keys())
|
|
181
|
+
response.end();
|
|
182
|
+
this.directoryStreams.clear();
|
|
73
183
|
for (const id of this.grants.keys())
|
|
74
184
|
this.revoke(id);
|
|
75
185
|
this.rendered.clear();
|
|
186
|
+
this.metricsCache.clear();
|
|
76
187
|
}
|
|
77
188
|
terminalAccess(request, origin) {
|
|
78
189
|
const site = request.headers["sec-fetch-site"];
|
|
@@ -109,11 +220,14 @@ export class WorkspaceSessions {
|
|
|
109
220
|
|| request.headers["content-type"]?.split(";")[0] !== "application/json"))
|
|
110
221
|
throw new RequestError(403, "工作台请求来源或格式无效。");
|
|
111
222
|
const imageRequest = route === "/image" && (request.method === "GET" || request.method === "HEAD");
|
|
112
|
-
|
|
223
|
+
const directoryRequest = route === "/directory" && (request.method === "GET" || request.method === "HEAD");
|
|
224
|
+
if (request.method !== "GET" && request.method !== "POST" && !imageRequest && !directoryRequest)
|
|
113
225
|
throw new RequestError(405, "工作台请求方法无效。");
|
|
114
226
|
const grant = this.grant(request, origin);
|
|
115
227
|
if (route === "/session" && request.method === "GET") {
|
|
116
228
|
const access = this.access();
|
|
229
|
+
response.setHeader(WORKSPACE_REVISION_HEADER, WORKSPACE_REVISION);
|
|
230
|
+
response.setHeader(WORKSPACE_INSTANCE_HEADER, WORKSPACE_INSTANCE);
|
|
117
231
|
this.json(response, 200, { available: access.mode !== "disabled", auth: access.mode, hint: access.hint, csrf: grant?.csrf });
|
|
118
232
|
return;
|
|
119
233
|
}
|
|
@@ -146,19 +260,82 @@ export class WorkspaceSessions {
|
|
|
146
260
|
this.revoke(idle[0]);
|
|
147
261
|
}
|
|
148
262
|
const abort = new AbortController();
|
|
149
|
-
this.grants.set(session, { ...access.credentials, origin, csrf, expires: at + TTL, abort, signal: abort.signal });
|
|
263
|
+
this.grants.set(session, { ...access.credentials, origin, csrf, expires: at + TTL, abort, signal: abort.signal, directories: new Map() });
|
|
150
264
|
response.setHeader("Set-Cookie", this.cookie(session, TTL / 1000, origin));
|
|
151
265
|
this.json(response, 200, { csrf, auth: access.mode });
|
|
152
266
|
return;
|
|
153
267
|
}
|
|
154
|
-
if (!grant)
|
|
268
|
+
if (!grant) {
|
|
269
|
+
response.setHeader(WORKSPACE_REVISION_HEADER, WORKSPACE_REVISION);
|
|
270
|
+
response.setHeader(WORKSPACE_INSTANCE_HEADER, WORKSPACE_INSTANCE);
|
|
155
271
|
throw new RequestError(401, "请登录工作台后继续。");
|
|
272
|
+
}
|
|
156
273
|
if (imageRequest) {
|
|
157
274
|
this.serveImage(request, response, url.searchParams);
|
|
158
275
|
return;
|
|
159
276
|
}
|
|
277
|
+
if (directoryRequest) {
|
|
278
|
+
const local = url.searchParams.get("local");
|
|
279
|
+
const task = local === null ? this.task(parse(id, url.searchParams.get("task"))).localSessionId : undefined;
|
|
280
|
+
const directory = parse(taskDirectoryId, local ?? url.searchParams.get("directory"));
|
|
281
|
+
const root = this.directoryRoot(grant, directory, task);
|
|
282
|
+
if (!root)
|
|
283
|
+
throw new RequestError(404, task ? "该目录未登记在当前任务中。" : "此目录链接已失效,请在地址栏重新输入路径。");
|
|
284
|
+
if (local !== null && url.searchParams.get("info") === "1" && request.method === "GET") {
|
|
285
|
+
this.json(response, 200, this.describeDirectory(directory, root));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const base = new URL(this.base.pathname + "/directory", origin);
|
|
289
|
+
if (task) {
|
|
290
|
+
base.searchParams.set("task", task);
|
|
291
|
+
base.searchParams.set("directory", directory);
|
|
292
|
+
}
|
|
293
|
+
else
|
|
294
|
+
base.searchParams.set("local", directory);
|
|
295
|
+
const invalidate = () => response.end();
|
|
296
|
+
if (request.method === "GET" && url.searchParams.get("api") === "events") {
|
|
297
|
+
this.directoryStreams.set(response, { grant, task, directory, root });
|
|
298
|
+
grant.signal.addEventListener("abort", invalidate, { once: true });
|
|
299
|
+
response.once("close", () => {
|
|
300
|
+
grant.signal.removeEventListener("abort", invalidate);
|
|
301
|
+
this.directoryStreams.delete(response);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
this.headers(response);
|
|
305
|
+
await this.viewer.serveTaskDirectory(request, response, url, root, base);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
160
308
|
if (request.method === "POST" && request.headers["x-workspace-csrf"] !== grant.csrf)
|
|
161
309
|
throw new RequestError(403, "工作台会话已变更,请刷新页面。");
|
|
310
|
+
if (route === "/directory-panel" && request.method === "POST") {
|
|
311
|
+
const input = parse(directoryPanelCommand, await this.body(request, 24_640));
|
|
312
|
+
this.json(response, 200, await this.updateDirectoryPanel(grant, input));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (route === "/directory" && request.method === "POST") {
|
|
316
|
+
const { address } = parse(z.object({ address: imageEntry }).strict(), await this.body(request, 24_640));
|
|
317
|
+
let resolved;
|
|
318
|
+
try {
|
|
319
|
+
resolved = await resolveWorkspaceDirectoryAddress(address);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
if (error instanceof WorkspaceError)
|
|
323
|
+
throw new RequestError(error.status, error.message);
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
const { root, entry } = resolved;
|
|
327
|
+
if (grant.signal.aborted || !this.valid(grant))
|
|
328
|
+
throw new RequestError(401, "工作台会话已过期。");
|
|
329
|
+
const fingerprint = process.platform === "win32" ? root.toLowerCase() : root;
|
|
330
|
+
const directory = createHmac("sha256", grant.csrf).update(fingerprint).digest("hex").slice(0, 32);
|
|
331
|
+
// Keep recently opened roots scoped to this login.
|
|
332
|
+
grant.directories.delete(directory);
|
|
333
|
+
grant.directories.set(directory, root);
|
|
334
|
+
if (grant.directories.size > 128)
|
|
335
|
+
grant.directories.delete(grant.directories.keys().next().value);
|
|
336
|
+
this.json(response, 200, { ...this.describeDirectory(directory, root), entry });
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
162
339
|
if (route === "/logout" && request.method === "POST") {
|
|
163
340
|
this.revoke(this.sessionId(request));
|
|
164
341
|
this.pruneGrants();
|
|
@@ -174,11 +351,83 @@ export class WorkspaceSessions {
|
|
|
174
351
|
this.json(response, 200, this.list(url.searchParams));
|
|
175
352
|
return;
|
|
176
353
|
}
|
|
354
|
+
if (route === "/task-agents" && request.method === "GET") {
|
|
355
|
+
this.json(response, 200, this.options.controller.controlWorkspaceAgents());
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (route === "/draft-settings" && request.method === "GET") {
|
|
359
|
+
const agent = parse(id, url.searchParams.get("agent"));
|
|
360
|
+
await this.controlAction(grant, async () => {
|
|
361
|
+
this.json(response, 200, await this.options.controller.controlWorkspaceDraftSettings(agent));
|
|
362
|
+
});
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (route === "/tasks" && request.method === "POST") {
|
|
366
|
+
const input = parse(newTask, await this.body(request));
|
|
367
|
+
await this.controlAction(grant, async () => {
|
|
368
|
+
const localId = "sess_" + input.request.replaceAll("-", "");
|
|
369
|
+
const fingerprint = hash(JSON.stringify([grant.owner, input]));
|
|
370
|
+
const store = this.options.store;
|
|
371
|
+
const alreadyCreated = () => {
|
|
372
|
+
if (!store.getSession(localId))
|
|
373
|
+
return false;
|
|
374
|
+
if (store.getTaskMetadata(localId, "workspace-create", "request") !== fingerprint)
|
|
375
|
+
throw new RequestError(409, "该请求标识已用于另一个新任务。");
|
|
376
|
+
this.json(response, 201, { id: localId });
|
|
377
|
+
return true;
|
|
378
|
+
};
|
|
379
|
+
if (alreadyCreated())
|
|
380
|
+
return;
|
|
381
|
+
const cwd = input.directory ? (await resolveWorkspaceDirectoryAddress(input.directory, { directoryOnly: true })).root : undefined;
|
|
382
|
+
let thinking = input.thinking;
|
|
383
|
+
if (input.model || input.thinking) {
|
|
384
|
+
const settings = await this.options.controller.controlWorkspaceDraftSettings(input.agent);
|
|
385
|
+
const model = settings.models.find((item) => item.id === (input.model ?? settings.model))
|
|
386
|
+
?? (!input.model ? settings.models.find((item) => item.isDefault) : undefined);
|
|
387
|
+
if ((input.model && !model) || (input.thinking && !model?.supportedReasoningEfforts.some((item) => item.value === input.thinking))) {
|
|
388
|
+
throw new RequestError(400, "当前 Agent 不支持选中的模型或思考强度。");
|
|
389
|
+
}
|
|
390
|
+
if (input.model && !thinking)
|
|
391
|
+
thinking = model?.supportedReasoningEfforts.some((item) => item.value === settings.thinking)
|
|
392
|
+
? settings.thinking : model?.defaultReasoningEffort;
|
|
393
|
+
}
|
|
394
|
+
if (!this.valid(grant))
|
|
395
|
+
throw new RequestError(401, "工作台会话已过期。");
|
|
396
|
+
if (alreadyCreated())
|
|
397
|
+
return;
|
|
398
|
+
this.options.controller.controlCreateWorkspaceTask(localId, grant.owner, input.title, input.agent, cwd, input.model, thinking);
|
|
399
|
+
store.setTaskMetadata(localId, "workspace-create", "request", fingerprint);
|
|
400
|
+
this.json(response, 201, { id: localId });
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (route === "/task-settings") {
|
|
405
|
+
const input = request.method === "POST" ? parse(taskSetting, await this.body(request)) : undefined;
|
|
406
|
+
const task = this.task(input?.task ?? parse(id, url.searchParams.get("task")));
|
|
407
|
+
if (task.status === "closed")
|
|
408
|
+
throw new RequestError(409, "任务已归档。");
|
|
409
|
+
await this.controlAction(grant, async () => {
|
|
410
|
+
const settings = await this.options.controller.controlTaskSettings(task.localSessionId, input?.setting, input?.value, { quiet: true });
|
|
411
|
+
const selected = settings.pendingProvider?.settings ?? settings.session;
|
|
412
|
+
this.json(response, 200, { model: selected.model, provider: selected.modelProvider, thinking: selected.reasoningEffort,
|
|
413
|
+
models: settings.models, reasoningOptions: settings.reasoningOptions, pending: Boolean(settings.pendingProvider) });
|
|
414
|
+
});
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
if (route === "/attachment" && request.method === "GET") {
|
|
418
|
+
await this.serveAttachment(response, url.searchParams);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
177
421
|
if (route === "/task" && request.method === "GET") {
|
|
178
422
|
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
179
423
|
const before = parse(id.optional(), url.searchParams.get("before") ?? undefined);
|
|
180
424
|
const anchor = parse(id.optional(), url.searchParams.get("anchor") ?? undefined);
|
|
181
|
-
|
|
425
|
+
const after = parse(id.optional(), url.searchParams.get("after") ?? undefined);
|
|
426
|
+
if (after && (before || anchor))
|
|
427
|
+
throw new RequestError(400, "对话分页参数冲突。");
|
|
428
|
+
const stream = after ? this.streams.get(url.searchParams.get("page") ?? "") : undefined;
|
|
429
|
+
const version = stream?.grant === grant && stream.task === task.localSessionId ? stream.version : undefined;
|
|
430
|
+
this.json(response, 200, { ...this.history(task, origin, before, anchor, after), version });
|
|
182
431
|
return;
|
|
183
432
|
}
|
|
184
433
|
if (route === "/focus" && request.method === "POST") {
|
|
@@ -195,42 +444,168 @@ export class WorkspaceSessions {
|
|
|
195
444
|
this.json(response, 200, { ...(task && this.history(task, origin, undefined, input.anchor)), version: stream.version, generation: stream.generation });
|
|
196
445
|
return;
|
|
197
446
|
}
|
|
447
|
+
if (route === "/queue" && request.method === "GET") {
|
|
448
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
449
|
+
const promptId = parse(id, url.searchParams.get("prompt"));
|
|
450
|
+
const prompt = this.requireQueuedPrompt(task.localSessionId, promptId);
|
|
451
|
+
const run = this.options.store.schedules.getRun(promptId);
|
|
452
|
+
const requestId = run ? run.id.slice("schedule_run_".length)
|
|
453
|
+
: promptId.startsWith("workspace:") ? key.safeParse(promptId.slice("workspace:".length)).data : undefined;
|
|
454
|
+
const files = this.attachmentLinks(task.localSessionId, requestId);
|
|
455
|
+
this.json(response, 200, { text: run ? queuedPromptContent(prompt).text : files?.length ? prompt.displayPrompt ?? prompt.text : prompt.text,
|
|
456
|
+
revision: queuePromptRevision(prompt), files, images: this.attachments(task, prompt.localImagePaths) });
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
if (route === "/queue/edit" && request.method === "GET") {
|
|
460
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
461
|
+
const prompt = this.requireQueuedPrompt(task.localSessionId, parse(id, url.searchParams.get("prompt")));
|
|
462
|
+
this.json(response, 200, { text: queuedPromptContent(prompt).text, revision: queuePromptRevision(prompt) });
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (route === "/queue/edit" && request.method === "POST") {
|
|
466
|
+
const input = parse(queueEdit, await this.body(request));
|
|
467
|
+
await this.controlAction(grant, async () => {
|
|
468
|
+
this.task(input.task);
|
|
469
|
+
const prompt = this.requireQueuedPrompt(input.task, input.prompt);
|
|
470
|
+
const content = queuedPromptContent(prompt);
|
|
471
|
+
if (input.text === content.text) {
|
|
472
|
+
this.json(response, 200, this.describeQueuedPrompt(prompt));
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (input.revision !== queuePromptRevision(prompt))
|
|
476
|
+
throw new RequestError(409, "这条消息已被修改,请重新打开编辑。");
|
|
477
|
+
const images = prompt.localImagePaths?.length ?? 0;
|
|
478
|
+
if (!input.text && !images && !content.fileCount)
|
|
479
|
+
throw new RequestError(400, "请输入消息内容。");
|
|
480
|
+
const text = input.text || (content.fileCount ? defaultResourcePromptFromCounts(images, content.fileCount) : "");
|
|
481
|
+
const run = this.options.store.schedules.getRun(prompt.promptId);
|
|
482
|
+
const job = run && this.options.store.schedules.get(run.jobId);
|
|
483
|
+
const displayPrompt = job && run
|
|
484
|
+
? `[定时任务:${job.spec.name} · ${new Date(run.scheduledFor).toISOString()}]\n${scheduleDisplayPrompt(job, text)}`
|
|
485
|
+
: prompt.displayPrompt !== undefined || content.suffix ? text : undefined;
|
|
486
|
+
const updated = { text: text + content.suffix, displayPrompt };
|
|
487
|
+
if (!(await this.options.controller.controlEditWorkspaceQueue(prompt, updated))) {
|
|
488
|
+
throw new RequestError(409, "这条消息已被修改或离开队列。");
|
|
489
|
+
}
|
|
490
|
+
this.json(response, 200, this.describeQueuedPrompt({ ...prompt, ...updated }));
|
|
491
|
+
});
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (route === "/queue" && request.method === "POST") {
|
|
495
|
+
const input = parse(queueCancel, await this.body(request));
|
|
496
|
+
await this.controlAction(grant, async () => {
|
|
497
|
+
this.task(input.task);
|
|
498
|
+
if (input.revision && !this.options.store.workspaceRequest(input.request)) {
|
|
499
|
+
const prompt = this.requireQueuedPrompt(input.task, input.prompt);
|
|
500
|
+
if (input.revision !== queuePromptRevision(prompt))
|
|
501
|
+
throw new RequestError(409, "这条消息已被修改,请重新恢复。");
|
|
502
|
+
}
|
|
503
|
+
const cancelled = await this.options.controller.controlCancelWorkspaceQueue(input.task, input.prompt, input.request);
|
|
504
|
+
this.json(response, 200, { cancelled });
|
|
505
|
+
});
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (route === "/schedules" && request.method === "GET") {
|
|
509
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
510
|
+
const offset = parse(z.coerce.number().int().min(0).max(1_000_000), url.searchParams.get("offset") ?? 0);
|
|
511
|
+
const jobs = this.options.store.schedules.listForSession(task.localSessionId, grant.owner, 21, offset);
|
|
512
|
+
this.json(response, 200, { jobs: jobs.slice(0, 20).map(job => this.describeSchedule(job)), more: jobs.length > 20 });
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (route === "/schedules" && request.method === "POST") {
|
|
516
|
+
await this.controlAction(grant, async () => {
|
|
517
|
+
const input = parse(scheduleCreate, await this.body(request, MAX_OPERATION_BYTES));
|
|
518
|
+
this.json(response, 201, this.describeSchedule(await this.createSchedule(input, grant)));
|
|
519
|
+
});
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
if (route === "/schedules/runs" && request.method === "GET") {
|
|
523
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
524
|
+
const job = this.scheduleForTask(task.localSessionId, parse(id, url.searchParams.get("job")), grant.owner);
|
|
525
|
+
this.json(response, 200, { runs: this.options.store.schedules.runs(job.id, 10) });
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (route === "/schedules/action" && request.method === "POST") {
|
|
529
|
+
const input = parse(scheduleAction, await this.body(request));
|
|
530
|
+
await this.controlAction(grant, async () => {
|
|
531
|
+
const task = this.task(input.task);
|
|
532
|
+
const job = this.scheduleForTask(task.localSessionId, input.job, grant.owner);
|
|
533
|
+
if (job.revision !== input.revision)
|
|
534
|
+
throw new RequestError(409, "计划已变化,请刷新后重试。");
|
|
535
|
+
const controller = this.options.controller;
|
|
536
|
+
if (input.action === "edit")
|
|
537
|
+
controller.controlEditWorkspaceSchedule(job, input.schedule);
|
|
538
|
+
else
|
|
539
|
+
await controller.controlWorkspaceScheduleAction(job, input.action);
|
|
540
|
+
this.json(response, 200, { ok: true });
|
|
541
|
+
});
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (route === "/answer" && request.method === "GET") {
|
|
545
|
+
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
546
|
+
const turn = parse(id, url.searchParams.get("turn"));
|
|
547
|
+
this.requireBranchTurn(task, turn);
|
|
548
|
+
const markdown = this.options.store.workspaceTurnAnswer(turn);
|
|
549
|
+
if (!markdown)
|
|
550
|
+
throw new RequestError(404, "该轮次没有最终回答。");
|
|
551
|
+
this.json(response, 200, { markdown, filename: turnAnswerFilename(turn) });
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (route === "/turn-action" && request.method === "POST") {
|
|
555
|
+
const input = parse(turnAction, await this.body(request));
|
|
556
|
+
await this.controlAction(grant, async () => {
|
|
557
|
+
const task = this.task(input.task);
|
|
558
|
+
this.requireBranchTurn(task, input.turn);
|
|
559
|
+
if (input.action === "reset") {
|
|
560
|
+
if (task.status === "closed")
|
|
561
|
+
throw new RequestError(409, "任务已归档。");
|
|
562
|
+
if (activeTaskStatuses.has(this.describe(task).status))
|
|
563
|
+
throw new RequestError(409, "当前任务仍在执行,请等待任务完成后再重置。");
|
|
564
|
+
}
|
|
565
|
+
if (this.options.store.getTurnPromptSummary(input.turn)?.status !== "completed")
|
|
566
|
+
throw new RequestError(409, "只能从已完成的轮次继续。");
|
|
567
|
+
if (this.turnActions.has(input.task))
|
|
568
|
+
throw new RequestError(409, "该任务正在重置或创建分支。");
|
|
569
|
+
this.turnActions.add(input.task);
|
|
570
|
+
try {
|
|
571
|
+
const controller = this.options.controller;
|
|
572
|
+
const result = input.action === "reset"
|
|
573
|
+
? await controller.controlResetTaskToTurn(input.task, input.turn, { quiet: true })
|
|
574
|
+
: await controller.controlForkWorkspaceTask(input.task, input.turn);
|
|
575
|
+
this.json(response, 200, { id: result.localSessionId });
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
this.turnActions.delete(input.task);
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
198
583
|
if ((route === "/detail" || route === "/tool") && request.method === "GET") {
|
|
199
584
|
const task = this.task(parse(id, url.searchParams.get("task")));
|
|
200
585
|
const turn = parse(id, url.searchParams.get("turn"));
|
|
201
|
-
const head = this.
|
|
202
|
-
if (turn !== head && this.options.store.workspaceTurnPage(task.localSessionId, head, turn, 1).beforeMissing) {
|
|
203
|
-
throw new RequestError(404, "当前对话分支中没有该轮次。");
|
|
204
|
-
}
|
|
586
|
+
const head = this.requireBranchTurn(task, turn);
|
|
205
587
|
const state = this.options.store.getTurnSnapshot(turn);
|
|
206
588
|
if (!state)
|
|
207
589
|
throw new RequestError(404, "执行记录已不可用。");
|
|
208
|
-
const tools = (state.activities ?? []).filter((item) => item.kind === "tool");
|
|
209
590
|
if (route === "/tool") {
|
|
210
591
|
const toolId = parse(id, url.searchParams.get("tool"));
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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) });
|
|
592
|
+
const offset = parse(z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER - MAX_EXECUTION_CHARS), url.searchParams.get("offset") ?? 0);
|
|
593
|
+
const revision = parse(z.string().max(64).optional(), url.searchParams.get("revision") ?? undefined);
|
|
594
|
+
const page = await this.toolPage(task, state, toolId, offset, revision);
|
|
595
|
+
if (grant.signal.aborted || !this.valid(grant))
|
|
596
|
+
throw new RequestError(401, "工作台会话已过期。");
|
|
597
|
+
const currentHead = this.head(this.task(task.localSessionId));
|
|
598
|
+
if (currentHead !== head && currentHead !== turn && this.options.store.workspaceTurnPage(task.localSessionId, currentHead, turn, 1).beforeMissing) {
|
|
599
|
+
throw new RequestError(404, "当前对话分支中没有该轮次。");
|
|
600
|
+
}
|
|
601
|
+
this.json(response, 200, page);
|
|
223
602
|
return;
|
|
224
603
|
}
|
|
604
|
+
const cwd = state.projectCwd ?? task.cwd;
|
|
605
|
+
const changes = this.toolFiles(task, cwd, workspaceFileSummary(state, cwd));
|
|
225
606
|
this.json(response, 200, {
|
|
226
607
|
plan: (state.plan ?? []).slice(0, 30),
|
|
227
|
-
|
|
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
|
-
})),
|
|
608
|
+
changes: changes.files, changesTruncated: changes.filesTruncated,
|
|
234
609
|
compact: Boolean(state.previewJournal || state.activitiesTruncated || state.historyDetail === "summary"),
|
|
235
610
|
});
|
|
236
611
|
return;
|
|
@@ -245,12 +620,119 @@ export class WorkspaceSessions {
|
|
|
245
620
|
return;
|
|
246
621
|
}
|
|
247
622
|
if (route === "/operation" && request.method === "POST") {
|
|
248
|
-
|
|
249
|
-
|
|
623
|
+
if (this.operationBodies >= 4)
|
|
624
|
+
throw new RequestError(429, "当前请求较多,未提交此操作。");
|
|
625
|
+
this.operationBodies++;
|
|
626
|
+
try {
|
|
627
|
+
const input = parse(instruction, await this.body(request, MAX_OPERATION_BYTES));
|
|
628
|
+
if (grant.signal.aborted || !this.valid(grant))
|
|
629
|
+
throw new RequestError(401, "工作台会话已过期,未提交此操作。");
|
|
630
|
+
this.json(response, 200, await this.submit(input, url.searchParams.get("retry") === "1"));
|
|
631
|
+
}
|
|
632
|
+
finally {
|
|
633
|
+
this.operationBodies--;
|
|
634
|
+
}
|
|
250
635
|
return;
|
|
251
636
|
}
|
|
252
637
|
throw new RequestError(404, "工作台接口不存在。");
|
|
253
638
|
}
|
|
639
|
+
describeDirectory(id, root) {
|
|
640
|
+
return { id, name: path.basename(root) || root, path: root };
|
|
641
|
+
}
|
|
642
|
+
async controlAction(grant, action) {
|
|
643
|
+
if (!this.valid(grant))
|
|
644
|
+
throw new RequestError(401, "工作台会话已过期。");
|
|
645
|
+
if (!this.options.canSubmit())
|
|
646
|
+
throw new RequestError(503, "服务正在启动或切换,请稍后重试。");
|
|
647
|
+
if (this.operationBodies >= 4)
|
|
648
|
+
throw new RequestError(429, "当前请求较多,请稍后重试。");
|
|
649
|
+
this.operationBodies++;
|
|
650
|
+
try {
|
|
651
|
+
await action();
|
|
652
|
+
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
if (error instanceof RequestError)
|
|
655
|
+
throw error;
|
|
656
|
+
throw new RequestError(error instanceof WorkspaceError ? error.status : 409, displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "操作未完成。"));
|
|
657
|
+
}
|
|
658
|
+
finally {
|
|
659
|
+
this.operationBodies--;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
directoryRoot(grant, directory, task) {
|
|
663
|
+
return task ? this.readDirectoryPanel(task).roots[directory] ??
|
|
664
|
+
this.options.store.getTaskMetadata(task, TASK_DIRECTORY_KIND, directory) : grant.directories.get(directory);
|
|
665
|
+
}
|
|
666
|
+
readDirectoryPanel(task) {
|
|
667
|
+
const saved = this.options.store.getTaskMetadata(task, directoryPanelKind, directoryPanelKey);
|
|
668
|
+
if (saved) {
|
|
669
|
+
try {
|
|
670
|
+
const result = directoryPanelState.safeParse(JSON.parse(saved));
|
|
671
|
+
if (result.success)
|
|
672
|
+
return result.data;
|
|
673
|
+
}
|
|
674
|
+
catch { /* Recover from invalid saved panel state. */ }
|
|
675
|
+
}
|
|
676
|
+
return { roots: {}, tabs: [], active: null };
|
|
677
|
+
}
|
|
678
|
+
describeDirectoryPanel(task, state = this.readDirectoryPanel(task)) {
|
|
679
|
+
return { tabs: state.tabs.map((id) => this.describeDirectory(id, state.roots[id])), active: state.active,
|
|
680
|
+
directories: Object.entries(state.roots).map(([id, root]) => this.describeDirectory(id, root)) };
|
|
681
|
+
}
|
|
682
|
+
async updateDirectoryPanel(grant, input) {
|
|
683
|
+
const task = this.task(input.task);
|
|
684
|
+
let opened;
|
|
685
|
+
if (input.action === "open-path" || input.action === "open-recorded") {
|
|
686
|
+
const address = input.action === "open-path" ? input.address.trim() : this.directoryRoot(grant, input.directory, input.task);
|
|
687
|
+
if (!address)
|
|
688
|
+
throw new RequestError(404, "该目录未登记在当前任务中。");
|
|
689
|
+
try {
|
|
690
|
+
const { root } = await resolveWorkspaceDirectoryAddress(address, { directoryOnly: true });
|
|
691
|
+
const primary = this.project(task).root;
|
|
692
|
+
const canonicalPrimary = primary
|
|
693
|
+
? await resolveWorkspaceDirectoryAddress(primary, { directoryOnly: true }).then(({ root }) => root, () => primary) : undefined;
|
|
694
|
+
const fingerprint = (value) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
695
|
+
if (!canonicalPrimary || fingerprint(canonicalPrimary) !== fingerprint(root)) {
|
|
696
|
+
opened = { id: hash(fingerprint(root)).slice(0, 32), root };
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
if (error instanceof WorkspaceError)
|
|
701
|
+
throw new RequestError(error.status, error.message);
|
|
702
|
+
throw error;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
if (grant.signal.aborted || !this.valid(grant))
|
|
706
|
+
throw new RequestError(401, "工作台会话已过期。");
|
|
707
|
+
const state = this.readDirectoryPanel(input.task);
|
|
708
|
+
if (input.action === "activate") {
|
|
709
|
+
if (input.directory && !state.tabs.includes(input.directory))
|
|
710
|
+
throw new RequestError(404, "该目录标签已关闭。");
|
|
711
|
+
state.active = input.directory;
|
|
712
|
+
}
|
|
713
|
+
else if (input.action === "close") {
|
|
714
|
+
const index = state.tabs.indexOf(input.directory);
|
|
715
|
+
if (index >= 0) {
|
|
716
|
+
state.tabs.splice(index, 1);
|
|
717
|
+
if (state.active === input.directory)
|
|
718
|
+
state.active = state.tabs[index] ?? state.tabs[index - 1] ?? null;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
else if (opened) {
|
|
722
|
+
if (!state.tabs.includes(opened.id)) {
|
|
723
|
+
if (state.tabs.length >= maxDirectoryTabs)
|
|
724
|
+
throw new RequestError(400, "打开的目录标签已达上限,请先关闭一个标签。");
|
|
725
|
+
state.tabs.push(opened.id);
|
|
726
|
+
}
|
|
727
|
+
state.roots[opened.id] = opened.root;
|
|
728
|
+
state.active = opened.id;
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
state.active = null;
|
|
732
|
+
}
|
|
733
|
+
this.options.store.setTaskMetadata(input.task, directoryPanelKind, directoryPanelKey, JSON.stringify(state));
|
|
734
|
+
return this.describeDirectoryPanel(input.task, state);
|
|
735
|
+
}
|
|
254
736
|
eligible(task) {
|
|
255
737
|
return task.runtimeKind === "codex" || (task.runtimeKind === undefined && this.options.isAppServer?.(task.agentName) === true);
|
|
256
738
|
}
|
|
@@ -264,15 +746,76 @@ export class WorkspaceSessions {
|
|
|
264
746
|
const root = detectProjectlessWorkspace(task.cwd) ? undefined : path.resolve(task.cwd);
|
|
265
747
|
return { id: root ? (process.platform === "win32" ? root.toLowerCase() : root) : "", name: root ? path.basename(root) || root : "无项目", root };
|
|
266
748
|
}
|
|
749
|
+
describeSchedule(job) {
|
|
750
|
+
const { name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes } = job.spec;
|
|
751
|
+
return { id: job.id, revision: job.revision, name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes,
|
|
752
|
+
status: job.status, nextRunAt: job.nextRunAt, notice: job.notice,
|
|
753
|
+
images: job.attachments?.images.length, files: job.attachments?.files.map(file => file.fileName) };
|
|
754
|
+
}
|
|
755
|
+
scheduleForTask(task, id, owner) {
|
|
756
|
+
const job = this.options.store.schedules.get(id);
|
|
757
|
+
if (!job || job.status === "deleted" || job.localSessionId !== task || job.ownerId !== owner)
|
|
758
|
+
throw new RequestError(404, "找不到此定时任务。");
|
|
759
|
+
return job;
|
|
760
|
+
}
|
|
761
|
+
async createSchedule(input, grant) {
|
|
762
|
+
const task = this.task(input.task);
|
|
763
|
+
const fingerprint = hash(JSON.stringify(input));
|
|
764
|
+
const store = this.options.store.schedules;
|
|
765
|
+
const create = (attachments) => this.options.controller.controlCreateWorkspaceSchedule(task.localSessionId, input.schedule, input.request, { attachments, fingerprint });
|
|
766
|
+
const previous = store.getByRequest(input.request);
|
|
767
|
+
if (previous?.creationFingerprint) {
|
|
768
|
+
if (previous.localSessionId !== task.localSessionId || previous.ownerId !== grant.owner || previous.creationFingerprint !== fingerprint) {
|
|
769
|
+
throw new RequestError(409, "该请求标识已用于另一项计划。");
|
|
770
|
+
}
|
|
771
|
+
return previous;
|
|
772
|
+
}
|
|
773
|
+
const { images, files } = this.decodeAttachments(input.images ?? [], input.files ?? []);
|
|
774
|
+
if (!images.length && !files.length)
|
|
775
|
+
return create();
|
|
776
|
+
if (previous)
|
|
777
|
+
throw new RequestError(409, "该请求标识已用于另一项计划。");
|
|
778
|
+
const { directory, attachments } = await this.writePromptAttachments(images, files);
|
|
779
|
+
let keep = false;
|
|
780
|
+
try {
|
|
781
|
+
if (!this.valid(grant))
|
|
782
|
+
throw new RequestError(401, "工作台会话已过期,未创建计划。");
|
|
783
|
+
const alreadyCreated = store.getByRequest(input.request);
|
|
784
|
+
const job = create(attachments);
|
|
785
|
+
keep = !alreadyCreated;
|
|
786
|
+
return job;
|
|
787
|
+
}
|
|
788
|
+
finally {
|
|
789
|
+
if (!keep)
|
|
790
|
+
await this.removePromptAttachments(directory);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
requireQueuedPrompt(task, promptId) {
|
|
794
|
+
const prompt = this.options.store.getQueuedPrompt(task, promptId);
|
|
795
|
+
if (!prompt)
|
|
796
|
+
throw new RequestError(404, "这条消息已离开队列。");
|
|
797
|
+
return prompt;
|
|
798
|
+
}
|
|
799
|
+
describeQueuedPrompt(prompt) {
|
|
800
|
+
const { text, fileCount } = queuedPromptContent(prompt);
|
|
801
|
+
return { id: prompt.promptId, text: (prompt.displayPrompt ?? text).slice(0, 180),
|
|
802
|
+
...(fileCount || prompt.localImagePaths?.length ? { hasAttachments: true } : {}) };
|
|
803
|
+
}
|
|
804
|
+
describeQueue(task) {
|
|
805
|
+
const queuedPrompts = this.options.store.listQueuedPrompts(task).map(prompt => this.describeQueuedPrompt(prompt));
|
|
806
|
+
return { queued: queuedPrompts.length, queuedPrompts };
|
|
807
|
+
}
|
|
267
808
|
describe(task, fileOrigin) {
|
|
268
809
|
const project = this.project(task);
|
|
269
|
-
return { id: task.localSessionId, title: task.title?.slice(0, 200) ||
|
|
270
|
-
provider: task.modelProvider, model: task.model, project, updatedAt: task.updatedAt,
|
|
810
|
+
return { id: task.localSessionId, title: task.title?.trim().slice(0, 200) || null, agent: task.agentName,
|
|
811
|
+
provider: task.modelProvider, model: task.model, thinking: task.reasoningEffort, project, updatedAt: task.updatedAt,
|
|
271
812
|
status: task.status === "closed" ? "closed" : task.status === "running" || task.status === "starting"
|
|
272
813
|
? (task.lastTurnStatus === "waiting_for_approval" ? task.lastTurnStatus : task.status)
|
|
273
814
|
: task.lastTurnStatus ?? task.status,
|
|
274
815
|
...(fileOrigin ? { workspace: project.root && this.viewer.createWorkspaceUrl(project.root, fileOrigin),
|
|
275
|
-
|
|
816
|
+
directories: listTaskDirectories(this.options.store, task.localSessionId),
|
|
817
|
+
directoryPanel: this.describeDirectoryPanel(task.localSessionId),
|
|
818
|
+
...this.describeQueue(task.localSessionId) } : {}),
|
|
276
819
|
};
|
|
277
820
|
}
|
|
278
821
|
list(params) {
|
|
@@ -296,7 +839,8 @@ export class WorkspaceSessions {
|
|
|
296
839
|
const matches = all.filter((task) => this.project(task).id === project && (!search
|
|
297
840
|
|| `${task.title ?? "未命名任务"}\n${this.project(task).name}\n${task.cwd}\n${task.agentName}`.toLowerCase().includes(search)));
|
|
298
841
|
const index = cursor ? matches.findIndex((task) => task.localSessionId === cursor) + 1 : 0;
|
|
299
|
-
return { items: matches.slice(index, index +
|
|
842
|
+
return { items: matches.slice(index, index + TASK_PAGE_SIZE).map((task) => this.describeTaskRow(task)),
|
|
843
|
+
more: matches.length > index + TASK_PAGE_SIZE };
|
|
300
844
|
}
|
|
301
845
|
const values = [...groups.values()];
|
|
302
846
|
const index = cursor === null ? 0 : values.findIndex((group) => group.id === cursor) + 1;
|
|
@@ -305,16 +849,49 @@ export class WorkspaceSessions {
|
|
|
305
849
|
head(task) {
|
|
306
850
|
return this.options.store.workspaceTurnHead(task);
|
|
307
851
|
}
|
|
308
|
-
|
|
852
|
+
conversationMetrics(task, head) {
|
|
853
|
+
const session = task.localSessionId;
|
|
854
|
+
const now = Date.now(), cached = this.metricsCache.get(session);
|
|
855
|
+
if (cached && cached.head === head && cached.expires > now)
|
|
856
|
+
return cached.value;
|
|
857
|
+
const bytes = this.options.sessionStorageBytes?.(task);
|
|
858
|
+
const value = { ...this.options.store.workspaceConversationMetrics(session, head),
|
|
859
|
+
storageSize: bytes === undefined ? undefined : formatStorageSize(bytes) };
|
|
860
|
+
this.metricsCache.delete(session);
|
|
861
|
+
if (this.metricsCache.size >= 64)
|
|
862
|
+
this.metricsCache.delete(this.metricsCache.keys().next().value);
|
|
863
|
+
this.metricsCache.set(session, { head, expires: now + 5_000, value });
|
|
864
|
+
return value;
|
|
865
|
+
}
|
|
866
|
+
requireBranchTurn(task, turn) {
|
|
309
867
|
const head = this.head(task);
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
868
|
+
if (turn !== head && this.options.store.workspaceTurnPage(task.localSessionId, head, turn, 1).beforeMissing)
|
|
869
|
+
throw new RequestError(404, "当前对话分支中没有该轮次。");
|
|
870
|
+
return head;
|
|
871
|
+
}
|
|
872
|
+
describeTaskRow(task, row = this.describe(task)) {
|
|
873
|
+
const store = this.options.store;
|
|
874
|
+
const executing = activeTaskStatuses.has(row.status);
|
|
875
|
+
let summary = executing && task.lastTurnId ? store.getTurnPromptSummary(task.lastTurnId) : undefined;
|
|
876
|
+
if (!summary?.status || !activeTaskStatuses.has(summary.status)) {
|
|
877
|
+
const head = this.head(task);
|
|
878
|
+
summary = head ? store.getTurnPromptSummary(head) : undefined;
|
|
879
|
+
}
|
|
880
|
+
const liveStatus = executing && summary?.status && activeTaskStatuses.has(summary.status) ? summary.status : undefined;
|
|
881
|
+
return { ...row, status: liveStatus ?? row.status,
|
|
882
|
+
promptPreview: executing && !liveStatus ? null : workspacePromptPreview(summary?.prompt) };
|
|
883
|
+
}
|
|
884
|
+
history(task, origin, before, anchor, after) {
|
|
885
|
+
const head = this.head(task), store = this.options.store;
|
|
886
|
+
const anchored = Boolean(anchor && anchor !== head && !store.workspaceTurnPage(task.localSessionId, head, anchor, 1).beforeMissing);
|
|
887
|
+
const page = after ? store.workspaceTurnsAfter(task.localSessionId, head, after, MAX_HISTORY)
|
|
888
|
+
: store.workspaceTurnPage(task.localSessionId, anchored ? anchor : head, before, MAX_HISTORY);
|
|
889
|
+
if ("cursorMissing" in page ? page.cursorMissing : page.beforeMissing)
|
|
313
890
|
throw new RequestError(409, "对话分支已有变更,请重新加载历史。");
|
|
314
891
|
const turns = [];
|
|
315
892
|
let bytes = 0;
|
|
316
893
|
for (const turnId of page.ids) {
|
|
317
|
-
const turn = this.turn(task, turnId);
|
|
894
|
+
const turn = this.turn(task, turnId, turnId === head);
|
|
318
895
|
if (!turn)
|
|
319
896
|
continue;
|
|
320
897
|
const cost = Buffer.byteLength(JSON.stringify(turn));
|
|
@@ -323,36 +900,118 @@ export class WorkspaceSessions {
|
|
|
323
900
|
turns.push(turn);
|
|
324
901
|
bytes += cost;
|
|
325
902
|
}
|
|
326
|
-
|
|
327
|
-
|
|
903
|
+
const summary = head ? store.getTurnPromptSummary(head) : undefined;
|
|
904
|
+
return { task: { ...this.describe(task, origin), promptPreview: workspacePromptPreview(summary?.prompt),
|
|
905
|
+
metrics: this.conversationMetrics(task, head) }, head, headStatus: summary?.status,
|
|
906
|
+
execution: this.activeExecution(task, head, summary?.status),
|
|
907
|
+
plan: head ? store.workspaceTurnPlan(head) : [],
|
|
908
|
+
turns: after ? turns : turns.reverse(), more: page.more || turns.length < page.ids.length, anchored };
|
|
909
|
+
}
|
|
910
|
+
activeExecution(task, turnId, status) {
|
|
911
|
+
if (!turnId || !status || !activeTaskStatuses.has(status) || task.status === "closed")
|
|
912
|
+
return undefined;
|
|
913
|
+
const store = this.options.store;
|
|
914
|
+
const snapshot = store.workspaceTurnExecution(turnId);
|
|
915
|
+
const submission = store.provenance.forTurn(turnId, task.localSessionId);
|
|
916
|
+
return {
|
|
917
|
+
startedAt: toolTimestamp(snapshot?.startedAt) ?? toolTimestamp(submission?.submittedAt),
|
|
918
|
+
model: submission?.settings.model ?? snapshot?.model ?? undefined,
|
|
919
|
+
thinking: submission?.settings.reasoningEffort ?? snapshot?.thinking ?? undefined,
|
|
920
|
+
};
|
|
328
921
|
}
|
|
329
|
-
turn(task, turnId) {
|
|
922
|
+
turn(task, turnId, current = false) {
|
|
330
923
|
const row = this.options.store.workspaceTurnText(turnId);
|
|
331
924
|
if (!row)
|
|
332
925
|
return undefined;
|
|
333
|
-
const
|
|
334
|
-
const
|
|
926
|
+
const activities = JSON.parse(row.activities);
|
|
927
|
+
const reasoning = JSON.parse(row.reasoning);
|
|
928
|
+
const answer = row.answer || row.live;
|
|
335
929
|
return { id: turnId, status: row.status, startedAt: row.startedAt, prompt: row.prompt?.slice(0, 24_000),
|
|
930
|
+
promptRequestId: row.promptRequestId ?? undefined,
|
|
931
|
+
promptFiles: this.attachmentLinks(task.localSessionId, row.promptRequestId ?? undefined),
|
|
336
932
|
promptImages: this.attachments(task, row.promptImages ? JSON.parse(row.promptImages) : undefined),
|
|
337
|
-
answer: answer ? this.render(task, answer) : undefined,
|
|
338
|
-
|
|
933
|
+
answer: answer ? this.render(task, answer) : undefined, final: Boolean(answer && (row.answer || row.status === "completed")),
|
|
934
|
+
answerExport: Boolean(row.answer), previewUrl: row.answer ? this.viewer.createTurnPreviewUrl(turnId) : undefined,
|
|
935
|
+
timeline: workspaceTimeline(activities, reasoning, answer, current && activeTaskStatuses.has(row.status)).map((item) => {
|
|
936
|
+
if (item.kind === "execution")
|
|
937
|
+
return item;
|
|
938
|
+
if (item.kind === "reasoning")
|
|
939
|
+
return { id: item.id, kind: item.kind, rich: this.render(task, item.text, true) };
|
|
339
940
|
const images = item.kind === "user" ? this.attachments(task, item.images) : undefined;
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
941
|
+
const rich = item.text && item.kind === "assistant" ? this.render(task, item.text, true) : undefined;
|
|
942
|
+
const requestId = item.kind === "user" && item.id.startsWith("steer:workspace:") ? item.id.slice("steer:workspace:".length) : undefined;
|
|
943
|
+
return { id: item.id, kind: item.kind, text: rich ? undefined : item.text, images, rich, requestId,
|
|
944
|
+
files: this.attachmentLinks(task.localSessionId, requestId) };
|
|
344
945
|
}),
|
|
946
|
+
hasDetails: row.changeCount > 0, fileChangeCount: row.changeCount || undefined,
|
|
947
|
+
detailRevision: row.changeSummary && row.changeCount ? hash(row.changeSummary) : undefined,
|
|
948
|
+
compact: Boolean(row.compact),
|
|
345
949
|
error: row.error || row.notice ? displayRuntimeError(row.error || row.notice) : undefined, summary: row.detail === "summary",
|
|
346
950
|
delivered: row.status === "completed" && row.answer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined, };
|
|
347
951
|
}
|
|
952
|
+
async toolPage(task, state, toolId, offset, revision) {
|
|
953
|
+
const journal = this.options.store.previews;
|
|
954
|
+
const read = (snapshot) => journal.toolTextPage(snapshot.previewTurnId ?? snapshot.turnId, toolId, offset, MAX_EXECUTION_CHARS);
|
|
955
|
+
let page = await read(state);
|
|
956
|
+
if (!page && state.historyDetail === "summary" && this.options.loadTurnDetails && !journal.has(state.previewTurnId ?? state.turnId)) {
|
|
957
|
+
state = await this.options.loadTurnDetails(state.turnId) ?? state;
|
|
958
|
+
page = await read(state);
|
|
959
|
+
}
|
|
960
|
+
if (page && "busy" in page)
|
|
961
|
+
throw new RequestError(429, "正在读取其他工具记录,请稍后重试。");
|
|
962
|
+
const activity = state.activities?.find((item) => item.kind === "tool" && item.id === toolId);
|
|
963
|
+
const files = offset === 0 ? page?.files ?? (activity?.kind === "tool" ? activity.tool.files : undefined) : undefined;
|
|
964
|
+
const fileDetails = files?.length ? this.toolFiles(task, state.projectCwd ?? task.cwd, files) : {};
|
|
965
|
+
if (page) {
|
|
966
|
+
if (revision && revision !== page.revision)
|
|
967
|
+
throw new RequestError(409, "工具日志已更新,请从开头重新读取。");
|
|
968
|
+
const { toolKind, files: _files, ...text } = page;
|
|
969
|
+
return { ...formatWorkspaceToolPage(text, offset, toolKind), ...fileDetails, partial: false };
|
|
970
|
+
}
|
|
971
|
+
if (activity?.kind !== "tool") {
|
|
972
|
+
throw new RequestError(404, state.historyDetailError ?? "未保存该工具的执行记录。");
|
|
973
|
+
}
|
|
974
|
+
const tool = activity.tool;
|
|
975
|
+
const command = tool.command ?? "", output = state.fullToolOutputs?.[toolId] ?? tool.output ?? "";
|
|
976
|
+
const error = state.fullToolErrors?.[toolId] ?? tool.error ?? "";
|
|
977
|
+
const outputIsError = Boolean(output && error === output);
|
|
978
|
+
const fields = { command, output, error: outputIsError ? "" : error };
|
|
979
|
+
const end = offset + MAX_EXECUTION_CHARS, remaining = toolTextFields.filter((name) => fields[name].length > end);
|
|
980
|
+
const partial = Boolean(state.previewJournal || state.historyDetail === "summary");
|
|
981
|
+
const pageText = { command: fields.command.slice(offset, end), output: fields.output.slice(offset, end), error: fields.error.slice(offset, end),
|
|
982
|
+
remaining, next: remaining.length ? end : undefined, outputIsError: outputIsError || undefined };
|
|
983
|
+
return { ...formatWorkspaceToolPage(pageText, offset, tool.kind), ...fileDetails, partial, reason: partial ? state.historyDetailError : undefined };
|
|
984
|
+
}
|
|
985
|
+
toolFiles(task, cwd, files) {
|
|
986
|
+
const primary = this.project(task).root;
|
|
987
|
+
const roots = [...(primary ? [{ root: primary, source: undefined }] : []),
|
|
988
|
+
...Object.entries(this.readDirectoryPanel(task.localSessionId).roots).map(([source, root]) => ({ root, source }))];
|
|
989
|
+
roots.sort((a, b) => b.root.length - a.root.length);
|
|
990
|
+
const entries = files.slice(0, MAX_TOOL_FILE_ENTRIES).map(({ path: recordedPath, moveTo, additions, deletions, patch, patchTruncated }) => {
|
|
991
|
+
const target = path.resolve(cwd, moveTo || recordedPath);
|
|
992
|
+
const patchHtml = patch ? highlightRecordedPatch(patch, target, recordedPath) : undefined;
|
|
993
|
+
const name = (primary && this.relativeWorkspaceEntry(primary, target)) || target;
|
|
994
|
+
for (const { root, source } of roots) {
|
|
995
|
+
const entry = this.projectFileEntry(root, target);
|
|
996
|
+
if (entry) {
|
|
997
|
+
const original = moveTo ? this.projectFileEntry(root, path.resolve(cwd, recordedPath)) : undefined;
|
|
998
|
+
return { name, entry, source, original, additions, deletions, patch, patchHtml, patchTruncated };
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return { name, additions, deletions, patch, patchHtml, patchTruncated };
|
|
1002
|
+
});
|
|
1003
|
+
return { files: entries, filesTruncated: files.length > entries.length || undefined };
|
|
1004
|
+
}
|
|
348
1005
|
fileEntry(task, file) {
|
|
349
1006
|
const { root } = this.project(task);
|
|
350
1007
|
if (!root)
|
|
351
1008
|
return;
|
|
352
|
-
|
|
353
|
-
|
|
1009
|
+
return this.projectFileEntry(root, file);
|
|
1010
|
+
}
|
|
1011
|
+
projectFileEntry(root, file) {
|
|
1012
|
+
const entry = this.relativeWorkspaceEntry(root, file);
|
|
1013
|
+
if (!entry)
|
|
354
1014
|
return;
|
|
355
|
-
const entry = relative.split(path.sep).join("/");
|
|
356
1015
|
try {
|
|
357
1016
|
resolveWorkspacePath(root, entry, true);
|
|
358
1017
|
return entry;
|
|
@@ -361,6 +1020,12 @@ export class WorkspaceSessions {
|
|
|
361
1020
|
return;
|
|
362
1021
|
}
|
|
363
1022
|
}
|
|
1023
|
+
relativeWorkspaceEntry(root, file) {
|
|
1024
|
+
const relative = path.relative(root, file);
|
|
1025
|
+
if (!relative || path.isAbsolute(relative) || relative === ".." || relative.startsWith(`..${path.sep}`))
|
|
1026
|
+
return;
|
|
1027
|
+
return relative.split(path.sep).join("/");
|
|
1028
|
+
}
|
|
364
1029
|
imageRoot(task) {
|
|
365
1030
|
return task ? path.resolve(task.cwd) : this.options.inboundImageDirectory;
|
|
366
1031
|
}
|
|
@@ -391,6 +1056,41 @@ export class WorkspaceSessions {
|
|
|
391
1056
|
return url ? url.pathname + url.search : null;
|
|
392
1057
|
});
|
|
393
1058
|
}
|
|
1059
|
+
attachmentEntries(task, request) {
|
|
1060
|
+
const saved = this.options.store.getTaskMetadata(task, attachmentKind, request);
|
|
1061
|
+
if (saved)
|
|
1062
|
+
return z.array(attachmentEntry).parse(JSON.parse(saved));
|
|
1063
|
+
const run = this.options.store.schedules.getRun(`schedule_run_${request}`);
|
|
1064
|
+
const job = run && this.options.store.schedules.get(run.jobId);
|
|
1065
|
+
if (job?.localSessionId === task && job.attachments?.files.length)
|
|
1066
|
+
return this.promptFileEntries(job.attachments.files);
|
|
1067
|
+
}
|
|
1068
|
+
attachmentLinks(task, request) {
|
|
1069
|
+
if (!request)
|
|
1070
|
+
return;
|
|
1071
|
+
return this.attachmentEntries(task, request)?.map(({ name }, index) => {
|
|
1072
|
+
const url = new URL(this.base);
|
|
1073
|
+
url.pathname += "/attachment";
|
|
1074
|
+
url.search = new URLSearchParams({ task, request, index: String(index) }).toString();
|
|
1075
|
+
return { name, url: url.pathname + url.search };
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
async serveAttachment(response, params) {
|
|
1079
|
+
const task = this.task(parse(id, params.get("task")));
|
|
1080
|
+
const request = parse(key, params.get("request"));
|
|
1081
|
+
const index = parse(z.string().regex(/^[0-3]$/u), params.get("index"));
|
|
1082
|
+
const attachment = this.attachmentEntries(task.localSessionId, request)?.[Number(index)];
|
|
1083
|
+
if (!attachment)
|
|
1084
|
+
throw new RequestError(404, "找不到此附件。");
|
|
1085
|
+
const data = await Promise.resolve().then(() => readFile(resolveWorkspacePath(this.options.inboundImageDirectory, attachment.entry))).catch(() => undefined);
|
|
1086
|
+
if (!data)
|
|
1087
|
+
throw new RequestError(404, "此附件已不可用。");
|
|
1088
|
+
const name = encodeURIComponent(attachment.name).replace(/['()*]/gu, (char) => "%" + char.charCodeAt(0).toString(16));
|
|
1089
|
+
this.headers(response);
|
|
1090
|
+
response.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Length": data.length,
|
|
1091
|
+
"Content-Disposition": `attachment; filename*=UTF-8''${name}` });
|
|
1092
|
+
response.end(data);
|
|
1093
|
+
}
|
|
394
1094
|
serveImage(request, response, params) {
|
|
395
1095
|
const { task: taskId, entry, proof } = parse(imageQuery, Object.fromEntries(params));
|
|
396
1096
|
const task = taskId ? this.task(taskId) : undefined;
|
|
@@ -426,8 +1126,10 @@ export class WorkspaceSessions {
|
|
|
426
1126
|
if (typeof href === "string" && href.startsWith(this.base.origin + this.base.pathname + "/?file=")) {
|
|
427
1127
|
const url = new URL(href);
|
|
428
1128
|
const entry = url.searchParams.get("file");
|
|
429
|
-
if (entry)
|
|
1129
|
+
if (entry) {
|
|
430
1130
|
item.attrSet("data-chat-file", entry);
|
|
1131
|
+
item.attrSet("data-tooltip", entry + url.hash.replace(/^#L(\d+)$/u, ":$1"));
|
|
1132
|
+
}
|
|
431
1133
|
item.attrSet("href", url.hash || "#");
|
|
432
1134
|
}
|
|
433
1135
|
}
|
|
@@ -482,7 +1184,7 @@ export class WorkspaceSessions {
|
|
|
482
1184
|
response.once("close", () => { if (this.streams.get(page) === stream)
|
|
483
1185
|
this.streams.delete(page); });
|
|
484
1186
|
// Reconnects always reconcile with an authoritative snapshot; no per-token replay is needed.
|
|
485
|
-
this.event(stream, "sync", {});
|
|
1187
|
+
this.event(stream, "sync", { revision: WORKSPACE_REVISION, instance: WORKSPACE_INSTANCE });
|
|
486
1188
|
}
|
|
487
1189
|
poll() {
|
|
488
1190
|
if (!this.streams.size && !this.grants.size)
|
|
@@ -493,11 +1195,18 @@ export class WorkspaceSessions {
|
|
|
493
1195
|
this.nextPrune = at + 5_000;
|
|
494
1196
|
this.pruneGrants();
|
|
495
1197
|
}
|
|
1198
|
+
for (const [response, { grant, task, directory, root }] of this.directoryStreams) {
|
|
1199
|
+
if (grant.signal.aborted || this.directoryRoot(grant, directory, task) !== root)
|
|
1200
|
+
response.end();
|
|
1201
|
+
}
|
|
496
1202
|
if (!this.streams.size)
|
|
497
1203
|
return;
|
|
498
1204
|
if (at >= this.nextCatalogue) {
|
|
499
1205
|
this.nextCatalogue = at + 2_000;
|
|
500
|
-
const next = hash(JSON.stringify(this.options.store.listAllSessions().filter((task) => this.eligible(task)).map((task) =>
|
|
1206
|
+
const next = hash(JSON.stringify(this.options.store.listAllSessions().filter((task) => this.eligible(task)).map((task) => {
|
|
1207
|
+
const row = this.describe(task);
|
|
1208
|
+
return activeTaskStatuses.has(row.status) ? this.describeTaskRow(task, row) : row;
|
|
1209
|
+
})));
|
|
501
1210
|
if (this.catalogueHash !== next) {
|
|
502
1211
|
this.catalogueHash = next;
|
|
503
1212
|
this.catalogue++;
|
|
@@ -511,9 +1220,19 @@ export class WorkspaceSessions {
|
|
|
511
1220
|
}
|
|
512
1221
|
if (stream.task) {
|
|
513
1222
|
if (!tails.has(stream.task)) {
|
|
514
|
-
const task = this.options.store.getSession(stream.task)
|
|
515
|
-
|
|
516
|
-
turn
|
|
1223
|
+
const task = this.options.store.getSession(stream.task);
|
|
1224
|
+
if (task && this.eligible(task)) {
|
|
1225
|
+
const head = this.head(task), turn = head ? this.turn(task, head, true) : null;
|
|
1226
|
+
tails.set(stream.task, { task: { ...this.describe(task), promptPreview: workspacePromptPreview(turn?.prompt),
|
|
1227
|
+
metrics: this.conversationMetrics(task, head),
|
|
1228
|
+
directories: listTaskDirectories(this.options.store, task.localSessionId) },
|
|
1229
|
+
...this.describeQueue(task.localSessionId), turn,
|
|
1230
|
+
execution: this.activeExecution(task, head, turn?.status),
|
|
1231
|
+
plan: head ? this.options.store.workspaceTurnPlan(head) : [],
|
|
1232
|
+
parent: head ? this.options.store.getTurnParent(head, task.localSessionId) : undefined });
|
|
1233
|
+
}
|
|
1234
|
+
else
|
|
1235
|
+
tails.set(stream.task, null);
|
|
517
1236
|
}
|
|
518
1237
|
const next = JSON.stringify(tails.get(stream.task));
|
|
519
1238
|
if (next !== stream.tail) {
|
|
@@ -541,7 +1260,7 @@ export class WorkspaceSessions {
|
|
|
541
1260
|
}
|
|
542
1261
|
stream.response.write(packet);
|
|
543
1262
|
}
|
|
544
|
-
async submit(input) {
|
|
1263
|
+
async submit(input, retry) {
|
|
545
1264
|
const task = this.task(input.task);
|
|
546
1265
|
const store = this.options.store;
|
|
547
1266
|
const fingerprint = hash(JSON.stringify(input));
|
|
@@ -549,29 +1268,48 @@ export class WorkspaceSessions {
|
|
|
549
1268
|
if (previous) {
|
|
550
1269
|
if (previous.fingerprint !== fingerprint)
|
|
551
1270
|
throw new RequestError(409, "该请求标识已用于另一项操作。");
|
|
552
|
-
|
|
1271
|
+
// Only an explicit retry of a proven unsubmitted operation may reopen its ID.
|
|
1272
|
+
if (!retry || previous.status !== "failed" || previous.posted || this.running.has(input.request))
|
|
1273
|
+
return this.operation(input.request, previous);
|
|
553
1274
|
}
|
|
554
1275
|
if (task.status === "closed")
|
|
555
1276
|
throw new RequestError(409, "任务已归档,不能发送或停止。");
|
|
556
1277
|
if (!this.options.canSubmit())
|
|
557
|
-
throw new RequestError(503, "
|
|
1278
|
+
throw new RequestError(503, "服务正在启动或切换,未提交此操作,请稍后重试。");
|
|
558
1279
|
if (this.running.size >= 16)
|
|
559
1280
|
throw new RequestError(429, "当前请求较多,未提交此操作。");
|
|
560
|
-
|
|
1281
|
+
const { images, files } = input.action === "stop" ? { images: [], files: [] } : this.decodeAttachments(input.images ?? [], input.files ?? []);
|
|
1282
|
+
if (previous)
|
|
1283
|
+
store.updateWorkspaceRequest(input.request, "pending");
|
|
1284
|
+
else
|
|
1285
|
+
store.beginWorkspaceRequest(input.request, task.localSessionId, fingerprint);
|
|
1286
|
+
this.lastSubmissionAt = Math.max(Date.now(), (this.lastSubmissionAt ?? 0) + 1);
|
|
561
1287
|
this.running.add(input.request);
|
|
562
|
-
let ambiguous = input.action
|
|
1288
|
+
let ambiguous = input.action === "stop", directory;
|
|
563
1289
|
try {
|
|
1290
|
+
let localImagePaths, localFiles = [];
|
|
1291
|
+
if (images.length || files.length) {
|
|
1292
|
+
const saved = await this.writePromptAttachments(images, files);
|
|
1293
|
+
directory = saved.directory;
|
|
1294
|
+
localImagePaths = saved.attachments.images.length ? saved.attachments.images : undefined;
|
|
1295
|
+
localFiles = saved.attachments.files;
|
|
1296
|
+
if (localFiles.length) {
|
|
1297
|
+
store.setTaskMetadata(task.localSessionId, attachmentKind, input.request, JSON.stringify(this.promptFileEntries(localFiles)));
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
564
1300
|
if (input.action === "stop") {
|
|
565
1301
|
const result = await this.options.controller.controlStopTask(task.localSessionId, input.turn);
|
|
566
1302
|
store.updateWorkspaceRequest(input.request, result === "stale" ? "stale" : "accepted");
|
|
567
1303
|
}
|
|
568
1304
|
else if (input.action === "queue") {
|
|
569
|
-
|
|
1305
|
+
ambiguous = true;
|
|
1306
|
+
await this.options.controller.controlQueueTaskPrompt(task.localSessionId, input.text, localImagePaths, input.request, ...(localFiles.length ? [localFiles] : []));
|
|
570
1307
|
store.updateWorkspaceRequest(input.request, "accepted");
|
|
571
1308
|
}
|
|
572
1309
|
else {
|
|
573
1310
|
await this.options.controller.controlSendTaskPrompt(task.localSessionId, input.text, {
|
|
574
|
-
requestId: input.request,
|
|
1311
|
+
requestId: input.request, localImagePaths, ...(localFiles.length ? { files: localFiles } : {}),
|
|
1312
|
+
...(input.action === "steer" ? { expectedTurnId: input.turn } : {}),
|
|
575
1313
|
onPosting: () => { ambiguous = true; },
|
|
576
1314
|
onPosted: () => { store.updateWorkspaceRequest(input.request, "pending", true); },
|
|
577
1315
|
});
|
|
@@ -580,16 +1318,80 @@ export class WorkspaceSessions {
|
|
|
580
1318
|
}
|
|
581
1319
|
catch (error) {
|
|
582
1320
|
const message = displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "操作未完成。");
|
|
583
|
-
|
|
1321
|
+
const stale = input.action === "steer" && error instanceof TurnNotSubmittedError;
|
|
1322
|
+
store.updateWorkspaceRequest(input.request, stale ? "stale" : ambiguous ? "unknown" : "failed", false, message);
|
|
1323
|
+
if (directory && (!ambiguous || stale)) {
|
|
1324
|
+
if (files.length)
|
|
1325
|
+
store.removeTaskMetadata(task.localSessionId, attachmentKind, input.request);
|
|
1326
|
+
await this.removePromptAttachments(directory);
|
|
1327
|
+
}
|
|
584
1328
|
}
|
|
585
1329
|
finally {
|
|
586
1330
|
this.running.delete(input.request);
|
|
587
1331
|
}
|
|
588
1332
|
return this.operation(input.request, store.workspaceRequest(input.request));
|
|
589
1333
|
}
|
|
1334
|
+
promptFileEntries(files) {
|
|
1335
|
+
return files.map(({ fileName, filePath }) => ({ name: fileName, entry: path.relative(this.options.inboundImageDirectory, filePath).split(path.sep).join("/") }));
|
|
1336
|
+
}
|
|
1337
|
+
async writePromptAttachments(images, files) {
|
|
1338
|
+
const root = path.resolve(this.options.inboundImageDirectory);
|
|
1339
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
1340
|
+
const directory = await mkdtemp(path.join(root, "workspace-"));
|
|
1341
|
+
const attachments = { images: [], files: [] };
|
|
1342
|
+
try {
|
|
1343
|
+
for (const [index, image] of images.entries()) {
|
|
1344
|
+
const filePath = path.join(directory, `${index + 1}${image.extension}`);
|
|
1345
|
+
await writeFile(filePath, image.bytes, { flag: "wx", mode: 0o600 });
|
|
1346
|
+
attachments.images.push(filePath);
|
|
1347
|
+
}
|
|
1348
|
+
for (const [index, file] of files.entries()) {
|
|
1349
|
+
const filePath = path.join(directory, `file-${index + 1}-${file.name}`);
|
|
1350
|
+
await writeFile(filePath, file.bytes, { flag: "wx", mode: 0o600 });
|
|
1351
|
+
attachments.files.push({ fileName: file.name, filePath });
|
|
1352
|
+
}
|
|
1353
|
+
return { directory, attachments };
|
|
1354
|
+
}
|
|
1355
|
+
catch (error) {
|
|
1356
|
+
await this.removePromptAttachments(directory);
|
|
1357
|
+
throw error;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
async removePromptAttachments(directory) {
|
|
1361
|
+
await rm(directory, { recursive: true, force: true }).catch((error) => {
|
|
1362
|
+
this.options.logger.warn({ error }, "Failed to remove unused Workspace attachments.");
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
decodeAttachments(images, files) {
|
|
1366
|
+
let total = 0;
|
|
1367
|
+
const decode = (data) => {
|
|
1368
|
+
const bytes = Buffer.from(data, "base64");
|
|
1369
|
+
total += bytes.length;
|
|
1370
|
+
if (bytes.length > MAX_ATTACHMENT_BYTES || total > MAX_ATTACHMENT_TOTAL)
|
|
1371
|
+
throw new RequestError(413, "附件至多 4 个;单个不超过 5 MiB,合计不超过 12 MiB。");
|
|
1372
|
+
if (bytes.toString("base64") !== data)
|
|
1373
|
+
throw new RequestError(415, "附件编码无法读取。");
|
|
1374
|
+
return bytes;
|
|
1375
|
+
};
|
|
1376
|
+
const decodedImages = images.map((image) => {
|
|
1377
|
+
const bytes = decode(image);
|
|
1378
|
+
const extension = workspaceImageExtension(bytes);
|
|
1379
|
+
if (!extension)
|
|
1380
|
+
throw new RequestError(415, "图片不可读,仅支持 PNG、JPEG、GIF 或 WebP。");
|
|
1381
|
+
return { bytes, extension };
|
|
1382
|
+
});
|
|
1383
|
+
const decodedFiles = files.map((file) => {
|
|
1384
|
+
const basename = path.win32.basename(file.name).replace(/[<>:"/\\|?*\x00-\x1f\x7f]/gu, "_")
|
|
1385
|
+
.trim().slice(0, 180).replace(/[\uD800-\uDFFF]/gu, "_").replace(/[. ]+$/u, "") || "file";
|
|
1386
|
+
const name = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(basename) ? "_" + basename : basename;
|
|
1387
|
+
return { name, bytes: decode(file.data) };
|
|
1388
|
+
});
|
|
1389
|
+
return { images: decodedImages, files: decodedFiles };
|
|
1390
|
+
}
|
|
590
1391
|
operation(request, record) {
|
|
591
1392
|
return { status: record.status === "pending" && !this.running.has(request) ? "unknown" : record.status,
|
|
592
|
-
posted: Boolean(record.posted), message: record.message ?? undefined
|
|
1393
|
+
posted: Boolean(record.posted), message: record.message ?? undefined,
|
|
1394
|
+
queued: record.status === "accepted" && this.options.store.hasQueuedPrompt(`workspace:${request}`) || undefined };
|
|
593
1395
|
}
|
|
594
1396
|
access() {
|
|
595
1397
|
const password = this.options.password(), owner = this.options.owner();
|
|
@@ -646,15 +1448,15 @@ export class WorkspaceSessions {
|
|
|
646
1448
|
const servicePath = new URL(".", this.base).pathname;
|
|
647
1449
|
return `${this.cookieName}=${value}; Path=${servicePath}; HttpOnly; SameSite=Strict; Max-Age=${age}${origin.startsWith("https:") ? "; Secure" : ""}`;
|
|
648
1450
|
}
|
|
649
|
-
async body(request) {
|
|
650
|
-
if (Number(request.headers["content-length"]) >
|
|
1451
|
+
async body(request, limit = 150_000) {
|
|
1452
|
+
if (Number(request.headers["content-length"]) > limit)
|
|
651
1453
|
throw new RequestError(413, "请求内容过大。");
|
|
652
1454
|
const chunks = [];
|
|
653
1455
|
let bytes = 0;
|
|
654
1456
|
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
655
1457
|
const buffer = Buffer.from(chunk);
|
|
656
1458
|
bytes += buffer.length;
|
|
657
|
-
if (bytes >
|
|
1459
|
+
if (bytes > limit) {
|
|
658
1460
|
request.resume();
|
|
659
1461
|
throw new RequestError(413, "请求内容过大。");
|
|
660
1462
|
}
|