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