@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,5 +1,5 @@
|
|
|
1
1
|
import { TurnPreviewProjection, type TurnPreviewJournal } from "../state/TurnPreviewJournal.js";
|
|
2
|
-
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import http, { type IncomingMessage, type ServerResponse } from "node:http";
|
|
@@ -7,14 +7,14 @@ import type { Duplex } from "node:stream";
|
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import hljs from "highlight.js/lib/common";
|
|
10
|
-
import dos from "highlight.js/lib/languages/dos";
|
|
11
|
-
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
12
|
-
import powershell from "highlight.js/lib/languages/powershell";
|
|
13
10
|
import MarkdownIt from "markdown-it";
|
|
14
11
|
import { CSV_PREVIEW_CSS, renderCsvPreview, csvSourcePreview } from "./CsvPreview.js";
|
|
15
12
|
import { GIT_DIFF_PREVIEW_CSS, readGitFileDiff, renderGitFileDiff } from "./GitDiffPreview.js";
|
|
16
|
-
import { renderWorkspacePage, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
13
|
+
import { renderWorkspacePage, WORKSPACE_ICON, WORKSPACE_ICON_NAME, WORKSPACE_INSTANCE, WORKSPACE_INSTANCE_HEADER, WORKSPACE_REVISION, WORKSPACE_REVISION_HEADER, WORKSPACE_SCRIPT } from "./WorkspacePage.js";
|
|
14
|
+
import { PREVIEW_CODE_FONT, PREVIEW_CODE_FONT_NAME, previewCodeFontCss } from "./PreviewCodeFont.js";
|
|
15
|
+
import { highlightLines, highlightTextLines, MAX_SYNTAX_HIGHLIGHT_BYTES, syntaxLanguageFor } from "./PreviewSyntaxHighlight.js";
|
|
17
16
|
import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
|
|
17
|
+
import { WorkspaceFileEvents } from "./WorkspaceFileEvents.js";
|
|
18
18
|
import { readWebPageTitle } from "./WebPageTitle.js";
|
|
19
19
|
import { WorkspaceError, readWorkspaceAddress, readWorkspaceEntries, readWorkspaceGitStatus, readWorkspaceChanges, readWorkspaceFileVersions, createWorkspaceDiff, renderWorkspaceDiff, resolveWorkspacePath, type WorkspaceChange } from "./WorkspaceFiles.js";
|
|
20
20
|
import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
@@ -42,21 +42,18 @@ const SHORT_TOKEN_BYTES = 12;
|
|
|
42
42
|
const SHORT_TOKEN_LENGTH = 16;
|
|
43
43
|
const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
|
|
44
44
|
const MAX_CONTENT_SAMPLE_BYTES = 64 * 1024;
|
|
45
|
-
const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
46
45
|
const DIRECTORY_PAGE_SIZE = 100;
|
|
47
46
|
const WORKSPACE_QUERY = z.object({
|
|
48
47
|
api: z.string().optional(), entry: z.string().default(""),
|
|
49
48
|
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
50
49
|
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
50
|
+
source: z.literal("1").optional(),
|
|
51
51
|
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
52
|
+
refresh: z.enum(["1"]).optional(),
|
|
52
53
|
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
53
54
|
});
|
|
54
55
|
const MARKDOWN_EXTENSIONS = new Set([".markdown", ".md", ".mdown", ".mkd", ".mkdn"]);
|
|
55
56
|
const HTML_EXTENSIONS = new Set([".html", ".htm"]);
|
|
56
|
-
hljs.registerLanguage("dos", dos);
|
|
57
|
-
hljs.registerLanguage("dockerfile", dockerfile);
|
|
58
|
-
hljs.registerLanguage("powershell", powershell);
|
|
59
|
-
|
|
60
57
|
const MARKDOWN_RENDERER = new MarkdownIt({
|
|
61
58
|
breaks: false,
|
|
62
59
|
html: false,
|
|
@@ -73,29 +70,20 @@ const MARKDOWN_RENDERER = new MarkdownIt({
|
|
|
73
70
|
},
|
|
74
71
|
});
|
|
75
72
|
enableDiagramFences(MARKDOWN_RENDERER);
|
|
76
|
-
MARKDOWN_RENDERER.renderer.rules.table_open = () =>
|
|
77
|
-
'<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0"><table>\n';
|
|
73
|
+
MARKDOWN_RENDERER.renderer.rules.table_open = (tokens, index, _options, _env, renderer) =>
|
|
74
|
+
'<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0"><table' + renderer.renderAttrs(tokens[index]!) + '>\n';
|
|
78
75
|
MARKDOWN_RENDERER.renderer.rules.table_close = () => '</table></div>\n';
|
|
76
|
+
for (const kind of ["fence", "code_block"] as const) {
|
|
77
|
+
const render = MARKDOWN_RENDERER.renderer.rules[kind]!;
|
|
78
|
+
MARKDOWN_RENDERER.renderer.rules[kind] = (tokens, index, options, env, renderer) => {
|
|
79
|
+
const html = render(tokens, index, options, env, renderer), token = tokens[index]!;
|
|
80
|
+
const start = token.attrGet("data-source-start"), end = token.attrGet("data-source-end");
|
|
81
|
+
return start === null ? html : `<div data-source-start="${start}" data-source-end="${end}">${html}</div>\n`;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
79
84
|
const validateMarkdownLink = MARKDOWN_RENDERER.validateLink.bind(MARKDOWN_RENDERER);
|
|
80
85
|
MARKDOWN_RENDERER.validateLink = (url) => isFileUrl(url) || validateMarkdownLink(url);
|
|
81
86
|
|
|
82
|
-
const HIGHLIGHT_LANGUAGE_BY_EXTENSION: Readonly<Record<string, string>> = {
|
|
83
|
-
".bash": "bash", ".bat": "dos", ".c": "c", ".cc": "cpp", ".cmd": "dos", ".cpp": "cpp",
|
|
84
|
-
".cs": "csharp", ".css": "css", ".cxx": "cpp", ".diff": "diff", ".go": "go", ".h": "cpp",
|
|
85
|
-
".hpp": "cpp", ".htm": "xml", ".html": "xml", ".ini": "ini", ".ipynb": "json", ".java": "java",
|
|
86
|
-
".js": "javascript", ".json": "json", ".jsonl": "json", ".jsx": "javascript", ".kt": "kotlin",
|
|
87
|
-
".kts": "kotlin", ".less": "less", ".lua": "lua", ".markdown": "markdown", ".md": "markdown",
|
|
88
|
-
".mjs": "javascript", ".patch": "diff", ".php": "php", ".pl": "perl", ".ps1": "powershell",
|
|
89
|
-
".py": "python", ".r": "r", ".rb": "ruby", ".rs": "rust", ".scss": "scss", ".sh": "bash",
|
|
90
|
-
".sql": "sql", ".swift": "swift", ".toml": "ini", ".ts": "typescript", ".tsx": "typescript",
|
|
91
|
-
".vue": "xml", ".xml": "xml", ".yaml": "yaml", ".yml": "yaml", ".zsh": "bash",
|
|
92
|
-
};
|
|
93
|
-
const HIGHLIGHT_LANGUAGE_BY_FILENAME: Readonly<Record<string, string>> = {
|
|
94
|
-
".env": "ini",
|
|
95
|
-
".gitignore": "ini",
|
|
96
|
-
"dockerfile": "dockerfile",
|
|
97
|
-
"makefile": "makefile",
|
|
98
|
-
};
|
|
99
87
|
const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
100
88
|
const eventsUrl = document.body.dataset.eventsUrl;
|
|
101
89
|
const content = document.getElementById("viewer-content");
|
|
@@ -143,9 +131,9 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
143
131
|
const diffBlocks = [];
|
|
144
132
|
if (diffPrevious && diffNext) {
|
|
145
133
|
for (const line of content.querySelectorAll(".git-diff .diff-addition, .git-diff .diff-deletion")) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
134
|
+
if (!line.previousElementSibling?.matches(".diff-addition, .diff-deletion")) {
|
|
135
|
+
diffBlocks.push({ first: line, hash: "#diff-" + line.id });
|
|
136
|
+
}
|
|
149
137
|
}
|
|
150
138
|
}
|
|
151
139
|
let diffPositions = [], selectedDiff = -1;
|
|
@@ -175,8 +163,9 @@ const VIEWER_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
|
175
163
|
const height = window.innerHeight;
|
|
176
164
|
const readerCenter = (header.getBoundingClientRect().height + height) / 2;
|
|
177
165
|
const maxTop = Math.max(0, document.documentElement.scrollHeight - height);
|
|
178
|
-
diffPositions = diffBlocks.map(({ first
|
|
179
|
-
const
|
|
166
|
+
diffPositions = diffBlocks.map(({ first }) => {
|
|
167
|
+
const line = first.getBoundingClientRect();
|
|
168
|
+
const center = (line.top + line.bottom) / 2;
|
|
180
169
|
return Math.min(maxTop, Math.max(0, window.scrollY + center - readerCenter));
|
|
181
170
|
});
|
|
182
171
|
updateDiffNavigation();
|
|
@@ -379,6 +368,7 @@ export class LocalFileViewerServer {
|
|
|
379
368
|
private address?: LocalFileViewerAddress;
|
|
380
369
|
private basePath = "";
|
|
381
370
|
private readonly services = new Map<string, LocalFileViewerService>();
|
|
371
|
+
private readonly workspaceFileEvents = new WorkspaceFileEvents();
|
|
382
372
|
private workspaceAppBase?: string;
|
|
383
373
|
|
|
384
374
|
enableWorkspaceApp(base: string): void { this.workspaceAppBase = base; }
|
|
@@ -466,6 +456,7 @@ export class LocalFileViewerServer {
|
|
|
466
456
|
async close(): Promise<void> {
|
|
467
457
|
await Promise.all([...this.services.values()].map((service) => service.close()));
|
|
468
458
|
this.services.clear();
|
|
459
|
+
this.workspaceFileEvents.close();
|
|
469
460
|
const server = this.server;
|
|
470
461
|
this.server = undefined;
|
|
471
462
|
this.address = undefined;
|
|
@@ -557,7 +548,20 @@ export class LocalFileViewerServer {
|
|
|
557
548
|
|
|
558
549
|
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
559
550
|
const route = routeWithinBasePath(requestUrl.pathname, this.basePath);
|
|
551
|
+
const workspaceIcon = route === "/assets/" + WORKSPACE_ICON_NAME;
|
|
552
|
+
if (workspaceIcon || route === "/assets/" + PREVIEW_CODE_FONT_NAME) {
|
|
553
|
+
const asset = workspaceIcon ? WORKSPACE_ICON : PREVIEW_CODE_FONT;
|
|
554
|
+
setSecurityHeaders(response);
|
|
555
|
+
response.statusCode = 200;
|
|
556
|
+
response.setHeader("Content-Type", workspaceIcon ? "image/x-icon" : "font/woff2");
|
|
557
|
+
response.setHeader("Cache-Control", "public, max-age=86400");
|
|
558
|
+
response.setHeader("Content-Length", asset.length);
|
|
559
|
+
response.end(request.method === "HEAD" ? undefined : asset);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
560
562
|
if (route === "/assets/workspace.js") {
|
|
563
|
+
response.setHeader(WORKSPACE_REVISION_HEADER, WORKSPACE_REVISION);
|
|
564
|
+
response.setHeader(WORKSPACE_INSTANCE_HEADER, WORKSPACE_INSTANCE);
|
|
561
565
|
this.sendJavascript(response, request.method === "HEAD", WORKSPACE_SCRIPT);
|
|
562
566
|
return;
|
|
563
567
|
}
|
|
@@ -571,8 +575,7 @@ export class LocalFileViewerServer {
|
|
|
571
575
|
}
|
|
572
576
|
try { await this.handleWorkspace(request, response, requestUrl, root); }
|
|
573
577
|
catch (error) {
|
|
574
|
-
|
|
575
|
-
this.sendWorkspaceJson(response, error instanceof WorkspaceError ? error.status : code === "ENOENT" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500,
|
|
578
|
+
this.sendWorkspaceJson(response, this.workspaceErrorStatus(error),
|
|
576
579
|
{ error: error instanceof Error ? error.message : String(error) }, request.method === "HEAD");
|
|
577
580
|
}
|
|
578
581
|
return;
|
|
@@ -614,7 +617,7 @@ export class LocalFileViewerServer {
|
|
|
614
617
|
}
|
|
615
618
|
const detailKey = requestUrl.searchParams.get("detail");
|
|
616
619
|
let snapshot = recorded
|
|
617
|
-
? journal!.
|
|
620
|
+
? await journal!.loadAsync(journalId, detailKey ?? false)
|
|
618
621
|
: this.options.getTurnSnapshot?.(turnId);
|
|
619
622
|
if (!recorded && this.options.loadTurnSnapshot && request.method !== "HEAD"
|
|
620
623
|
&& requestUrl.searchParams.get("events") !== "1" && !requestUrl.searchParams.has("detail")) {
|
|
@@ -983,14 +986,16 @@ export class LocalFileViewerServer {
|
|
|
983
986
|
if (request.method === "HEAD") { response.end(); return; }
|
|
984
987
|
response.flushHeaders();
|
|
985
988
|
const language = detectTurnPreviewLanguage(request.headers["accept-language"]);
|
|
986
|
-
|
|
989
|
+
let projection = new TurnPreviewProjection(false);
|
|
987
990
|
let offset = 0;
|
|
988
991
|
let closed = false;
|
|
989
992
|
let initial = true;
|
|
990
993
|
const cursor = request.headers["last-event-id"] ?? new URL(request.url!, "http://localhost").searchParams.get("after");
|
|
991
994
|
if (typeof cursor === "string" && /^\d+$/u.test(cursor) && Number.isSafeInteger(Number(cursor)) && Number(cursor) > 0
|
|
992
995
|
&& Number(cursor) <= fs.statSync(journal.file(turnId)).size) {
|
|
993
|
-
|
|
996
|
+
const cached = journal.cachedProjection(turnId, Number(cursor));
|
|
997
|
+
if (cached) { projection = cached; offset = Number(cursor); }
|
|
998
|
+
while (!cached && offset < Number(cursor)) {
|
|
994
999
|
const batch = journal.read(turnId, offset, 256 * 1024, Number(cursor));
|
|
995
1000
|
for (const record of batch.records) projection.apply(record, ++projection.revision);
|
|
996
1001
|
if (batch.offset === offset) break;
|
|
@@ -1095,32 +1100,77 @@ export class LocalFileViewerServer {
|
|
|
1095
1100
|
response.once("close", cleanup);
|
|
1096
1101
|
}
|
|
1097
1102
|
|
|
1098
|
-
private sendWorkspaceJson(response: ServerResponse, status: number, value: unknown, headOnly: boolean): void {
|
|
1103
|
+
private sendWorkspaceJson(response: ServerResponse, status: number, value: unknown, headOnly: boolean, request?: IncomingMessage): void {
|
|
1099
1104
|
const body = Buffer.from(JSON.stringify(value), "utf8");
|
|
1100
1105
|
setSecurityHeaders(response);
|
|
1106
|
+
if (request) {
|
|
1107
|
+
const etag = '"' + createHash("sha256").update(body).digest("base64url") + '"';
|
|
1108
|
+
response.setHeader("ETag", etag);
|
|
1109
|
+
if (request.headers["if-none-match"] === etag) {
|
|
1110
|
+
response.writeHead(304, { "Cache-Control": "no-store" }); response.end(); return;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1101
1113
|
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "Content-Length": body.length });
|
|
1102
1114
|
response.end(headOnly ? undefined : body);
|
|
1103
1115
|
}
|
|
1104
1116
|
|
|
1105
|
-
|
|
1106
|
-
|
|
1117
|
+
async serveTaskDirectory(request: IncomingMessage, response: ServerResponse, url: URL, root: string, base: URL): Promise<void> {
|
|
1118
|
+
try {
|
|
1119
|
+
await this.handleWorkspace(request, response, url, root, base);
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
if (response.headersSent) throw error;
|
|
1122
|
+
const status = this.workspaceErrorStatus(error);
|
|
1123
|
+
const message = status < 500 && error instanceof Error ? error.message : "暂时无法打开此目录,请重试。";
|
|
1124
|
+
if (url.searchParams.has("api")) this.sendWorkspaceJson(response, status, { error: message }, request.method === "HEAD");
|
|
1125
|
+
else this.sendHtml(response, status, errorPage("无法打开任务目录", message), request.method === "HEAD", "embedded");
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
private workspaceErrorStatus(error: unknown): number {
|
|
1130
|
+
if (error instanceof WorkspaceError) return error.status;
|
|
1131
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
1132
|
+
return code === "ENOENT" || code === "ENOTDIR" ? 404 : code === "EACCES" || code === "EPERM" ? 403 : 500;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
private async handleWorkspace(request: IncomingMessage, response: ServerResponse, url: URL, root: string, scopedBase?: URL): Promise<void> {
|
|
1136
|
+
if (!fs.statSync(resolveWorkspacePath(root)).isDirectory()) throw new WorkspaceError("目录已不可用。", 404);
|
|
1107
1137
|
const headOnly = request.method === "HEAD";
|
|
1108
1138
|
const published = new URL(this.address!.publicBaseUrl);
|
|
1109
|
-
const origin = request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request);
|
|
1110
|
-
const workspaceUrl = this.createWorkspaceUrl(root, origin)!;
|
|
1111
|
-
if (!url.searchParams.
|
|
1112
|
-
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js",
|
|
1139
|
+
const origin = scopedBase?.origin ?? (request.headers.host === published.host ? published.origin : directWorkspaceOrigin(request));
|
|
1140
|
+
const workspaceUrl = scopedBase?.href ?? this.createWorkspaceUrl(root, origin)!;
|
|
1141
|
+
if (!url.searchParams.get("api")) {
|
|
1142
|
+
this.sendHtml(response, 200, renderWorkspacePage(root, workspaceUrl, this.basePath + "/assets/workspace.js",
|
|
1143
|
+
scopedBase ? undefined : this.workspaceAppBase, Boolean(scopedBase)), headOnly, scopedBase ? "embedded" : true);
|
|
1113
1144
|
return;
|
|
1114
1145
|
}
|
|
1115
1146
|
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1116
1147
|
if (!parsed.success) throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1117
|
-
const { api, entry, page, mode, original, prefetch, query, instance } = parsed.data;
|
|
1118
|
-
if (
|
|
1119
|
-
|
|
1148
|
+
const { api, entry, page, mode, original, prefetch, query, instance, refresh, source } = parsed.data;
|
|
1149
|
+
if (scopedBase && (api === "terminal" || api === "web-title")) throw new WorkspaceError("该目录只支持文件浏览。", 404);
|
|
1150
|
+
if (api === "events") {
|
|
1151
|
+
if (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)) {
|
|
1152
|
+
throw new WorkspaceError("项目实时连接来源不受信任。", 403);
|
|
1153
|
+
}
|
|
1154
|
+
if (headOnly) this.sendWorkspaceJson(response, 200, {}, true);
|
|
1155
|
+
else this.workspaceFileEvents.subscribe(root, response);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (api === "tree" || api === "changes") {
|
|
1159
|
+
if (refresh) this.workspaceFileEvents.invalidateGit(root);
|
|
1160
|
+
const read = api === "tree" ? readWorkspaceEntries : readWorkspaceChanges;
|
|
1161
|
+
const data = await read(root, entry, page, {
|
|
1162
|
+
prefetch: prefetch === "1" && request.headers["save-data"] !== "on", query, readGitStatus: () => this.workspaceFileEvents.gitStatus(root),
|
|
1163
|
+
});
|
|
1164
|
+
if (!headOnly && !query && page === 0) {
|
|
1165
|
+
this.workspaceFileEvents.watchDirectory(root, entry);
|
|
1166
|
+
if ("preloaded" in data && data.preloaded) for (const item of data.preloaded) if (item.directory) this.workspaceFileEvents.watchDirectory(root, item.path);
|
|
1167
|
+
}
|
|
1168
|
+
this.sendWorkspaceJson(response, 200, data, headOnly, request);
|
|
1120
1169
|
return;
|
|
1121
1170
|
}
|
|
1122
|
-
if (api === "
|
|
1123
|
-
|
|
1171
|
+
if (api === "changes-summary") {
|
|
1172
|
+
const { changes, repository, branch, notice } = await this.workspaceFileEvents.gitStatus(root);
|
|
1173
|
+
this.sendWorkspaceJson(response, 200, { totalChanges: changes.length, repository, branch, notice }, headOnly, request);
|
|
1124
1174
|
return;
|
|
1125
1175
|
}
|
|
1126
1176
|
if (api === "address") {
|
|
@@ -1131,10 +1181,6 @@ export class LocalFileViewerServer {
|
|
|
1131
1181
|
this.sendWorkspaceJson(response, 200, headOnly ? {} : await readWebPageTitle(entry), headOnly);
|
|
1132
1182
|
return;
|
|
1133
1183
|
}
|
|
1134
|
-
if (api === "changes") {
|
|
1135
|
-
this.sendWorkspaceJson(response, 200, await readWorkspaceChanges(root, entry, page, { prefetch: prefetch === "1", query }), headOnly);
|
|
1136
|
-
return;
|
|
1137
|
-
}
|
|
1138
1184
|
if (api === "terminal") {
|
|
1139
1185
|
if (!instance) throw new WorkspaceError("终端标签标识无效。");
|
|
1140
1186
|
if (!this.options.createWorkspaceTerminalUrl) throw new WorkspaceError("网页终端服务未启用。", 503);
|
|
@@ -1147,12 +1193,12 @@ export class LocalFileViewerServer {
|
|
|
1147
1193
|
const file = resolveWorkspacePath(root, entry, true);
|
|
1148
1194
|
const before = classifyContentSample(versions.before, true), after = classifyContentSample(versions.after, true);
|
|
1149
1195
|
let html: string;
|
|
1150
|
-
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff
|
|
1196
|
+
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff。</div>';
|
|
1151
1197
|
else {
|
|
1152
1198
|
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1153
1199
|
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
1154
1200
|
}
|
|
1155
|
-
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly);
|
|
1201
|
+
this.sendWorkspaceJson(response, 200, { html, canViewFile: versions.canViewFile }, headOnly, request);
|
|
1156
1202
|
return;
|
|
1157
1203
|
}
|
|
1158
1204
|
if (api !== "file" && api !== "raw") throw new WorkspaceError("工作台接口不存在。", 404);
|
|
@@ -1167,18 +1213,20 @@ export class LocalFileViewerServer {
|
|
|
1167
1213
|
raw.searchParams.set("api", "raw"); raw.searchParams.set("entry", entry);
|
|
1168
1214
|
const classification = classifyFileContent(file, stat.size);
|
|
1169
1215
|
const type = binaryContentTypeFor(path.extname(file).toLowerCase());
|
|
1216
|
+
const canTogglePreview = classification.kind === "text" && isMarkdownFile(file);
|
|
1170
1217
|
let html: string;
|
|
1171
1218
|
if (classification.kind === "text") {
|
|
1172
1219
|
const preview = readTextPreview(file, stat.size, classification.encoding);
|
|
1173
1220
|
const lines = preview.text.split(/\r\n?|\n/u);
|
|
1174
|
-
|
|
1175
|
-
|
|
1221
|
+
const text = lines.slice(0, 10_000).join("\n");
|
|
1222
|
+
html = (preview.truncated || lines.length > 10_000 ? '<div class="workspace-notice">文件较大,仅显示前 2 MiB 或 10000 行。</div>' : "")
|
|
1223
|
+
+ (canTogglePreview && source !== "1" ? this.renderWorkspaceMarkdown(root, file, text, workspaceUrl) : renderText(text, file));
|
|
1176
1224
|
} else if (type.startsWith("image/")) {
|
|
1177
1225
|
html = '<div class="workspace-media"><img src="' + escapeAttribute(raw.toString()) + '" alt="' + escapeAttribute(path.basename(file)) + '"></div>';
|
|
1178
1226
|
} else if (type === "application/pdf") {
|
|
1179
|
-
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '"
|
|
1227
|
+
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '">当前浏览器无法显示 PDF 预览。</object>';
|
|
1180
1228
|
} else {
|
|
1181
|
-
html = '<div class="workspace-notice"
|
|
1229
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,当前没有可用的预览。</div>';
|
|
1182
1230
|
}
|
|
1183
1231
|
let change: WorkspaceChange | undefined, gitError: string | undefined;
|
|
1184
1232
|
try {
|
|
@@ -1186,11 +1234,17 @@ export class LocalFileViewerServer {
|
|
|
1186
1234
|
const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
1187
1235
|
change = (await readWorkspaceGitStatus(root)).changes.find(item => normalize(item.path) === normalize(relative));
|
|
1188
1236
|
} catch (error) { gitError = error instanceof Error ? error.message : String(error); }
|
|
1189
|
-
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly);
|
|
1237
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), canTogglePreview, change, gitError }, headOnly, request);
|
|
1190
1238
|
}
|
|
1191
1239
|
|
|
1192
1240
|
private renderWorkspaceMarkdown(root: string, file: string, value: string, workspaceUrl: string): string {
|
|
1193
1241
|
const environment = {}, tokens = MARKDOWN_RENDERER.parse(value, environment), targets = new Map<string, string>();
|
|
1242
|
+
for (const token of tokens) {
|
|
1243
|
+
if (token.map && !token.hidden && token.tag && token.nesting >= 0) {
|
|
1244
|
+
token.attrSet("data-source-start", String(token.map[0] + 1));
|
|
1245
|
+
token.attrSet("data-source-end", String(token.map[1]));
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1194
1248
|
rewriteMarkdownFileLinks(tokens, file, (target) => {
|
|
1195
1249
|
const entry = path.relative(root, target).split(path.sep).join("/");
|
|
1196
1250
|
try {
|
|
@@ -1315,12 +1369,12 @@ export class LocalFileViewerServer {
|
|
|
1315
1369
|
stream.pipe(response);
|
|
1316
1370
|
}
|
|
1317
1371
|
|
|
1318
|
-
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false, workspace = false): void {
|
|
1372
|
+
private sendHtml(response: ServerResponse, status: number, html: string, headOnly = false, workspace: boolean | "embedded" = false): void {
|
|
1319
1373
|
const body = Buffer.from(html, "utf8");
|
|
1320
1374
|
setSecurityHeaders(response);
|
|
1321
1375
|
// External frame redirects must not expose privileged viewer documents.
|
|
1322
|
-
response.setHeader("X-Frame-Options", "DENY");
|
|
1323
|
-
if (workspace) response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self' http: https:; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
|
|
1376
|
+
response.setHeader("X-Frame-Options", workspace === "embedded" ? "SAMEORIGIN" : "DENY");
|
|
1377
|
+
if (workspace) response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data: blob:; media-src 'self'; object-src 'self'; frame-src 'self' http: https:; script-src 'self'; connect-src 'self'; font-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors " + (workspace === "embedded" ? "'self'" : "'none'"));
|
|
1324
1378
|
else response.setHeader("Content-Security-Policy", String(response.getHeader("Content-Security-Policy")).replace("frame-ancestors 'self'", "frame-ancestors 'none'"));
|
|
1325
1379
|
response.statusCode = status;
|
|
1326
1380
|
response.setHeader("Cache-Control", "no-store");
|
|
@@ -1377,8 +1431,8 @@ function renderViewerPage(input: {
|
|
|
1377
1431
|
<meta charset="utf-8">
|
|
1378
1432
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1379
1433
|
<title>${escapeHtml(input.title)} · Agent Bot</title>
|
|
1380
|
-
<style>${input.diagramScriptPath ? DIAGRAM_PREVIEW_CSS : ""}
|
|
1381
|
-
:root { --viewer-header-offset: 56px;
|
|
1434
|
+
<style>${input.scriptPath ? previewCodeFontCss(input.scriptPath) : ""}${input.diagramScriptPath ? DIAGRAM_PREVIEW_CSS : ""}
|
|
1435
|
+
:root { --viewer-header-offset: 56px; color-scheme: light dark; font-family: Inter, "Segoe UI", system-ui, sans-serif; }
|
|
1382
1436
|
* { box-sizing: border-box; }
|
|
1383
1437
|
body { margin: 0; background: #f5f7fa; color: #1f2329; }
|
|
1384
1438
|
header { position: sticky; top: 0; z-index: 2; padding: 7px 12px; background: rgba(255,255,255,.96); border-bottom: 1px solid #dfe3e8; }
|
|
@@ -1401,10 +1455,10 @@ function renderViewerPage(input: {
|
|
|
1401
1455
|
main { padding: 0; }
|
|
1402
1456
|
.notice, .unsupported { margin: 8px; padding: 10px 12px; border: 1px solid #f3cf8f; background: #fff7e6; border-radius: 5px; }
|
|
1403
1457
|
.code { margin: 0; padding: 6px 0; overflow: auto; border: 0; border-radius: 0; background: #fff; color: #1f2329; font-size: 13px; line-height: 1.5; tab-size: 2; }
|
|
1404
|
-
.code, .code code, .code .line, .code .line * { font-family: var(--
|
|
1458
|
+
.code, .code code, .code .line, .code .line * { font-family: var(--preview-code-font); font-variant-ligatures: none; }
|
|
1405
1459
|
.line { display: block; min-height: 1.55em; padding-right: 16px; scroll-margin-top: var(--viewer-header-offset); }
|
|
1406
1460
|
.line:target, .line.is-target-line { background: #fff1b8; box-shadow: inset 4px 0 #e6a700; }
|
|
1407
|
-
.line-number { display: inline-block; width:
|
|
1461
|
+
.line-number { display: inline-block; box-sizing: content-box; width: var(--line-number-width, 2ch); margin-right: 8px; padding: 0 6px; text-align: right; color: #8f959e; border-right: 1px solid #eceff3; text-decoration: none; user-select: none; }
|
|
1408
1462
|
.hljs-comment, .hljs-quote { color: #6a737d; font-style: italic; }
|
|
1409
1463
|
.hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-section, .hljs-link { color: #a626a4; }
|
|
1410
1464
|
.hljs-string, .hljs-regexp, .hljs-title, .hljs-name, .hljs-type, .hljs-attribute, .hljs-symbol, .hljs-bullet, .hljs-addition, .hljs-variable, .hljs-template-tag, .hljs-template-variable { color: #087f5b; }
|
|
@@ -1428,7 +1482,7 @@ function renderViewerPage(input: {
|
|
|
1428
1482
|
.markdown-body blockquote { margin-left: 0; padding: .15em 1em; border-left: 4px solid #c9d0db; color: #646a73; }
|
|
1429
1483
|
.markdown-body a { color: #1456f0; text-decoration: none; }
|
|
1430
1484
|
.markdown-body a:hover { text-decoration: underline; }
|
|
1431
|
-
.markdown-body code { padding: .14em .35em; border-radius: 4px; background: #f2f3f5; font-family: var(--
|
|
1485
|
+
.markdown-body code { padding: .14em .35em; border-radius: 4px; background: #f2f3f5; font-family: var(--preview-code-font); font-size: .9em; }
|
|
1432
1486
|
.markdown-body .markdown-code-block { margin: 0 0 1em; padding: 14px 16px; overflow: auto; border-radius: 6px; background: #f6f8fa; line-height: 1.55; }
|
|
1433
1487
|
.markdown-body .markdown-code-block code { padding: 0; background: transparent; font-size: 13px; }
|
|
1434
1488
|
.markdown-body .diagram-source { padding: 14px 16px; }
|
|
@@ -1781,20 +1835,13 @@ function hasTextLikeCharacters(value: string): boolean {
|
|
|
1781
1835
|
function renderText(value: string, filePath: string): string {
|
|
1782
1836
|
const language = syntaxLanguageFor(filePath), lines = highlightTextLines(value, filePath);
|
|
1783
1837
|
const languageClass = language ? ` class="language-${escapeAttribute(language)}"` : "";
|
|
1784
|
-
|
|
1838
|
+
const numberWidth = Math.max(2, String(lines.length).length);
|
|
1839
|
+
return `<pre class="code hljs" style="--line-number-width:${numberWidth}ch"><code${languageClass}>${lines.map((line, index) => {
|
|
1785
1840
|
const lineNumber = index + 1;
|
|
1786
|
-
return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a>${line}</span>`;
|
|
1841
|
+
return `<span class="line" id="L${lineNumber}"><a class="line-number" href="#L${lineNumber}">${lineNumber}</a><span class="line-text">${line}</span></span>`;
|
|
1787
1842
|
}).join("")}</code></pre>`;
|
|
1788
1843
|
}
|
|
1789
1844
|
|
|
1790
|
-
function highlightTextLines(value: string, filePath: string): string[] {
|
|
1791
|
-
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
1792
|
-
const language = syntaxLanguageFor(filePath);
|
|
1793
|
-
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
1794
|
-
? highlightLines(normalized, language)
|
|
1795
|
-
: normalized.split("\n").map(escapeHtml);
|
|
1796
|
-
}
|
|
1797
|
-
|
|
1798
1845
|
function renderMarkdownDocument(value: string, filePath: string, createPreviewUrl: (filePath: string) => URL): string {
|
|
1799
1846
|
const environment = {};
|
|
1800
1847
|
const tokens = MARKDOWN_RENDERER.parse(value, environment);
|
|
@@ -1807,50 +1854,6 @@ function isMarkdownFile(filePath: string): boolean {
|
|
|
1807
1854
|
return MARKDOWN_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
1808
1855
|
}
|
|
1809
1856
|
|
|
1810
|
-
function syntaxLanguageFor(filePath: string): string | undefined {
|
|
1811
|
-
if (isMarkdownFile(filePath)) return "markdown";
|
|
1812
|
-
const fileName = path.basename(filePath).toLowerCase();
|
|
1813
|
-
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
1814
|
-
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
1815
|
-
}
|
|
1816
|
-
|
|
1817
|
-
function highlightLines(value: string, language: string): string[] {
|
|
1818
|
-
try {
|
|
1819
|
-
return splitHighlightedLines(hljs.highlight(value, { language, ignoreIllegals: true }).value);
|
|
1820
|
-
} catch {
|
|
1821
|
-
return value.split("\n").map(escapeHtml);
|
|
1822
|
-
}
|
|
1823
|
-
}
|
|
1824
|
-
|
|
1825
|
-
function splitHighlightedLines(value: string): string[] {
|
|
1826
|
-
const lines: string[] = [];
|
|
1827
|
-
const openTags: string[] = [];
|
|
1828
|
-
const tokenPattern = /<span class="[^"]+">|<\/span>|\n/gu;
|
|
1829
|
-
let current = "";
|
|
1830
|
-
let offset = 0;
|
|
1831
|
-
for (const match of value.matchAll(tokenPattern)) {
|
|
1832
|
-
const token = match[0];
|
|
1833
|
-
const index = match.index ?? offset;
|
|
1834
|
-
current += value.slice(offset, index);
|
|
1835
|
-
offset = index + token.length;
|
|
1836
|
-
if (token === "\n") {
|
|
1837
|
-
current += "</span>".repeat(openTags.length);
|
|
1838
|
-
lines.push(current);
|
|
1839
|
-
current = openTags.join("");
|
|
1840
|
-
} else if (token === "</span>") {
|
|
1841
|
-
current += token;
|
|
1842
|
-
openTags.pop();
|
|
1843
|
-
} else {
|
|
1844
|
-
current += token;
|
|
1845
|
-
openTags.push(token);
|
|
1846
|
-
}
|
|
1847
|
-
}
|
|
1848
|
-
current += value.slice(offset);
|
|
1849
|
-
current += "</span>".repeat(openTags.length);
|
|
1850
|
-
lines.push(current);
|
|
1851
|
-
return lines;
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
1857
|
function contentTypeFor(extension: string): string {
|
|
1855
1858
|
const known: Record<string, string> = {
|
|
1856
1859
|
".aac": "audio/aac", ".avi": "video/x-msvideo", ".bmp": "image/bmp", ".css": "text/css; charset=utf-8",
|
|
@@ -1927,7 +1930,7 @@ function writeServerSentEvent(response: ServerResponse, event: string, data: str
|
|
|
1927
1930
|
}
|
|
1928
1931
|
|
|
1929
1932
|
function setSecurityHeaders(response: ServerResponse): void {
|
|
1930
|
-
response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self'; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'");
|
|
1933
|
+
response.setHeader("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; object-src 'self'; frame-src 'self'; script-src 'self'; connect-src 'self'; font-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'");
|
|
1931
1934
|
response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
1932
1935
|
response.setHeader("Referrer-Policy", "no-referrer");
|
|
1933
1936
|
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export function turnAnswerFilename(turnId: string): string {
|
|
2
|
+
return `turn-${turnId.replace(/[^A-Za-z0-9_-]/gu, "_").slice(0, 80) || "answer"}.md`;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export const MARKDOWN_EXPORT_CLIENT_SCRIPT = `(() => {
|
|
6
|
+
async function copy(text) {
|
|
7
|
+
const clipboard = window.navigator?.clipboard;
|
|
8
|
+
if (typeof text !== "string" && clipboard?.write && window.ClipboardItem) {
|
|
9
|
+
try {
|
|
10
|
+
await clipboard.write([new window.ClipboardItem({ "text/plain": text.then(value => new Blob([value], { type: "text/plain" })) })]);
|
|
11
|
+
return;
|
|
12
|
+
} catch {}
|
|
13
|
+
}
|
|
14
|
+
if (typeof text !== "string") text = await text;
|
|
15
|
+
if (clipboard?.writeText) {
|
|
16
|
+
try { await clipboard.writeText(text); return; } catch {}
|
|
17
|
+
}
|
|
18
|
+
const active = document.activeElement, selection = window.getSelection?.();
|
|
19
|
+
const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i).cloneRange()) : [];
|
|
20
|
+
const field = document.createElement("textarea");
|
|
21
|
+
field.value = text;
|
|
22
|
+
field.readOnly = true;
|
|
23
|
+
field.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none";
|
|
24
|
+
document.body.append(field);
|
|
25
|
+
try {
|
|
26
|
+
field.focus({ preventScroll: true });
|
|
27
|
+
field.select();
|
|
28
|
+
field.setSelectionRange(0, text.length);
|
|
29
|
+
if (!document.execCommand?.("copy")) throw new Error("Clipboard unavailable");
|
|
30
|
+
} finally {
|
|
31
|
+
field.remove();
|
|
32
|
+
active?.focus?.({ preventScroll: true });
|
|
33
|
+
if (selection) {
|
|
34
|
+
selection.removeAllRanges();
|
|
35
|
+
for (const range of ranges) selection.addRange(range);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function download(markdown, filename) {
|
|
40
|
+
const url = URL.createObjectURL(new Blob([markdown], { type: "text/markdown;charset=utf-8" }));
|
|
41
|
+
const link = document.createElement("a");
|
|
42
|
+
try {
|
|
43
|
+
link.href = url;
|
|
44
|
+
link.download = filename;
|
|
45
|
+
link.hidden = true;
|
|
46
|
+
document.body.append(link);
|
|
47
|
+
link.click();
|
|
48
|
+
} finally {
|
|
49
|
+
link.remove();
|
|
50
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
window.agentBotMarkdown = { copy, download };
|
|
54
|
+
})();\n`;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
|
|
3
|
+
export const PREVIEW_CODE_FONT_NAME = "roboto-mono-latin.woff2";
|
|
4
|
+
export const PREVIEW_CODE_FONT = fs.readFileSync(new URL("../../assets/" + PREVIEW_CODE_FONT_NAME, import.meta.url));
|
|
5
|
+
|
|
6
|
+
export function previewCodeFontCss(scriptPath: string): string {
|
|
7
|
+
const assetPath = scriptPath.replace(/[^/]+$/u, PREVIEW_CODE_FONT_NAME);
|
|
8
|
+
return `
|
|
9
|
+
@font-face { font-family: "Roboto Mono"; src: url(${JSON.stringify(assetPath)}) format("woff2"); font-style: normal; font-weight: 400; font-display: swap; }
|
|
10
|
+
:root { --preview-code-font: "Roboto Mono", "Cascadia Mono", Consolas, Menlo, "Liberation Mono", "Noto Sans Mono CJK SC", "Microsoft YaHei", monospace; }
|
|
11
|
+
`;
|
|
12
|
+
}
|