@cerebriline/ui 0.0.0-stage → 4.100.313

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 (222) hide show
  1. package/ADOPTION.md +833 -0
  2. package/LICENSE +201 -0
  3. package/RADIX-COLORS-LICENSE +21 -0
  4. package/README.md +427 -2
  5. package/components/agent-approval-card.css +70 -0
  6. package/components/agent-approval-card.tsx +109 -0
  7. package/components/agent-ask-question.css +103 -0
  8. package/components/agent-ask-question.tsx +276 -0
  9. package/components/agent-aurora.css +228 -0
  10. package/components/agent-aurora.tsx +96 -0
  11. package/components/agent-changes.css +13 -0
  12. package/components/agent-changes.tsx +167 -0
  13. package/components/agent-chat/agent-chat.css +556 -0
  14. package/components/agent-chat/index.tsx +1037 -0
  15. package/components/agent-chat/tool-diff.tsx +165 -0
  16. package/components/agent-chat/tool-summary/agents.ts +114 -0
  17. package/components/agent-chat/tool-summary/diff.ts +152 -0
  18. package/components/agent-chat/tool-summary/index.ts +928 -0
  19. package/components/agent-chat/tool-summary/parsers.ts +611 -0
  20. package/components/agent-chat/tool-summary/paths.ts +84 -0
  21. package/components/agent-chat/tool-summary/team.ts +401 -0
  22. package/components/agent-command-output.tsx +63 -0
  23. package/components/agent-composer.tsx +263 -0
  24. package/components/agent-context-usage.tsx +181 -0
  25. package/components/agent-conversation-layout.tsx +139 -0
  26. package/components/agent-hero-heading.css +53 -0
  27. package/components/agent-hero-heading.tsx +45 -0
  28. package/components/agent-image-lightbox.tsx +48 -0
  29. package/components/agent-prompt-queue.css +20 -0
  30. package/components/agent-prompt-queue.tsx +350 -0
  31. package/components/agent-pull-request-bar.css +13 -0
  32. package/components/agent-pull-request-bar.tsx +346 -0
  33. package/components/agent-quick-actions.css +19 -0
  34. package/components/agent-quick-actions.tsx +70 -0
  35. package/components/agent-session-row.tsx +183 -0
  36. package/components/agent-welcome-hero-pointer.ts +199 -0
  37. package/components/agent-welcome-hero.css +205 -0
  38. package/components/agent-welcome-hero.tsx +68 -0
  39. package/components/attachment-drop-zone.tsx +154 -0
  40. package/components/badge.tsx +21 -0
  41. package/components/button.tsx +324 -0
  42. package/components/generated-media.tsx +173 -0
  43. package/components/github-icon.tsx +19 -0
  44. package/components/index.ts +133 -0
  45. package/components/markdown.css +490 -0
  46. package/components/markdown.ts +365 -0
  47. package/components/mermaid-block.tsx +722 -0
  48. package/components/mermaid-diagram.ts +1260 -0
  49. package/components/mermaid-dom.ts +301 -0
  50. package/components/message-scroller.css +118 -0
  51. package/components/message-scroller.tsx +114 -0
  52. package/components/search-combobox.css +67 -0
  53. package/components/search-combobox.tsx +433 -0
  54. package/components/session-status.css +19 -0
  55. package/components/session-status.tsx +39 -0
  56. package/components/switch.css +221 -0
  57. package/components/switch.tsx +48 -0
  58. package/components.css +16 -0
  59. package/dist/components/agent-approval-card.d.ts +14 -0
  60. package/dist/components/agent-approval-card.d.ts.map +1 -0
  61. package/dist/components/agent-approval-card.js +12 -0
  62. package/dist/components/agent-approval-card.js.map +1 -0
  63. package/dist/components/agent-ask-question.d.ts +18 -0
  64. package/dist/components/agent-ask-question.d.ts.map +1 -0
  65. package/dist/components/agent-ask-question.js +101 -0
  66. package/dist/components/agent-ask-question.js.map +1 -0
  67. package/dist/components/agent-aurora.d.ts +3 -0
  68. package/dist/components/agent-aurora.d.ts.map +1 -0
  69. package/dist/components/agent-aurora.js +60 -0
  70. package/dist/components/agent-aurora.js.map +1 -0
  71. package/dist/components/agent-changes.d.ts +26 -0
  72. package/dist/components/agent-changes.d.ts.map +1 -0
  73. package/dist/components/agent-changes.js +19 -0
  74. package/dist/components/agent-changes.js.map +1 -0
  75. package/dist/components/agent-chat/disclosure.d.ts +25 -0
  76. package/dist/components/agent-chat/disclosure.d.ts.map +1 -0
  77. package/dist/components/agent-chat/disclosure.js +39 -0
  78. package/dist/components/agent-chat/disclosure.js.map +1 -0
  79. package/dist/components/agent-chat/index.d.ts +140 -0
  80. package/dist/components/agent-chat/index.d.ts.map +1 -0
  81. package/dist/components/agent-chat/index.js +379 -0
  82. package/dist/components/agent-chat/index.js.map +1 -0
  83. package/dist/components/agent-chat/tool-diff.d.ts +32 -0
  84. package/dist/components/agent-chat/tool-diff.d.ts.map +1 -0
  85. package/dist/components/agent-chat/tool-diff.js +97 -0
  86. package/dist/components/agent-chat/tool-diff.js.map +1 -0
  87. package/dist/components/agent-chat/tool-summary/agents.d.ts +10 -0
  88. package/dist/components/agent-chat/tool-summary/agents.d.ts.map +1 -0
  89. package/dist/components/agent-chat/tool-summary/agents.js +100 -0
  90. package/dist/components/agent-chat/tool-summary/agents.js.map +1 -0
  91. package/dist/components/agent-chat/tool-summary/diff.d.ts +22 -0
  92. package/dist/components/agent-chat/tool-summary/diff.d.ts.map +1 -0
  93. package/dist/components/agent-chat/tool-summary/diff.js +127 -0
  94. package/dist/components/agent-chat/tool-summary/diff.js.map +1 -0
  95. package/dist/components/agent-chat/tool-summary/index.d.ts +145 -0
  96. package/dist/components/agent-chat/tool-summary/index.d.ts.map +1 -0
  97. package/dist/components/agent-chat/tool-summary/index.js +663 -0
  98. package/dist/components/agent-chat/tool-summary/index.js.map +1 -0
  99. package/dist/components/agent-chat/tool-summary/parsers.d.ts +114 -0
  100. package/dist/components/agent-chat/tool-summary/parsers.d.ts.map +1 -0
  101. package/dist/components/agent-chat/tool-summary/parsers.js +502 -0
  102. package/dist/components/agent-chat/tool-summary/parsers.js.map +1 -0
  103. package/dist/components/agent-chat/tool-summary/paths.d.ts +10 -0
  104. package/dist/components/agent-chat/tool-summary/paths.d.ts.map +1 -0
  105. package/dist/components/agent-chat/tool-summary/paths.js +88 -0
  106. package/dist/components/agent-chat/tool-summary/paths.js.map +1 -0
  107. package/dist/components/agent-chat/tool-summary/team.d.ts +16 -0
  108. package/dist/components/agent-chat/tool-summary/team.d.ts.map +1 -0
  109. package/dist/components/agent-chat/tool-summary/team.js +283 -0
  110. package/dist/components/agent-chat/tool-summary/team.js.map +1 -0
  111. package/dist/components/agent-command-output.d.ts +14 -0
  112. package/dist/components/agent-command-output.d.ts.map +1 -0
  113. package/dist/components/agent-command-output.js +22 -0
  114. package/dist/components/agent-command-output.js.map +1 -0
  115. package/dist/components/agent-composer.d.ts +34 -0
  116. package/dist/components/agent-composer.d.ts.map +1 -0
  117. package/dist/components/agent-composer.js +65 -0
  118. package/dist/components/agent-composer.js.map +1 -0
  119. package/dist/components/agent-context-usage.d.ts +28 -0
  120. package/dist/components/agent-context-usage.d.ts.map +1 -0
  121. package/dist/components/agent-context-usage.js +51 -0
  122. package/dist/components/agent-context-usage.js.map +1 -0
  123. package/dist/components/agent-conversation-layout.d.ts +30 -0
  124. package/dist/components/agent-conversation-layout.d.ts.map +1 -0
  125. package/dist/components/agent-conversation-layout.js +24 -0
  126. package/dist/components/agent-conversation-layout.js.map +1 -0
  127. package/dist/components/agent-hero-heading.d.ts +2 -0
  128. package/dist/components/agent-hero-heading.d.ts.map +1 -0
  129. package/dist/components/agent-hero-heading.js +20 -0
  130. package/dist/components/agent-hero-heading.js.map +1 -0
  131. package/dist/components/agent-image-lightbox.d.ts +11 -0
  132. package/dist/components/agent-image-lightbox.d.ts.map +1 -0
  133. package/dist/components/agent-image-lightbox.js +8 -0
  134. package/dist/components/agent-image-lightbox.js.map +1 -0
  135. package/dist/components/agent-prompt-queue.d.ts +14 -0
  136. package/dist/components/agent-prompt-queue.d.ts.map +1 -0
  137. package/dist/components/agent-prompt-queue.js +114 -0
  138. package/dist/components/agent-prompt-queue.js.map +1 -0
  139. package/dist/components/agent-pull-request-bar.d.ts +72 -0
  140. package/dist/components/agent-pull-request-bar.d.ts.map +1 -0
  141. package/dist/components/agent-pull-request-bar.js +90 -0
  142. package/dist/components/agent-pull-request-bar.js.map +1 -0
  143. package/dist/components/agent-quick-actions.d.ts +14 -0
  144. package/dist/components/agent-quick-actions.d.ts.map +1 -0
  145. package/dist/components/agent-quick-actions.js +12 -0
  146. package/dist/components/agent-quick-actions.js.map +1 -0
  147. package/dist/components/agent-session-row.d.ts +45 -0
  148. package/dist/components/agent-session-row.d.ts.map +1 -0
  149. package/dist/components/agent-session-row.js +34 -0
  150. package/dist/components/agent-session-row.js.map +1 -0
  151. package/dist/components/agent-welcome-hero-pointer.d.ts +3 -0
  152. package/dist/components/agent-welcome-hero-pointer.d.ts.map +1 -0
  153. package/dist/components/agent-welcome-hero-pointer.js +169 -0
  154. package/dist/components/agent-welcome-hero-pointer.js.map +1 -0
  155. package/dist/components/agent-welcome-hero.d.ts +9 -0
  156. package/dist/components/agent-welcome-hero.d.ts.map +1 -0
  157. package/dist/components/agent-welcome-hero.js +14 -0
  158. package/dist/components/agent-welcome-hero.js.map +1 -0
  159. package/dist/components/attachment-drop-zone.d.ts +15 -0
  160. package/dist/components/attachment-drop-zone.d.ts.map +1 -0
  161. package/dist/components/attachment-drop-zone.js +64 -0
  162. package/dist/components/attachment-drop-zone.js.map +1 -0
  163. package/dist/components/badge.d.ts +5 -0
  164. package/dist/components/badge.d.ts.map +1 -0
  165. package/dist/components/badge.js +7 -0
  166. package/dist/components/badge.js.map +1 -0
  167. package/dist/components/button.d.ts +27 -0
  168. package/dist/components/button.d.ts.map +1 -0
  169. package/dist/components/button.js +209 -0
  170. package/dist/components/button.js.map +1 -0
  171. package/dist/components/generated-media.d.ts +12 -0
  172. package/dist/components/generated-media.d.ts.map +1 -0
  173. package/dist/components/generated-media.js +105 -0
  174. package/dist/components/generated-media.js.map +1 -0
  175. package/dist/components/github-icon.d.ts +3 -0
  176. package/dist/components/github-icon.d.ts.map +1 -0
  177. package/dist/components/github-icon.js +6 -0
  178. package/dist/components/github-icon.js.map +1 -0
  179. package/dist/components/index.d.ts +24 -0
  180. package/dist/components/index.d.ts.map +1 -0
  181. package/dist/components/index.js +25 -0
  182. package/dist/components/index.js.map +1 -0
  183. package/dist/components/markdown.d.ts +48 -0
  184. package/dist/components/markdown.d.ts.map +1 -0
  185. package/dist/components/markdown.js +264 -0
  186. package/dist/components/markdown.js.map +1 -0
  187. package/dist/components/mermaid-block.d.ts +14 -0
  188. package/dist/components/mermaid-block.d.ts.map +1 -0
  189. package/dist/components/mermaid-block.js +339 -0
  190. package/dist/components/mermaid-block.js.map +1 -0
  191. package/dist/components/mermaid-diagram.d.ts +264 -0
  192. package/dist/components/mermaid-diagram.d.ts.map +1 -0
  193. package/dist/components/mermaid-diagram.js +999 -0
  194. package/dist/components/mermaid-diagram.js.map +1 -0
  195. package/dist/components/mermaid-dom.d.ts +51 -0
  196. package/dist/components/mermaid-dom.d.ts.map +1 -0
  197. package/dist/components/mermaid-dom.js +246 -0
  198. package/dist/components/mermaid-dom.js.map +1 -0
  199. package/dist/components/message-scroller.d.ts +23 -0
  200. package/dist/components/message-scroller.d.ts.map +1 -0
  201. package/dist/components/message-scroller.js +31 -0
  202. package/dist/components/message-scroller.js.map +1 -0
  203. package/dist/components/search-combobox.d.ts +44 -0
  204. package/dist/components/search-combobox.d.ts.map +1 -0
  205. package/dist/components/search-combobox.js +191 -0
  206. package/dist/components/search-combobox.js.map +1 -0
  207. package/dist/components/session-status.d.ts +9 -0
  208. package/dist/components/session-status.d.ts.map +1 -0
  209. package/dist/components/session-status.js +11 -0
  210. package/dist/components/session-status.js.map +1 -0
  211. package/dist/components/switch.d.ts +7 -0
  212. package/dist/components/switch.d.ts.map +1 -0
  213. package/dist/components/switch.js +14 -0
  214. package/dist/components/switch.js.map +1 -0
  215. package/package.json +177 -5
  216. package/theme/base.css +83 -0
  217. package/theme/component-theme.css +126 -0
  218. package/theme/index.css +3 -0
  219. package/theme/palette.css +347 -0
  220. package/theme/scoped-tokens.css +503 -0
  221. package/theme/theme.css +90 -0
  222. package/theme/tokens.css +165 -0
