@molecule/app-ide-panel-logic 0.0.0-stage → 1.1.0

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 (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2927 -2
  3. package/dist/chatTimelineOrdering.d.ts +50 -0
  4. package/dist/chatTimelineOrdering.d.ts.map +1 -0
  5. package/dist/chatTimelineOrdering.js +46 -0
  6. package/dist/chatTimelineOrdering.js.map +1 -0
  7. package/dist/command-metadata.d.ts +117 -0
  8. package/dist/command-metadata.d.ts.map +1 -0
  9. package/dist/command-metadata.js +271 -0
  10. package/dist/command-metadata.js.map +1 -0
  11. package/dist/components/activity-utilities.d.ts +107 -0
  12. package/dist/components/activity-utilities.d.ts.map +1 -0
  13. package/dist/components/activity-utilities.js +154 -0
  14. package/dist/components/activity-utilities.js.map +1 -0
  15. package/dist/components/chat-autocommit-utilities.d.ts +172 -0
  16. package/dist/components/chat-autocommit-utilities.d.ts.map +1 -0
  17. package/dist/components/chat-autocommit-utilities.js +185 -0
  18. package/dist/components/chat-autocommit-utilities.js.map +1 -0
  19. package/dist/components/chat-card-style.d.ts +81 -0
  20. package/dist/components/chat-card-style.d.ts.map +1 -0
  21. package/dist/components/chat-card-style.js +78 -0
  22. package/dist/components/chat-card-style.js.map +1 -0
  23. package/dist/components/chat-commands.d.ts +17 -0
  24. package/dist/components/chat-commands.d.ts.map +1 -0
  25. package/dist/components/chat-commands.js +17 -0
  26. package/dist/components/chat-commands.js.map +1 -0
  27. package/dist/components/chat-commit-utilities.d.ts +29 -0
  28. package/dist/components/chat-commit-utilities.d.ts.map +1 -0
  29. package/dist/components/chat-commit-utilities.js +31 -0
  30. package/dist/components/chat-commit-utilities.js.map +1 -0
  31. package/dist/components/chat-cost-utilities.d.ts +62 -0
  32. package/dist/components/chat-cost-utilities.d.ts.map +1 -0
  33. package/dist/components/chat-cost-utilities.js +66 -0
  34. package/dist/components/chat-cost-utilities.js.map +1 -0
  35. package/dist/components/chat-effort-utilities.d.ts +104 -0
  36. package/dist/components/chat-effort-utilities.d.ts.map +1 -0
  37. package/dist/components/chat-effort-utilities.js +99 -0
  38. package/dist/components/chat-effort-utilities.js.map +1 -0
  39. package/dist/components/chat-help-utilities.d.ts +89 -0
  40. package/dist/components/chat-help-utilities.d.ts.map +1 -0
  41. package/dist/components/chat-help-utilities.js +131 -0
  42. package/dist/components/chat-help-utilities.js.map +1 -0
  43. package/dist/components/chat-model-mode-utilities.d.ts +169 -0
  44. package/dist/components/chat-model-mode-utilities.d.ts.map +1 -0
  45. package/dist/components/chat-model-mode-utilities.js +221 -0
  46. package/dist/components/chat-model-mode-utilities.js.map +1 -0
  47. package/dist/components/chat-models-utilities.d.ts +162 -0
  48. package/dist/components/chat-models-utilities.d.ts.map +1 -0
  49. package/dist/components/chat-models-utilities.js +302 -0
  50. package/dist/components/chat-models-utilities.js.map +1 -0
  51. package/dist/components/chat-report-utilities.d.ts +149 -0
  52. package/dist/components/chat-report-utilities.d.ts.map +1 -0
  53. package/dist/components/chat-report-utilities.js +151 -0
  54. package/dist/components/chat-report-utilities.js.map +1 -0
  55. package/dist/components/chat-scripts-utilities.d.ts +185 -0
  56. package/dist/components/chat-scripts-utilities.d.ts.map +1 -0
  57. package/dist/components/chat-scripts-utilities.js +199 -0
  58. package/dist/components/chat-scripts-utilities.js.map +1 -0
  59. package/dist/components/chat-settings-utilities.d.ts +72 -0
  60. package/dist/components/chat-settings-utilities.d.ts.map +1 -0
  61. package/dist/components/chat-settings-utilities.js +56 -0
  62. package/dist/components/chat-settings-utilities.js.map +1 -0
  63. package/dist/components/chat-share-utilities.d.ts +110 -0
  64. package/dist/components/chat-share-utilities.d.ts.map +1 -0
  65. package/dist/components/chat-share-utilities.js +90 -0
  66. package/dist/components/chat-share-utilities.js.map +1 -0
  67. package/dist/components/chat-skills-utilities.d.ts +242 -0
  68. package/dist/components/chat-skills-utilities.d.ts.map +1 -0
  69. package/dist/components/chat-skills-utilities.js +433 -0
  70. package/dist/components/chat-skills-utilities.js.map +1 -0
  71. package/dist/components/chat-stream-utilities.d.ts +74 -0
  72. package/dist/components/chat-stream-utilities.d.ts.map +1 -0
  73. package/dist/components/chat-stream-utilities.js +103 -0
  74. package/dist/components/chat-stream-utilities.js.map +1 -0
  75. package/dist/components/chat-timestamps-utilities.d.ts +123 -0
  76. package/dist/components/chat-timestamps-utilities.d.ts.map +1 -0
  77. package/dist/components/chat-timestamps-utilities.js +177 -0
  78. package/dist/components/chat-timestamps-utilities.js.map +1 -0
  79. package/dist/components/chat-tips-utilities.d.ts +108 -0
  80. package/dist/components/chat-tips-utilities.d.ts.map +1 -0
  81. package/dist/components/chat-tips-utilities.js +137 -0
  82. package/dist/components/chat-tips-utilities.js.map +1 -0
  83. package/dist/components/device-cycle.d.ts +84 -0
  84. package/dist/components/device-cycle.d.ts.map +1 -0
  85. package/dist/components/device-cycle.js +77 -0
  86. package/dist/components/device-cycle.js.map +1 -0
  87. package/dist/components/fileExplorerPersistence.d.ts +50 -0
  88. package/dist/components/fileExplorerPersistence.d.ts.map +1 -0
  89. package/dist/components/fileExplorerPersistence.js +63 -0
  90. package/dist/components/fileExplorerPersistence.js.map +1 -0
  91. package/dist/components/search-utilities.d.ts +15 -0
  92. package/dist/components/search-utilities.d.ts.map +1 -0
  93. package/dist/components/search-utilities.js +26 -0
  94. package/dist/components/search-utilities.js.map +1 -0
  95. package/dist/components/tests-bar-utilities.d.ts +106 -0
  96. package/dist/components/tests-bar-utilities.d.ts.map +1 -0
  97. package/dist/components/tests-bar-utilities.js +167 -0
  98. package/dist/components/tests-bar-utilities.js.map +1 -0
  99. package/dist/components/tests-card-utilities.d.ts +280 -0
  100. package/dist/components/tests-card-utilities.d.ts.map +1 -0
  101. package/dist/components/tests-card-utilities.js +591 -0
  102. package/dist/components/tests-card-utilities.js.map +1 -0
  103. package/dist/components/tool-call-utilities.d.ts +262 -0
  104. package/dist/components/tool-call-utilities.d.ts.map +1 -0
  105. package/dist/components/tool-call-utilities.js +1007 -0
  106. package/dist/components/tool-call-utilities.js.map +1 -0
  107. package/dist/components/user-avatar-utilities.d.ts +41 -0
  108. package/dist/components/user-avatar-utilities.d.ts.map +1 -0
  109. package/dist/components/user-avatar-utilities.js +56 -0
  110. package/dist/components/user-avatar-utilities.js.map +1 -0
  111. package/dist/components/workspace-layout-utilities.d.ts +37 -0
  112. package/dist/components/workspace-layout-utilities.d.ts.map +1 -0
  113. package/dist/components/workspace-layout-utilities.js +58 -0
  114. package/dist/components/workspace-layout-utilities.js.map +1 -0
  115. package/dist/customEventCards.d.ts +147 -0
  116. package/dist/customEventCards.d.ts.map +1 -0
  117. package/dist/customEventCards.js +36 -0
  118. package/dist/customEventCards.js.map +1 -0
  119. package/dist/icon-names.d.ts +26 -0
  120. package/dist/icon-names.d.ts.map +1 -0
  121. package/dist/icon-names.js +14 -0
  122. package/dist/icon-names.js.map +1 -0
  123. package/dist/index.d.ts +51 -0
  124. package/dist/index.d.ts.map +1 -0
  125. package/dist/index.js +51 -0
  126. package/dist/index.js.map +1 -0
  127. package/dist/keyboard-shortcut-utilities.d.ts +63 -0
  128. package/dist/keyboard-shortcut-utilities.d.ts.map +1 -0
  129. package/dist/keyboard-shortcut-utilities.js +100 -0
  130. package/dist/keyboard-shortcut-utilities.js.map +1 -0
  131. package/dist/panels.d.ts +26 -0
  132. package/dist/panels.d.ts.map +1 -0
  133. package/dist/panels.js +26 -0
  134. package/dist/panels.js.map +1 -0
  135. package/dist/settings-metadata.d.ts +78 -0
  136. package/dist/settings-metadata.d.ts.map +1 -0
  137. package/dist/settings-metadata.js +137 -0
  138. package/dist/settings-metadata.js.map +1 -0
  139. package/dist/types.d.ts +588 -0
  140. package/dist/types.d.ts.map +1 -0
  141. package/dist/types.js +9 -0
  142. package/dist/types.js.map +1 -0
  143. package/dist/viewport-queries.d.ts +19 -0
  144. package/dist/viewport-queries.d.ts.map +1 -0
  145. package/dist/viewport-queries.js +19 -0
  146. package/dist/viewport-queries.js.map +1 -0
  147. package/package.json +74 -4
@@ -0,0 +1,1007 @@
1
+ /**
2
+ * Pure utility functions for tool call display.
3
+ *
4
+ * Extracted from ToolCallCard for testability — these functions have no
5
+ * React dependencies and can be unit-tested directly.
6
+ *
7
+ * @module
8
+ */
9
+ import { t } from '@molecule/app-i18n';
10
+ /**
11
+ * Read a model-supplied field as a string.
12
+ *
13
+ * Tool input is authored by a language model. Its schema says a field is a string; that
14
+ * is a request, and models miss it — `{ label: 'x' }` where a string was declared is the
15
+ * shape that blanked production on 2026-08-14. `as string` on one of these fields is a
16
+ * lie the compiler cannot catch, so every field this module reads goes through here
17
+ * instead: anything that isn't string-like becomes `undefined` and each call site's
18
+ * existing empty-value handling takes over.
19
+ *
20
+ * @param value - The raw field value.
21
+ * @returns The string, or `undefined` when the value cannot be one.
22
+ */
23
+ export function str(value) {
24
+ if (typeof value === 'string')
25
+ return value;
26
+ if (typeof value === 'number' || typeof value === 'boolean')
27
+ return String(value);
28
+ return undefined;
29
+ }
30
+ /**
31
+ * Read a model-supplied field as a number.
32
+ *
33
+ * The numeric twin of {@link str}, and it hides in the same way: `out.exitCode as number`
34
+ * on an object passes `!= null` and `!== 0`, so the guard reads as satisfied and the
35
+ * object goes straight into JSX. Numeric-looking strings are accepted because providers
36
+ * routinely send them.
37
+ *
38
+ * @param value - The raw field value.
39
+ * @returns The number, or `undefined` when the value cannot be one.
40
+ */
41
+ export function num(value) {
42
+ if (typeof value === 'number')
43
+ return Number.isFinite(value) ? value : undefined;
44
+ if (typeof value === 'string' && value.trim() !== '') {
45
+ const parsed = Number(value);
46
+ return Number.isFinite(parsed) ? parsed : undefined;
47
+ }
48
+ return undefined;
49
+ }
50
+ /**
51
+ * Extracts the last path segment from a file path (e.g. "a/b/c.ts" → "c.ts").
52
+ * @param path - The file path to extract the basename from.
53
+ * @returns The basename string, or empty string if path is undefined.
54
+ */
55
+ export function basename(path) {
56
+ if (!path)
57
+ return '';
58
+ return path.split('/').pop() ?? path;
59
+ }
60
+ /**
61
+ * Path of a `@molecule/*` package's README.md inside the sandbox, where every
62
+ * package is pre-installed. Used by the find_package / read_molecule_doc cards
63
+ * so clicking a package opens its docs in the editor. The filename here must
64
+ * stay the one npm tarballs actually ship — `molecule-doc-path-reality.test.ts`
65
+ * anchors it against the real installed fleet, because a doc-file rename that
66
+ * missed this consumer (MOLECULE.md → README.md, 2026-08-04) silently broke
67
+ * every card click: the editor opened a path that no longer existed.
68
+ * @param packageName - The package name, with or without the `@molecule/` prefix.
69
+ * @returns The absolute sandbox path to the package's README.md, or null for
70
+ * a name that isn't a plain molecule package slug.
71
+ */
72
+ export function moleculeDocPath(packageName) {
73
+ if (!packageName)
74
+ return null;
75
+ const bare = packageName.trim().replace(/^@molecule\//, '');
76
+ if (!/^[a-z0-9-]+$/.test(bare))
77
+ return null;
78
+ return `/workspace/node_modules/@molecule/${bare}/README.md`;
79
+ }
80
+ /** Truncate a string to `max` characters with a trailing ellipsis. */
81
+ function truncate(value, max = 60) {
82
+ return value.length > max ? `${value.slice(0, max)}…` : value;
83
+ }
84
+ /** How many file names a multi-file `read_file` label spells out before counting the rest. */
85
+ const MAX_LABEL_FILES = 3;
86
+ /**
87
+ * The files a `read_file` call asked for. The tool takes either one `path` or
88
+ * several in `paths` (a batch read); every place that shows the call reads
89
+ * both through here so a batch never renders as a bare "Read".
90
+ * @param input - The raw `read_file` input payload.
91
+ * @returns The requested paths, in order (empty while the input is still streaming in).
92
+ */
93
+ export function readFilePaths(input) {
94
+ const inp = (input ?? {});
95
+ if (Array.isArray(inp.paths))
96
+ return inp.paths.filter((p) => typeof p === 'string' && p !== '');
97
+ const one = str(inp.path);
98
+ return one ? [one] : [];
99
+ }
100
+ /**
101
+ * The `read_file` paths that contribute a NAME to the card label, each paired
102
+ * with the name it renders as. A path with no basename (`src/`, `/`) names
103
+ * nothing, so it is dropped here — and because the label's `code` segments and
104
+ * their click targets are indexed off the SAME list, dropping it here keeps
105
+ * them aligned. Deriving the click target from {@link readFilePaths} instead
106
+ * made every name after a nameless path open the wrong file (a batch of
107
+ * `['src/', 'App.tsx']` rendered `` `App.tsx` `` but opened `src/`).
108
+ *
109
+ * @param input - The raw `read_file` input payload.
110
+ * @returns The named entries, in request order (empty while input streams in).
111
+ */
112
+ export function readFileLabelEntries(input) {
113
+ const entries = [];
114
+ for (const path of readFilePaths(input)) {
115
+ const name = basename(path);
116
+ if (name !== '')
117
+ entries.push({ name, path });
118
+ }
119
+ return entries;
120
+ }
121
+ /**
122
+ * Human-readable label for a tool call (e.g. "Edit `ChatPanel.tsx`").
123
+ * @param name - The tool name (e.g. "write_file", "exec_command").
124
+ * @param input - The raw tool input payload.
125
+ * @returns A formatted label string with backtick-wrapped filenames.
126
+ */
127
+ export function toolLabel(name, input) {
128
+ const inp = (input ?? {});
129
+ const path = str(inp.path);
130
+ const cmd = str(inp.command);
131
+ const pattern = str(inp.pattern);
132
+ const url = str(inp.url);
133
+ // Wrap a value in a leading-space + backticks, or return '' when it's empty.
134
+ // While a tool call streams, its input arrives a beat after the block is
135
+ // created, so path/pattern/command are briefly undefined — emitting `Read ``
136
+ // (empty backticks) flashed before the real filename. Drop the backticks
137
+ // entirely until there's a value, so the label reads "Read" then "Read `x.ts`".
138
+ //
139
+ // The backticks are MARKUP: the card's label renderer splits the finished
140
+ // string on `` `([^`]+)` `` to turn each span into a clickable code segment
141
+ // (for a batch read_file, indexed against the very entries named here). A
142
+ // value carrying its own backtick — a file named `a`b.ts`, a command using
143
+ // command substitution — therefore closes the span early: the rendered label
144
+ // shreds, and the extra fragment pairs shift the entry indexing so a span
145
+ // holding SEPARATOR text became clickable and opened the next file. Backtick
146
+ // is not a character filenames or commands need rendered verbatim in a
147
+ // one-line label, so it is substituted (never dropped — the value stays one
148
+ // span, in position) and every label this module emits is split-safe.
149
+ const code = (value) => (value ? ` \`${value.replace(/`/g, "'")}\`` : '');
150
+ switch (name) {
151
+ case 'list_files':
152
+ return `List${code(basename(path) || 'project')}`;
153
+ case 'read_file': {
154
+ // One call can read several files (`paths`): name the first few, count the rest.
155
+ // A path with no basename (`src/`, `/`) names nothing, so it must not
156
+ // take one of the named slots: the old map-then-slice put the empty
157
+ // string in the list and the label read "Read , `b.ts`". Those files are
158
+ // still counted in the "+N more" tally. The named list comes from
159
+ // {@link readFileLabelEntries} so the card's click targets index the same
160
+ // entries this label spells out.
161
+ const files = readFilePaths(input);
162
+ const named = readFileLabelEntries(input)
163
+ .slice(0, MAX_LABEL_FILES)
164
+ .map((entry) => code(entry.name).trim());
165
+ const more = files.length - named.length;
166
+ return `Read${named.length ? ` ${named.join(', ')}` : ''}${more > 0 ? ` +${more} more` : ''}`;
167
+ }
168
+ case 'write_file':
169
+ return `Write${code(basename(path))}`;
170
+ case 'edit_file':
171
+ return `Edit${code(basename(path))}`;
172
+ case 'search_files':
173
+ return `Search${code(pattern ?? '')}`;
174
+ case 'create_directory':
175
+ return `Create dir${code(basename(path))}`;
176
+ case 'rename_file':
177
+ return `Rename${code(basename(str(inp.old_path)))}`;
178
+ case 'delete_file':
179
+ return `Delete${code(basename(path))}`;
180
+ case 'find_files':
181
+ return `Find${code(pattern ?? '')}`;
182
+ case 'load_skill':
183
+ return `Load skill${code(str(inp.name) ?? '')}`;
184
+ case 'find_package': {
185
+ const query = str(inp.query) ?? str(inp.category);
186
+ return `Find package${code(query ?? '')}`;
187
+ }
188
+ case 'read_molecule_doc': {
189
+ const pkg = str(inp.name)
190
+ ?.trim()
191
+ .replace(/^@molecule\//, '');
192
+ return `Read docs${code(pkg ? `@molecule/${pkg}` : '')}`;
193
+ }
194
+ case 'web_fetch': {
195
+ try {
196
+ return `Fetch ${new URL(url ?? '').hostname}`;
197
+ }
198
+ catch (_error) {
199
+ // URL parsing failed (malformed/empty URL) — fall back to raw URL string, safe to ignore.
200
+ return `Fetch ${url ?? ''}`;
201
+ }
202
+ }
203
+ case 'exec_command': {
204
+ // A detached command has no result to show here — the card would read as
205
+ // finished the moment it started. Say which it is.
206
+ // The executor's own one-line reason, when it gave one, says more than the raw
207
+ // command (which the expanded card shows in full). Backticks are label markup.
208
+ const why = str(inp.description)?.replace(/`/g, "'");
209
+ if (why)
210
+ return inp.run_in_background === true
211
+ ? `${truncate(why, 90)} (background)`
212
+ : truncate(why, 90);
213
+ return inp.run_in_background === true
214
+ ? `Bash (background)${code(truncate(cmd ?? ''))}`
215
+ : `Bash${code(truncate(cmd ?? ''))}`;
216
+ }
217
+ case 'sandbox_fetch': {
218
+ // The interesting part is WHICH endpoint (usually one the model just built) —
219
+ // show method + protocol-stripped URL, e.g. "GET `localhost:4000/api/todos`".
220
+ const method = (str(inp.method) ?? 'GET').toUpperCase();
221
+ const compact = (url ?? '').replace(/^https?:\/\//, '').replace(/\/$/, '');
222
+ return `${method}${code(truncate(compact))}`;
223
+ }
224
+ case 'navigate_preview':
225
+ return `Go to${code(str(inp.path) ?? '')}`;
226
+ case 'open_file':
227
+ return `Open${code(basename(path))}`;
228
+ case 'reload_preview':
229
+ return 'Reload preview';
230
+ case 'restart_preview':
231
+ return inp.restart === true ? 'Restart preview servers' : 'Start preview servers';
232
+ case 'read_preview_ui':
233
+ return 'Inspect preview';
234
+ case 'interact_preview': {
235
+ // Target priority mirrors the tool's own: molId is canonical, text is the
236
+ // visible name (usually the most readable), selector is the last resort.
237
+ // Deliberately NEVER show `value` — fill routinely types credentials.
238
+ const target = str(inp.text) ?? str(inp.molId) ?? str(inp.selector) ?? '';
239
+ const verb = { click: 'Click', fill: 'Fill', select: 'Select', waitFor: 'Wait for' }[str(inp.action) ?? ''];
240
+ return verb ? `${verb}${code(truncate(target, 40))}` : `Interact${code(truncate(target, 40))}`;
241
+ }
242
+ case 'get_ide_state':
243
+ return 'Check IDE status';
244
+ case 'read_logs': {
245
+ const source = str(inp.source) ?? '';
246
+ const filter = str(inp.filter) ?? '';
247
+ const which = source && source !== 'all' ? `Read ${source} logs` : 'Read logs';
248
+ return `${which}${code(truncate(filter, 30))}`;
249
+ }
250
+ case 'find_example':
251
+ return `Find example${code(truncate(str(inp.query) ?? '', 40))}`;
252
+ case 'save_script':
253
+ return `Save script${code(str(inp.name) ?? '')}`;
254
+ case 'request_repo_import':
255
+ return 'Import repository';
256
+ case 'web_search':
257
+ return `Search web${code(truncate(str(inp.query) ?? '', 40))}`;
258
+ case 'save_plan': {
259
+ const planName = str(inp.name) ?? '';
260
+ // Same split-safety as {@link code} above: the name is interpolated into
261
+ // the label's backtick markup directly, so a backtick in it must be
262
+ // substituted here too.
263
+ return planName ? `Save plan \`${planName.replace(/`/g, "'")}\`` : 'Save plan';
264
+ }
265
+ case 'set_mode': {
266
+ const targetMode = str(inp.mode) ?? '';
267
+ return targetMode ? `Switch to ${targetMode} mode` : 'Switch mode';
268
+ }
269
+ case 'ask_user':
270
+ return normalizeAskUserInput(inp).question || 'Question';
271
+ case 'spawn_agent': {
272
+ const kind = str(inp.type) ?? '';
273
+ const on = str(inp.model) ? ` on ${str(inp.model)}` : '';
274
+ if (kind === 'judge')
275
+ return `Subagent — acceptance judge${on}`;
276
+ if (kind === 'build')
277
+ return `Subagent — build${on}`;
278
+ return `Subagent — research${on}`;
279
+ }
280
+ case 'wait_for_task': {
281
+ // `command` is not part of the tool's input: the card fills it in from the
282
+ // exec_command that started the task, so the row says what is being waited on.
283
+ const command = str(inp.command);
284
+ return command
285
+ ? `Wait for${code(truncate(command, 80))}`
286
+ : `Wait for background task${code(truncate(str(inp.taskId) ?? ''))}`;
287
+ }
288
+ case 'list_sessions':
289
+ return 'Other sessions on this project';
290
+ case 'send_session_message':
291
+ return `Message another session${code(truncate(str(inp.message) ?? ''))}`;
292
+ case 'update_task_list': {
293
+ const rows = normalizeTaskListInput(inp);
294
+ return rows.length > 0 ? `Working plan — ${rows.length} tasks` : 'Working plan';
295
+ }
296
+ default: {
297
+ const label = name.replace(/_/g, ' ');
298
+ // Salient-argument fallback for tools without an explicit case: nearly every
299
+ // tool has ONE short string input that carries its intent — show the first
300
+ // one present so a new tool never renders as a bare name. Never dump JSON.
301
+ const salient = [path, url, inp.query, inp.name, pattern, cmd, inp.source, inp.text].find((v) => typeof v === 'string' && v.trim() !== '');
302
+ return (label.charAt(0).toUpperCase() + label.slice(1) + code(salient ? truncate(salient, 40) : ''));
303
+ }
304
+ }
305
+ }
306
+ /**
307
+ * Whether a tool result says the PERSON skipped this call.
308
+ *
309
+ * It is the honest third outcome, and it has to be recognisable on sight:
310
+ * a skipped call did not fail (nothing went wrong) and it did not succeed
311
+ * (the work never happened). Reading it as either one is the lie this
312
+ * predicate exists to prevent — so the summary word, the status dot, and the
313
+ * card's error handling all ask here rather than each deciding for themselves.
314
+ *
315
+ * @param output - The raw tool output payload.
316
+ * @returns True when the call was skipped by the user.
317
+ */
318
+ export function isSkippedByUser(output) {
319
+ if (typeof output !== 'object' || output === null)
320
+ return false;
321
+ return output.status === 'skipped_by_user';
322
+ }
323
+ /**
324
+ * Whether a tool result says a server restart cut this call off mid-run.
325
+ *
326
+ * Like a skip, it is neither a success nor a failure: whether the call took
327
+ * effect is unknown. The summary, the status dot and the card body all ask
328
+ * here so none of them shows it as "done".
329
+ *
330
+ * @param output - The raw tool output payload.
331
+ * @returns True when the call was interrupted by a restart.
332
+ */
333
+ export function isInterruptedByRestart(output) {
334
+ if (typeof output !== 'object' || output === null)
335
+ return false;
336
+ return output.status === 'interrupted_by_restart';
337
+ }
338
+ /**
339
+ * The sentence a card shows for a call a restart interrupted.
340
+ *
341
+ * @returns The localized sentence.
342
+ */
343
+ export function interruptedByRestartLine() {
344
+ return t('ide.toolCall.interruptedByRestart', undefined, {
345
+ defaultValue: 'This step was interrupted by a restart; its effect is unknown.',
346
+ });
347
+ }
348
+ /** Report openings the server writes when a subagent run did not finish. */
349
+ const SUBAGENT_FAILURE_REPORT = /^Subagent (failed|aborted|stopped)\b/;
350
+ /** Text that is a transport/runtime error, not a sentence written for a person. */
351
+ const RAW_ERROR_TEXT = /^\s*[A-Za-z]*Error\b|fetch failed|\bE[A-Z]{3,}\b|\n\s+at\s/;
352
+ /**
353
+ * The one line a subagent card shows when the run failed, or '' when it did not.
354
+ *
355
+ * The server's `error` is already a plain sentence and is shown as is; raw
356
+ * error text (`Error: fetch failed`) and a failure with no `error` at all
357
+ * get the translated fallback instead.
358
+ *
359
+ * @param error - The result's `error` field.
360
+ * @param report - The result's `report` field (model-facing).
361
+ * @returns The line to show, or '' for a run that did not fail.
362
+ */
363
+ export function subagentErrorLine(error, report) {
364
+ const fallback = () => t('ide.chat.subagent.failedFallback', undefined, {
365
+ defaultValue: 'This subagent stopped before it finished.',
366
+ });
367
+ if (typeof error === 'string') {
368
+ if (error.trim())
369
+ return RAW_ERROR_TEXT.test(error) ? fallback() : error.trim();
370
+ }
371
+ else if (error != null && error !== false) {
372
+ return fallback();
373
+ }
374
+ return SUBAGENT_FAILURE_REPORT.test(report) ? fallback() : '';
375
+ }
376
+ /**
377
+ * One-line result summary shown beneath the label.
378
+ * @param name - The tool name.
379
+ * @param output - The raw tool output payload.
380
+ * @param status - The execution status (pending, running, done, error).
381
+ * @returns A brief summary string describing the result.
382
+ */
383
+ export function toolSummary(name, output, status) {
384
+ if (status === 'pending')
385
+ return '';
386
+ if (status === 'running')
387
+ return t('ide.toolCall.statusRunning', undefined, { defaultValue: 'Running…' });
388
+ // Checked BEFORE every per-tool branch: a skipped `exec_command` carries no
389
+ // exit code and a skipped `write_file` no diff, so the branches below would
390
+ // fall through to the empty summary that means "it worked".
391
+ if (isSkippedByUser(output))
392
+ return t('ide.toolCall.statusSkipped', undefined, { defaultValue: 'Skipped' });
393
+ if (isInterruptedByRestart(output))
394
+ return t('ide.toolCall.statusInterrupted', undefined, { defaultValue: 'Interrupted' });
395
+ const out = output;
396
+ const hasError = typeof out === 'object' && out !== null && 'error' in out;
397
+ if (hasError) {
398
+ const msg = (str(out.error) ?? '').toLowerCase();
399
+ if (msg.includes('not found') || msg.includes('no such file'))
400
+ return t('ide.toolCall.statusNotFound', undefined, { defaultValue: 'Not found' });
401
+ if (msg.includes('permission') || msg.includes('access denied'))
402
+ return t('ide.toolCall.statusPermissionDenied', undefined, {
403
+ defaultValue: 'Permission denied',
404
+ });
405
+ return t('ide.toolCall.statusFailed', undefined, { defaultValue: 'Failed' });
406
+ }
407
+ switch (name) {
408
+ case 'write_file': {
409
+ const diff = out
410
+ ?.diff;
411
+ if (!diff)
412
+ return '';
413
+ if (diff.type === 'unchanged')
414
+ return t('ide.toolCall.statusUnchanged', undefined, { defaultValue: 'Unchanged' });
415
+ return '';
416
+ }
417
+ case 'edit_file':
418
+ return '';
419
+ case 'list_files': {
420
+ const entries = out?.entries;
421
+ return entries != null
422
+ ? t('ide.toolCall.entryCount', { count: entries.length }, {
423
+ defaultValue: '{{count}} entries',
424
+ })
425
+ : '';
426
+ }
427
+ case 'read_file':
428
+ return '';
429
+ case 'search_files': {
430
+ const matches = out?.matches;
431
+ return matches != null
432
+ ? t('ide.toolCall.matchCount', { count: matches.length }, {
433
+ defaultValue: '{{count}} matches',
434
+ })
435
+ : '';
436
+ }
437
+ case 'find_files': {
438
+ const files = out?.files;
439
+ return files != null
440
+ ? t('ide.toolCall.fileCount', { count: files.length }, {
441
+ defaultValue: '{{count}} files',
442
+ })
443
+ : '';
444
+ }
445
+ case 'create_directory':
446
+ return '';
447
+ case 'rename_file':
448
+ return '';
449
+ case 'delete_file':
450
+ return '';
451
+ case 'web_fetch':
452
+ case 'sandbox_fetch': {
453
+ const status_ = out?.status;
454
+ if (status_ == null)
455
+ return '';
456
+ if (status_ >= 200 && status_ < 300)
457
+ return '';
458
+ if (status_ === 404)
459
+ return t('ide.toolCall.statusNotFound', undefined, { defaultValue: 'Not found' });
460
+ if (status_ >= 400 && status_ < 500)
461
+ return t('ide.toolCall.statusFailed', undefined, { defaultValue: 'Failed' });
462
+ if (status_ >= 500)
463
+ return t('ide.toolCall.statusServerError', undefined, { defaultValue: 'Server error' });
464
+ return '';
465
+ }
466
+ case 'navigate_preview':
467
+ case 'interact_preview': {
468
+ // The snapshot's url is where the app actually landed — an auth-guard
469
+ // redirect is exactly what the user wants to see at a glance.
470
+ const landed = out?.url;
471
+ if (typeof landed !== 'string' || !landed)
472
+ return '';
473
+ try {
474
+ const u = new URL(landed);
475
+ return u.pathname + u.search;
476
+ }
477
+ catch (_error) {
478
+ // Not an absolute URL (already a path or malformed) — show it as-is.
479
+ return landed;
480
+ }
481
+ }
482
+ case 'exec_command': {
483
+ // The handle a background command returns is not an outcome: the command
484
+ // is still running, and the strip above the composer owns its real status.
485
+ if (out?.taskId != null) {
486
+ return t('ide.toolCall.startedInBackground', undefined, {
487
+ defaultValue: 'Running in the background',
488
+ });
489
+ }
490
+ const exitCode = out?.exitCode;
491
+ return exitCode != null && exitCode !== 0
492
+ ? t('ide.toolCall.statusFailed', undefined, { defaultValue: 'Failed' })
493
+ : '';
494
+ }
495
+ case 'wait_for_task': {
496
+ const w = out;
497
+ if (w?.status === 'running')
498
+ return t('ide.toolCall.stillRunning', undefined, { defaultValue: 'Still running' });
499
+ if (w?.exitCode != null && w.exitCode !== 0)
500
+ return t('ide.toolCall.statusFailed', undefined, { defaultValue: 'Failed' });
501
+ return '';
502
+ }
503
+ case 'list_sessions': {
504
+ const sessions = out?.sessions;
505
+ if (!Array.isArray(sessions))
506
+ return '';
507
+ return sessions.length === 0
508
+ ? t('ide.toolCall.onlySession', undefined, { defaultValue: 'Only this one' })
509
+ : t('ide.toolCall.sessionCount', { count: sessions.length }, { defaultValue: '{{count}} other sessions' });
510
+ }
511
+ case 'send_session_message': {
512
+ const to = out?.to;
513
+ return typeof to === 'string'
514
+ ? t('ide.toolCall.sentTo', { to }, { defaultValue: 'Sent to {{to}}' })
515
+ : '';
516
+ }
517
+ case 'find_package': {
518
+ const found = out?.found;
519
+ if (found == null)
520
+ return '';
521
+ if (found === 0)
522
+ return t('ide.toolCall.noMatches', undefined, { defaultValue: 'No matches' });
523
+ return t('ide.toolCall.packageCount', { count: found }, { defaultValue: '{{count}} packages' });
524
+ }
525
+ case 'ask_user': {
526
+ if (typeof out === 'string')
527
+ return out;
528
+ const askOut = out;
529
+ if (askOut?.status === 'awaiting_response')
530
+ return '';
531
+ return '';
532
+ }
533
+ default:
534
+ return '';
535
+ }
536
+ }
537
+ /**
538
+ * The keys a model reaches for when it ignores a `string` schema and hands back an
539
+ * option object instead (`{ label }`, `{ value }`, `{ title }`, `{ text }`, `{ name }`).
540
+ * Ordered by how likely each is to hold the human-readable text.
541
+ */
542
+ const OPTION_TEXT_KEYS = ['label', 'text', 'title', 'value', 'name', 'option'];
543
+ /**
544
+ * Coerce one model-authored value into a plain string safe to render as a React child.
545
+ *
546
+ * Tool input is authored by an LLM, not by us: a schema saying `type: 'string'` is a
547
+ * request, never a guarantee. A non-string reaching JSX throws React error #31 and —
548
+ * because the throw happens during render — takes down the whole app, not just the card.
549
+ *
550
+ * @param value - The raw value from the tool input.
551
+ * @returns The best human-readable string, or `''` when there is nothing to show.
552
+ */
553
+ function coerceToText(value) {
554
+ if (typeof value === 'string') {
555
+ // Weak models also send option OBJECTS pre-serialized as strings —
556
+ // observed live 2026-08-15: options: ['{"key": "build-new", "label":
557
+ // "Build a new app"}'] rendered its raw JSON as the button label. A string
558
+ // that parses to an object/array gets the same key-extraction treatment as
559
+ // a real object; any other string renders untouched.
560
+ const trimmed = value.trim();
561
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
562
+ const tryParse = (candidate) => {
563
+ try {
564
+ const parsed = JSON.parse(candidate);
565
+ return parsed !== null && typeof parsed === 'object' ? parsed : null;
566
+ }
567
+ catch (_error) {
568
+ // Not parseable — the caller falls through to the next recovery step.
569
+ return null;
570
+ }
571
+ };
572
+ const textKeyOf = (obj) => {
573
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj))
574
+ return null;
575
+ const record = obj;
576
+ for (const key of OPTION_TEXT_KEYS) {
577
+ const candidate = record[key];
578
+ if (typeof candidate === 'string' && candidate.trim() !== '')
579
+ return candidate;
580
+ }
581
+ return null;
582
+ };
583
+ // The model also emits MANGLED pseudo-JSON with mixed escaping — observed
584
+ // live: '{"key": "dev\\", \\"label\\": \\"I\'m a developer…"}'. That
585
+ // string PARSES as valid JSON into a label-less object (the stray \\"
586
+ // swallows the rest into the first value), so a direct parse alone is not
587
+ // enough: prefer whichever parse (direct, or with the stray escapes
588
+ // collapsed) actually yields a recognised text key.
589
+ const direct = tryParse(trimmed);
590
+ const directText = textKeyOf(direct);
591
+ if (directText)
592
+ return directText;
593
+ const unescaped = tryParse(trimmed.replace(/\\"/g, '"'));
594
+ const unescapedText = textKeyOf(unescaped);
595
+ if (unescapedText)
596
+ return unescapedText;
597
+ // Last resort for un-parseable wreckage: pull a text key out with a
598
+ // regex — better a recovered label than raw pseudo-JSON as a caption.
599
+ for (const key of OPTION_TEXT_KEYS) {
600
+ const m = trimmed.match(new RegExp(`\\\\?"${key}\\\\?"\\s*:\\s*\\\\?"((?:[^"\\\\]|\\\\.)*)`));
601
+ if (m?.[1])
602
+ return m[1].replace(/\\"/g, '"').replace(/\\$/, '');
603
+ }
604
+ // A well-formed object/array with no text key (or an array): recurse into
605
+ // the generic coercion so arrays flatten and objects stringify once.
606
+ if (direct)
607
+ return coerceToText(direct);
608
+ }
609
+ return value;
610
+ }
611
+ if (value == null)
612
+ return '';
613
+ if (typeof value === 'number' || typeof value === 'boolean')
614
+ return String(value);
615
+ if (Array.isArray(value))
616
+ return value.map(coerceToText).filter(Boolean).join(' ');
617
+ if (typeof value === 'object') {
618
+ const record = value;
619
+ for (const key of OPTION_TEXT_KEYS) {
620
+ const candidate = record[key];
621
+ if (typeof candidate === 'string' && candidate.trim() !== '')
622
+ return candidate;
623
+ }
624
+ // No recognisable text key — show the JSON rather than dropping the option
625
+ // silently, so the user can still pick it and we can see what the model sent.
626
+ try {
627
+ return JSON.stringify(value);
628
+ }
629
+ catch (_error) {
630
+ // Circular structure — nothing renderable is recoverable from it.
631
+ return '';
632
+ }
633
+ }
634
+ return '';
635
+ }
636
+ /** Coerce the plan-approval card's `planReview` payload (hostile-safe). */
637
+ function normalizePlanReview(raw) {
638
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
639
+ return undefined;
640
+ const record = raw;
641
+ const path = typeof record.path === 'string' && record.path.trim() ? record.path : null;
642
+ const name = typeof record.name === 'string' && record.name.trim() ? record.name : null;
643
+ const steps = Number.isFinite(Number(record.steps)) ? Math.max(0, Number(record.steps)) : 0;
644
+ const preview = Array.isArray(record.preview)
645
+ ? record.preview
646
+ .map((line) => coerceToText(line).slice(0, 160))
647
+ .filter((line) => line.trim() !== '')
648
+ .slice(0, 8)
649
+ : [];
650
+ if (!path && !name && steps === 0)
651
+ return undefined;
652
+ // goesLive is a declared optional boolean; a model sending junk (a string, a
653
+ // number) degrades to "not stated" rather than leaking into the card.
654
+ const goesLive = record.goesLive === true ? true : undefined;
655
+ return { path, name, steps, preview, goesLive };
656
+ }
657
+ /**
658
+ * Normalize one raw option (string or object) into an `AskUserOption`.
659
+ *
660
+ * The object form is the schema-sanctioned rich option, but the same recovery
661
+ * rules as `coerceToText` apply — a malformed object without a `label` still
662
+ * yields SOMETHING clickable (via the known text keys, or the JSON dump) rather
663
+ * than being dropped, so the user is never left with fewer answers than the
664
+ * model meant to offer.
665
+ */
666
+ function normalizeAskUserOption(raw) {
667
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
668
+ const record = raw;
669
+ const label = coerceToText(record.label).trim()
670
+ ? coerceToText(record.label)
671
+ : coerceToText(record);
672
+ if (!label.trim())
673
+ return null;
674
+ return {
675
+ label,
676
+ description: coerceToText(record.description).trim()
677
+ ? coerceToText(record.description)
678
+ : undefined,
679
+ preview: coerceToText(record.preview).trim() ? coerceToText(record.preview) : undefined,
680
+ };
681
+ }
682
+ const label = coerceToText(raw);
683
+ return label.trim() ? { label } : null;
684
+ }
685
+ /**
686
+ * Normalize raw `ask_user` tool input into renderable strings.
687
+ *
688
+ * The model is told `options` is a list of strings or `{ label, description?,
689
+ * preview? }` objects, and weaker models routinely send stranger shapes —
690
+ * `[{ label, value }]`, nested arrays, quote-escaped pseudo-JSON. Rendering one
691
+ * of those directly is React error #31, which crashes the entire IDE at the
692
+ * moment the user submits their first prompt. Everything the card renders goes
693
+ * through here.
694
+ *
695
+ * @param input - The raw tool input, straight off the model.
696
+ * @returns The same fields, coerced so each is safe as a React child.
697
+ */
698
+ export function normalizeAskUserInput(input) {
699
+ const raw = (input ?? {});
700
+ const rawOptions = Array.isArray(raw.options) ? raw.options : [];
701
+ return {
702
+ question: coerceToText(raw.question),
703
+ options: rawOptions
704
+ .map(normalizeAskUserOption)
705
+ .filter((option) => option !== null),
706
+ multiSelect: typeof raw.multiSelect === 'boolean' ? raw.multiSelect : false,
707
+ allowFreeText: typeof raw.allowFreeText === 'boolean' ? raw.allowFreeText : undefined,
708
+ hint: coerceToText(raw.hint),
709
+ planReview: normalizePlanReview(raw.planReview),
710
+ };
711
+ }
712
+ /**
713
+ * Coerce raw `update_task_list` input into renderable rows. The input comes
714
+ * straight off the model — every field is degraded to a safe default rather
715
+ * than rendered raw (same contract as `normalizeAskUserInput`).
716
+ *
717
+ * @param input - The raw tool input.
718
+ * @returns The rows worth rendering; empty when the model sent nothing usable.
719
+ */
720
+ export function normalizeTaskListInput(input) {
721
+ const raw = (input ?? {});
722
+ if (!Array.isArray(raw.todos))
723
+ return [];
724
+ const rows = [];
725
+ for (const entry of raw.todos.slice(0, 50)) {
726
+ if (entry == null || typeof entry !== 'object' || Array.isArray(entry))
727
+ continue;
728
+ const record = entry;
729
+ const content = coerceToText(record.content);
730
+ if (!content.trim())
731
+ continue;
732
+ const status = record.status === 'in_progress' || record.status === 'completed'
733
+ ? record.status
734
+ : 'pending';
735
+ const priority = record.priority === 'high' || record.priority === 'medium' || record.priority === 'low'
736
+ ? record.priority
737
+ : undefined;
738
+ rows.push({ content: content.slice(0, 200), status, priority });
739
+ }
740
+ return rows;
741
+ }
742
+ /**
743
+ * Parse a judge subagent's report into a structured verdict.
744
+ *
745
+ * The judge system prompt fixes the shape (`VERDICT: PASS|FAIL` then optional
746
+ * `ISSUES:` bullets then per-criterion evidence), but the model is the author —
747
+ * parse defensively (case-insensitive, leading whitespace tolerated) and return
748
+ * `null` when no verdict line is present so the card renders the plain report.
749
+ *
750
+ * @param report - The judge subagent's final report text.
751
+ * @returns The structured verdict, or null when the report carries none.
752
+ */
753
+ export function parseJudgeVerdict(report) {
754
+ const verdictMatch = report.match(/^\s*VERDICT:\s*(PASS|FAIL)\b/im);
755
+ if (!verdictMatch)
756
+ return null;
757
+ const verdict = verdictMatch[1].toUpperCase();
758
+ const withoutVerdict = report
759
+ .slice(verdictMatch.index + verdictMatch[0].length)
760
+ .replace(/^\s*VERDICT:\s*(?:PASS|FAIL)\b.*$/im, '');
761
+ // The block ends at a blank line, at the next heading (a line opening with a
762
+ // capital, e.g. `EVIDENCE:`), or at the end of the report — NOT at a bullet.
763
+ // The judge writes one `- ` bullet PER failure, so treating a bullet as the
764
+ // block's end kept only the first failure and dropped the rest from the
765
+ // card's `issues` list (the report body still carried them). Sections after
766
+ // ISSUES are separated by a blank line or a heading, so neither terminator
767
+ // is lost by dropping that alternative.
768
+ // The label is matched case-insensitively (a judge may write `issues:`), but
769
+ // the block's END is matched in a SEPARATE, case-SENSITIVE pass: the `i` flag
770
+ // that tolerates a lowercase label also widens `[A-Z]` to any letter, so a
771
+ // single case-insensitive regex ended the block at the first line opening
772
+ // with a lowercase letter — a plain (unbulleted) issue list kept only its
773
+ // first line, the same "one failure out of many" bug the bullet fix removed.
774
+ const issuesLabel = withoutVerdict.match(/ISSUES:\s*\n?/i);
775
+ // A label at index 0 is legal, so "found" is the match itself, not a truthy index.
776
+ const blockStart = issuesLabel?.index ?? 0;
777
+ const bodyStart = issuesLabel ? blockStart + issuesLabel[0].length : 0;
778
+ const body = issuesLabel ? withoutVerdict.slice(bodyStart) : '';
779
+ const terminator = body.search(/\n\s*\n|\n[A-Z]/);
780
+ const blockEnd = issuesLabel ? bodyStart + (terminator === -1 ? body.length : terminator) : 0;
781
+ const issues = (issuesLabel ? withoutVerdict.slice(bodyStart, blockEnd) : '')
782
+ .split('\n')
783
+ .map((line) => line.replace(/^\s*[-•*]\s*/, '').trim())
784
+ .filter((line) => line.length > 0)
785
+ .slice(0, 12);
786
+ // The whole ISSUES block is scaffold, not report body: its bullet lines are
787
+ // already the card's FAIL list, so leaving them here rendered every failure
788
+ // TWICE — once in the verdict list and again at the top of the expandable
789
+ // body (the previous replace stripped only the `ISSUES:` label). What is left
790
+ // is the evidence the verdict was decided on.
791
+ const scaffold = issuesLabel ? withoutVerdict.slice(blockStart, blockEnd) : '';
792
+ const rest = (scaffold ? withoutVerdict.replace(scaffold, '') : withoutVerdict).trim();
793
+ return { verdict, issues, rest };
794
+ }
795
+ /**
796
+ * Largest LCS table the exact diff may build, in cells (old × new). A full table
797
+ * for a whole-file edit — the shape an `edit_file` replacement takes when the
798
+ * model rewrites a file whole — is thousands of lines per side, i.e. tens of
799
+ * millions of cells: gigabytes of heap and seconds of frozen UI, on a path that
800
+ * runs inside render (for every edit card in a reloaded transcript, not just the
801
+ * live one). Above this cap the answer comes from {@link orderedCommonLines} —
802
+ * a provable, order-respecting common subsequence in O(n log n); below it the
803
+ * result is exact. 1 << 22 cells is a few milliseconds, and the two-row table
804
+ * keeps memory at O(min(old, new)) — at most √(1 << 22) = 2048 numbers per row.
805
+ */
806
+ const MAX_DIFF_CELLS = 1 << 22;
807
+ /**
808
+ * Longest common subsequence length of two line arrays, in bounded time and
809
+ * memory: two rows of the recurrence instead of the whole table, and — once the
810
+ * table would exceed {@link MAX_DIFF_CELLS} — the order-respecting lower bound
811
+ * from {@link orderedCommonLines}.
812
+ *
813
+ * @param a - The first line array.
814
+ * @param b - The second line array.
815
+ * @returns The common subsequence length (a lower bound for the capped inputs).
816
+ */
817
+ function lcsLength(a, b) {
818
+ if (a.length === 0 || b.length === 0)
819
+ return 0;
820
+ if (a.length * b.length > MAX_DIFF_CELLS)
821
+ return orderedCommonLines(a, b);
822
+ // The recurrence needs only the previous row, and a row is `cols` wide — so
823
+ // the SHORTER array belongs on the `cols` axis, which bounds every row by
824
+ // min(a, b) (≤ 2048 here, since min² ≤ a·b ≤ MAX_DIFF_CELLS) and is what the
825
+ // memory claim above rests on. Putting the shorter array on the ROW axis
826
+ // instead bounds the row COUNT and leaves each of the two rows sized by the
827
+ // longer side — linear in a length the cell cap does not bound (a 1-line
828
+ // against a 4-million-line side is inside the cap and allocated two
829
+ // 4-million-slot arrays). Swapping the axes costs nothing: the recurrence is
830
+ // symmetric, so the length it returns is the same either way.
831
+ let rows = a;
832
+ let cols = b;
833
+ if (cols.length > rows.length) {
834
+ rows = b;
835
+ cols = a;
836
+ }
837
+ let previous = new Array(cols.length + 1).fill(0);
838
+ let current = new Array(cols.length + 1).fill(0);
839
+ for (let i = 1; i <= rows.length; i++) {
840
+ const line = rows[i - 1];
841
+ for (let j = 1; j <= cols.length; j++) {
842
+ if (line === cols[j - 1]) {
843
+ current[j] = previous[j - 1] + 1;
844
+ }
845
+ else {
846
+ const above = previous[j];
847
+ const left = current[j - 1];
848
+ current[j] = above >= left ? above : left;
849
+ }
850
+ }
851
+ const swap = previous;
852
+ previous = current;
853
+ current = swap;
854
+ }
855
+ return previous[cols.length];
856
+ }
857
+ /**
858
+ * How many lines the two arrays share IN ORDER, for inputs too large for the
859
+ * exact table: the longest run of lines that appear in the same relative order
860
+ * on both sides, found among the lines that occur exactly once in `a` (their
861
+ * position is unambiguous) by reducing their `b` positions to a longest
862
+ * strictly increasing run — the standard patience LIS, O(n log n).
863
+ *
864
+ * Order is the whole point. Counting the lines as a multiset (order thrown
865
+ * away) is only an UPPER bound on the LCS, so it under-reports changes: a
866
+ * 3000-line file whose two halves were swapped shares every line, and the
867
+ * multiset count then reported the replacement as `+0 −0` — a card claiming a
868
+ * real edit changed nothing. Every line counted here is a real in-order match,
869
+ * so the answer is a LOWER bound on the LCS and the change count it feeds can
870
+ * only ever be over-stated, never denied. (A shared line that repeats on the
871
+ * left is skipped rather than paired arbitrarily, which makes the bound
872
+ * conservative on those inputs; it is exact for the shapes that reach it here —
873
+ * a wholesale rewrite, and a block move whose lines are distinct.)
874
+ *
875
+ * @param a - The first line array.
876
+ * @param b - The second line array.
877
+ * @returns A common subsequence length.
878
+ */
879
+ function orderedCommonLines(a, b) {
880
+ const occurrences = new Map();
881
+ for (const line of a)
882
+ occurrences.set(line, (occurrences.get(line) ?? 0) + 1);
883
+ const position = new Map();
884
+ a.forEach((line, index) => {
885
+ if (occurrences.get(line) === 1)
886
+ position.set(line, index);
887
+ });
888
+ // Patience: `tails[i]` is the smallest `b`-position that ends an increasing
889
+ // run of length `i + 1`.
890
+ const tails = [];
891
+ for (const line of b) {
892
+ const at = position.get(line);
893
+ if (at === undefined)
894
+ continue;
895
+ let lo = 0;
896
+ let hi = tails.length;
897
+ while (lo < hi) {
898
+ const mid = (lo + hi) >> 1;
899
+ if (tails[mid] < at)
900
+ lo = mid + 1;
901
+ else
902
+ hi = mid;
903
+ }
904
+ tails[lo] = at;
905
+ }
906
+ return tails.length;
907
+ }
908
+ /**
909
+ * Count truly added/removed lines between two line arrays using LCS.
910
+ *
911
+ * Bounded by construction, so a whole-file edit cannot allocate a quadratic
912
+ * table here: the longest common prefix and suffix are trimmed first (exact —
913
+ * those lines belong to every optimal diff, and on the usual small edit they
914
+ * shrink the table to the edited span), and what is left is capped
915
+ * (see {@link lcsLength}).
916
+ *
917
+ * @param oldLines - The original lines array.
918
+ * @param modifiedLines - The modified lines array.
919
+ * @returns An object with the number of added and removed lines.
920
+ */
921
+ export function diffLineCount(oldLines, newLines) {
922
+ const oldLength = oldLines.length;
923
+ const newLength = newLines.length;
924
+ const shared = Math.min(oldLength, newLength);
925
+ // Longest common prefix / suffix. `suffix` is bounded by `shared - prefix`, so
926
+ // the two trimmed runs can never overlap each other.
927
+ let prefix = 0;
928
+ while (prefix < shared && oldLines[prefix] === newLines[prefix])
929
+ prefix++;
930
+ let suffix = 0;
931
+ while (suffix < shared - prefix &&
932
+ oldLines[oldLength - 1 - suffix] === newLines[newLength - 1 - suffix]) {
933
+ suffix++;
934
+ }
935
+ const common = prefix +
936
+ suffix +
937
+ lcsLength(oldLines.slice(prefix, oldLength - suffix), newLines.slice(prefix, newLength - suffix));
938
+ return { added: newLength - common, removed: oldLength - common };
939
+ }
940
+ /**
941
+ * Compute lines added/removed from a file-changing tool call.
942
+ * @param name - The tool name (edit_file or write_file).
943
+ * @param input - The raw tool input payload.
944
+ * @param output - The raw tool output payload.
945
+ * @returns Diff stats with added and removed line counts, or null if not applicable.
946
+ */
947
+ export function fileDiffStats(name, input, output) {
948
+ if (name === 'edit_file') {
949
+ const inp = (input ?? {});
950
+ const replacements = Array.isArray(inp.replacements) ? inp.replacements : [];
951
+ if (replacements.length === 0)
952
+ return null;
953
+ let added = 0;
954
+ let removed = 0;
955
+ for (const entry of replacements) {
956
+ // `replacements` is model-authored, so an entry may be null/undefined or a
957
+ // bare primitive (`[null]`, `["a"]`) — reading `.old_string` off one of
958
+ // those throws a TypeError, and this runs inside a useMemo in the card's
959
+ // RENDER path, so the throw takes down the whole IDE rather than one card
960
+ // (the same hazard `renderIn` guards with `entry ?? {}`). Skip anything
961
+ // that is not an object; a well-formed entry is unaffected.
962
+ if (entry === null || typeof entry !== 'object')
963
+ continue;
964
+ const record = entry;
965
+ if (typeof record.old_string !== 'string' || typeof record.new_string !== 'string')
966
+ continue;
967
+ const d = diffLineCount(record.old_string.split('\n'), record.new_string.split('\n'));
968
+ added += d.added;
969
+ removed += d.removed;
970
+ }
971
+ return { added, removed };
972
+ }
973
+ if (name === 'write_file') {
974
+ const diff = output?.diff;
975
+ if (!diff || diff.type === 'unchanged')
976
+ return null;
977
+ if (diff.type === 'new')
978
+ return { added: diff.linesAdded, removed: 0 };
979
+ return { added: diff.linesAdded, removed: diff.linesRemoved };
980
+ }
981
+ return null;
982
+ }
983
+ /**
984
+ * Extracts the primary file path from a tool's input, if it operates on a single file.
985
+ * @param name - The tool name.
986
+ * @param input - The raw tool input payload.
987
+ * @returns The file path string, or null if the tool doesn't target a single file.
988
+ */
989
+ export function extractFilePath(name, input) {
990
+ const inp = (input ?? {});
991
+ switch (name) {
992
+ case 'read_file':
993
+ return readFilePaths(input)[0] ?? null;
994
+ case 'write_file':
995
+ case 'edit_file':
996
+ case 'open_file':
997
+ return str(inp.path) || null;
998
+ case 'rename_file':
999
+ return str(inp.new_path) || null;
1000
+ case 'read_molecule_doc':
1001
+ // Clicking the card opens the package's README.md (pre-installed in the sandbox).
1002
+ return moleculeDocPath(str(inp.name));
1003
+ default:
1004
+ return null;
1005
+ }
1006
+ }
1007
+ //# sourceMappingURL=tool-call-utilities.js.map