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