@@ -0,0 +1,928 @@
1
+ /**
2
+ * Shared, framework-free presentation logic for agent tool calls.
3
+ *
4
+ * Consumers (desktop app, cloud dashboard, future clients) feed the raw
5
+ * `{ toolName, input, result }` payload of a tool call in and get back a
6
+ * structured summary — label, per-item details, diff counts, extracted
7
+ * output text — which they render with the agent-chat primitives
8
+ * (`ToolActivityTrigger`, `ToolActivityDetails`, …) and their own icons.
9
+ *
10
+ * This module is pure data-in/data-out: no React, no DOM, no Node APIs, and
11
+ * no dependency on runtime schemas. Inputs are `unknown` and parsing is
12
+ * defensive; a malformed payload degrades to a generic label, never a throw.
13
+ */
14
+
15
+ import { AGENT_CONTROL_TOOL_NAMES, agentControlLabel } from "./agents.js";
16
+ import { countDiffLines, makeUnifiedDiff } from "./diff.js";
17
+ import {
18
+ extractOutputMedia,
19
+ extractOutputText,
20
+ isRecord,
21
+ normalizeValue,
22
+ parseApplyPatchInput,
23
+ parseAskQuestionInput,
24
+ parseEditorInput,
25
+ parseEditorResultDiffCounts,
26
+ parseReadFilesInput,
27
+ parseRunCommandsInput,
28
+ parseSearchInput,
29
+ parseSpawnAgentInput,
30
+ parseWebFetchInput,
31
+ type ToolOutputMedia,
32
+ } from "./parsers.js";
33
+ import { detectLanguage, displayFileName, shortenPath } from "./paths.js";
34
+ import { pluralize, type ToolAggregate, teamSummary } from "./team.js";
35
+
36
+ export {
37
+ countDiffLines,
38
+ FRAGMENT_HUNK_HEADER,
39
+ type MakeUnifiedDiffOptions,
40
+ makeUnifiedDiff,
41
+ } from "./diff.js";
42
+ export {
43
+ type ApplyPatchFile,
44
+ type ApplyPatchInfo,
45
+ type AskQuestionInfo,
46
+ buildReadFilesKeys,
47
+ type EditorInfo,
48
+ extractOutputMedia,
49
+ extractOutputText,
50
+ parseApplyPatchInput,
51
+ parseAskQuestionInput,
52
+ parseEditorInput,
53
+ parseEditorResultDiffCounts,
54
+ parseReadFilesInput,
55
+ parseRunCommandsInput,
56
+ parseSearchInput,
57
+ parseSpawnAgentInput,
58
+ parseWebFetchInput,
59
+ type ReadFilesInfo,
60
+ type RunCommandsInfo,
61
+ type SearchInfo,
62
+ type SpawnAgentInfo,
63
+ type ToolOutputMedia,
64
+ type WebFetchInfo,
65
+ } from "./parsers.js";
66
+ export { detectLanguage, displayFileName, shortenPath } from "./paths.js";
67
+ export { type ToolAggregate, teamSummary } from "./team.js";
68
+
69
+ export type ToolSummaryPayload = {
70
+ toolName: string;
71
+ /** Structured input, or a JSON string of it (both are accepted). */
72
+ input?: unknown;
73
+ /** Raw tool result: string, content-block array, or record. */
74
+ result?: unknown;
75
+ isError?: boolean;
76
+ inProgress?: boolean;
77
+ };
78
+
79
+ export type ToolKind =
80
+ | "read"
81
+ | "edit"
82
+ | "command"
83
+ | "search"
84
+ | "web"
85
+ | "spawn"
86
+ | "team"
87
+ | "skill"
88
+ | "mcp"
89
+ | "question"
90
+ | "other";
91
+
92
+ export type ToolSummaryItem =
93
+ | {
94
+ type: "file";
95
+ path: string;
96
+ displayPath: string;
97
+ startLine?: number;
98
+ endLine?: number;
99
+ language?: string;
100
+ additions?: number;
101
+ deletions?: number;
102
+ /** Unified diff text for this file, when reconstructable. */
103
+ diff?: string;
104
+ /**
105
+ * Raw before/after texts for rich diff renderers (e.g.
106
+ * @pierre/diffs). `oldText` is absent for created files.
107
+ */
108
+ oldText?: string;
109
+ newText?: string;
110
+ /**
111
+ * True when oldText/newText are fragments of the file rather than
112
+ * complete contents — renderers should hide absolute line numbers.
113
+ */
114
+ fragment?: boolean;
115
+ /**
116
+ * Per-hunk before/after texts when the change has more than one
117
+ * hunk (apply_patch). Render one diff per hunk — re-diffing
118
+ * concatenated hunks pairs deletions with unrelated additions.
119
+ * When present, prefer it over oldText/newText.
120
+ */
121
+ hunks?: Array<{ oldText: string; newText: string }>;
122
+ }
123
+ | { type: "command"; command: string }
124
+ | { type: "query"; query: string }
125
+ | { type: "url"; url: string }
126
+ | { type: "text"; text: string };
127
+
128
+ /**
129
+ * One styled segment of a row label. Segments with `code: true` carry code
130
+ * (file names, commands, queries, URLs) and should render in a monospace
131
+ * face; plain segments are prose.
132
+ */
133
+ export type ToolLabelPart = { text: string; code?: boolean };
134
+
135
+ export type ToolSummary = {
136
+ /** Normalized tool name (aliases applied). */
137
+ toolName: string;
138
+ kind: ToolKind;
139
+ /** Row label, e.g. `Read app.tsx (10–80)` or `$ bun test`. */
140
+ label: string;
141
+ /** The label broken into styled segments; joins to `label`. */
142
+ labelParts: ToolLabelPart[];
143
+ /** Present when this call can merge into grouped-row counts. */
144
+ aggregate?: ToolAggregate;
145
+ /** Structured per-item detail for custom rendering. */
146
+ items: ToolSummaryItem[];
147
+ /** Preformatted one-per-line details for the expanded panel. */
148
+ details: string[];
149
+ /** Net line changes, for the trigger's +/- badge. */
150
+ diff?: { additions: number; deletions: number };
151
+ /** Human-readable text extracted from the result, when useful. */
152
+ outputText?: string;
153
+ /** Validated inline media extracted from the result. */
154
+ outputMedia: ToolOutputMedia[];
155
+ /** Error text when the call failed. */
156
+ errorText?: string;
157
+ };
158
+
159
+ export type ToolSummaryOptions = {
160
+ /** How file paths render in labels/details. Default: "shortened". */
161
+ pathStyle?: "shortened" | "basename" | "full";
162
+ /** Cap on extracted output/error text. Default: 64 KiB. */
163
+ maxOutputChars?: number;
164
+ /**
165
+ * Optional cap on inline label text (commands, tasks, questions).
166
+ * Unlimited by default: labels carry the full text (whitespace collapsed
167
+ * to one line) and the consumer's layout ellipsizes at the container
168
+ * edge. Set a number only for width-constrained surfaces like TUIs.
169
+ */
170
+ maxInlineChars?: number;
171
+ };
172
+
173
+ const DEFAULT_OPTIONS: Required<ToolSummaryOptions> = {
174
+ pathStyle: "shortened",
175
+ maxOutputChars: 64 * 1024,
176
+ maxInlineChars: Number.POSITIVE_INFINITY,
177
+ };
178
+
179
+ export const TOOL_NAME_ALIASES: Record<string, string> = {
180
+ "apply-patch": "apply_patch",
181
+ bash: "run_commands",
182
+ edit: "editor",
183
+ edit_file: "editor",
184
+ "file-read": "read_files",
185
+ file_read: "read_files",
186
+ read_file: "read_files",
187
+ search: "search_codebase",
188
+ "spawn-agent": "spawn_agent",
189
+ spawn_agent_tool: "spawn_agent",
190
+ "spawn-swarm": "spawn_swarm",
191
+ "web-fetch": "fetch_web_content",
192
+ web_fetch: "fetch_web_content",
193
+ };
194
+
195
+ export function normalizeToolName(toolName: string): string {
196
+ const normalized = toolName.toLowerCase();
197
+ return TOOL_NAME_ALIASES[normalized] ?? normalized;
198
+ }
199
+
200
+ export function classifyTool(toolName: string): ToolKind {
201
+ const name = normalizeToolName(toolName);
202
+ if (name === "read_files") return "read";
203
+ if (name === "editor" || name === "apply_patch") return "edit";
204
+ if (name === "run_commands") return "command";
205
+ if (name === "search_codebase") return "search";
206
+ if (name === "fetch_web_content") return "web";
207
+ if (
208
+ name === "spawn_agent" ||
209
+ name === "spawn_swarm" ||
210
+ name.startsWith("subagent_")
211
+ )
212
+ return "spawn";
213
+ if (
214
+ name === "team" ||
215
+ name === "teams" ||
216
+ name.startsWith("team_") ||
217
+ AGENT_CONTROL_TOOL_NAMES.has(name)
218
+ )
219
+ return "team";
220
+ if (name === "skills" || name === "skill") return "skill";
221
+ if (name === "ask_question" || name === "ask_followup_question")
222
+ return "question";
223
+ if (name === "mcp" || name.startsWith("mcp_") || name.startsWith("mcp-"))
224
+ return "mcp";
225
+ // Fuzzy fallbacks for runtimes with their own tool names.
226
+ if (name.includes("command") || name.includes("terminal")) return "command";
227
+ if (name.includes("read")) return "read";
228
+ if (name.includes("edit") || name.includes("write")) return "edit";
229
+ if (name.includes("search") || name.includes("grep")) return "search";
230
+ if (
231
+ name.includes("browser") ||
232
+ name.includes("fetch") ||
233
+ name.includes("web")
234
+ )
235
+ return "web";
236
+ if (name.includes("mcp")) return "mcp";
237
+ return "other";
238
+ }
239
+
240
+ function truncate(text: string, maxLen: number): string {
241
+ const collapsed = text.replace(/\s+/g, " ").trim();
242
+ if (collapsed.length <= maxLen) return collapsed;
243
+ return `${collapsed.slice(0, Math.max(1, maxLen - 1)).trimEnd()}…`;
244
+ }
245
+
246
+ function humanizeToolName(toolName: string): string {
247
+ const cleaned = toolName
248
+ .replace(/^mcp[-_]+/i, "")
249
+ .replace(/[-_]+/g, " ")
250
+ .trim();
251
+ if (!cleaned) return toolName;
252
+ return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
253
+ }
254
+
255
+ function formatPath(
256
+ path: string,
257
+ style: Required<ToolSummaryOptions>["pathStyle"],
258
+ ): string {
259
+ if (style === "basename") return displayFileName(path);
260
+ if (style === "full") return path;
261
+ return shortenPath(path);
262
+ }
263
+
264
+ /** ` (10–80)` / ` (10+)` label suffix for a partial-file read. */
265
+ function lineRangeLabelSuffix(startLine?: number, endLine?: number): string {
266
+ if (startLine !== undefined && endLine !== undefined)
267
+ return ` (${startLine}–${endLine})`;
268
+ if (startLine !== undefined) return ` (${startLine}+)`;
269
+ if (endLine !== undefined) return ` (1–${endLine})`;
270
+ return "";
271
+ }
272
+
273
+ /** `:10-80` detail suffix for a partial-file read. */
274
+ function lineRangeDetailSuffix(startLine?: number, endLine?: number): string {
275
+ if (startLine !== undefined && endLine !== undefined)
276
+ return `:${startLine}-${endLine}`;
277
+ if (startLine !== undefined) return `:${startLine}+`;
278
+ if (endLine !== undefined) return `:1-${endLine}`;
279
+ return "";
280
+ }
281
+
282
+ function capText(
283
+ text: string | undefined,
284
+ maxChars: number,
285
+ ): string | undefined {
286
+ if (text === undefined) return undefined;
287
+ if (text.length <= maxChars) return text;
288
+ return `${text.slice(0, maxChars)}\n\n[output truncated]`;
289
+ }
290
+
291
+ function extractErrorText(
292
+ result: unknown,
293
+ maxChars: number,
294
+ ): string | undefined {
295
+ const normalized = normalizeValue(result);
296
+ if (isRecord(normalized) && typeof normalized.error === "string") {
297
+ return capText(normalized.error, maxChars);
298
+ }
299
+ return capText(extractOutputText(normalized), maxChars);
300
+ }
301
+
302
+ function fallbackLabel(kind: ToolKind, toolName: string, inProgress: boolean) {
303
+ switch (kind) {
304
+ case "read":
305
+ return inProgress ? "Reading file" : "Read file";
306
+ case "edit":
307
+ return inProgress ? "Editing file" : "Edited file";
308
+ case "command":
309
+ return inProgress ? "Running command" : "Ran command";
310
+ case "search":
311
+ return inProgress ? "Searching" : "Searched";
312
+ case "web":
313
+ return inProgress ? "Fetching web content" : "Fetched web content";
314
+ case "spawn":
315
+ return inProgress ? "Spawning agent" : "Spawned agent";
316
+ case "skill":
317
+ return inProgress ? "Using skill" : "Used skill";
318
+ case "question":
319
+ return inProgress ? "Asking a question" : "Asked a question";
320
+ case "mcp":
321
+ return inProgress ? "Calling MCP tool" : "Called MCP tool";
322
+ default:
323
+ return inProgress
324
+ ? `Running ${humanizeToolName(toolName)}`
325
+ : humanizeToolName(toolName);
326
+ }
327
+ }
328
+
329
+ const READ_AGGREGATE = {
330
+ key: "read-files",
331
+ noun: "file",
332
+ completedVerb: "Read",
333
+ progressVerb: "Reading",
334
+ } as const;
335
+ const EDIT_AGGREGATE = {
336
+ key: "edited-files",
337
+ noun: "file",
338
+ completedVerb: "Edited",
339
+ progressVerb: "Editing",
340
+ } as const;
341
+ const COMMAND_AGGREGATE = {
342
+ key: "commands",
343
+ noun: "command",
344
+ completedVerb: "Ran",
345
+ progressVerb: "Running",
346
+ } as const;
347
+ const SEARCH_AGGREGATE = {
348
+ key: "searches",
349
+ noun: "search",
350
+ pluralNoun: "searches",
351
+ completedVerb: "Explored",
352
+ progressVerb: "Exploring",
353
+ } as const;
354
+ const WEB_AGGREGATE = {
355
+ key: "links",
356
+ noun: "link",
357
+ completedVerb: "Explored",
358
+ progressVerb: "Exploring",
359
+ } as const;
360
+ const SPAWN_AGGREGATE = {
361
+ key: "spawned-agents",
362
+ noun: "agent",
363
+ completedVerb: "Spawned",
364
+ progressVerb: "Spawning",
365
+ } as const;
366
+
367
+ function aggregateLabel(
368
+ aggregate: Omit<ToolAggregate, "count">,
369
+ count: number,
370
+ inProgress: boolean,
371
+ ): string {
372
+ const verb = inProgress ? aggregate.progressVerb : aggregate.completedVerb;
373
+ return `${verb} ${pluralize(count, aggregate.noun, aggregate.pluralNoun)}`;
374
+ }
375
+
376
+ /** Derive the plain-text label and its styled segments together. */
377
+ function labeled(
378
+ parts: ToolLabelPart[],
379
+ ): Pick<ToolSummary, "label" | "labelParts"> {
380
+ return { label: parts.map((part) => part.text).join(""), labelParts: parts };
381
+ }
382
+
383
+ // Fallback summaries (unparsable or absent input) still carry an aggregate
384
+ // so consecutive calls merge into grouped counts ("Spawned 3 agents") rather
385
+ // than repeating the generic label.
386
+ const FALLBACK_AGGREGATES: Partial<
387
+ Record<ToolKind, Omit<ToolAggregate, "count">>
388
+ > = {
389
+ command: COMMAND_AGGREGATE,
390
+ edit: EDIT_AGGREGATE,
391
+ read: READ_AGGREGATE,
392
+ search: SEARCH_AGGREGATE,
393
+ spawn: SPAWN_AGGREGATE,
394
+ web: WEB_AGGREGATE,
395
+ };
396
+
397
+ /**
398
+ * Build the presentation summary for one tool call.
399
+ *
400
+ * Single-item calls carry their specifics inline in the label
401
+ * (`Read app.tsx (10–80)`, `Ran bun test`, `Edited chat-view.tsx`); calls
402
+ * over multiple items aggregate (`Read 3 files`) with per-item lines in
403
+ * `details`. Never throws on malformed input.
404
+ */
405
+ export function buildToolSummary(
406
+ payload: ToolSummaryPayload,
407
+ options?: ToolSummaryOptions,
408
+ ): ToolSummary {
409
+ const opts = { ...DEFAULT_OPTIONS, ...options };
410
+ const toolName = normalizeToolName(payload.toolName || "tool");
411
+ const kind = classifyTool(toolName);
412
+ const inProgress = payload.inProgress ?? false;
413
+ const isError = payload.isError ?? false;
414
+ const input = normalizeValue(payload.input);
415
+ const fallbackAggregate = FALLBACK_AGGREGATES[kind];
416
+ const base: ToolSummary = {
417
+ toolName,
418
+ kind,
419
+ ...labeled([{ text: fallbackLabel(kind, toolName, inProgress) }]),
420
+ aggregate: fallbackAggregate
421
+ ? { ...fallbackAggregate, count: 1 }
422
+ : undefined,
423
+ items: [],
424
+ details: [],
425
+ outputMedia: extractOutputMedia(payload.result),
426
+ };
427
+ if (isError) {
428
+ base.errorText = extractErrorText(payload.result, opts.maxOutputChars);
429
+ }
430
+
431
+ const control = agentControlLabel(toolName, input, inProgress);
432
+ if (control) {
433
+ return {
434
+ ...base,
435
+ ...labeled([{ text: control }]),
436
+ outputText: isError
437
+ ? undefined
438
+ : capText(extractOutputText(payload.result), opts.maxOutputChars),
439
+ };
440
+ }
441
+
442
+ if (kind === "team") {
443
+ const team = teamSummary(
444
+ toolName,
445
+ input,
446
+ payload.result,
447
+ inProgress,
448
+ isError,
449
+ );
450
+ if (team) {
451
+ return {
452
+ ...base,
453
+ ...labeled([{ text: team.label }]),
454
+ aggregate: team.aggregate,
455
+ details: team.details,
456
+ items: team.details.map((text) => ({ type: "text", text })),
457
+ };
458
+ }
459
+ }
460
+
461
+ if (toolName === "read_files") {
462
+ const info = parseReadFilesInput(input);
463
+ if (info) {
464
+ const items: ToolSummaryItem[] = info.files.map((file) => ({
465
+ type: "file",
466
+ path: file.path,
467
+ displayPath: formatPath(file.path, opts.pathStyle),
468
+ startLine: file.startLine,
469
+ endLine: file.endLine,
470
+ language: detectLanguage(file.path),
471
+ }));
472
+ const single = info.files.length === 1 ? info.files[0] : null;
473
+ return {
474
+ ...base,
475
+ ...labeled(
476
+ single
477
+ ? [
478
+ { text: `${inProgress ? "Reading" : "Read"} file ` },
479
+ {
480
+ text: `${displayFileName(single.path)}${lineRangeLabelSuffix(single.startLine, single.endLine)}`,
481
+ code: true,
482
+ },
483
+ ]
484
+ : [
485
+ {
486
+ text: aggregateLabel(
487
+ READ_AGGREGATE,
488
+ info.files.length,
489
+ inProgress,
490
+ ),
491
+ },
492
+ ],
493
+ ),
494
+ aggregate: { ...READ_AGGREGATE, count: info.files.length },
495
+ items,
496
+ details: info.files.map(
497
+ (file) =>
498
+ `${formatPath(file.path, opts.pathStyle)}${lineRangeDetailSuffix(file.startLine, file.endLine)}`,
499
+ ),
500
+ };
501
+ }
502
+ }
503
+
504
+ if (toolName === "run_commands") {
505
+ const info = parseRunCommandsInput(input);
506
+ if (info) {
507
+ const commands = info.commands.map((command) => command.trim());
508
+ const singleInline =
509
+ commands.length === 1
510
+ ? truncate(commands[0], opts.maxInlineChars)
511
+ : null;
512
+ return {
513
+ ...base,
514
+ // Single commands lead with the action, command in mono after.
515
+ ...labeled(
516
+ singleInline !== null
517
+ ? [
518
+ { text: `${inProgress ? "Running" : "Ran"} command ` },
519
+ { text: singleInline, code: true },
520
+ ]
521
+ : [
522
+ {
523
+ text: aggregateLabel(
524
+ COMMAND_AGGREGATE,
525
+ commands.length,
526
+ inProgress,
527
+ ),
528
+ },
529
+ ],
530
+ ),
531
+ aggregate: { ...COMMAND_AGGREGATE, count: commands.length },
532
+ items: commands.map((command) => ({ type: "command", command })),
533
+ // The label may be ellipsized by the consumer's layout, so the
534
+ // expanded panel always carries the full command text.
535
+ details: commands,
536
+ outputText: isError
537
+ ? undefined
538
+ : capText(extractOutputText(payload.result), opts.maxOutputChars),
539
+ };
540
+ }
541
+ }
542
+
543
+ if (toolName === "search_codebase") {
544
+ const info = parseSearchInput(input);
545
+ if (info) {
546
+ return {
547
+ ...base,
548
+ ...labeled(
549
+ info.queries.length === 1
550
+ ? [
551
+ { text: `${inProgress ? "Searching" : "Searched"} ` },
552
+ {
553
+ text: truncate(info.queries[0], opts.maxInlineChars),
554
+ code: true,
555
+ },
556
+ ]
557
+ : [
558
+ {
559
+ text: aggregateLabel(
560
+ SEARCH_AGGREGATE,
561
+ info.queries.length,
562
+ inProgress,
563
+ ),
564
+ },
565
+ ],
566
+ ),
567
+ aggregate: { ...SEARCH_AGGREGATE, count: info.queries.length },
568
+ items: info.queries.map((query) => ({ type: "query", query })),
569
+ details: info.queries,
570
+ };
571
+ }
572
+ }
573
+
574
+ if (toolName === "fetch_web_content") {
575
+ const info = parseWebFetchInput(input);
576
+ if (info) {
577
+ return {
578
+ ...base,
579
+ ...labeled(
580
+ info.urls.length === 1
581
+ ? [
582
+ { text: `${inProgress ? "Fetching" : "Fetched"} ` },
583
+ {
584
+ text: truncate(info.urls[0], opts.maxInlineChars),
585
+ code: true,
586
+ },
587
+ ]
588
+ : [
589
+ {
590
+ text: aggregateLabel(
591
+ WEB_AGGREGATE,
592
+ info.urls.length,
593
+ inProgress,
594
+ ),
595
+ },
596
+ ],
597
+ ),
598
+ aggregate: { ...WEB_AGGREGATE, count: info.urls.length },
599
+ items: info.urls.map((url) => ({ type: "url", url })),
600
+ details: info.urls,
601
+ };
602
+ }
603
+ }
604
+
605
+ if (toolName === "apply_patch") {
606
+ const info = parseApplyPatchInput(input);
607
+ if (info) {
608
+ const single = info.files.length === 1 ? info.files[0] : null;
609
+ const actionVerb = (action: "add" | "update" | "delete") =>
610
+ action === "add"
611
+ ? inProgress
612
+ ? "Creating file"
613
+ : "Created file"
614
+ : action === "delete"
615
+ ? inProgress
616
+ ? "Deleting file"
617
+ : "Deleted file"
618
+ : inProgress
619
+ ? "Editing file"
620
+ : "Edited file";
621
+ // Renames display as `old → new`.
622
+ const fileLabel = (file: (typeof info.files)[number]) =>
623
+ file.movedTo
624
+ ? `${displayFileName(file.path)} → ${displayFileName(file.movedTo)}`
625
+ : displayFileName(file.path);
626
+ const filePathDetail = (file: (typeof info.files)[number]) =>
627
+ file.movedTo
628
+ ? `${formatPath(file.path, opts.pathStyle)} → ${formatPath(file.movedTo, opts.pathStyle)}`
629
+ : formatPath(file.path, opts.pathStyle);
630
+ return {
631
+ ...base,
632
+ ...labeled(
633
+ single
634
+ ? [
635
+ { text: `${actionVerb(single.action)} ` },
636
+ { text: fileLabel(single), code: true },
637
+ ]
638
+ : [
639
+ {
640
+ text: aggregateLabel(
641
+ EDIT_AGGREGATE,
642
+ info.files.length,
643
+ inProgress,
644
+ ),
645
+ },
646
+ ],
647
+ ),
648
+ aggregate: { ...EDIT_AGGREGATE, count: info.files.length },
649
+ diff: { additions: info.additions, deletions: info.deletions },
650
+ items: info.files.map((file) => ({
651
+ type: "file",
652
+ path: file.movedTo ?? file.path,
653
+ displayPath: formatPath(file.movedTo ?? file.path, opts.pathStyle),
654
+ language: detectLanguage(file.movedTo ?? file.path),
655
+ additions: file.additions,
656
+ deletions: file.deletions,
657
+ diff: file.diff,
658
+ // Deletions have no meaningful rich diff; single-hunk changes
659
+ // expose plain texts, multi-hunk changes must render per hunk.
660
+ oldText:
661
+ file.action !== "delete" && file.hunks.length === 1
662
+ ? file.action === "add"
663
+ ? undefined
664
+ : file.hunks[0].oldText
665
+ : undefined,
666
+ newText:
667
+ file.action !== "delete" && file.hunks.length === 1
668
+ ? file.hunks[0].newText
669
+ : undefined,
670
+ hunks:
671
+ file.action !== "delete" && file.hunks.length > 1
672
+ ? file.hunks
673
+ : undefined,
674
+ fragment: file.action !== "add",
675
+ })),
676
+ details: info.files.map((file) =>
677
+ file.action === "delete"
678
+ ? `Deleted ${filePathDetail(file)}`
679
+ : `${filePathDetail(file)} +${file.additions} -${file.deletions}`,
680
+ ),
681
+ };
682
+ }
683
+ return {
684
+ ...base,
685
+ ...labeled([{ text: inProgress ? "Applying patch" : "Applied patch" }]),
686
+ aggregate: { ...EDIT_AGGREGATE, count: 1 },
687
+ };
688
+ }
689
+
690
+ if (toolName === "editor") {
691
+ const info = parseEditorInput(input);
692
+ const inputRecord = isRecord(input) ? input : null;
693
+ const path =
694
+ info?.path ??
695
+ (typeof inputRecord?.path === "string" ? inputRecord.path : undefined);
696
+ // The editor schema has no `command`; derive the action from the shape.
697
+ const command =
698
+ typeof inputRecord?.command === "string"
699
+ ? inputRecord.command
700
+ : inputRecord?.insert_line != null
701
+ ? "insert"
702
+ : typeof inputRecord?.old_text === "string"
703
+ ? "str_replace"
704
+ : typeof inputRecord?.new_text === "string"
705
+ ? "create"
706
+ : "edit";
707
+ const verb = inProgress
708
+ ? command === "create"
709
+ ? "Creating file"
710
+ : command === "insert"
711
+ ? "Inserting into"
712
+ : "Editing file"
713
+ : command === "create"
714
+ ? "Created file"
715
+ : command === "insert"
716
+ ? "Inserted into"
717
+ : "Edited file";
718
+
719
+ let diff: ToolSummary["diff"];
720
+ let diffText: string | undefined;
721
+ if (info && (info.oldText !== undefined || command === "create")) {
722
+ // str_replace texts are fragments of the file, not whole contents;
723
+ // fragment mode keeps the hunk header from claiming line positions.
724
+ diffText = makeUnifiedDiff(
725
+ info.oldText ?? "",
726
+ info.newText,
727
+ info.path,
728
+ 3,
729
+ {
730
+ fragment: command !== "create",
731
+ },
732
+ );
733
+ diff = countDiffLines(diffText);
734
+ } else {
735
+ diff = parseEditorResultDiffCounts(payload.result) ?? undefined;
736
+ }
737
+
738
+ if (path) {
739
+ return {
740
+ ...base,
741
+ ...labeled([
742
+ { text: `${verb} ` },
743
+ { text: displayFileName(path), code: true },
744
+ ]),
745
+ aggregate: { ...EDIT_AGGREGATE, count: 1 },
746
+ diff,
747
+ items: [
748
+ {
749
+ type: "file",
750
+ path,
751
+ displayPath: formatPath(path, opts.pathStyle),
752
+ language: detectLanguage(path),
753
+ additions: diff?.additions,
754
+ deletions: diff?.deletions,
755
+ diff: diffText,
756
+ oldText: info?.oldText,
757
+ newText: info?.newText,
758
+ fragment: command !== "create",
759
+ },
760
+ ],
761
+ // The label carries the basename; the expanded panel leads with
762
+ // the fuller path above the diff, matching read rows.
763
+ details: [formatPath(path, opts.pathStyle)],
764
+ };
765
+ }
766
+ }
767
+
768
+ if (toolName === "spawn_swarm") {
769
+ // A swarm's own shape: how many workers, not one task. The count is
770
+ // what a reader wants -- a round of six reads very differently from a
771
+ // round of one, and the per-worker tasks are in the digest.
772
+ const swarm = input as
773
+ | { task?: unknown; tasks?: unknown; count?: unknown }
774
+ | undefined;
775
+ const tasks = Array.isArray(swarm?.tasks) ? swarm.tasks.length : undefined;
776
+ const count =
777
+ tasks ??
778
+ (typeof swarm?.count === "number"
779
+ ? swarm.count
780
+ : swarm?.count === "max"
781
+ ? undefined
782
+ : 1);
783
+ const how =
784
+ count === undefined ? "as many agents as fit" : `${count} agents`;
785
+ return {
786
+ ...base,
787
+ ...labeled([{ text: `${inProgress ? "Spawning" : "Spawned"} ${how}` }]),
788
+ aggregate: { ...SPAWN_AGGREGATE, count: count ?? 1 },
789
+ };
790
+ }
791
+
792
+ if (toolName === "spawn_agent" || toolName.startsWith("subagent_")) {
793
+ const info = parseSpawnAgentInput(input);
794
+ if (info) {
795
+ return {
796
+ ...base,
797
+ ...labeled([
798
+ { text: `${inProgress ? "Spawning" : "Spawned"} agent: ` },
799
+ { text: truncate(info.task, opts.maxInlineChars) },
800
+ ]),
801
+ aggregate: { ...SPAWN_AGGREGATE, count: 1 },
802
+ items: [{ type: "text", text: info.task }],
803
+ details: [info.task],
804
+ };
805
+ }
806
+ }
807
+
808
+ if (kind === "skill") {
809
+ const record = isRecord(input) ? input : null;
810
+ const skill = typeof record?.skill === "string" ? record.skill : "";
811
+ const args = typeof record?.args === "string" ? record.args : "";
812
+ if (skill) {
813
+ const detail = args ? `${skill} ${args}` : skill;
814
+ return {
815
+ ...base,
816
+ ...labeled([
817
+ { text: `${inProgress ? "Using" : "Used"} skill ` },
818
+ { text: truncate(skill, opts.maxInlineChars), code: true },
819
+ ]),
820
+ items: [{ type: "text", text: detail }],
821
+ details: [detail],
822
+ };
823
+ }
824
+ }
825
+
826
+ if (kind === "question") {
827
+ const info = parseAskQuestionInput(input);
828
+ if (info) {
829
+ return {
830
+ ...base,
831
+ ...labeled([
832
+ {
833
+ text: `${inProgress ? "Asking" : "Asked"} "${truncate(info.question, opts.maxInlineChars)}"`,
834
+ },
835
+ ]),
836
+ items: [
837
+ { type: "text", text: info.question },
838
+ ...info.options.map((option): ToolSummaryItem => {
839
+ return { type: "text", text: option };
840
+ }),
841
+ ],
842
+ details: info.options,
843
+ outputText: isError
844
+ ? undefined
845
+ : capText(extractOutputText(payload.result), opts.maxOutputChars),
846
+ };
847
+ }
848
+ }
849
+
850
+ // Unknown/MCP tools: humanized name, plus whatever text the result holds.
851
+ const normalizedResult = normalizeValue(payload.result);
852
+ const resultRecord = isRecord(normalizedResult) ? normalizedResult : null;
853
+ const query =
854
+ typeof resultRecord?.query === "string" ? resultRecord.query : "";
855
+ return {
856
+ ...base,
857
+ ...(query ? labeled([{ text: truncate(query, opts.maxInlineChars) }]) : {}),
858
+ outputText: isError
859
+ ? undefined
860
+ : capText(extractOutputText(normalizedResult), opts.maxOutputChars),
861
+ };
862
+ }
863
+
864
+ /**
865
+ * Merge the labels of consecutive tool calls into one grouped-row label.
866
+ * Adjacent same-kind aggregates merge their counts ("Read 3 files"); other
867
+ * labels pass through, joined with " · ".
868
+ */
869
+ export function buildGroupedToolLabel(
870
+ summaries: Array<{
871
+ label: string;
872
+ aggregate?: ToolAggregate;
873
+ inProgress?: boolean;
874
+ }>,
875
+ ): string {
876
+ if (summaries.length === 1) {
877
+ return summaries[0]?.label ?? "Tool";
878
+ }
879
+
880
+ type Segment =
881
+ | { type: "label"; label: string }
882
+ | { type: "aggregate"; aggregate: ToolAggregate & { inProgress: boolean } };
883
+ const segments: Segment[] = [];
884
+ for (const summary of summaries) {
885
+ const aggregate = summary.aggregate;
886
+ if (!aggregate) {
887
+ segments.push({ type: "label", label: summary.label });
888
+ continue;
889
+ }
890
+
891
+ const previous = segments.at(-1);
892
+ if (
893
+ previous?.type === "aggregate" &&
894
+ previous.aggregate.key === aggregate.key
895
+ ) {
896
+ segments[segments.length - 1] = {
897
+ type: "aggregate",
898
+ aggregate: {
899
+ ...previous.aggregate,
900
+ count: previous.aggregate.count + aggregate.count,
901
+ inProgress:
902
+ previous.aggregate.inProgress || (summary.inProgress ?? false),
903
+ },
904
+ };
905
+ continue;
906
+ }
907
+
908
+ segments.push({
909
+ type: "aggregate",
910
+ aggregate: { ...aggregate, inProgress: summary.inProgress ?? false },
911
+ });
912
+ }
913
+
914
+ return segments
915
+ .map((segment) => {
916
+ if (segment.type === "label") return segment.label;
917
+ const { aggregate } = segment;
918
+ const verb = aggregate.inProgress
919
+ ? aggregate.progressVerb
920
+ : aggregate.completedVerb;
921
+ return `${verb} ${pluralize(
922
+ aggregate.count,
923
+ aggregate.noun,
924
+ aggregate.pluralNoun,
925
+ )}`;
926
+ })
927
+ .join(" · ");
928
+ }