@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,611 @@
1
+ import { editorFilePath, validateImageMedia } from "@cerebriline/shared/browser";
2
+ import { FRAGMENT_HUNK_HEADER, hunkHeader } from "./diff.js";
3
+
4
+ export function isRecord(value: unknown): value is Record<string, unknown> {
5
+ return !!value && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+
8
+ /**
9
+ * Tool inputs and results sometimes arrive as JSON strings rather than
10
+ * structured objects (archived transcripts, some transports). Re-parse
11
+ * anything that looks like serialized JSON; leave other values untouched.
12
+ */
13
+ export function normalizeValue(value: unknown): unknown {
14
+ if (typeof value !== "string") return value;
15
+ const trimmed = value.trim();
16
+ if (
17
+ (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
18
+ (trimmed.startsWith("[") && trimmed.endsWith("]"))
19
+ ) {
20
+ try {
21
+ return JSON.parse(trimmed) as unknown;
22
+ } catch {
23
+ return value;
24
+ }
25
+ }
26
+ return value;
27
+ }
28
+
29
+ export interface ReadFilesInfo {
30
+ files: { path: string; startLine?: number; endLine?: number }[];
31
+ }
32
+
33
+ /**
34
+ * read_files accepts many input shapes across runtimes: `{ files: [{ path,
35
+ * start_line, end_line }] }`, `{ files: "path" }`, `{ file_paths: [...] }`,
36
+ * `{ paths: [...] }`, a bare array, or a bare string.
37
+ */
38
+ export function parseReadFilesInput(input: unknown): ReadFilesInfo | undefined {
39
+ const normalized = normalizeValue(input);
40
+ const files: ReadFilesInfo["files"] = [];
41
+ const push = (value: unknown) => {
42
+ if (typeof value === "string" && value.length > 0) {
43
+ files.push({ path: value });
44
+ return;
45
+ }
46
+ if (isRecord(value) && typeof value.path === "string" && value.path) {
47
+ files.push({
48
+ path: value.path,
49
+ startLine:
50
+ typeof value.start_line === "number" ? value.start_line : undefined,
51
+ endLine:
52
+ typeof value.end_line === "number" ? value.end_line : undefined,
53
+ });
54
+ }
55
+ };
56
+
57
+ const record = isRecord(normalized) ? normalized : null;
58
+ const candidates =
59
+ record?.files ?? record?.file_paths ?? record?.paths ?? normalized;
60
+ if (Array.isArray(candidates)) {
61
+ for (const candidate of candidates) push(candidate);
62
+ } else {
63
+ push(candidates);
64
+ }
65
+ return files.length > 0 ? { files } : undefined;
66
+ }
67
+
68
+ // A read_files call can list the same path more than once, so the raw path is
69
+ // not a unique key. Prefix the array index to keep keys unique per row.
70
+ export function buildReadFilesKeys(files: { path: string }[]): string[] {
71
+ return files.map((f, i) => `${i}:${f.path}`);
72
+ }
73
+
74
+ export interface RunCommandsInfo {
75
+ commands: string[];
76
+ }
77
+
78
+ /**
79
+ * run_commands accepts every shape in core's RunCommandsInputUnionSchema:
80
+ * `{ commands: [...] }` (strings or `{ command, args }` entries, or a single
81
+ * entry instead of an array), a bare array of either, a top-level
82
+ * `{ command, args }`, `{ cmd }`, or a bare string.
83
+ */
84
+ export function parseRunCommandsInput(
85
+ input: unknown,
86
+ ): RunCommandsInfo | undefined {
87
+ const normalized = normalizeValue(input);
88
+ const commands: string[] = [];
89
+ const pushEntry = (entry: unknown) => {
90
+ if (typeof entry === "string" && entry.length > 0) {
91
+ commands.push(entry);
92
+ return;
93
+ }
94
+ if (isRecord(entry) && typeof entry.command === "string" && entry.command) {
95
+ const args = Array.isArray(entry.args)
96
+ ? entry.args.filter((a): a is string => typeof a === "string").join(" ")
97
+ : "";
98
+ commands.push(args ? `${entry.command} ${args}` : entry.command);
99
+ }
100
+ };
101
+
102
+ if (typeof normalized === "string" || Array.isArray(normalized)) {
103
+ for (const entry of Array.isArray(normalized) ? normalized : [normalized]) {
104
+ pushEntry(entry);
105
+ }
106
+ } else if (isRecord(normalized)) {
107
+ if (normalized.commands !== undefined) {
108
+ const raw = normalized.commands;
109
+ for (const entry of Array.isArray(raw) ? raw : [raw]) {
110
+ pushEntry(entry);
111
+ }
112
+ } else if (typeof normalized.command === "string") {
113
+ pushEntry(normalized);
114
+ } else if (typeof normalized.cmd === "string") {
115
+ pushEntry(normalized.cmd);
116
+ }
117
+ }
118
+ return commands.length > 0 ? { commands } : undefined;
119
+ }
120
+
121
+ export interface EditorInfo {
122
+ path: string;
123
+ oldText?: string;
124
+ newText: string;
125
+ insertLine?: number;
126
+ }
127
+
128
+ export function parseEditorInput(input: unknown): EditorInfo | undefined {
129
+ const normalized = normalizeValue(input);
130
+ if (!isRecord(normalized)) return undefined;
131
+ const path = editorFilePath(normalized);
132
+ if (path === undefined) return undefined;
133
+ if (typeof normalized.new_text !== "string") return undefined;
134
+
135
+ return {
136
+ path,
137
+ oldText:
138
+ typeof normalized.old_text === "string" ? normalized.old_text : undefined,
139
+ newText: normalized.new_text,
140
+ insertLine:
141
+ typeof normalized.insert_line === "number"
142
+ ? normalized.insert_line
143
+ : undefined,
144
+ };
145
+ }
146
+
147
+ export interface SearchInfo {
148
+ queries: string[];
149
+ }
150
+
151
+ export function parseSearchInput(input: unknown): SearchInfo | undefined {
152
+ const normalized = normalizeValue(input);
153
+ if (!isRecord(normalized)) return undefined;
154
+ if (!Array.isArray(normalized.queries)) return undefined;
155
+ const queries = normalized.queries.filter(
156
+ (q): q is string => typeof q === "string" && q.length > 0,
157
+ );
158
+ return queries.length > 0 ? { queries } : undefined;
159
+ }
160
+
161
+ export interface WebFetchInfo {
162
+ urls: string[];
163
+ }
164
+
165
+ export function parseWebFetchInput(input: unknown): WebFetchInfo | undefined {
166
+ const normalized = normalizeValue(input);
167
+ if (!isRecord(normalized)) return undefined;
168
+ if (!Array.isArray(normalized.requests)) return undefined;
169
+ const urls = normalized.requests
170
+ .filter((r): r is Record<string, unknown> => isRecord(r))
171
+ .map((r) => (typeof r.url === "string" ? r.url : ""))
172
+ .filter(Boolean);
173
+ return urls.length > 0 ? { urls } : undefined;
174
+ }
175
+
176
+ export interface SpawnAgentInfo {
177
+ task: string;
178
+ }
179
+
180
+ export function parseSpawnAgentInput(
181
+ input: unknown,
182
+ ): SpawnAgentInfo | undefined {
183
+ const normalized = normalizeValue(input);
184
+ if (!isRecord(normalized)) return undefined;
185
+ if (typeof normalized.task !== "string") return undefined;
186
+ return { task: normalized.task };
187
+ }
188
+
189
+ export interface AskQuestionInfo {
190
+ question: string;
191
+ options: string[];
192
+ }
193
+
194
+ export function parseAskQuestionInput(
195
+ input: unknown,
196
+ ): AskQuestionInfo | undefined {
197
+ const normalized = normalizeValue(input);
198
+ if (!isRecord(normalized)) return undefined;
199
+ if (typeof normalized.question !== "string") return undefined;
200
+ const options = Array.isArray(normalized.options)
201
+ ? normalized.options.filter((o): o is string => typeof o === "string")
202
+ : [];
203
+ return { question: normalized.question, options };
204
+ }
205
+
206
+ /** Before/after texts reconstructed from one `@@`-delimited patch section. */
207
+ export interface ApplyPatchHunk {
208
+ oldText: string;
209
+ newText: string;
210
+ }
211
+
212
+ export interface ApplyPatchFile {
213
+ path: string;
214
+ /** From the section header: `Add File`, `Update File`, or `Delete File`. */
215
+ action: "add" | "update" | "delete";
216
+ /** Destination path from a `*** Move to:` line, when the file was renamed. */
217
+ movedTo?: string;
218
+ additions: number;
219
+ deletions: number;
220
+ diff: string;
221
+ /**
222
+ * Per-hunk before/after texts, boundaries preserved. Rendering each hunk
223
+ * separately matters: concatenating hunks and re-diffing would let a
224
+ * deletion in one hunk pair up with an addition in another.
225
+ */
226
+ hunks: ApplyPatchHunk[];
227
+ }
228
+
229
+ export interface ApplyPatchInfo {
230
+ files: ApplyPatchFile[];
231
+ additions: number;
232
+ deletions: number;
233
+ diff: string;
234
+ }
235
+
236
+ const FILE_ACTION_RE = /^\*\*\* (Add|Update|Delete) File: (.+)/;
237
+ const MOVE_TO_RE = /^\*\*\* Move to: (.+)/;
238
+ // `@@ …` context markers delimit hunks and are handled separately below.
239
+ const HUNK_MARKER_RE = /^@@/;
240
+ const SKIP_LINES =
241
+ /^(?:\*\*\* (?:Begin|End) Patch|%%bash|```|EOF|apply_patch\b|\*\*\* End of File)/;
242
+
243
+ /**
244
+ * Parse the apply_patch envelope (`*** Add/Update/Delete File:` sections)
245
+ * into per-file additions/deletions and a synthetic unified diff.
246
+ */
247
+ export function parseApplyPatchInput(
248
+ input: unknown,
249
+ ): ApplyPatchInfo | undefined {
250
+ const normalized = normalizeValue(input);
251
+ const raw =
252
+ typeof normalized === "string"
253
+ ? normalized
254
+ : isRecord(normalized) && typeof normalized.input === "string"
255
+ ? normalized.input
256
+ : null;
257
+ if (!raw) return undefined;
258
+
259
+ const files: ApplyPatchFile[] = [];
260
+ let current: {
261
+ path: string;
262
+ action: "add" | "update" | "delete";
263
+ movedTo?: string;
264
+ lines: string[];
265
+ hunk: string[];
266
+ oldLines: string[];
267
+ newLines: string[];
268
+ hunks: ApplyPatchHunk[];
269
+ additions: number;
270
+ deletions: number;
271
+ } | null = null;
272
+
273
+ const flushHunk = () => {
274
+ if (!current || current.hunk.length === 0) return;
275
+ // Update/Delete sections are file fragments; only Add File sections
276
+ // carry complete contents, so only they get real hunk positions.
277
+ current.lines.push(
278
+ current.action === "add"
279
+ ? hunkHeader(current.hunk)
280
+ : FRAGMENT_HUNK_HEADER,
281
+ ...current.hunk,
282
+ );
283
+ current.hunks.push({
284
+ oldText: current.oldLines.join("\n"),
285
+ newText: current.newLines.join("\n"),
286
+ });
287
+ current.hunk = [];
288
+ current.oldLines = [];
289
+ current.newLines = [];
290
+ };
291
+ const flushFile = () => {
292
+ if (!current) return;
293
+ flushHunk();
294
+ files.push({
295
+ path: current.path,
296
+ action: current.action,
297
+ movedTo: current.movedTo,
298
+ additions: current.additions,
299
+ deletions: current.deletions,
300
+ diff: current.lines.join("\n"),
301
+ hunks: current.hunks,
302
+ });
303
+ current = null;
304
+ };
305
+
306
+ for (const line of raw.split("\n")) {
307
+ const fileMatch = FILE_ACTION_RE.exec(line);
308
+ if (fileMatch) {
309
+ flushFile();
310
+ const path = fileMatch[2].trim();
311
+ current = {
312
+ path,
313
+ action: fileMatch[1].toLowerCase() as "add" | "update" | "delete",
314
+ lines: [`--- a/${path}`, `+++ b/${path}`],
315
+ hunk: [],
316
+ oldLines: [],
317
+ newLines: [],
318
+ hunks: [],
319
+ additions: 0,
320
+ deletions: 0,
321
+ };
322
+ continue;
323
+ }
324
+ const moveMatch = MOVE_TO_RE.exec(line);
325
+ if (moveMatch) {
326
+ if (current) current.movedTo = moveMatch[1].trim();
327
+ continue;
328
+ }
329
+ if (HUNK_MARKER_RE.test(line.trim())) {
330
+ flushHunk();
331
+ continue;
332
+ }
333
+ if (SKIP_LINES.test(line.trim())) continue;
334
+ if (!current) continue;
335
+
336
+ if (line.startsWith("+")) {
337
+ current.additions++;
338
+ current.newLines.push(line.slice(1));
339
+ } else if (line.startsWith("-")) {
340
+ current.deletions++;
341
+ current.oldLines.push(line.slice(1));
342
+ } else {
343
+ const context = line.startsWith(" ") ? line.slice(1) : line;
344
+ current.oldLines.push(context);
345
+ current.newLines.push(context);
346
+ }
347
+
348
+ if (line.startsWith("+") || line.startsWith("-") || line.startsWith(" ")) {
349
+ current.hunk.push(line);
350
+ } else {
351
+ current.hunk.push(` ${line}`);
352
+ }
353
+ }
354
+ flushFile();
355
+
356
+ if (files.length === 0) return undefined;
357
+ return {
358
+ files,
359
+ additions: files.reduce((sum, f) => sum + f.additions, 0),
360
+ deletions: files.reduce((sum, f) => sum + f.deletions, 0),
361
+ diff: files.map((f) => f.diff).join("\n"),
362
+ };
363
+ }
364
+
365
+ /**
366
+ * The editor tool's result text encodes changed lines as `+12: …` / `-12: …`.
367
+ * Used as a fallback when the input texts are unavailable for diffing.
368
+ */
369
+ export function parseEditorResultDiffCounts(
370
+ result: unknown,
371
+ ): { additions: number; deletions: number } | null {
372
+ const normalized = normalizeValue(result);
373
+ const value = isRecord(normalized) ? normalized.result : normalized;
374
+ if (typeof value !== "string") return null;
375
+ let additions = 0;
376
+ let deletions = 0;
377
+ for (const line of value.split("\n")) {
378
+ if (/^\+\d+:/.test(line)) additions += 1;
379
+ if (/^-\d+:/.test(line)) deletions += 1;
380
+ }
381
+ if (additions === 0 && deletions === 0) return null;
382
+ return { additions, deletions };
383
+ }
384
+
385
+ export interface ToolOutputMedia {
386
+ modality: "image" | "audio" | "video" | "file";
387
+ mediaType: string;
388
+ data: string;
389
+ name?: string;
390
+ }
391
+
392
+ function contentBlockMediaType(part: Record<string, unknown>): string {
393
+ for (const key of ["mimeType", "mediaType", "mime_type"] as const) {
394
+ const value = part[key];
395
+ if (typeof value === "string" && value.trim()) return value.trim();
396
+ }
397
+ return "";
398
+ }
399
+
400
+ function chunkBase64(data: string): string {
401
+ return data.match(/.{1,76}/g)?.join("\n") ?? data;
402
+ }
403
+
404
+ function contentBlockText(part: Record<string, unknown>): string | undefined {
405
+ if (part.type === "text" && typeof part.text === "string") {
406
+ return part.text;
407
+ }
408
+ if (part.type === "resource" && isRecord(part.resource)) {
409
+ if (typeof part.resource.text === "string") {
410
+ return part.resource.text;
411
+ }
412
+ if (typeof part.resource.blob === "string" && part.resource.blob) {
413
+ const label =
414
+ typeof part.resource.uri === "string"
415
+ ? `[resource: ${part.resource.uri}]`
416
+ : "[resource]";
417
+ return `${label}\n${chunkBase64(part.resource.blob)}`;
418
+ }
419
+ if (typeof part.resource.uri === "string") {
420
+ return `[resource: ${part.resource.uri}]`;
421
+ }
422
+ return "[resource]";
423
+ }
424
+ if (part.type === "resource_link" && typeof part.uri === "string") {
425
+ return `[resource_link: ${part.uri}]`;
426
+ }
427
+ if (part.type === "image" || part.type === "audio") {
428
+ const mediaType = contentBlockMediaType(part);
429
+ return mediaType ? `[${part.type}: ${mediaType}]` : `[${part.type}]`;
430
+ }
431
+ if (part.type === "media" && isRecord(part.media)) {
432
+ const modality =
433
+ typeof part.media.modality === "string" ? part.media.modality : "media";
434
+ const mediaType =
435
+ typeof part.media.mediaType === "string" ? part.media.mediaType : "";
436
+ return mediaType ? `[${modality}: ${mediaType}]` : `[${modality}]`;
437
+ }
438
+ return typeof part.type === "string" ? `[${part.type}]` : undefined;
439
+ }
440
+
441
+ function extractOutputArrayText(raw: unknown[]): string | undefined {
442
+ const parts: string[] = [];
443
+ for (const item of raw) {
444
+ if (typeof item === "string") {
445
+ if (item) parts.push(item);
446
+ continue;
447
+ }
448
+ if (!isRecord(item)) continue;
449
+
450
+ if ("result" in item) {
451
+ const text = extractOutputText(item.result);
452
+ if (text) parts.push(text);
453
+ continue;
454
+ }
455
+
456
+ const blockText = contentBlockText(item);
457
+ if (blockText) {
458
+ parts.push(blockText);
459
+ continue;
460
+ }
461
+
462
+ if (Array.isArray(item.content)) {
463
+ const text = extractOutputText(item.content);
464
+ if (text) parts.push(text);
465
+ }
466
+ }
467
+ return parts.length > 0 ? parts.join("\n") : undefined;
468
+ }
469
+
470
+ function inlineContentBlockMedia(
471
+ part: Record<string, unknown>,
472
+ ): ToolOutputMedia | undefined {
473
+ if (part.type !== "image" && part.type !== "audio") return undefined;
474
+ const mediaType = contentBlockMediaType(part);
475
+ const data =
476
+ typeof part.data === "string"
477
+ ? part.data
478
+ : typeof part.image === "string"
479
+ ? part.image
480
+ : "";
481
+ if (!data) return undefined;
482
+ if (part.type === "image") {
483
+ const validation = validateImageMedia(mediaType || undefined, data);
484
+ return validation.ok
485
+ ? {
486
+ modality: "image",
487
+ mediaType: validation.mediaType,
488
+ data: validation.base64,
489
+ }
490
+ : undefined;
491
+ }
492
+ if (!mediaType) return undefined;
493
+ return {
494
+ modality: "audio",
495
+ mediaType,
496
+ data,
497
+ };
498
+ }
499
+
500
+ function canonicalInlineMedia(
501
+ part: Record<string, unknown>,
502
+ ): ToolOutputMedia | undefined {
503
+ if (part.type !== "media" || !isRecord(part.media)) return undefined;
504
+ const { media } = part;
505
+ if (
506
+ (media.modality !== "image" &&
507
+ media.modality !== "audio" &&
508
+ media.modality !== "video" &&
509
+ media.modality !== "file") ||
510
+ typeof media.mediaType !== "string" ||
511
+ !isRecord(media.source) ||
512
+ media.source.type !== "base64" ||
513
+ typeof media.source.data !== "string"
514
+ ) {
515
+ return undefined;
516
+ }
517
+ const output: ToolOutputMedia = {
518
+ modality: media.modality,
519
+ mediaType: media.mediaType,
520
+ data: media.source.data,
521
+ name: typeof media.name === "string" ? media.name : undefined,
522
+ };
523
+ if (output.modality !== "image") return output;
524
+ const validation = validateImageMedia(output.mediaType, output.data);
525
+ return validation.ok
526
+ ? {
527
+ ...output,
528
+ mediaType: validation.mediaType,
529
+ data: validation.base64,
530
+ }
531
+ : undefined;
532
+ }
533
+
534
+ function collectOutputMedia(raw: unknown, output: ToolOutputMedia[]): void {
535
+ const normalized = normalizeValue(raw);
536
+ if (Array.isArray(normalized)) {
537
+ for (const item of normalized) collectOutputMedia(item, output);
538
+ return;
539
+ }
540
+ if (!isRecord(normalized)) return;
541
+
542
+ const direct =
543
+ inlineContentBlockMedia(normalized) ?? canonicalInlineMedia(normalized);
544
+ if (direct) {
545
+ output.push(direct);
546
+ return;
547
+ }
548
+
549
+ if ("result" in normalized) {
550
+ collectOutputMedia(normalized.result, output);
551
+ }
552
+ if (Array.isArray(normalized.content)) {
553
+ collectOutputMedia(normalized.content, output);
554
+ }
555
+ }
556
+
557
+ /** Extract inline media blocks from direct, wrapped, or batched tool output. */
558
+ export function extractOutputMedia(raw: unknown): ToolOutputMedia[] {
559
+ const output: ToolOutputMedia[] = [];
560
+ collectOutputMedia(raw, output);
561
+ return output.filter(
562
+ (media, index) =>
563
+ output.findIndex(
564
+ (candidate) =>
565
+ candidate.modality === media.modality &&
566
+ candidate.mediaType === media.mediaType &&
567
+ candidate.data === media.data,
568
+ ) === index,
569
+ );
570
+ }
571
+
572
+ /**
573
+ * Extract human-readable text from a tool result: plain strings,
574
+ * `[{ result }]` arrays, direct content-block arrays, and MCP
575
+ * `{ content: [...] }` shapes are all handled. Binary payloads are represented
576
+ * by compact placeholders; visual consumers render them via
577
+ * `extractOutputMedia` instead of dumping base64 into the transcript.
578
+ */
579
+ export function extractOutputText(raw: unknown): string | undefined {
580
+ if (raw === null || raw === undefined) return undefined;
581
+ if (typeof raw === "string") return raw;
582
+
583
+ if (Array.isArray(raw)) {
584
+ const text = extractOutputArrayText(raw);
585
+ if (text) return text;
586
+ }
587
+
588
+ if (typeof raw === "object") {
589
+ // MCP tools return {content: [{type: "text", text}, ...]}. Extract the
590
+ // text so multi-line results keep real newlines instead of being
591
+ // JSON-escaped into one giant line. Non-text blocks keep identifying
592
+ // placeholders while their binary payloads are returned separately by
593
+ // extractOutputMedia.
594
+ const content = (raw as { content?: unknown }).content;
595
+ if (Array.isArray(content)) {
596
+ const text = extractOutputArrayText(content);
597
+ if (text) return text;
598
+ }
599
+ if (isRecord(raw) && "result" in raw) {
600
+ const text = extractOutputText(raw.result);
601
+ if (text) return text;
602
+ }
603
+ try {
604
+ return JSON.stringify(raw, null, 2);
605
+ } catch {
606
+ return String(raw);
607
+ }
608
+ }
609
+
610
+ return String(raw);
611
+ }
@@ -0,0 +1,84 @@
1
+ const EXT_TO_LANGUAGE: Record<string, string> = {
2
+ ".ts": "typescript",
3
+ ".tsx": "tsx",
4
+ ".js": "javascript",
5
+ ".jsx": "jsx",
6
+ ".py": "python",
7
+ ".rb": "ruby",
8
+ ".rs": "rust",
9
+ ".go": "go",
10
+ ".java": "java",
11
+ ".kt": "kotlin",
12
+ ".swift": "swift",
13
+ ".c": "c",
14
+ ".cpp": "cpp",
15
+ ".h": "c",
16
+ ".hpp": "cpp",
17
+ ".cs": "csharp",
18
+ ".css": "css",
19
+ ".scss": "scss",
20
+ ".html": "html",
21
+ ".vue": "vue",
22
+ ".svelte": "svelte",
23
+ ".json": "json",
24
+ ".yaml": "yaml",
25
+ ".yml": "yaml",
26
+ ".toml": "toml",
27
+ ".md": "markdown",
28
+ ".sql": "sql",
29
+ ".sh": "bash",
30
+ ".bash": "bash",
31
+ ".zsh": "bash",
32
+ ".fish": "fish",
33
+ ".lua": "lua",
34
+ ".php": "php",
35
+ ".r": "r",
36
+ ".ex": "elixir",
37
+ ".exs": "elixir",
38
+ ".erl": "erlang",
39
+ ".zig": "zig",
40
+ ".dockerfile": "dockerfile",
41
+ ".xml": "xml",
42
+ ".graphql": "graphql",
43
+ ".proto": "protobuf",
44
+ };
45
+
46
+ function splitSegments(filePath: string): string[] {
47
+ return filePath.split(/[\\/]/);
48
+ }
49
+
50
+ /** Final path segment ("basename"), tolerant of both slash styles. */
51
+ export function displayFileName(filePath: string): string {
52
+ const segments = splitSegments(filePath);
53
+ return segments.at(-1) || filePath;
54
+ }
55
+
56
+ /**
57
+ * Shorten a long path to `.../parent/file` form, keeping as many trailing
58
+ * directories as fit within maxLen. Short paths pass through untouched.
59
+ */
60
+ export function shortenPath(filePath: string, maxLen = 50): string {
61
+ if (filePath.length <= maxLen) return filePath;
62
+ const parts = splitSegments(filePath);
63
+ const fileName = parts.pop() ?? "";
64
+ if (fileName.length >= maxLen - 4) return `.../${fileName}`;
65
+ let result = fileName;
66
+ for (let i = parts.length - 1; i >= 0; i--) {
67
+ const candidate = `${parts[i]}/${result}`;
68
+ if (candidate.length + 4 > maxLen) break;
69
+ result = candidate;
70
+ }
71
+ return `.../${result}`;
72
+ }
73
+
74
+ /** Best-effort language id from a file extension or well-known file name. */
75
+ export function detectLanguage(filePath: string): string | undefined {
76
+ const base = displayFileName(filePath).toLowerCase();
77
+ const dotIndex = base.lastIndexOf(".");
78
+ const ext = dotIndex > 0 ? base.slice(dotIndex) : "";
79
+ if (ext && EXT_TO_LANGUAGE[ext]) return EXT_TO_LANGUAGE[ext];
80
+ if (base === "dockerfile") return "dockerfile";
81
+ if (base === "makefile") return "makefile";
82
+ if (base === "cmakelists.txt") return "cmake";
83
+ return undefined;
84
+ }