reifyui 0.13.8 → 0.14.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.
@@ -0,0 +1,357 @@
1
+ // What a tool call IS, in a person's words, for every harness's vocabulary.
2
+ //
3
+ // Harnesses name the same act differently: Claude Code's `Bash`, Codex's `exec_command`, Gemini
4
+ // CLI's `run_shell_command`, Hermes's `terminal`, Goose's `developer__shell`, OpenHands's
5
+ // `execute_bash`. They pass through a gateway untouched, so the renderer is the one place that can
6
+ // read them all. describeTool(name, args) folds a call into one of a few kinds and pulls out the
7
+ // one thing a reader wants to see (the command, the file, the query, the URL), plus what the call
8
+ // changed (lines added and removed) and, for planning tools, the plan itself.
9
+ //
10
+ // Pure functions, no React: the reducer and the tests use them too.
11
+
12
+ /** Parse tool arguments that may be a JSON string, an object, or garbage. Never throws. */
13
+ export function parseToolArgs(args) {
14
+ if (args && typeof args === 'object') return args;
15
+ if (typeof args !== 'string' || !args.trim()) return {};
16
+ try {
17
+ const v = JSON.parse(args);
18
+ return v && typeof v === 'object' ? v : { value: v };
19
+ } catch {
20
+ return { _raw: args };
21
+ }
22
+ }
23
+
24
+ const KIND_BY_NAME = {};
25
+ function kinds(kind, names) { for (const n of names) KIND_BY_NAME[n] = kind; }
26
+ kinds('shell', ['bash', 'shell', 'exec_command', 'local_shell', 'run_shell_command', 'terminal', 'execute_bash',
27
+ 'run_command', 'command', 'run_terminal_cmd', 'execute_command', 'powershell', 'cmd', 'command_execution',
28
+ 'exec', 'run', 'sh', 'process']);
29
+ kinds('shell_output', ['bashoutput', 'bash_output', 'killshell', 'kill_shell', 'killbash']);
30
+ kinds('read', ['read', 'read_file', 'readfile', 'view', 'view_file', 'cat', 'read_many_files', 'notebookread',
31
+ 'file_read', 'open_file', 'readmanyfiles', 'read_text_file']);
32
+ kinds('write', ['write', 'write_file', 'writefile', 'create_file', 'file_write', 'create', 'write_to_file']);
33
+ kinds('edit', ['edit', 'multiedit', 'multi_edit', 'str_replace', 'str_replace_editor', 'str_replace_based_edit_tool',
34
+ 'replace', 'apply_patch', 'patch', 'edit_file', 'strreplacefile', 'notebookedit', 'text_editor', 'file_change',
35
+ 'search_replace', 'insert', 'replace_in_file', 'editor']);
36
+ kinds('search', ['grep', 'search_file_content', 'search_files', 'rg', 'ripgrep', 'codebase_search', 'search',
37
+ 'grep_search', 'file_grep']);
38
+ kinds('glob', ['glob', 'find_files', 'file_search', 'find', 'glob_files']);
39
+ kinds('list', ['ls', 'list', 'list_directory', 'list_dir', 'listdir', 'list_files', 'tree']);
40
+ kinds('web_search', ['websearch', 'web_search', 'google_web_search', 'searchweb', 'search_web', 'tavily_search',
41
+ 'brave_search', 'web_search_preview', 'internet_search']);
42
+ kinds('web_fetch', ['webfetch', 'web_fetch', 'fetch', 'fetchurl', 'fetch_url', 'web_extract', 'read_url', 'browse',
43
+ 'url_fetch', 'http_get', 'curl']);
44
+ kinds('agent', ['task', 'agent', 'delegate_task', 'spawn_agent', 'subagent', 'dispatch_agent', 'run_agent',
45
+ 'launch_agent', 'call_agent']);
46
+ kinds('todo', ['todowrite', 'todo_write', 'todo', 'todos', 'update_plan', 'write_todos', 'settodolist',
47
+ 'set_todo_list', 'task_tracker', 'todoread', 'todo_read', 'plan', 'update_todos', 'manage_todo_list']);
48
+ kinds('skill', ['skill', 'use_skill', 'load_skill']);
49
+ kinds('think', ['think', 'sequentialthinking', 'sequential_thinking', 'reflect']);
50
+ kinds('toolsearch', ['toolsearch', 'tool_search', 'load_tools']);
51
+ kinds('browser', ['browser', 'computer', 'playwright', 'browser_use', 'navigate', 'screenshot']);
52
+
53
+ // Namespaces that prefix a tool name without changing what it does.
54
+ const NS = /^(developer|platform|computercontroller|builtin|default|functions|tools?)(__|\.|:)/;
55
+
56
+ /** The kind of a tool name, or 'mcp' for a connected tool, or 'tool' when it is unknown. */
57
+ export function toolKind(name) {
58
+ const raw = String(name || '').trim();
59
+ if (!raw) return 'tool';
60
+ if (/^mcp__/i.test(raw)) return 'mcp';
61
+ const n = raw.toLowerCase().replace(NS, '');
62
+ if (KIND_BY_NAME[n]) return KIND_BY_NAME[n];
63
+ if (/^browser[_\-.]|[_\-.]browser$|^playwright|^computer[_\-.]/.test(n)) return 'browser';
64
+ const flat = n.replace(/[^a-z0-9]/g, '');
65
+ if (KIND_BY_NAME[flat]) return KIND_BY_NAME[flat];
66
+ // `server.tool` (Codex) and `server__tool` (Goose, others) are connected tools
67
+ if (/[a-z0-9](\.|__)[a-z0-9]/.test(n)) return 'mcp';
68
+ return 'tool';
69
+ }
70
+
71
+ function str(v) { return v == null ? '' : typeof v === 'string' ? v : Array.isArray(v) ? v.join(' ') : String(v); }
72
+ function firstOf(a, keys) {
73
+ for (const k of keys) {
74
+ const v = a[k];
75
+ if (v != null && v !== '' && !(Array.isArray(v) && !v.length)) return v;
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ export function baseNameOf(p) {
81
+ const s = str(p).replace(/[\\/]+$/, '');
82
+ const i = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'));
83
+ return i >= 0 ? s.slice(i + 1) : s;
84
+ }
85
+
86
+ /** A shell command as one readable line: argv arrays joined, `bash -lc '…'` unwrapped. */
87
+ export function commandText(a) {
88
+ let c = firstOf(a, ['command', 'cmd', 'commands', 'script', 'code', 'input', 'args']);
89
+ if (Array.isArray(c)) {
90
+ // ["bash", "-lc", "npm test"] -> npm test
91
+ if (c.length >= 3 && /(^|\/)(ba|z)?sh$/.test(String(c[0])) && /^-\w*c$/.test(String(c[1]))) c = c.slice(2).join(' ');
92
+ else c = c.join(' ');
93
+ }
94
+ return str(c).trim();
95
+ }
96
+
97
+ export function lineCount(s) {
98
+ const t = str(s);
99
+ if (!t) return 0;
100
+ const n = t.split('\n').length;
101
+ return t.endsWith('\n') ? n - 1 : n;
102
+ }
103
+
104
+ /** Lines added and removed by a unified diff / apply_patch body. */
105
+ export function patchStats(patch) {
106
+ let added = 0; let removed = 0;
107
+ for (const ln of str(patch).split('\n')) {
108
+ if (/^(\+\+\+|---|\*\*\*|@@)/.test(ln)) continue;
109
+ if (ln.startsWith('+')) added++;
110
+ else if (ln.startsWith('-')) removed++;
111
+ }
112
+ return { added, removed };
113
+ }
114
+
115
+ function patchFiles(patch) {
116
+ const out = [];
117
+ for (const ln of str(patch).split('\n')) {
118
+ const m = ln.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/) || ln.match(/^\+\+\+ (?:b\/)?(.+)$/);
119
+ if (m && m[1] !== '/dev/null' && !out.includes(m[1].trim())) out.push(m[1].trim());
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /** What a write/edit call changed: {added, removed}, or null when the call does not say. */
125
+ export function diffOf(kind, a) {
126
+ if (kind === 'write') {
127
+ const body = firstOf(a, ['content', 'file_text', 'text', 'contents', 'data']);
128
+ return body == null ? null : { added: lineCount(body), removed: 0 };
129
+ }
130
+ if (kind !== 'edit') return null;
131
+ const cmd = str(a.command).toLowerCase();
132
+ if (cmd === 'view' || cmd === 'undo_edit') return null;
133
+ if (cmd === 'create' || cmd === 'write') {
134
+ const body = firstOf(a, ['file_text', 'content', 'text']);
135
+ return body == null ? null : { added: lineCount(body), removed: 0 };
136
+ }
137
+ if (Array.isArray(a.edits)) {
138
+ let added = 0; let removed = 0;
139
+ for (const e of a.edits) {
140
+ added += lineCount(firstOf(e || {}, ['new_string', 'new_str', 'newText', 'replacement']) || '');
141
+ removed += lineCount(firstOf(e || {}, ['old_string', 'old_str', 'oldText', 'search']) || '');
142
+ }
143
+ return { added, removed };
144
+ }
145
+ const neu = firstOf(a, ['new_string', 'new_str', 'newText', 'new_text', 'replacement', 'replace']);
146
+ const old = firstOf(a, ['old_string', 'old_str', 'oldText', 'old_text', 'search']);
147
+ if (neu != null || old != null) return { added: lineCount(neu || ''), removed: lineCount(old || '') };
148
+ const patch = firstOf(a, ['patch', 'diff', 'input', '_raw']);
149
+ if (typeof patch === 'string' && /^(\*\*\* Begin Patch|---|\+\+\+|@@|diff )/m.test(patch)) return patchStats(patch);
150
+ if (Array.isArray(a.changes)) {
151
+ let added = 0; let removed = 0; let any = false;
152
+ for (const c of a.changes) {
153
+ const d = c && (c.diff || c.unified_diff || c.patch);
154
+ if (typeof d === 'string') { const s = patchStats(d); added += s.added; removed += s.removed; any = true; }
155
+ }
156
+ return any ? { added, removed } : null;
157
+ }
158
+ return null;
159
+ }
160
+
161
+ const TODO_STATUS = { completed: 'completed', complete: 'completed', done: 'completed', finished: 'completed',
162
+ in_progress: 'in_progress', inprogress: 'in_progress', active: 'in_progress', doing: 'in_progress', running: 'in_progress',
163
+ pending: 'pending', todo: 'pending', not_started: 'pending', open: 'pending', cancelled: 'cancelled', canceled: 'cancelled' };
164
+
165
+ /** The plan a todo/plan tool call states, as [{text, status}], or null when it states none. */
166
+ export function todosOf(a) {
167
+ const list = firstOf(a, ['todos', 'plan', 'items', 'tasks', 'todo_list', 'steps', 'task_list']);
168
+ if (!Array.isArray(list) || !list.length) return null;
169
+ const out = [];
170
+ for (const t of list) {
171
+ if (typeof t === 'string') { out.push({ text: t, status: 'pending' }); continue; }
172
+ if (!t || typeof t !== 'object') continue;
173
+ const text = str(firstOf(t, ['content', 'step', 'title', 'text', 'description', 'task', 'name'])).trim();
174
+ if (!text) continue;
175
+ let st = str(firstOf(t, ['status', 'state'])).toLowerCase().replace(/[\s-]+/g, '_');
176
+ if (!st && typeof t.done === 'boolean') st = t.done ? 'completed' : 'pending';
177
+ if (!st && typeof t.completed === 'boolean') st = t.completed ? 'completed' : 'pending';
178
+ out.push({ text, status: TODO_STATUS[st] || 'pending' });
179
+ }
180
+ return out.length ? out : null;
181
+ }
182
+
183
+ function shortUrl(u) {
184
+ const s = str(u);
185
+ try {
186
+ const x = new URL(s);
187
+ return (x.host + (x.pathname === '/' ? '' : x.pathname)).replace(/\/$/, '');
188
+ } catch { return s; }
189
+ }
190
+
191
+ function humanizeName(n) {
192
+ return str(n).replace(/^mcp__/i, '').replace(/__|\./g, ' · ').replace(/[_-]+/g, ' ')
193
+ .replace(/([a-z])([A-Z])/g, '$1 $2').trim().replace(/^\w/, (c) => c.toUpperCase());
194
+ }
195
+
196
+ // [running, done] verbs per kind. The target follows the verb.
197
+ const VERBS = {
198
+ shell: ['Running', 'Ran'], shell_output: ['Reading output of', 'Read output of'],
199
+ read: ['Reading', 'Read'], write: ['Writing', 'Created'], edit: ['Editing', 'Edited'],
200
+ search: ['Searching for', 'Searched for'], glob: ['Finding', 'Found'], list: ['Listing', 'Listed'],
201
+ web_search: ['Searching the web for', 'Searched the web for'], web_fetch: ['Fetching', 'Fetched'],
202
+ agent: ['Running agent', 'Ran agent'], todo: ['Updating the plan', 'Updated the plan'],
203
+ skill: ['Using skill', 'Used skill'], think: ['Thinking', 'Thought'], toolsearch: ['Loading tools', 'Loaded tools'],
204
+ browser: ['Using the browser', 'Used the browser'], mcp: ['Using', 'Used'], tool: ['Using', 'Used'],
205
+ };
206
+
207
+ /**
208
+ * describeTool(name, args) -> {
209
+ * kind, one of the kinds above
210
+ * target, the short thing the call acts on ('' when it has none)
211
+ * targetFull, the long form for a tooltip (full path, full command)
212
+ * mono, true when the target is code (a command, a path, a pattern)
213
+ * running, done, the verb phrases ("Running", "Ran") the row and the live line use
214
+ * diff, {added, removed} | null
215
+ * todos, [{text, status}] | null
216
+ * note, a secondary label (an agent's type, a skill)
217
+ * }
218
+ */
219
+ export function describeTool(name, args) {
220
+ const a = parseToolArgs(args);
221
+ let kind = toolKind(name);
222
+ const nm = str(name);
223
+ // One editor tool, several acts (Anthropic's str_replace_editor, Goose's text_editor).
224
+ if (kind === 'edit' && /^(view|read)$/i.test(str(a.command))) kind = 'read';
225
+ if (kind === 'edit' && /^(create|write)$/i.test(str(a.command))) kind = 'write';
226
+ let target = ''; let targetFull = ''; let mono = false; let note = '';
227
+ const pathOf = () => firstOf(a, ['file_path', 'path', 'filePath', 'absolute_path', 'target_file', 'filename',
228
+ 'file', 'notebook_path', 'paths', 'absolute_paths', 'dir_path', 'directory']);
229
+ switch (kind) {
230
+ case 'shell': {
231
+ const desc = str(firstOf(a, ['description', 'summary', 'title'])).trim();
232
+ const cmd = commandText(a);
233
+ targetFull = cmd || desc;
234
+ if (desc) { target = desc; note = cmd; } else { target = cmd; mono = !!cmd; }
235
+ break;
236
+ }
237
+ case 'shell_output': target = str(firstOf(a, ['bash_id', 'shell_id', 'id'])); mono = true; break;
238
+ case 'read': case 'write': case 'edit': case 'list': {
239
+ let p = pathOf();
240
+ if (Array.isArray(p)) p = p.length > 1 ? `${baseNameOf(p[0])} and ${p.length - 1} more` : p[0];
241
+ if (!p && kind === 'edit') {
242
+ const files = patchFiles(firstOf(a, ['patch', 'input', '_raw']) || '')
243
+ .concat(Array.isArray(a.changes) ? a.changes.map((c) => c && c.path).filter(Boolean) : []);
244
+ if (files.length) p = files.length > 1 ? `${baseNameOf(files[0])} and ${files.length - 1} more` : files[0];
245
+ }
246
+ targetFull = str(p);
247
+ target = kind === 'list' ? (str(p) || '.') : baseNameOf(p);
248
+ mono = !!target;
249
+ break;
250
+ }
251
+ case 'search': case 'glob': {
252
+ const pat = firstOf(a, ['pattern', 'query', 'regex', 'q', 'glob', 'search', 'text']);
253
+ const where = firstOf(a, ['path', 'dir_path', 'directory', 'include']);
254
+ target = str(pat); mono = true;
255
+ targetFull = where ? `${str(pat)} in ${str(where)}` : str(pat);
256
+ break;
257
+ }
258
+ case 'web_search': target = str(firstOf(a, ['query', 'q', 'search_query', 'queries', 'search'])); targetFull = target; break;
259
+ case 'web_fetch': {
260
+ const u = firstOf(a, ['url', 'urls', 'uri', 'href', 'link']);
261
+ targetFull = Array.isArray(u) ? u.join(' ') : str(u);
262
+ target = Array.isArray(u) ? `${shortUrl(u[0])}${u.length > 1 ? ` and ${u.length - 1} more` : ''}` : shortUrl(u);
263
+ break;
264
+ }
265
+ case 'agent':
266
+ target = str(firstOf(a, ['description', 'task', 'title', 'name', 'goal'])) || str(firstOf(a, ['prompt'])).slice(0, 80);
267
+ note = str(firstOf(a, ['subagent_type', 'agent', 'agent_type', 'role']));
268
+ targetFull = str(firstOf(a, ['prompt', 'task', 'description']));
269
+ break;
270
+ case 'skill': target = str(firstOf(a, ['skill', 'name', 'command', 'skill_name'])); mono = true; targetFull = target; break;
271
+ case 'browser': {
272
+ const act = str(firstOf(a, ['action', 'command', 'type']));
273
+ const u = str(firstOf(a, ['url', 'selector', 'text']));
274
+ target = [act, u ? shortUrl(u) : ''].filter(Boolean).join(' ');
275
+ targetFull = target;
276
+ if (/^browser[_\-.]/i.test(nm)) note = humanizeName(nm.replace(/^browser[_\-.]/i, ''));
277
+ break;
278
+ }
279
+ case 'mcp': case 'tool': {
280
+ target = humanizeName(nm);
281
+ targetFull = nm;
282
+ break;
283
+ }
284
+ default: break;
285
+ }
286
+ const v = VERBS[kind] || VERBS.tool;
287
+ return {
288
+ kind, target: target.replace(/\s+/g, ' ').trim(), targetFull, mono, note,
289
+ running: v[0], done: v[1],
290
+ diff: diffOf(kind, a),
291
+ todos: kind === 'todo' ? todosOf(a) : null,
292
+ };
293
+ }
294
+
295
+ /** "Ran npm test", "Read app.ts", "Created analyze.py": verb + target, one line. */
296
+ export function toolLine(d, state) {
297
+ const verb = state === 'running' ? d.running : d.done;
298
+ if (d.kind === 'todo' || d.kind === 'toolsearch' || d.kind === 'think') return verb;
299
+ if (d.kind === 'shell' && d.target && !d.mono) return d.target; // the agent's own description
300
+ if (d.kind === 'mcp' || d.kind === 'tool') return `${verb} ${d.target || 'a tool'}`;
301
+ return d.target ? `${verb} ${d.target}` : `${verb} ${KIND_NOUN[d.kind] || 'a tool'}`;
302
+ }
303
+ const KIND_NOUN = { shell: 'a command', read: 'a file', write: 'a file', edit: 'a file', search: 'code', glob: 'files',
304
+ list: 'a folder', web_search: '', web_fetch: 'a page', agent: '', skill: 'a skill', browser: '', shell_output: 'a command' };
305
+
306
+ // Group recap: one phrase per kind, counted, in first-seen order.
307
+ const PHRASES = {
308
+ shell: (n) => (n === 1 ? 'ran a command' : `ran ${n} commands`),
309
+ shell_output: (n) => (n === 1 ? 'checked a command' : `checked ${n} commands`),
310
+ read: (n) => (n === 1 ? 'read a file' : `read ${n} files`),
311
+ write: (n) => (n === 1 ? 'created a file' : `created ${n} files`),
312
+ edit: (n) => (n === 1 ? 'edited a file' : `edited ${n} files`),
313
+ search: (n) => (n === 1 ? 'searched code' : `searched code ${n} times`),
314
+ glob: () => 'found files',
315
+ list: (n) => (n === 1 ? 'listed a folder' : `listed ${n} folders`),
316
+ web_search: (n) => (n === 1 ? 'searched the web' : `searched the web ${n} times`),
317
+ web_fetch: (n) => (n === 1 ? 'fetched a page' : `fetched ${n} pages`),
318
+ agent: (n) => (n === 1 ? 'ran an agent' : `ran ${n} agents`),
319
+ todo: () => 'updated the plan',
320
+ skill: (n) => (n === 1 ? 'used a skill' : `used ${n} skills`),
321
+ think: () => 'thought it through',
322
+ toolsearch: () => 'loaded tools',
323
+ browser: () => 'used the browser',
324
+ mcp: (n) => (n === 1 ? 'used a tool' : `used ${n} tools`),
325
+ tool: (n) => (n === 1 ? 'used a tool' : `used ${n} tools`),
326
+ };
327
+
328
+ /**
329
+ * One past-tense line for a run of finished calls: "Ran 3 commands, edited app.ts".
330
+ * A single call reads as itself ("Read app.ts"). `calls` are [{name, args}].
331
+ */
332
+ export function summarizeCalls(calls) {
333
+ const list = (calls || []).filter(Boolean);
334
+ if (!list.length) return '';
335
+ if (list.length === 1) return toolLine(describeTool(list[0].name, list[0].args), 'done');
336
+ const order = []; const count = {};
337
+ for (const c of list) {
338
+ let k = toolKind(c.name);
339
+ if (k === 'mcp') k = 'tool';
340
+ if (!(k in count)) { count[k] = 0; order.push(k); }
341
+ count[k]++;
342
+ }
343
+ // mcp and unknown tools share one phrase ("used 3 tools"), placed where the first appeared
344
+ const s = order.map((k) => (PHRASES[k] || PHRASES.tool)(count[k])).join(', ');
345
+ return s.charAt(0).toUpperCase() + s.slice(1);
346
+ }
347
+
348
+ /** A short result summary for a finished call ("120 lines", "3 files"), or ''. */
349
+ export function resultNote(kind, output) {
350
+ const out = str(output);
351
+ if (!out.trim()) return '';
352
+ const n = lineCount(out.trim());
353
+ if (kind === 'read') return n === 1 ? '1 line' : `${n} lines`;
354
+ if (kind === 'glob') return n === 1 ? '1 file' : `${n} files`;
355
+ if (kind === 'search') return n === 1 ? '1 match' : `${n} matches`;
356
+ return '';
357
+ }