@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +77 -12
- package/README.zh.md +77 -12
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +26 -14
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +40 -10
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +133 -117
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +23 -269
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +20 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +22 -8
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +120 -120
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +24 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -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
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import path from "node:path";
|
|
1
2
|
import hljs from "highlight.js/lib/common";
|
|
2
3
|
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
|
3
4
|
import dos from "highlight.js/lib/languages/dos";
|
|
@@ -8,7 +9,26 @@ hljs.registerLanguage("dos", dos);
|
|
|
8
9
|
hljs.registerLanguage("powershell", powershell);
|
|
9
10
|
|
|
10
11
|
const LANGUAGE_ALIASES: Readonly<Record<string, string>> = { zsh: "bash", pwsh: "powershell" };
|
|
12
|
+
const HIGHLIGHT_LANGUAGE_BY_EXTENSION: Readonly<Record<string, string>> = {
|
|
13
|
+
".bash": "bash", ".bat": "dos", ".c": "c", ".cc": "cpp", ".cmd": "dos", ".cpp": "cpp",
|
|
14
|
+
".cs": "csharp", ".css": "css", ".cxx": "cpp", ".diff": "diff", ".go": "go", ".h": "cpp",
|
|
15
|
+
".hpp": "cpp", ".htm": "xml", ".html": "xml", ".ini": "ini", ".ipynb": "json", ".java": "java",
|
|
16
|
+
".js": "javascript", ".json": "json", ".jsonl": "json", ".jsx": "javascript", ".kt": "kotlin",
|
|
17
|
+
".kts": "kotlin", ".less": "less", ".lua": "lua", ".markdown": "markdown", ".md": "markdown",
|
|
18
|
+
".mdown": "markdown", ".mkd": "markdown", ".mkdn": "markdown",
|
|
19
|
+
".mjs": "javascript", ".patch": "diff", ".php": "php", ".pl": "perl", ".ps1": "powershell",
|
|
20
|
+
".py": "python", ".r": "r", ".rb": "ruby", ".rs": "rust", ".scss": "scss", ".sh": "bash",
|
|
21
|
+
".sql": "sql", ".swift": "swift", ".toml": "ini", ".ts": "typescript", ".tsx": "typescript",
|
|
22
|
+
".vue": "xml", ".xml": "xml", ".yaml": "yaml", ".yml": "yaml", ".zsh": "bash",
|
|
23
|
+
};
|
|
24
|
+
const HIGHLIGHT_LANGUAGE_BY_FILENAME: Readonly<Record<string, string>> = {
|
|
25
|
+
".env": "ini",
|
|
26
|
+
".gitignore": "ini",
|
|
27
|
+
"dockerfile": "dockerfile",
|
|
28
|
+
"makefile": "makefile",
|
|
29
|
+
};
|
|
11
30
|
export const MAX_PREVIEW_HIGHLIGHT_BYTES = 64 * 1024;
|
|
31
|
+
export const MAX_SYNTAX_HIGHLIGHT_BYTES = 512 * 1024;
|
|
12
32
|
const MAX_CACHE_BYTES = 1024 * 1024;
|
|
13
33
|
const MAX_CACHE_ENTRIES = 32;
|
|
14
34
|
const cache = new Map<string, { html: string; bytes: number }>();
|
|
@@ -44,6 +64,61 @@ export function highlightPreviewCode(value: string, language: string): string {
|
|
|
44
64
|
}
|
|
45
65
|
}
|
|
46
66
|
|
|
67
|
+
export function syntaxLanguageFor(filePath: string): string | undefined {
|
|
68
|
+
const fileName = path.basename(filePath).toLowerCase();
|
|
69
|
+
return Object.hasOwn(HIGHLIGHT_LANGUAGE_BY_FILENAME, fileName) ? HIGHLIGHT_LANGUAGE_BY_FILENAME[fileName]
|
|
70
|
+
: HIGHLIGHT_LANGUAGE_BY_EXTENSION[path.extname(fileName)];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function highlightTextLines(value: string, filePath: string): string[] {
|
|
74
|
+
const normalized = value.replace(/\r\n?/gu, "\n");
|
|
75
|
+
const language = syntaxLanguageFor(filePath);
|
|
76
|
+
return language && Buffer.byteLength(normalized, "utf8") <= MAX_SYNTAX_HIGHLIGHT_BYTES
|
|
77
|
+
? highlightLines(normalized, language)
|
|
78
|
+
: normalized.split("\n").map(escapeHtml);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function highlightLines(value: string, language: string): string[] {
|
|
82
|
+
try {
|
|
83
|
+
return splitHighlightedLines(hljs.highlight(value, { language, ignoreIllegals: true }).value);
|
|
84
|
+
} catch {
|
|
85
|
+
return value.split("\n").map(escapeHtml);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function splitHighlightedLines(value: string): string[] {
|
|
90
|
+
const lines: string[] = [];
|
|
91
|
+
const openTags: string[] = [];
|
|
92
|
+
const tokenPattern = /<span class="[^"]+">|<\/span>|\n/gu;
|
|
93
|
+
let current = "";
|
|
94
|
+
let offset = 0;
|
|
95
|
+
for (const match of value.matchAll(tokenPattern)) {
|
|
96
|
+
const token = match[0];
|
|
97
|
+
const index = match.index ?? offset;
|
|
98
|
+
current += value.slice(offset, index);
|
|
99
|
+
offset = index + token.length;
|
|
100
|
+
if (token === "\n") {
|
|
101
|
+
current += "</span>".repeat(openTags.length);
|
|
102
|
+
lines.push(current);
|
|
103
|
+
current = openTags.join("");
|
|
104
|
+
} else if (token === "</span>") {
|
|
105
|
+
current += token;
|
|
106
|
+
openTags.pop();
|
|
107
|
+
} else {
|
|
108
|
+
current += token;
|
|
109
|
+
openTags.push(token);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
current += value.slice(offset);
|
|
113
|
+
current += "</span>".repeat(openTags.length);
|
|
114
|
+
lines.push(current);
|
|
115
|
+
return lines;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function escapeHtml(value: string): string {
|
|
119
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
120
|
+
}
|
|
121
|
+
|
|
47
122
|
export const PREVIEW_SYNTAX_CSS = `
|
|
48
123
|
.markdown pre { --syntax-comment:#667080; --syntax-keyword:#9639a5; --syntax-string:#087f5b; --syntax-number:#986801; --syntax-title:#005cc5; --syntax-deletion:#b31d28; }
|
|
49
124
|
.markdown pre .hljs-comment, .markdown pre .hljs-quote { color:var(--syntax-comment); }
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { displayToolCommand, formatShellCommandForDisplay } from "../feishu/CardRenderer.js";
|
|
2
|
+
import type { ToolState } from "../runtime/types.js";
|
|
3
|
+
|
|
4
|
+
type PreviewTool = Pick<ToolState, "title" | "kind" | "command">;
|
|
5
|
+
|
|
6
|
+
export interface PreviewToolHeading {
|
|
7
|
+
title: string;
|
|
8
|
+
command?: true;
|
|
9
|
+
repl?: true;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function previewToolHeading(tool: PreviewTool, commandLabel: string): PreviewToolHeading {
|
|
13
|
+
const repl = isReplTool(tool);
|
|
14
|
+
const command = tool.command || (tool.kind === "command" && shellPayload(tool.title) ? tool.title : undefined);
|
|
15
|
+
const display = renderableToolCommand(command, repl);
|
|
16
|
+
const fallback = repl ? "REPL" : command?.trim() ? (tool.kind === "command" ? commandLabel : tool.kind) : tool.title.trim() || tool.kind;
|
|
17
|
+
return { title: display ? summarizeToolCommand(display) : fallback, command: display ? true : undefined, repl: repl ? true : undefined };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function summarizeToolCommand(command: string): string {
|
|
21
|
+
const summary = command.replace(/[\\`^][ \t]*\r?\n/gu, " ").replace(/\s+/gu, " ").trim();
|
|
22
|
+
if (summary.length <= 160) return summary;
|
|
23
|
+
return `${summary.slice(0, 157).trimEnd()}…`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function normalizeToolOutput(value: string): string {
|
|
27
|
+
return value.replace(/\r\n?/gu, "\n").trim();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function formatPreviewToolCommand(command: string): string {
|
|
31
|
+
const normalized = (shellPayload(command) || command).replace(/\r\n?/gu, "\n").trim();
|
|
32
|
+
const newline = normalized.indexOf("\n");
|
|
33
|
+
if (newline >= 0) {
|
|
34
|
+
const name = normalized.slice(0, newline).trim();
|
|
35
|
+
const payload = normalized.slice(newline + 1).trim();
|
|
36
|
+
if (name) {
|
|
37
|
+
try {
|
|
38
|
+
const parsed: unknown = JSON.parse(payload);
|
|
39
|
+
if (parsed && typeof parsed === "object") return `${name}\n${JSON.stringify(parsed, null, 2)}`;
|
|
40
|
+
} catch {
|
|
41
|
+
// A multiline shell command need not contain JSON arguments.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return formatShellCommandForDisplay(normalized);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function shellPayload(command: string): string | undefined {
|
|
49
|
+
const value = command.trim();
|
|
50
|
+
const unwrapped = displayToolCommand(value);
|
|
51
|
+
if (unwrapped !== undefined || !value.endsWith("…")) return unwrapped;
|
|
52
|
+
// Saved summaries can end before the shell wrapper's closing quote.
|
|
53
|
+
return displayToolCommand(value + "'") ?? displayToolCommand(value + '"');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function isReplTool(tool: PreviewTool): boolean {
|
|
57
|
+
const title = tool.title.trim();
|
|
58
|
+
const titleLooksLikeToolName = title.length <= 120 && !/[\s"'`]/u.test(title);
|
|
59
|
+
return tool.kind.toLowerCase().includes("repl")
|
|
60
|
+
|| (titleLooksLikeToolName && /(?:^|[._-])repl(?:$|[._-])/iu.test(title));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function renderableToolCommand(command: string | undefined, repl: boolean): string | undefined {
|
|
64
|
+
if (!command) return undefined;
|
|
65
|
+
if (!repl) return formatPreviewToolCommand(command);
|
|
66
|
+
const normalized = (shellPayload(command) || command).trim();
|
|
67
|
+
const newline = normalized.indexOf("\n");
|
|
68
|
+
if (newline >= 0) {
|
|
69
|
+
try {
|
|
70
|
+
const parsed: unknown = JSON.parse(normalized.slice(newline + 1).trim());
|
|
71
|
+
if (parsed && typeof parsed === "object") {
|
|
72
|
+
for (const key of ["input", "code", "script", "javascript", "source"]) {
|
|
73
|
+
const value = (parsed as Record<string, unknown>)[key];
|
|
74
|
+
if (typeof value === "string" && value.trim()) return formatReplSource(value);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} catch {
|
|
78
|
+
// Keep the original payload when a provider uses a non-JSON argument format.
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return formatReplSource(newline >= 0 ? normalized.slice(0, newline) : normalized);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function formatReplSource(source: string): string {
|
|
85
|
+
const normalized = source.replace(/\r\n?/gu, "\n").trim();
|
|
86
|
+
if (normalized.includes("\n")) return normalized;
|
|
87
|
+
const lines: string[] = [];
|
|
88
|
+
let current = "";
|
|
89
|
+
let quote: "'" | "\"" | "`" | undefined;
|
|
90
|
+
let escaped = false;
|
|
91
|
+
for (const character of normalized) {
|
|
92
|
+
current += character;
|
|
93
|
+
if (escaped) { escaped = false; continue; }
|
|
94
|
+
if (character === "\\" && quote) { escaped = true; continue; }
|
|
95
|
+
if (quote) { if (character === quote) quote = undefined; continue; }
|
|
96
|
+
if (character === "'" || character === "\"" || character === "`") { quote = character; continue; }
|
|
97
|
+
if (character === ";") {
|
|
98
|
+
lines.push(current.trim());
|
|
99
|
+
current = "";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (current.trim()) lines.push(current.trim());
|
|
103
|
+
return lines.join("\n");
|
|
104
|
+
}
|
|
@@ -7,12 +7,16 @@ import MarkdownIt from "markdown-it";
|
|
|
7
7
|
import { highlightPreviewCode, PREVIEW_SYNTAX_CSS } from "./PreviewSyntaxHighlight.js";
|
|
8
8
|
import type { ApprovalRequest, ToolState } from "../runtime/types.js";
|
|
9
9
|
import type { FileSummary, TurnActivity, TurnReasoningItem, TurnViewState, TurnViewStatus } from "../presentation/turnViewTypes.js";
|
|
10
|
-
import { displayFilePath,
|
|
10
|
+
import { displayFilePath, toolStatusIcon } from "../feishu/CardRenderer.js";
|
|
11
|
+
import { isReplTool, normalizeToolOutput, previewToolHeading, renderableToolCommand } from "./ToolCommandDisplay.js";
|
|
11
12
|
import { turnReasoningItems } from "../presentation/turnReasoning.js";
|
|
12
13
|
import { visibleTurnActivities } from "../presentation/visibleTurnActivities.js";
|
|
13
14
|
import { formatModelQueueDuration, liveModelQueueActivity, systemActivityQuote, USER_ACTIVITY_ICON } from "../presentation/turnActivity.js";
|
|
14
15
|
import { displayRuntimeError } from "../runtime/responseErrors.js";
|
|
15
16
|
import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
|
|
17
|
+
import { toolTimestamp } from "../utils/toolTimestamp.js";
|
|
18
|
+
import { MARKDOWN_EXPORT_CLIENT_SCRIPT, turnAnswerFilename } from "./MarkdownExport.js";
|
|
19
|
+
import { LIVE_MARKUP_CLIENT_SCRIPT } from "./LiveMarkup.js";
|
|
16
20
|
|
|
17
21
|
type PreviewFileUrl = (filePath: string, options?: { diff?: boolean }) => string | undefined;
|
|
18
22
|
|
|
@@ -149,7 +153,7 @@ export function detectTurnPreviewLanguage(
|
|
|
149
153
|
return /^zh(?:[-_]|$)/iu.test(candidates[0]?.tag ?? "") ? "zh" : "en";
|
|
150
154
|
}
|
|
151
155
|
|
|
152
|
-
export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() => {
|
|
156
|
+
export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + MARKDOWN_EXPORT_CLIENT_SCRIPT + LIVE_MARKUP_CLIENT_SCRIPT + `(() => {
|
|
153
157
|
const eventsUrl = document.body.dataset.eventsUrl;
|
|
154
158
|
const content = document.getElementById("turn-content");
|
|
155
159
|
const metadata = document.getElementById("turn-metadata");
|
|
@@ -172,35 +176,6 @@ export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() =
|
|
|
172
176
|
copyFailed: isChinese ? "复制失败,请检查浏览器剪贴板权限后重试。" : "Copy failed. Check clipboard permissions and retry.",
|
|
173
177
|
downloadFailed: isChinese ? "下载失败,请重试。" : "Download failed. Please retry.",
|
|
174
178
|
};
|
|
175
|
-
const copyMarkdownFallback = (text) => {
|
|
176
|
-
const active = document.activeElement;
|
|
177
|
-
const selection = window.getSelection?.();
|
|
178
|
-
const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i).cloneRange()) : [];
|
|
179
|
-
const textarea = document.createElement("textarea");
|
|
180
|
-
textarea.value = text;
|
|
181
|
-
textarea.readOnly = true;
|
|
182
|
-
textarea.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none";
|
|
183
|
-
document.body.append(textarea);
|
|
184
|
-
try {
|
|
185
|
-
textarea.focus({ preventScroll: true });
|
|
186
|
-
textarea.select();
|
|
187
|
-
textarea.setSelectionRange(0, text.length);
|
|
188
|
-
if (!document.execCommand?.("copy")) throw new Error("Clipboard unavailable");
|
|
189
|
-
} finally {
|
|
190
|
-
textarea.remove();
|
|
191
|
-
active?.focus?.({ preventScroll: true });
|
|
192
|
-
if (selection) {
|
|
193
|
-
selection.removeAllRanges();
|
|
194
|
-
for (const range of ranges) selection.addRange(range);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
const copyMarkdown = async (text) => {
|
|
199
|
-
if (window.navigator?.clipboard?.writeText) {
|
|
200
|
-
try { await window.navigator.clipboard.writeText(text); return; } catch {}
|
|
201
|
-
}
|
|
202
|
-
copyMarkdownFallback(text);
|
|
203
|
-
};
|
|
204
179
|
const answerActionsInFlight = new WeakSet();
|
|
205
180
|
content.addEventListener("click", async (event) => {
|
|
206
181
|
const button = event.target.closest?.("button[data-answer-action]");
|
|
@@ -214,21 +189,8 @@ export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() =
|
|
|
214
189
|
button.disabled = true;
|
|
215
190
|
try {
|
|
216
191
|
const markdown = new TextDecoder("utf-8", { ignoreBOM: true }).decode(Uint8Array.from(atob(section.dataset.answerMarkdown), (char) => char.charCodeAt(0)));
|
|
217
|
-
if (action === "copy") await
|
|
218
|
-
else
|
|
219
|
-
const url = URL.createObjectURL(new Blob([markdown], { type: "text/markdown;charset=utf-8" }));
|
|
220
|
-
const link = document.createElement("a");
|
|
221
|
-
try {
|
|
222
|
-
link.href = url;
|
|
223
|
-
link.download = section.dataset.answerFilename;
|
|
224
|
-
link.hidden = true;
|
|
225
|
-
document.body.append(link);
|
|
226
|
-
link.click();
|
|
227
|
-
} finally {
|
|
228
|
-
link.remove();
|
|
229
|
-
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
192
|
+
if (action === "copy") await window.agentBotMarkdown.copy(markdown);
|
|
193
|
+
else window.agentBotMarkdown.download(markdown, section.dataset.answerFilename);
|
|
232
194
|
if (feedback) feedback.textContent = action === "copy" ? labels.copied : labels.downloaded;
|
|
233
195
|
} catch {
|
|
234
196
|
if (feedback) feedback.textContent = action === "copy" ? labels.copyFailed : labels.downloadFailed;
|
|
@@ -258,7 +220,7 @@ export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() =
|
|
|
258
220
|
document.querySelectorAll("[data-live-tool-duration]").forEach((element) => {
|
|
259
221
|
const startedAt = Number(element.dataset.startedAt);
|
|
260
222
|
const completedAt = Number(element.dataset.completedAt) || Date.now();
|
|
261
|
-
if (!Number.isFinite(startedAt)) return;
|
|
223
|
+
if (!Number.isFinite(startedAt) || startedAt <= 0) return;
|
|
262
224
|
const seconds = Math.max(0, Math.floor((completedAt - startedAt) / 1000));
|
|
263
225
|
const hours = Math.floor(seconds / 3600);
|
|
264
226
|
const minutes = Math.floor((seconds % 3600) / 60);
|
|
@@ -316,106 +278,7 @@ export const TURN_PREVIEW_CLIENT_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + `(() =
|
|
|
316
278
|
}
|
|
317
279
|
};
|
|
318
280
|
|
|
319
|
-
const nodeKey
|
|
320
|
-
if (node.nodeType !== 1) return undefined;
|
|
321
|
-
for (const attribute of ["data-preview-key", "data-activity", "data-activity-id", "data-scroll-id", "data-reasoning-field", "data-reasoning-part"]) {
|
|
322
|
-
if (node.hasAttribute(attribute)) return attribute + ":" + node.getAttribute(attribute);
|
|
323
|
-
}
|
|
324
|
-
if (node.tagName === "IMG") return "image:" + node.getAttribute("src");
|
|
325
|
-
// Keep Markdown image paragraphs/links anchored when text is inserted before them.
|
|
326
|
-
if (["P", "A", "FIGURE", "PICTURE"].includes(node.tagName)) {
|
|
327
|
-
const image = node.querySelector("img");
|
|
328
|
-
if (image) return node.tagName + ":image:" + image.getAttribute("src");
|
|
329
|
-
}
|
|
330
|
-
for (const name of ["markdown", "tool-command", "tool-image", "files", "tool-header", "tool-body", "tool-footer"]) {
|
|
331
|
-
if (node.classList.contains(name)) return node.tagName + ":" + name;
|
|
332
|
-
}
|
|
333
|
-
return undefined;
|
|
334
|
-
};
|
|
335
|
-
const compatible = (current, next) => current.nodeType === next.nodeType && current.nodeName === next.nodeName;
|
|
336
|
-
const patchNode = (current, next) => {
|
|
337
|
-
if (!compatible(current, next)) {
|
|
338
|
-
current.replaceWith(next.cloneNode(true));
|
|
339
|
-
return;
|
|
340
|
-
}
|
|
341
|
-
// Summary snapshots never own a detail body that has already been fetched.
|
|
342
|
-
if (current.nodeType === 1 && current.hasAttribute("data-detail-body") && next.hasAttribute("data-detail-body")) return;
|
|
343
|
-
if (current.isEqualNode(next)) return;
|
|
344
|
-
if (current.nodeType !== 1) {
|
|
345
|
-
if (current.nodeValue !== next.nodeValue) current.nodeValue = next.nodeValue;
|
|
346
|
-
return;
|
|
347
|
-
}
|
|
348
|
-
if (current.hasAttribute("data-diagram") && next.hasAttribute("data-diagram")) {
|
|
349
|
-
const code = current.querySelector(".diagram-source code");
|
|
350
|
-
const nextCode = next.querySelector(".diagram-source code");
|
|
351
|
-
if (code && nextCode && code.textContent !== nextCode.textContent) {
|
|
352
|
-
code.textContent = nextCode.textContent;
|
|
353
|
-
window.agentBotDiagrams.refresh(current);
|
|
354
|
-
}
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
const preserveOpen = current.tagName === "DETAILS";
|
|
358
|
-
for (const attribute of Array.from(current.attributes)) {
|
|
359
|
-
if (preserveOpen && attribute.name === "open") continue;
|
|
360
|
-
if (!next.hasAttribute(attribute.name)) current.removeAttribute(attribute.name);
|
|
361
|
-
}
|
|
362
|
-
for (const attribute of Array.from(next.attributes)) {
|
|
363
|
-
if (preserveOpen && attribute.name === "open") continue;
|
|
364
|
-
if (current.getAttribute(attribute.name) !== attribute.value) current.setAttribute(attribute.name, attribute.value);
|
|
365
|
-
}
|
|
366
|
-
patchChildren(current, next);
|
|
367
|
-
};
|
|
368
|
-
const patchChildren = (parent, next) => {
|
|
369
|
-
const nextChildren = Array.from(next.childNodes);
|
|
370
|
-
const nextKeys = new Set(nextChildren.map(nodeKey).filter((key) => key !== undefined));
|
|
371
|
-
const remaining = new Set(Array.from(parent.childNodes));
|
|
372
|
-
const keyed = new Map();
|
|
373
|
-
for (const child of remaining) {
|
|
374
|
-
const key = nodeKey(child);
|
|
375
|
-
if (key === undefined) continue;
|
|
376
|
-
if (!nextKeys.has(key)) {
|
|
377
|
-
child.remove();
|
|
378
|
-
remaining.delete(child);
|
|
379
|
-
continue;
|
|
380
|
-
}
|
|
381
|
-
const matches = keyed.get(key) || [];
|
|
382
|
-
matches.push(child);
|
|
383
|
-
keyed.set(key, matches);
|
|
384
|
-
}
|
|
385
|
-
let cursor = parent.firstChild;
|
|
386
|
-
for (const child of nextChildren) {
|
|
387
|
-
const key = nodeKey(child);
|
|
388
|
-
const matches = key === undefined ? undefined : keyed.get(key);
|
|
389
|
-
const current = key === undefined
|
|
390
|
-
? cursor && nodeKey(cursor) === undefined && compatible(cursor, child) ? cursor : undefined
|
|
391
|
-
: matches?.find((candidate) => remaining.has(candidate) && compatible(candidate, child));
|
|
392
|
-
if (current) {
|
|
393
|
-
remaining.delete(current);
|
|
394
|
-
// Drop obsolete text/markup before a retained block without detaching that block.
|
|
395
|
-
while (cursor && cursor !== current && nodeKey(cursor) === undefined) {
|
|
396
|
-
const obsolete = cursor;
|
|
397
|
-
cursor = cursor.nextSibling;
|
|
398
|
-
remaining.delete(obsolete);
|
|
399
|
-
obsolete.remove();
|
|
400
|
-
}
|
|
401
|
-
if (current !== cursor) {
|
|
402
|
-
if (typeof parent.moveBefore === "function" && current.isConnected) parent.moveBefore(current, cursor);
|
|
403
|
-
else parent.insertBefore(current, cursor);
|
|
404
|
-
}
|
|
405
|
-
patchNode(current, child);
|
|
406
|
-
cursor = current.nextSibling;
|
|
407
|
-
} else {
|
|
408
|
-
const added = child.cloneNode(true);
|
|
409
|
-
parent.insertBefore(added, cursor);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
for (const child of remaining) child.remove();
|
|
413
|
-
};
|
|
414
|
-
const patchMarkup = (element, markup) => {
|
|
415
|
-
const template = document.createElement("template");
|
|
416
|
-
template.innerHTML = markup;
|
|
417
|
-
patchChildren(element, template.content);
|
|
418
|
-
};
|
|
281
|
+
const { nodeKey, patchNode, patchMarkup } = window.agentBotLiveMarkup;
|
|
419
282
|
const detailStates = new WeakMap();
|
|
420
283
|
const detailState = (details) => {
|
|
421
284
|
if (!detailStates.has(details)) detailStates.set(details, {});
|
|
@@ -791,7 +654,7 @@ function renderApprovalNotice(request: ApprovalRequest, renderText: (value: stri
|
|
|
791
654
|
|
|
792
655
|
function renderFinalAnswer(markdown: string, turnId: string, renderText: (value: string) => string, language: TurnPreviewLanguage): string {
|
|
793
656
|
const labels = previewLabels(language);
|
|
794
|
-
const filename =
|
|
657
|
+
const filename = turnAnswerFilename(turnId);
|
|
795
658
|
const icon = (paths: string): string => `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${paths}</svg>`;
|
|
796
659
|
const button = (action: string, label: string, paths: string): string => `<button type="button" class="answer-action" data-answer-action="${action}" title="${escapeAttribute(label)}" aria-label="${escapeAttribute(label)}">${icon(paths)}</button>`;
|
|
797
660
|
const actions = button("download", labels.downloadMarkdown, '<path d="M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5"/>')
|
|
@@ -978,15 +841,8 @@ function renderToolActivity(
|
|
|
978
841
|
deferDetails = false,
|
|
979
842
|
): string {
|
|
980
843
|
const labels = previewLabels(language);
|
|
981
|
-
const
|
|
982
|
-
const
|
|
983
|
-
const displayCommand = repl
|
|
984
|
-
? formatReplCommand(command ?? "")
|
|
985
|
-
: command
|
|
986
|
-
? formatToolCommand(command)
|
|
987
|
-
: undefined;
|
|
988
|
-
const title = displayCommand ? summarizeToolCommand(displayCommand) : toolTitle(tool, command, repl, language);
|
|
989
|
-
const titleMarkup = displayCommand
|
|
844
|
+
const { title, command } = previewToolHeading(tool, labels.command);
|
|
845
|
+
const titleMarkup = command
|
|
990
846
|
? `<code class="tool-command-title">${escapeHtml(title)}</code>`
|
|
991
847
|
: `<span class="tool-title">${escapeHtml(title)}</span>`;
|
|
992
848
|
const timing = renderToolTiming(tool, "header");
|
|
@@ -1010,13 +866,12 @@ function renderToolBody(
|
|
|
1010
866
|
projectCwd?: string,
|
|
1011
867
|
): string {
|
|
1012
868
|
const labels = previewLabels(language);
|
|
1013
|
-
const command = tool.command ? (displayToolCommand(tool.command) || tool.command.trim()) : undefined;
|
|
1014
869
|
const repl = isReplTool(tool);
|
|
1015
|
-
const displayCommand =
|
|
870
|
+
const displayCommand = renderableToolCommand(tool.command, repl);
|
|
1016
871
|
const status = `<span class="tool-state ${tool.status}">${escapeHtml(toolStatusLabel(tool.status, language))}</span>`;
|
|
1017
872
|
const output = fullToolOutputs?.[tool.id] ?? tool.output;
|
|
1018
873
|
const error = fullToolErrors?.[tool.id] ?? tool.error;
|
|
1019
|
-
const sameError = Boolean(output && error &&
|
|
874
|
+
const sameError = Boolean(output && error && normalizeToolOutput(output) === normalizeToolOutput(error));
|
|
1020
875
|
const displayOutput = output && repl && !sameError ? formatReplOutput(output) : output;
|
|
1021
876
|
const displayError = sameError ? undefined : error;
|
|
1022
877
|
const detailParts = [
|
|
@@ -1039,103 +894,16 @@ function renderToolBody(
|
|
|
1039
894
|
export function renderToolFooter(tool: ToolState, characterCount: number, language: TurnPreviewLanguage): string {
|
|
1040
895
|
const labels = previewLabels(language);
|
|
1041
896
|
const status = `<span class="tool-state ${tool.status}">${escapeHtml(toolStatusLabel(tool.status, language))}</span>`;
|
|
1042
|
-
const
|
|
897
|
+
const timestamp = toolTimestamp(tool.startedAt);
|
|
898
|
+
const startedAt = timestamp === undefined ? undefined : new Date(timestamp);
|
|
1043
899
|
const startTime = startedAt
|
|
1044
900
|
? `<time datetime="${startedAt.toISOString()}" title="${escapeAttribute(labels.startingTime)}">${new Intl.DateTimeFormat(language === "zh" ? "zh-CN" : "en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).format(startedAt)}</time>`
|
|
1045
901
|
: `<span title="${escapeAttribute(labels.startingTime)}">${escapeHtml(labels.unknown)}</span>`;
|
|
1046
902
|
return `${status}${startTime}${renderToolTiming(tool, "footer")}<span>${formatNumber(characterCount)} ${escapeHtml(labels.characters)}</span>`;
|
|
1047
903
|
}
|
|
1048
904
|
|
|
1049
|
-
function toolTitle(tool: ToolState, command?: string, repl = false, language: TurnPreviewLanguage = "zh"): string {
|
|
1050
|
-
if (repl) return "REPL";
|
|
1051
|
-
if (command) return tool.kind === "command" ? previewLabels(language).command : tool.kind;
|
|
1052
|
-
const title = tool.title.trim();
|
|
1053
|
-
return title || tool.kind;
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
function summarizeToolCommand(command: string): string {
|
|
1057
|
-
const summary = command.replace(/[\\`^][ \t]*\r?\n/gu, " ").replace(/\s+/gu, " ").trim();
|
|
1058
|
-
if (summary.length <= 160) return summary;
|
|
1059
|
-
return `${summary.slice(0, 157).trimEnd()}…`;
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
function isReplTool(tool: ToolState): boolean {
|
|
1063
|
-
const title = tool.title.trim();
|
|
1064
|
-
const titleLooksLikeToolName = title.length <= 120 && !/[\s"'`]/u.test(title);
|
|
1065
|
-
return tool.kind.toLowerCase().includes("repl")
|
|
1066
|
-
|| (titleLooksLikeToolName && /(?:^|[._-])repl(?:$|[._-])/iu.test(title));
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
function formatReplCommand(command: string): string {
|
|
1070
|
-
const normalized = command.trim();
|
|
1071
|
-
const newline = normalized.indexOf("\n");
|
|
1072
|
-
if (newline >= 0) {
|
|
1073
|
-
const payload = normalized.slice(newline + 1).trim();
|
|
1074
|
-
try {
|
|
1075
|
-
const parsed: unknown = JSON.parse(payload);
|
|
1076
|
-
if (parsed && typeof parsed === "object") {
|
|
1077
|
-
for (const key of ["input", "code", "script", "javascript", "source"]) {
|
|
1078
|
-
const value = (parsed as Record<string, unknown>)[key];
|
|
1079
|
-
if (typeof value === "string" && value.trim()) return formatReplSource(value);
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
} catch {
|
|
1083
|
-
// Keep the original payload when a provider uses a non-JSON argument format.
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
return formatReplSource(newline >= 0 ? normalized.slice(0, newline) : normalized);
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
function formatToolCommand(command: string): string {
|
|
1090
|
-
const normalized = command.replace(/\r\n?/gu, "\n").trim();
|
|
1091
|
-
const newline = normalized.indexOf("\n");
|
|
1092
|
-
if (newline >= 0) {
|
|
1093
|
-
const name = normalized.slice(0, newline).trim();
|
|
1094
|
-
const payload = normalized.slice(newline + 1).trim();
|
|
1095
|
-
const formattedPayload = formatJsonPayload(payload);
|
|
1096
|
-
if (name && formattedPayload) return `${name}\n${formattedPayload}`;
|
|
1097
|
-
}
|
|
1098
|
-
return formatShellCommandForDisplay(normalized);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
function formatJsonPayload(value: string): string | undefined {
|
|
1102
|
-
try {
|
|
1103
|
-
const parsed: unknown = JSON.parse(value);
|
|
1104
|
-
if (parsed && typeof parsed === "object") return JSON.stringify(parsed, null, 2);
|
|
1105
|
-
} catch {
|
|
1106
|
-
// Keep non-JSON tool arguments in their original readable form.
|
|
1107
|
-
}
|
|
1108
|
-
return undefined;
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
function formatReplSource(source: string): string {
|
|
1112
|
-
const normalized = source.replace(/\r\n?/gu, "\n").trim();
|
|
1113
|
-
if (normalized.includes("\n")) return normalized;
|
|
1114
|
-
const lines: string[] = [];
|
|
1115
|
-
let current = "";
|
|
1116
|
-
let quote: "'" | "\"" | "`" | undefined;
|
|
1117
|
-
let escaped = false;
|
|
1118
|
-
for (const character of normalized) {
|
|
1119
|
-
current += character;
|
|
1120
|
-
if (escaped) { escaped = false; continue; }
|
|
1121
|
-
if (character === "\\" && quote) { escaped = true; continue; }
|
|
1122
|
-
if (quote) { if (character === quote) quote = undefined; continue; }
|
|
1123
|
-
if (character === "'" || character === "\"" || character === "`") { quote = character; continue; }
|
|
1124
|
-
if (character === ";") {
|
|
1125
|
-
lines.push(current.trim());
|
|
1126
|
-
current = "";
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
if (current.trim()) lines.push(current.trim());
|
|
1130
|
-
return lines.join("\n");
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
function normalizeOutput(value: string): string {
|
|
1134
|
-
return value.replace(/\r\n?/gu, "\n").trim();
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
905
|
function formatReplOutput(value: string): string {
|
|
1138
|
-
const normalized =
|
|
906
|
+
const normalized = normalizeToolOutput(value);
|
|
1139
907
|
if (!normalized) return normalized;
|
|
1140
908
|
try {
|
|
1141
909
|
const parsed: unknown = JSON.parse(normalized);
|
|
@@ -1183,7 +951,7 @@ function renderToolTiming(tool: ToolState, placement: "header" | "footer"): stri
|
|
|
1183
951
|
if (duration === undefined) {
|
|
1184
952
|
return `<span class="${className}">?</span>`;
|
|
1185
953
|
}
|
|
1186
|
-
const live = tool.status === "running" && tool.completedAt === undefined;
|
|
954
|
+
const live = tool.status === "running" && toolTimestamp(tool.completedAt) === undefined;
|
|
1187
955
|
return `<span class="${className}"${live ? ` data-live-tool-duration data-started-at="${tool.startedAt}" data-short-duration="1"` : ""}>${formatShortDuration(duration)}</span>`;
|
|
1188
956
|
}
|
|
1189
957
|
|
|
@@ -1350,9 +1118,10 @@ function toolStatusLabel(status: ToolState["status"], language: TurnPreviewLangu
|
|
|
1350
1118
|
}
|
|
1351
1119
|
|
|
1352
1120
|
function toolDuration(tool: ToolState): string | undefined {
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1121
|
+
const start = toolTimestamp(tool.startedAt);
|
|
1122
|
+
if (start === undefined) return undefined;
|
|
1123
|
+
const end = toolTimestamp(tool.completedAt) ?? (tool.status === "running" ? Date.now() : undefined);
|
|
1124
|
+
return end === undefined ? undefined : formatDuration(end - start);
|
|
1356
1125
|
}
|
|
1357
1126
|
|
|
1358
1127
|
function formatDuration(durationMs: number): string {
|