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