@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.
Files changed (159) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +102 -18
  3. package/README.zh.md +102 -18
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +2676 -243
  9. package/assets/workspace.css +553 -44
  10. package/assets/workspace.js +3429 -327
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +51 -22
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +106 -14
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +141 -122
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +53 -276
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +43 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +24 -6
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +1153 -104
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +129 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +15 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +31 -22
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +335 -113
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +53 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +19 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +213 -23
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +157 -39
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +22 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/promptQuotes.js +47 -0
  103. package/dist/utils/promptQuotes.js.map +1 -0
  104. package/dist/utils/toolTimestamp.js +6 -0
  105. package/dist/utils/toolTimestamp.js.map +1 -0
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +1 -1
  108. package/skills/agent-bot/SKILL.md +23 -2
  109. package/src/cli/SelfUpdateObserver.ts +111 -0
  110. package/src/cli/SelfUpdateRunner.ts +271 -85
  111. package/src/cli/SelfUpdater.ts +53 -16
  112. package/src/cli/controlProtocol.ts +1 -0
  113. package/src/cli/help.ts +6 -0
  114. package/src/cli.ts +71 -5
  115. package/src/codex/CodexEventMapper.ts +25 -5
  116. package/src/codex/CodexRuntime.ts +4 -0
  117. package/src/feishu/CardRenderer.ts +48 -13
  118. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  119. package/src/feishu/FeishuMarkdown.ts +2 -14
  120. package/src/feishu/FeishuMessageClient.ts +10 -0
  121. package/src/feishu/FeishuTurnPresenter.ts +49 -16
  122. package/src/feishu/types.ts +1 -0
  123. package/src/index.ts +47 -12
  124. package/src/local-files/DiagramPreview.ts +11 -6
  125. package/src/local-files/GitDiffPreview.ts +107 -15
  126. package/src/local-files/LiveMarkup.ts +103 -0
  127. package/src/local-files/LocalFileViewerServer.ts +128 -125
  128. package/src/local-files/MarkdownExport.ts +54 -0
  129. package/src/local-files/PreviewCodeFont.ts +12 -0
  130. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  131. package/src/local-files/ToolCommandDisplay.ts +104 -0
  132. package/src/local-files/TurnPreviewPage.ts +58 -261
  133. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  134. package/src/local-files/WorkspaceFiles.ts +72 -5
  135. package/src/local-files/WorkspaceImages.ts +35 -0
  136. package/src/local-files/WorkspacePage.ts +24 -6
  137. package/src/local-files/WorkspaceSessions.ts +1057 -111
  138. package/src/local-files/WorkspaceTimeline.ts +135 -0
  139. package/src/presentation/OutboundRouter.ts +18 -4
  140. package/src/presentation/TurnStateReducer.ts +30 -19
  141. package/src/presentation/turnViewTypes.ts +3 -1
  142. package/src/proxy/ProxySessionController.ts +336 -96
  143. package/src/proxy/TaskMetadata.ts +81 -0
  144. package/src/runtime/types.ts +2 -1
  145. package/src/scheduling/ScheduleCards.ts +10 -4
  146. package/src/scheduling/ScheduleCommand.ts +4 -0
  147. package/src/scheduling/ScheduledTaskStore.ts +56 -9
  148. package/src/scheduling/types.ts +27 -4
  149. package/src/state/StateStore.ts +227 -24
  150. package/src/state/TurnPreviewJournal.ts +155 -38
  151. package/src/state/TurnToolText.ts +156 -0
  152. package/src/state/migrations.ts +4 -0
  153. package/src/supervision/SafeRestartNotifier.ts +9 -6
  154. package/src/terminal/TerminalPage.ts +5 -0
  155. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  156. package/src/updates/ManualUpdateController.ts +8 -3
  157. package/src/utils/promptAttachments.ts +27 -0
  158. package/src/utils/promptQuotes.ts +48 -0
  159. package/src/utils/toolTimestamp.ts +5 -0
@@ -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
+ export 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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
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, displayToolCommand, formatShellCommandForDisplay, toolStatusIcon } from "../feishu/CardRenderer.js";
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 copyMarkdown(markdown);
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 = (node) => {
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 = `turn-${turnId.replace(/[^A-Za-z0-9_-]/gu, "_").slice(0, 80) || "answer"}.md`;
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 command = tool.command ? (displayToolCommand(tool.command) || tool.command.trim()) : undefined;
982
- const repl = isReplTool(tool);
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 = repl ? formatReplCommand(command ?? "") : command ? formatToolCommand(command) : undefined;
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 && normalizeOutput(output) === normalizeOutput(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 startedAt = tool.startedAt === undefined ? undefined : new Date(tool.startedAt);
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 = normalizeOutput(value);
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
 
@@ -1297,8 +1065,41 @@ function fileDelta(file: { additions?: number; deletions?: number }): string {
1297
1065
  return additions || deletions ? `<span class="file-delta">${additions}${deletions}</span>` : "";
1298
1066
  }
1299
1067
 
1068
+ type TurnUsage = Partial<Record<"totalTokens" | "cachedInputTokens" | "totalTokensIncludingCache" | "modelCallCount" | "totalToolCount", number | null>>;
1069
+ type TurnUsageField = { text: string; title?: string };
1070
+
1071
+ export function turnUsageFields(usage: TurnUsage, language: TurnPreviewLanguage = "zh") {
1072
+ const labels = previewLabels(language);
1073
+ const tokens: TurnUsageField[] = [], activity: TurnUsageField[] = [];
1074
+ if (usage.totalTokens != null) {
1075
+ const amount = `${formatTokenCount(usage.totalTokens)} tokens`;
1076
+ tokens.push(usage.cachedInputTokens == null ? { text: amount, title: labels.turnTokens } : {
1077
+ text: `${labels.nonCachedTokens} ${amount}`, title: `${labels.nonCachedTokens}: ${formatNumber(usage.totalTokens)} tokens`,
1078
+ });
1079
+ }
1080
+ if (usage.totalTokensIncludingCache != null) {
1081
+ tokens.push({
1082
+ text: `${labels.totalTokens} ${formatTokenCount(usage.totalTokensIncludingCache)} tokens`,
1083
+ title: `${labels.totalTokens}: ${formatNumber(usage.totalTokensIncludingCache)} tokens`,
1084
+ });
1085
+ }
1086
+ if (usage.modelCallCount != null && Number.isSafeInteger(usage.modelCallCount) && usage.modelCallCount >= 0) {
1087
+ activity.push({
1088
+ text: `${labels.modelCalls} ${formatNumber(usage.modelCallCount)}${language === "zh" ? " 次" : ""}`,
1089
+ title: labels.modelCallsDescription,
1090
+ });
1091
+ }
1092
+ if (usage.totalToolCount != null && usage.totalToolCount > 0) {
1093
+ activity.push({ text: `${formatNumber(usage.totalToolCount)} ${labels.tools}` });
1094
+ }
1095
+ return { tokens, activity };
1096
+ }
1097
+
1300
1098
  function renderMetadata(state: TurnViewState, language: TurnPreviewLanguage): string {
1301
1099
  const labels = previewLabels(language);
1100
+ const usage = turnUsageFields(state, language);
1101
+ const renderField = ({ text, title }: TurnUsageField) =>
1102
+ `<span${title ? ` title="${escapeAttribute(title)}"` : ""}>${escapeHtml(text)}</span>`;
1302
1103
  const completedAt = state.completedAt ?? (isTerminal(state.status) && state.durationMs !== undefined
1303
1104
  ? state.startedAt + state.durationMs
1304
1105
  : undefined);
@@ -1307,15 +1108,10 @@ function renderMetadata(state: TurnViewState, language: TurnPreviewLanguage): st
1307
1108
  elapsed,
1308
1109
  state.modelProvider?.trim() ? `<span title="Provider">${escapeHtml(state.modelProvider.trim())}</span>` : "",
1309
1110
  state.model?.trim() ? `<span title="${escapeAttribute(labels.model)}">${escapeHtml(state.model.trim())}</span>` : "",
1310
- state.totalTokens === undefined ? "" : state.cachedInputTokens === undefined
1311
- ? `<span title="${escapeAttribute(labels.turnTokens)}">${formatTokenCount(state.totalTokens)} tokens</span>`
1312
- : `<span title="${escapeAttribute(labels.nonCachedTokens)}: ${formatNumber(state.totalTokens)} tokens">${escapeHtml(labels.nonCachedTokens)} ${formatTokenCount(state.totalTokens)} tokens</span>`,
1313
- state.totalTokensIncludingCache === undefined ? "" : `<span title="${escapeAttribute(labels.totalTokens)}: ${formatNumber(state.totalTokensIncludingCache)} tokens">${escapeHtml(labels.totalTokens)} ${formatTokenCount(state.totalTokensIncludingCache)} tokens</span>`,
1111
+ ...usage.tokens.map(renderField),
1314
1112
  state.latestContextTokens !== undefined && Number.isFinite(state.latestContextTokens) && state.latestContextTokens >= 0
1315
1113
  ? `<span title="${escapeAttribute(labels.contextTokens)}: ${formatNumber(state.latestContextTokens)} tokens">${escapeHtml(labels.contextTokens)} ${formatTokenCount(state.latestContextTokens)} tokens</span>` : "",
1316
- state.modelCallCount !== undefined && Number.isSafeInteger(state.modelCallCount) && state.modelCallCount >= 0
1317
- ? `<span title="${escapeAttribute(labels.modelCallsDescription)}">${escapeHtml(labels.modelCalls)} ${formatNumber(state.modelCallCount)}${language === "zh" ? " 次" : ""}</span>` : "",
1318
- (state.totalToolCount ?? 0) > 0 ? `<span>${formatNumber(state.totalToolCount ?? 0)} ${escapeHtml(labels.tools)}</span>` : "",
1114
+ ...usage.activity.map(renderField),
1319
1115
  ].filter(Boolean);
1320
1116
  return fields.join("");
1321
1117
  }
@@ -1350,9 +1146,10 @@ function toolStatusLabel(status: ToolState["status"], language: TurnPreviewLangu
1350
1146
  }
1351
1147
 
1352
1148
  function toolDuration(tool: ToolState): string | undefined {
1353
- if (tool.startedAt === undefined) return undefined;
1354
- const end = tool.completedAt ?? (tool.status === "running" ? Date.now() : undefined);
1355
- return end === undefined ? undefined : formatDuration(end - tool.startedAt);
1149
+ const start = toolTimestamp(tool.startedAt);
1150
+ if (start === undefined) return undefined;
1151
+ const end = toolTimestamp(tool.completedAt) ?? (tool.status === "running" ? Date.now() : undefined);
1152
+ return end === undefined ? undefined : formatDuration(end - start);
1356
1153
  }
1357
1154
 
1358
1155
  function formatDuration(durationMs: number): string {