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,1952 @@
1
+ import {
2
+ Chevron,
3
+ IcDoc,
4
+ IcGlobe,
5
+ IcList,
6
+ IcPaperclip,
7
+ IcPlug,
8
+ IcScroll,
9
+ IcSearch,
10
+ IcSend,
11
+ IcSkill,
12
+ IcSpawn,
13
+ IcTerminal,
14
+ IcThink,
15
+ IcTool,
16
+ IcX
17
+ } from "./chunk-WAND7AYD.js";
18
+ import "./chunk-PZ5AY32C.js";
19
+
20
+ // src/agent-chat/tools.js
21
+ function parseToolArgs(args) {
22
+ if (args && typeof args === "object") return args;
23
+ if (typeof args !== "string" || !args.trim()) return {};
24
+ try {
25
+ const v = JSON.parse(args);
26
+ return v && typeof v === "object" ? v : { value: v };
27
+ } catch {
28
+ return { _raw: args };
29
+ }
30
+ }
31
+ var KIND_BY_NAME = {};
32
+ function kinds(kind, names) {
33
+ for (const n of names) KIND_BY_NAME[n] = kind;
34
+ }
35
+ kinds("shell", [
36
+ "bash",
37
+ "shell",
38
+ "exec_command",
39
+ "local_shell",
40
+ "run_shell_command",
41
+ "terminal",
42
+ "execute_bash",
43
+ "run_command",
44
+ "command",
45
+ "run_terminal_cmd",
46
+ "execute_command",
47
+ "powershell",
48
+ "cmd",
49
+ "command_execution",
50
+ "exec",
51
+ "run",
52
+ "sh",
53
+ "process"
54
+ ]);
55
+ kinds("shell_output", ["bashoutput", "bash_output", "killshell", "kill_shell", "killbash"]);
56
+ kinds("read", [
57
+ "read",
58
+ "read_file",
59
+ "readfile",
60
+ "view",
61
+ "view_file",
62
+ "cat",
63
+ "read_many_files",
64
+ "notebookread",
65
+ "file_read",
66
+ "open_file",
67
+ "readmanyfiles",
68
+ "read_text_file"
69
+ ]);
70
+ kinds("write", ["write", "write_file", "writefile", "create_file", "file_write", "create", "write_to_file"]);
71
+ kinds("edit", [
72
+ "edit",
73
+ "multiedit",
74
+ "multi_edit",
75
+ "str_replace",
76
+ "str_replace_editor",
77
+ "str_replace_based_edit_tool",
78
+ "replace",
79
+ "apply_patch",
80
+ "patch",
81
+ "edit_file",
82
+ "strreplacefile",
83
+ "notebookedit",
84
+ "text_editor",
85
+ "file_change",
86
+ "search_replace",
87
+ "insert",
88
+ "replace_in_file",
89
+ "editor"
90
+ ]);
91
+ kinds("search", [
92
+ "grep",
93
+ "search_file_content",
94
+ "search_files",
95
+ "rg",
96
+ "ripgrep",
97
+ "codebase_search",
98
+ "search",
99
+ "grep_search",
100
+ "file_grep"
101
+ ]);
102
+ kinds("glob", ["glob", "find_files", "file_search", "find", "glob_files"]);
103
+ kinds("list", ["ls", "list", "list_directory", "list_dir", "listdir", "list_files", "tree"]);
104
+ kinds("web_search", [
105
+ "websearch",
106
+ "web_search",
107
+ "google_web_search",
108
+ "searchweb",
109
+ "search_web",
110
+ "tavily_search",
111
+ "brave_search",
112
+ "web_search_preview",
113
+ "internet_search"
114
+ ]);
115
+ kinds("web_fetch", [
116
+ "webfetch",
117
+ "web_fetch",
118
+ "fetch",
119
+ "fetchurl",
120
+ "fetch_url",
121
+ "web_extract",
122
+ "read_url",
123
+ "browse",
124
+ "url_fetch",
125
+ "http_get",
126
+ "curl"
127
+ ]);
128
+ kinds("agent", [
129
+ "task",
130
+ "agent",
131
+ "delegate_task",
132
+ "spawn_agent",
133
+ "subagent",
134
+ "dispatch_agent",
135
+ "run_agent",
136
+ "launch_agent",
137
+ "call_agent"
138
+ ]);
139
+ kinds("todo", [
140
+ "todowrite",
141
+ "todo_write",
142
+ "todo",
143
+ "todos",
144
+ "update_plan",
145
+ "write_todos",
146
+ "settodolist",
147
+ "set_todo_list",
148
+ "task_tracker",
149
+ "todoread",
150
+ "todo_read",
151
+ "plan",
152
+ "update_todos",
153
+ "manage_todo_list"
154
+ ]);
155
+ kinds("skill", ["skill", "use_skill", "load_skill"]);
156
+ kinds("think", ["think", "sequentialthinking", "sequential_thinking", "reflect"]);
157
+ kinds("toolsearch", ["toolsearch", "tool_search", "load_tools"]);
158
+ kinds("browser", ["browser", "computer", "playwright", "browser_use", "navigate", "screenshot"]);
159
+ var NS = /^(developer|platform|computercontroller|builtin|default|functions|tools?)(__|\.|:)/;
160
+ function toolKind(name) {
161
+ const raw = String(name || "").trim();
162
+ if (!raw) return "tool";
163
+ if (/^mcp__/i.test(raw)) return "mcp";
164
+ const n = raw.toLowerCase().replace(NS, "");
165
+ if (KIND_BY_NAME[n]) return KIND_BY_NAME[n];
166
+ if (/^browser[_\-.]|[_\-.]browser$|^playwright|^computer[_\-.]/.test(n)) return "browser";
167
+ const flat = n.replace(/[^a-z0-9]/g, "");
168
+ if (KIND_BY_NAME[flat]) return KIND_BY_NAME[flat];
169
+ if (/[a-z0-9](\.|__)[a-z0-9]/.test(n)) return "mcp";
170
+ return "tool";
171
+ }
172
+ function str(v) {
173
+ return v == null ? "" : typeof v === "string" ? v : Array.isArray(v) ? v.join(" ") : String(v);
174
+ }
175
+ function firstOf(a, keys) {
176
+ for (const k of keys) {
177
+ const v = a[k];
178
+ if (v != null && v !== "" && !(Array.isArray(v) && !v.length)) return v;
179
+ }
180
+ return void 0;
181
+ }
182
+ function baseNameOf(p) {
183
+ const s = str(p).replace(/[\\/]+$/, "");
184
+ const i = Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\"));
185
+ return i >= 0 ? s.slice(i + 1) : s;
186
+ }
187
+ function commandText(a) {
188
+ let c = firstOf(a, ["command", "cmd", "commands", "script", "code", "input", "args"]);
189
+ if (Array.isArray(c)) {
190
+ if (c.length >= 3 && /(^|\/)(ba|z)?sh$/.test(String(c[0])) && /^-\w*c$/.test(String(c[1]))) c = c.slice(2).join(" ");
191
+ else c = c.join(" ");
192
+ }
193
+ return str(c).trim();
194
+ }
195
+ function lineCount(s) {
196
+ const t = str(s);
197
+ if (!t) return 0;
198
+ const n = t.split("\n").length;
199
+ return t.endsWith("\n") ? n - 1 : n;
200
+ }
201
+ function patchStats(patch) {
202
+ let added = 0;
203
+ let removed = 0;
204
+ for (const ln of str(patch).split("\n")) {
205
+ if (/^(\+\+\+|---|\*\*\*|@@)/.test(ln)) continue;
206
+ if (ln.startsWith("+")) added++;
207
+ else if (ln.startsWith("-")) removed++;
208
+ }
209
+ return { added, removed };
210
+ }
211
+ function patchFiles(patch) {
212
+ const out = [];
213
+ for (const ln of str(patch).split("\n")) {
214
+ const m = ln.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/) || ln.match(/^\+\+\+ (?:b\/)?(.+)$/);
215
+ if (m && m[1] !== "/dev/null" && !out.includes(m[1].trim())) out.push(m[1].trim());
216
+ }
217
+ return out;
218
+ }
219
+ function diffOf(kind, a) {
220
+ if (kind === "write") {
221
+ const body = firstOf(a, ["content", "file_text", "text", "contents", "data"]);
222
+ return body == null ? null : { added: lineCount(body), removed: 0 };
223
+ }
224
+ if (kind !== "edit") return null;
225
+ const cmd = str(a.command).toLowerCase();
226
+ if (cmd === "view" || cmd === "undo_edit") return null;
227
+ if (cmd === "create" || cmd === "write") {
228
+ const body = firstOf(a, ["file_text", "content", "text"]);
229
+ return body == null ? null : { added: lineCount(body), removed: 0 };
230
+ }
231
+ if (Array.isArray(a.edits)) {
232
+ let added = 0;
233
+ let removed = 0;
234
+ for (const e of a.edits) {
235
+ added += lineCount(firstOf(e || {}, ["new_string", "new_str", "newText", "replacement"]) || "");
236
+ removed += lineCount(firstOf(e || {}, ["old_string", "old_str", "oldText", "search"]) || "");
237
+ }
238
+ return { added, removed };
239
+ }
240
+ const neu = firstOf(a, ["new_string", "new_str", "newText", "new_text", "replacement", "replace"]);
241
+ const old = firstOf(a, ["old_string", "old_str", "oldText", "old_text", "search"]);
242
+ if (neu != null || old != null) return { added: lineCount(neu || ""), removed: lineCount(old || "") };
243
+ const patch = firstOf(a, ["patch", "diff", "input", "_raw"]);
244
+ if (typeof patch === "string" && /^(\*\*\* Begin Patch|---|\+\+\+|@@|diff )/m.test(patch)) return patchStats(patch);
245
+ if (Array.isArray(a.changes)) {
246
+ let added = 0;
247
+ let removed = 0;
248
+ let any = false;
249
+ for (const c of a.changes) {
250
+ const d = c && (c.diff || c.unified_diff || c.patch);
251
+ if (typeof d === "string") {
252
+ const s = patchStats(d);
253
+ added += s.added;
254
+ removed += s.removed;
255
+ any = true;
256
+ }
257
+ }
258
+ return any ? { added, removed } : null;
259
+ }
260
+ return null;
261
+ }
262
+ var TODO_STATUS = {
263
+ completed: "completed",
264
+ complete: "completed",
265
+ done: "completed",
266
+ finished: "completed",
267
+ in_progress: "in_progress",
268
+ inprogress: "in_progress",
269
+ active: "in_progress",
270
+ doing: "in_progress",
271
+ running: "in_progress",
272
+ pending: "pending",
273
+ todo: "pending",
274
+ not_started: "pending",
275
+ open: "pending",
276
+ cancelled: "cancelled",
277
+ canceled: "cancelled"
278
+ };
279
+ function todosOf(a) {
280
+ const list = firstOf(a, ["todos", "plan", "items", "tasks", "todo_list", "steps", "task_list"]);
281
+ if (!Array.isArray(list) || !list.length) return null;
282
+ const out = [];
283
+ for (const t of list) {
284
+ if (typeof t === "string") {
285
+ out.push({ text: t, status: "pending" });
286
+ continue;
287
+ }
288
+ if (!t || typeof t !== "object") continue;
289
+ const text = str(firstOf(t, ["content", "step", "title", "text", "description", "task", "name"])).trim();
290
+ if (!text) continue;
291
+ let st = str(firstOf(t, ["status", "state"])).toLowerCase().replace(/[\s-]+/g, "_");
292
+ if (!st && typeof t.done === "boolean") st = t.done ? "completed" : "pending";
293
+ if (!st && typeof t.completed === "boolean") st = t.completed ? "completed" : "pending";
294
+ out.push({ text, status: TODO_STATUS[st] || "pending" });
295
+ }
296
+ return out.length ? out : null;
297
+ }
298
+ function shortUrl(u) {
299
+ const s = str(u);
300
+ try {
301
+ const x = new URL(s);
302
+ return (x.host + (x.pathname === "/" ? "" : x.pathname)).replace(/\/$/, "");
303
+ } catch {
304
+ return s;
305
+ }
306
+ }
307
+ function humanizeName(n) {
308
+ return str(n).replace(/^mcp__/i, "").replace(/__|\./g, " \xB7 ").replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim().replace(/^\w/, (c) => c.toUpperCase());
309
+ }
310
+ var VERBS = {
311
+ shell: ["Running", "Ran"],
312
+ shell_output: ["Reading output of", "Read output of"],
313
+ read: ["Reading", "Read"],
314
+ write: ["Writing", "Created"],
315
+ edit: ["Editing", "Edited"],
316
+ search: ["Searching for", "Searched for"],
317
+ glob: ["Finding", "Found"],
318
+ list: ["Listing", "Listed"],
319
+ web_search: ["Searching the web for", "Searched the web for"],
320
+ web_fetch: ["Fetching", "Fetched"],
321
+ agent: ["Running agent", "Ran agent"],
322
+ todo: ["Updating the plan", "Updated the plan"],
323
+ skill: ["Using skill", "Used skill"],
324
+ think: ["Thinking", "Thought"],
325
+ toolsearch: ["Loading tools", "Loaded tools"],
326
+ browser: ["Using the browser", "Used the browser"],
327
+ mcp: ["Using", "Used"],
328
+ tool: ["Using", "Used"]
329
+ };
330
+ function describeTool(name, args) {
331
+ const a = parseToolArgs(args);
332
+ let kind = toolKind(name);
333
+ const nm = str(name);
334
+ if (kind === "edit" && /^(view|read)$/i.test(str(a.command))) kind = "read";
335
+ if (kind === "edit" && /^(create|write)$/i.test(str(a.command))) kind = "write";
336
+ let target = "";
337
+ let targetFull = "";
338
+ let mono = false;
339
+ let note = "";
340
+ const pathOf = () => firstOf(a, [
341
+ "file_path",
342
+ "path",
343
+ "filePath",
344
+ "absolute_path",
345
+ "target_file",
346
+ "filename",
347
+ "file",
348
+ "notebook_path",
349
+ "paths",
350
+ "absolute_paths",
351
+ "dir_path",
352
+ "directory"
353
+ ]);
354
+ switch (kind) {
355
+ case "shell": {
356
+ const desc = str(firstOf(a, ["description", "summary", "title"])).trim();
357
+ const cmd = commandText(a);
358
+ targetFull = cmd || desc;
359
+ if (desc) {
360
+ target = desc;
361
+ note = cmd;
362
+ } else {
363
+ target = cmd;
364
+ mono = !!cmd;
365
+ }
366
+ break;
367
+ }
368
+ case "shell_output":
369
+ target = str(firstOf(a, ["bash_id", "shell_id", "id"]));
370
+ mono = true;
371
+ break;
372
+ case "read":
373
+ case "write":
374
+ case "edit":
375
+ case "list": {
376
+ let p = pathOf();
377
+ if (Array.isArray(p)) p = p.length > 1 ? `${baseNameOf(p[0])} and ${p.length - 1} more` : p[0];
378
+ if (!p && kind === "edit") {
379
+ const files = patchFiles(firstOf(a, ["patch", "input", "_raw"]) || "").concat(Array.isArray(a.changes) ? a.changes.map((c) => c && c.path).filter(Boolean) : []);
380
+ if (files.length) p = files.length > 1 ? `${baseNameOf(files[0])} and ${files.length - 1} more` : files[0];
381
+ }
382
+ targetFull = str(p);
383
+ target = kind === "list" ? str(p) || "." : baseNameOf(p);
384
+ mono = !!target;
385
+ break;
386
+ }
387
+ case "search":
388
+ case "glob": {
389
+ const pat = firstOf(a, ["pattern", "query", "regex", "q", "glob", "search", "text"]);
390
+ const where = firstOf(a, ["path", "dir_path", "directory", "include"]);
391
+ target = str(pat);
392
+ mono = true;
393
+ targetFull = where ? `${str(pat)} in ${str(where)}` : str(pat);
394
+ break;
395
+ }
396
+ case "web_search":
397
+ target = str(firstOf(a, ["query", "q", "search_query", "queries", "search"]));
398
+ targetFull = target;
399
+ break;
400
+ case "web_fetch": {
401
+ const u = firstOf(a, ["url", "urls", "uri", "href", "link"]);
402
+ targetFull = Array.isArray(u) ? u.join(" ") : str(u);
403
+ target = Array.isArray(u) ? `${shortUrl(u[0])}${u.length > 1 ? ` and ${u.length - 1} more` : ""}` : shortUrl(u);
404
+ break;
405
+ }
406
+ case "agent":
407
+ target = str(firstOf(a, ["description", "task", "title", "name", "goal"])) || str(firstOf(a, ["prompt"])).slice(0, 80);
408
+ note = str(firstOf(a, ["subagent_type", "agent", "agent_type", "role"]));
409
+ targetFull = str(firstOf(a, ["prompt", "task", "description"]));
410
+ break;
411
+ case "skill":
412
+ target = str(firstOf(a, ["skill", "name", "command", "skill_name"]));
413
+ mono = true;
414
+ targetFull = target;
415
+ break;
416
+ case "browser": {
417
+ const act = str(firstOf(a, ["action", "command", "type"]));
418
+ const u = str(firstOf(a, ["url", "selector", "text"]));
419
+ target = [act, u ? shortUrl(u) : ""].filter(Boolean).join(" ");
420
+ targetFull = target;
421
+ if (/^browser[_\-.]/i.test(nm)) note = humanizeName(nm.replace(/^browser[_\-.]/i, ""));
422
+ break;
423
+ }
424
+ case "mcp":
425
+ case "tool": {
426
+ target = humanizeName(nm);
427
+ targetFull = nm;
428
+ break;
429
+ }
430
+ default:
431
+ break;
432
+ }
433
+ const v = VERBS[kind] || VERBS.tool;
434
+ return {
435
+ kind,
436
+ target: target.replace(/\s+/g, " ").trim(),
437
+ targetFull,
438
+ mono,
439
+ note,
440
+ running: v[0],
441
+ done: v[1],
442
+ diff: diffOf(kind, a),
443
+ todos: kind === "todo" ? todosOf(a) : null
444
+ };
445
+ }
446
+ function toolLine(d, state) {
447
+ const verb = state === "running" ? d.running : d.done;
448
+ if (d.kind === "todo" || d.kind === "toolsearch" || d.kind === "think") return verb;
449
+ if (d.kind === "shell" && d.target && !d.mono) return d.target;
450
+ if (d.kind === "mcp" || d.kind === "tool") return `${verb} ${d.target || "a tool"}`;
451
+ return d.target ? `${verb} ${d.target}` : `${verb} ${KIND_NOUN[d.kind] || "a tool"}`;
452
+ }
453
+ var KIND_NOUN = {
454
+ shell: "a command",
455
+ read: "a file",
456
+ write: "a file",
457
+ edit: "a file",
458
+ search: "code",
459
+ glob: "files",
460
+ list: "a folder",
461
+ web_search: "",
462
+ web_fetch: "a page",
463
+ agent: "",
464
+ skill: "a skill",
465
+ browser: "",
466
+ shell_output: "a command"
467
+ };
468
+ var PHRASES = {
469
+ shell: (n) => n === 1 ? "ran a command" : `ran ${n} commands`,
470
+ shell_output: (n) => n === 1 ? "checked a command" : `checked ${n} commands`,
471
+ read: (n) => n === 1 ? "read a file" : `read ${n} files`,
472
+ write: (n) => n === 1 ? "created a file" : `created ${n} files`,
473
+ edit: (n) => n === 1 ? "edited a file" : `edited ${n} files`,
474
+ search: (n) => n === 1 ? "searched code" : `searched code ${n} times`,
475
+ glob: () => "found files",
476
+ list: (n) => n === 1 ? "listed a folder" : `listed ${n} folders`,
477
+ web_search: (n) => n === 1 ? "searched the web" : `searched the web ${n} times`,
478
+ web_fetch: (n) => n === 1 ? "fetched a page" : `fetched ${n} pages`,
479
+ agent: (n) => n === 1 ? "ran an agent" : `ran ${n} agents`,
480
+ todo: () => "updated the plan",
481
+ skill: (n) => n === 1 ? "used a skill" : `used ${n} skills`,
482
+ think: () => "thought it through",
483
+ toolsearch: () => "loaded tools",
484
+ browser: () => "used the browser",
485
+ mcp: (n) => n === 1 ? "used a tool" : `used ${n} tools`,
486
+ tool: (n) => n === 1 ? "used a tool" : `used ${n} tools`
487
+ };
488
+ function summarizeCalls(calls) {
489
+ const list = (calls || []).filter(Boolean);
490
+ if (!list.length) return "";
491
+ if (list.length === 1) return toolLine(describeTool(list[0].name, list[0].args), "done");
492
+ const order = [];
493
+ const count = {};
494
+ for (const c of list) {
495
+ let k = toolKind(c.name);
496
+ if (k === "mcp") k = "tool";
497
+ if (!(k in count)) {
498
+ count[k] = 0;
499
+ order.push(k);
500
+ }
501
+ count[k]++;
502
+ }
503
+ const s = order.map((k) => (PHRASES[k] || PHRASES.tool)(count[k])).join(", ");
504
+ return s.charAt(0).toUpperCase() + s.slice(1);
505
+ }
506
+ function resultNote(kind, output) {
507
+ const out = str(output);
508
+ if (!out.trim()) return "";
509
+ const n = lineCount(out.trim());
510
+ if (kind === "read") return n === 1 ? "1 line" : `${n} lines`;
511
+ if (kind === "glob") return n === 1 ? "1 file" : `${n} files`;
512
+ if (kind === "search") return n === 1 ? "1 match" : `${n} matches`;
513
+ return "";
514
+ }
515
+
516
+ // src/agent-chat/turn.js
517
+ var TERMINAL = /* @__PURE__ */ new Set(["done", "failed", "cancelled", "incomplete"]);
518
+ function newTurn(opts = {}) {
519
+ return {
520
+ id: opts.id || null,
521
+ sessionId: opts.sessionId || null,
522
+ status: opts.status || "running",
523
+ user: opts.user ? { text: String(opts.user.text || ""), files: (opts.user.files || []).map((f) => ({ name: f.name, size: f.size, src: f.src })) } : null,
524
+ items: [],
525
+ files: [],
526
+ startedAt: opts.startedAt ?? null,
527
+ endedAt: null,
528
+ elapsedMs: null,
529
+ lastEventAt: null,
530
+ usage: null,
531
+ error: null,
532
+ incomplete: null,
533
+ model: opts.model || null,
534
+ _oi: {}
535
+ // output_index -> item id, to route deltas that name only their index
536
+ };
537
+ }
538
+ function isTerminal(status) {
539
+ return TERMINAL.has(status);
540
+ }
541
+ function mapStatus(s) {
542
+ const v = String(s || "").toLowerCase();
543
+ if (v === "completed" || v === "done" || v === "succeeded") return "done";
544
+ if (v === "cancelled" || v === "canceled") return "cancelled";
545
+ if (v === "incomplete" || v === "max_turns" || v === "timeout" || v === "max_steps") return "incomplete";
546
+ if (v === "failed" || v === "error") return "failed";
547
+ if (v === "running" || v === "in_progress" || v === "queued" || v === "starting") return "running";
548
+ return "done";
549
+ }
550
+ function findIdx(items, pred) {
551
+ for (let i = items.length - 1; i >= 0; i--) if (pred(items[i])) return i;
552
+ return -1;
553
+ }
554
+ function patchItem(turn, i, patch) {
555
+ const items = turn.items.slice();
556
+ items[i] = { ...items[i], ...patch };
557
+ return { ...turn, items };
558
+ }
559
+ function pushItem(turn, item, oi) {
560
+ const t = { ...turn, items: [...turn.items, item] };
561
+ if (oi !== void 0 && oi !== null) t._oi = { ...turn._oi, [oi]: item.id };
562
+ return t;
563
+ }
564
+ function isAgentTool(name) {
565
+ return toolKind(name) === "agent";
566
+ }
567
+ function settleOpenCalls(turn) {
568
+ let changed = false;
569
+ const items = turn.items.map((it) => {
570
+ if (it.kind === "tool" && it.status === "running" && !isAgentTool(it.name)) {
571
+ changed = true;
572
+ return { ...it, status: "done" };
573
+ }
574
+ return it;
575
+ });
576
+ return changed ? { ...turn, items } : turn;
577
+ }
578
+ function closeThinking(turn, at) {
579
+ const i = findIdx(turn.items, (x) => x.kind === "thinking" && x.endedAt == null && x.open);
580
+ if (i < 0) return turn;
581
+ return patchItem(turn, i, { open: false, endedAt: at ?? null });
582
+ }
583
+ function outputFailed(item) {
584
+ if (!item) return false;
585
+ if (item.is_error === true || item.isError === true) return true;
586
+ const s = String(item.status || "").toLowerCase();
587
+ return s === "failed" || s === "error" || s === "incomplete";
588
+ }
589
+ function textOf(v) {
590
+ return v == null ? "" : typeof v === "string" ? v : JSON.stringify(v);
591
+ }
592
+ function idOf(prefix, turn) {
593
+ return `${prefix}_${turn.items.length}`;
594
+ }
595
+ function reduceTurn(turn, ev, at = null) {
596
+ if (!ev || typeof ev !== "object") return turn;
597
+ let t = turn || newTurn();
598
+ const type = String(ev.type || "");
599
+ if (at != null) t = { ...t, lastEventAt: at };
600
+ switch (type) {
601
+ case "harness.turn.started": {
602
+ if (!t.user && ev.user_text) t = { ...t, user: { text: String(ev.user_text), files: [] } };
603
+ return t;
604
+ }
605
+ case "response.created":
606
+ case "response.in_progress":
607
+ case "response.queued": {
608
+ const r = ev.response || {};
609
+ return {
610
+ ...t,
611
+ id: r.id || t.id,
612
+ sessionId: r.metadata && r.metadata.session_id || t.sessionId,
613
+ model: r.model || t.model,
614
+ startedAt: t.startedAt ?? (at ?? (r.created_at ? r.created_at * 1e3 : null))
615
+ };
616
+ }
617
+ case "response.output_item.added":
618
+ case "response.output_item.done": {
619
+ const item = ev.item || {};
620
+ const added = type.endsWith(".added");
621
+ const oi = ev.output_index;
622
+ if (item.type === "reasoning") {
623
+ const i = findIdx(t.items, (x) => x.id === item.id);
624
+ const summary = Array.isArray(item.summary) ? item.summary.map((p) => p && p.text).filter(Boolean).join("\n\n") : "";
625
+ if (i < 0) {
626
+ t = settleOpenCalls(t);
627
+ t = pushItem(t, { kind: "thinking", id: item.id || idOf("rs", t), text: summary, startedAt: at, endedAt: added ? null : at, open: added }, oi);
628
+ return t;
629
+ }
630
+ if (!added) {
631
+ const cur = t.items[i];
632
+ return patchItem(t, i, { open: false, endedAt: cur.endedAt ?? at, text: cur.text || summary });
633
+ }
634
+ return t;
635
+ }
636
+ if (item.type === "message") {
637
+ const i = findIdx(t.items, (x) => x.id === item.id);
638
+ const full = Array.isArray(item.content) ? item.content.map((p) => p && (p.text || p.refusal) || "").join("") : "";
639
+ if (i < 0) {
640
+ t = closeThinking(settleOpenCalls(t), at);
641
+ const last = t.items[t.items.length - 1];
642
+ if (last && last.kind === "text" && !last.closed) {
643
+ t = { ...t, _oi: oi != null ? { ...t._oi, [oi]: last.id } : t._oi };
644
+ if (!added && full && !last.text) t = patchItem(t, t.items.length - 1, { text: full });
645
+ return t;
646
+ }
647
+ return pushItem(t, { kind: "text", id: item.id || idOf("msg", t), text: added ? "" : full }, oi);
648
+ }
649
+ if (!added && full && !t.items[i].text) return patchItem(t, i, { text: full });
650
+ return t;
651
+ }
652
+ if (item.type === "function_call" || item.type === "custom_tool_call" || item.type === "mcp_call") {
653
+ const callId = item.call_id || item.id || idOf("call", t);
654
+ const args = textOf(item.arguments ?? item.input ?? "");
655
+ const i = findIdx(t.items, (x) => x.kind === "tool" && (x.id === callId || x.itemId === item.id));
656
+ if (i >= 0) {
657
+ const cur = t.items[i];
658
+ const patch = {};
659
+ if (args && (!cur.args || cur.args === "{}")) patch.args = args;
660
+ if (item.name && (!cur.name || cur.name === "tool")) patch.name = item.name;
661
+ return Object.keys(patch).length ? patchItem(t, i, patch) : t;
662
+ }
663
+ t = closeThinking(t, at);
664
+ const lastText = findIdx(t.items, (x) => x.kind === "text");
665
+ if (lastText >= 0) t = patchItem(t, lastText, { closed: true });
666
+ return pushItem(t, {
667
+ kind: "tool",
668
+ id: callId,
669
+ itemId: item.id || null,
670
+ name: item.name || "tool",
671
+ args,
672
+ output: void 0,
673
+ status: "running",
674
+ startedAt: at,
675
+ endedAt: null
676
+ }, oi);
677
+ }
678
+ if (item.type === "function_call_output" || item.type === "custom_tool_call_output") {
679
+ const callId = item.call_id || "";
680
+ const i = findIdx(t.items, (x) => x.kind === "tool" && x.id === callId);
681
+ const failed = outputFailed(item);
682
+ const output = textOf(item.output);
683
+ if (i < 0) {
684
+ return pushItem(t, {
685
+ kind: "tool",
686
+ id: callId || idOf("out", t),
687
+ itemId: null,
688
+ name: "tool",
689
+ args: "",
690
+ output,
691
+ status: failed ? "failed" : "done",
692
+ startedAt: null,
693
+ endedAt: at
694
+ });
695
+ }
696
+ const cur = t.items[i];
697
+ if (cur.output !== void 0 && cur.status !== "running") return t;
698
+ return patchItem(t, i, { output, status: failed ? "failed" : "done", endedAt: at });
699
+ }
700
+ return t;
701
+ }
702
+ case "response.reasoning_summary_part.added":
703
+ return t;
704
+ case "response.reasoning_summary_text.delta":
705
+ case "response.reasoning_text.delta": {
706
+ const d = String(ev.delta || "");
707
+ let i = findIdx(t.items, (x) => x.kind === "thinking" && (x.id === ev.item_id || ev.output_index != null && t._oi[ev.output_index] === x.id));
708
+ if (i < 0) i = t.items.length && t.items[t.items.length - 1].kind === "thinking" ? t.items.length - 1 : -1;
709
+ if (i < 0) {
710
+ t = settleOpenCalls(t);
711
+ return pushItem(t, { kind: "thinking", id: ev.item_id || idOf("rs", t), text: d, startedAt: at, endedAt: null, open: true }, ev.output_index);
712
+ }
713
+ const cur = t.items[i];
714
+ return patchItem(t, i, { text: cur.text + d });
715
+ }
716
+ case "response.reasoning_summary_part.done":
717
+ return t;
718
+ case "response.output_text.delta": {
719
+ const d = String(ev.delta || "");
720
+ if (!d) return t;
721
+ let i = findIdx(t.items, (x) => x.kind === "text" && (x.id === ev.item_id || ev.output_index != null && t._oi[ev.output_index] === x.id));
722
+ if (i < 0 && t.items.length && t.items[t.items.length - 1].kind === "text" && !t.items[t.items.length - 1].closed) i = t.items.length - 1;
723
+ if (i < 0) {
724
+ t = closeThinking(settleOpenCalls(t), at);
725
+ return pushItem(t, { kind: "text", id: ev.item_id || idOf("msg", t), text: d }, ev.output_index);
726
+ }
727
+ if (i !== t.items.length - 1) {
728
+ t = closeThinking(settleOpenCalls(t), at);
729
+ }
730
+ return patchItem(t, i, { text: t.items[i].text + d });
731
+ }
732
+ case "response.output_text.done": {
733
+ const i = findIdx(t.items, (x) => x.kind === "text" && x.id === ev.item_id);
734
+ if (i >= 0 && !t.items[i].text && ev.text) return patchItem(t, i, { text: String(ev.text) });
735
+ return t;
736
+ }
737
+ case "response.function_call_arguments.delta": {
738
+ const i = findIdx(t.items, (x) => x.kind === "tool" && (x.itemId === ev.item_id || ev.output_index != null && t._oi[ev.output_index] === x.id));
739
+ if (i < 0) return t;
740
+ return patchItem(t, i, { args: (t.items[i].args || "") + String(ev.delta || "") });
741
+ }
742
+ case "response.function_call_arguments.done": {
743
+ const i = findIdx(t.items, (x) => x.kind === "tool" && (x.itemId === ev.item_id || ev.output_index != null && t._oi[ev.output_index] === x.id));
744
+ if (i < 0) return t;
745
+ return patchItem(t, i, { args: String(ev.arguments ?? t.items[i].args ?? "") });
746
+ }
747
+ case "response.output_text.annotation.added": {
748
+ const a = ev.annotation || {};
749
+ if (a.type !== "container_file_citation") return t;
750
+ const same = (f) => a.file_id ? f.file_id === a.file_id && f.container_id === a.container_id : f.filename === a.filename;
751
+ if (t.files.some(same)) return t;
752
+ return { ...t, files: [...t.files, {
753
+ container_id: a.container_id,
754
+ file_id: a.file_id,
755
+ filename: a.filename,
756
+ ...a.download_url ? { download_url: a.download_url } : {}
757
+ }] };
758
+ }
759
+ case "response.completed":
760
+ case "response.incomplete":
761
+ case "response.failed":
762
+ case "response.cancelled": {
763
+ const r = ev.response || {};
764
+ let status = type === "response.completed" ? "done" : type === "response.incomplete" ? "incomplete" : type === "response.cancelled" ? "cancelled" : mapStatus(r.status || "failed");
765
+ if (type === "response.failed" && (ev.reason === "cancelled" || r.status === "cancelled")) status = "cancelled";
766
+ if (type === "response.failed" && status === "done") status = "failed";
767
+ return finish(t, status, at, r);
768
+ }
769
+ case "error": {
770
+ const msg = String(ev.message || ev.error && ev.error.message || "").trim();
771
+ return msg ? { ...t, error: msg } : t;
772
+ }
773
+ default:
774
+ return t;
775
+ }
776
+ }
777
+ function finish(turn, status, at = null, response = null) {
778
+ const r = response || {};
779
+ const st = isTerminal(status) ? status : mapStatus(status);
780
+ const items = turn.items.map((it) => {
781
+ if (it.kind === "tool" && it.status === "running") return { ...it, status: st === "done" ? "done" : "stopped" };
782
+ if (it.kind === "thinking" && it.open) return { ...it, open: false, endedAt: it.endedAt ?? at };
783
+ return it;
784
+ });
785
+ const inc = r.incomplete_details;
786
+ const err = r.error && (r.error.message || r.error.code);
787
+ return {
788
+ ...turn,
789
+ items,
790
+ status: st,
791
+ endedAt: turn.endedAt ?? at,
792
+ id: r.id || turn.id,
793
+ usage: r.usage || turn.usage,
794
+ model: r.served_model || r.model || turn.model,
795
+ error: turn.error || (st === "failed" && err ? String(err) : turn.error),
796
+ incomplete: st === "incomplete" && inc ? { reason: inc.reason || "", detail: inc.detail || "" } : turn.incomplete
797
+ };
798
+ }
799
+ function turnFromEvents(events, opts = {}) {
800
+ let t = newTurn(opts);
801
+ for (const ev of events || []) t = reduceTurn(t, ev, opts.at ?? null);
802
+ return t;
803
+ }
804
+ function turnFromResponse(resp, opts = {}) {
805
+ const r = resp || {};
806
+ let t = newTurn({ ...opts, id: r.id, model: r.model });
807
+ const events = [];
808
+ (r.output || []).forEach((item, i) => events.push({ type: "response.output_item.done", output_index: i, item }));
809
+ for (const ev of events) t = reduceTurn(t, ev, null);
810
+ const st = mapStatus(r.status);
811
+ if (st === "running") return { ...t, status: "running" };
812
+ const created = r.created_at ? r.created_at * 1e3 : null;
813
+ t = finish(t, st, null, r);
814
+ return { ...t, startedAt: opts.startedAt ?? created, endedAt: opts.endedAt ?? null };
815
+ }
816
+ function turnFromHistory(h) {
817
+ const x = h || {};
818
+ let t = newTurn({ id: x.id, user: x.user || (x.user_files || []).length ? { text: x.user || "", files: x.user_files || [] } : null });
819
+ const items = [];
820
+ (x.tools || []).forEach((c, i) => {
821
+ const out = c.output ?? c.result;
822
+ items.push({
823
+ kind: "tool",
824
+ id: c.call_id || `call_${i}`,
825
+ itemId: null,
826
+ name: c.name || "tool",
827
+ args: textOf(c.arguments ?? ""),
828
+ output: out == null ? void 0 : String(out),
829
+ status: c.is_error ? "failed" : "done",
830
+ startedAt: null,
831
+ endedAt: null,
832
+ truncated: c.output_truncated || null
833
+ });
834
+ });
835
+ if (x.assistant) items.push({ kind: "text", id: `msg_${items.length}`, text: String(x.assistant) });
836
+ const status = mapStatus(x.status);
837
+ t = {
838
+ ...t,
839
+ items,
840
+ files: (x.files || []).slice(),
841
+ status,
842
+ model: x.served_model || x._model || null,
843
+ elapsedMs: typeof x.elapsed === "number" ? Math.round(x.elapsed * 1e3) : null,
844
+ error: x.error || null,
845
+ incomplete: status === "incomplete" && (x.incomplete_reason || x.incomplete_detail) ? { reason: x.incomplete_reason || "", detail: x.incomplete_detail || "" } : null
846
+ };
847
+ if (status === "running") {
848
+ t.items = t.items.map((it) => it.kind === "tool" && it.output === void 0 ? { ...it, status: "running" } : it);
849
+ }
850
+ return t;
851
+ }
852
+ function turnFromMessage(msg, clock = null, user = null) {
853
+ const m = msg || {};
854
+ const status = m.status ? mapStatus(m.status) : "done";
855
+ const byCall = {};
856
+ const thinkingClocks = [];
857
+ if (clock) {
858
+ for (const it of clock.items) {
859
+ if (it.kind === "tool") byCall[it.id] = it;
860
+ else if (it.kind === "thinking") thinkingClocks.push(it);
861
+ }
862
+ }
863
+ const items = [];
864
+ let errText = "";
865
+ let thinkN = 0;
866
+ (m.blocks || []).forEach((b, bi) => {
867
+ if (b.kind === "text") {
868
+ if (b.error) {
869
+ errText = String(b.text || "").replace(/^\s*Error:\s*/, "").trim();
870
+ return;
871
+ }
872
+ if (b.text) items.push({ kind: "text", id: `msg_${bi}`, text: b.text });
873
+ return;
874
+ }
875
+ if (b.kind === "tools") {
876
+ if (b.reasoning) {
877
+ const c = thinkingClocks[thinkN++];
878
+ items.push({
879
+ kind: "thinking",
880
+ id: `rs_${bi}`,
881
+ text: b.reasoning,
882
+ startedAt: c ? c.startedAt : null,
883
+ endedAt: c ? c.endedAt : null,
884
+ open: c ? !!c.open : false
885
+ });
886
+ }
887
+ (b.steps || []).forEach((s, si) => {
888
+ const c = s.callId ? byCall[s.callId] : null;
889
+ const answered = s.result !== void 0;
890
+ let st = c ? c.status : answered ? "done" : status === "running" ? "running" : status === "done" ? "done" : "stopped";
891
+ if (answered && st === "running") st = "done";
892
+ if (st === "running" && status !== "running") st = status === "done" ? "done" : "stopped";
893
+ items.push({
894
+ kind: "tool",
895
+ id: s.callId || `call_${bi}_${si}`,
896
+ itemId: null,
897
+ name: s.name || "tool",
898
+ args: textOf(s.args ?? ""),
899
+ output: answered ? String(s.result) : c ? c.output : void 0,
900
+ status: st,
901
+ startedAt: c ? c.startedAt : null,
902
+ endedAt: c ? c.endedAt : null
903
+ });
904
+ });
905
+ }
906
+ });
907
+ let t = {
908
+ ...newTurn({ user: user || null }),
909
+ id: clock && clock.id || m.id || null,
910
+ status,
911
+ items,
912
+ files: (m.files || []).slice(),
913
+ startedAt: clock ? clock.startedAt : null,
914
+ endedAt: clock ? clock.endedAt : null,
915
+ lastEventAt: clock ? clock.lastEventAt : null,
916
+ usage: clock ? clock.usage : null,
917
+ model: clock && clock.model || null,
918
+ error: errText || clock && clock.error || null,
919
+ elapsedMs: typeof m.elapsed === "number" ? Math.round(m.elapsed * 1e3) : null,
920
+ incomplete: status === "incomplete" && (m.incompleteReason || m.incompleteDetail) ? { reason: m.incompleteReason || "", detail: m.incompleteDetail || "" } : null
921
+ };
922
+ if (status === "running") {
923
+ let lastSpeech = -1;
924
+ t.items.forEach((it, i) => {
925
+ if (it.kind === "text" || it.kind === "thinking") lastSpeech = i;
926
+ });
927
+ t.items = t.items.map((it, i) => it.kind === "tool" && it.status === "running" && i < lastSpeech && !isAgentTool(it.name) ? { ...it, status: "done" } : it);
928
+ }
929
+ return t;
930
+ }
931
+ function liveState(turn) {
932
+ if (!turn || turn.status !== "running") return null;
933
+ const items = turn.items || [];
934
+ for (let i = items.length - 1; i >= 0; i--) {
935
+ const it = items[i];
936
+ if (it.kind === "tool" && it.status === "running") return { phase: "tool", tool: it };
937
+ if (it.kind === "text" || it.kind === "thinking") break;
938
+ }
939
+ const last = items[items.length - 1];
940
+ if (!last) return { phase: turn.id ? "thinking" : "starting", tool: null };
941
+ if (last.kind === "thinking") return { phase: "thinking", tool: null };
942
+ if (last.kind === "text" && !last.closed) return { phase: "writing", tool: null };
943
+ return { phase: "thinking", tool: null };
944
+ }
945
+ function segments(turn) {
946
+ const out = [];
947
+ for (const it of turn && turn.items || []) {
948
+ if (it.kind === "text") {
949
+ if (!it.text) continue;
950
+ out.push({ type: "text", item: it });
951
+ } else {
952
+ const last = out[out.length - 1];
953
+ if (last && last.type === "work") last.items.push(it);
954
+ else out.push({ type: "work", items: [it] });
955
+ }
956
+ }
957
+ return out;
958
+ }
959
+ function latestPlan(turn, describe) {
960
+ const items = turn && turn.items || [];
961
+ for (let i = items.length - 1; i >= 0; i--) {
962
+ const it = items[i];
963
+ if (it.kind !== "tool" || toolKind(it.name) !== "todo") continue;
964
+ const d = describe(it.name, it.args);
965
+ if (d.todos && d.todos.length) return d.todos;
966
+ }
967
+ return null;
968
+ }
969
+
970
+ // src/agent-chat/time.js
971
+ import { useEffect, useState } from "react";
972
+ function formatElapsed(ms) {
973
+ if (ms == null || !isFinite(ms) || ms < 0) return "";
974
+ const s = Math.floor(ms / 1e3);
975
+ if (s < 60) return `${s}s`;
976
+ const m = Math.floor(s / 60);
977
+ if (m < 60) return `${m}m ${s % 60}s`;
978
+ const h = Math.floor(m / 60);
979
+ return `${h}h ${m % 60}m`;
980
+ }
981
+ function formatDuration(ms) {
982
+ if (ms == null || !isFinite(ms) || ms < 0) return "";
983
+ if (ms < 1e3) return `${Math.max(0.1, Math.round(ms / 100) / 10).toFixed(1)}s`;
984
+ if (ms < 1e4) return `${(Math.round(ms / 100) / 10).toFixed(1)}s`;
985
+ return formatElapsed(ms);
986
+ }
987
+ function formatTokens(n) {
988
+ if (n == null || !isFinite(n)) return "";
989
+ if (n < 1e3) return String(Math.round(n));
990
+ if (n < 1e6) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
991
+ return `${(Math.round(n / 1e5) / 10).toFixed(1).replace(/\.0$/, "")}M`;
992
+ }
993
+ function useNow(on, everyMs = 1e3) {
994
+ const [now, setNow] = useState(() => Date.now());
995
+ useEffect(() => {
996
+ if (!on) return void 0;
997
+ setNow(Date.now());
998
+ let iv = null;
999
+ const t0 = setTimeout(() => {
1000
+ setNow(Date.now());
1001
+ iv = setInterval(() => setNow(Date.now()), everyMs);
1002
+ }, everyMs - Date.now() % everyMs);
1003
+ return () => {
1004
+ clearTimeout(t0);
1005
+ if (iv) clearInterval(iv);
1006
+ };
1007
+ }, [on, everyMs]);
1008
+ return now;
1009
+ }
1010
+ function useElapsed(start, end = null) {
1011
+ const live = start != null && end == null;
1012
+ const now = useNow(live);
1013
+ if (start == null) return null;
1014
+ return Math.max(0, (end ?? now) - start);
1015
+ }
1016
+
1017
+ // src/agent-chat/marks.js
1018
+ var MARK_MOTIONS = {
1019
+ "claude-code": "bloom",
1020
+ claude: "bloom",
1021
+ anthropic: "bloom",
1022
+ codex: "sheen",
1023
+ openai: "sheen",
1024
+ gemini: "glint",
1025
+ "gemini-cli": "glint",
1026
+ hermes: "flutter",
1027
+ goose: "glide",
1028
+ opencode: "blink",
1029
+ pi: "flip",
1030
+ omp: "flip",
1031
+ dsh: "swim",
1032
+ deepseek: "swim",
1033
+ qwen: "spin",
1034
+ grok: "spin",
1035
+ systemone: "spin",
1036
+ opensquilla: "spin",
1037
+ openhands: "wave",
1038
+ cheetahclaws: "dash",
1039
+ zeroclaw: "scuttle",
1040
+ minimax: "equalize",
1041
+ cline: "bob",
1042
+ agentzero: "bob",
1043
+ qoder: "bob",
1044
+ nanobot: "bob",
1045
+ kimi: "sheen",
1046
+ kilo: "sheen",
1047
+ jcode: "pulse",
1048
+ mimo: "pulse",
1049
+ aider: "pulse"
1050
+ };
1051
+ var MOTIONS = [
1052
+ "bloom",
1053
+ "sheen",
1054
+ "glint",
1055
+ "flutter",
1056
+ "glide",
1057
+ "blink",
1058
+ "flip",
1059
+ "swim",
1060
+ "spin",
1061
+ "wave",
1062
+ "dash",
1063
+ "scuttle",
1064
+ "equalize",
1065
+ "bob",
1066
+ "pulse",
1067
+ "dots"
1068
+ ];
1069
+ function motionFor(base) {
1070
+ const k = String(base || "").toLowerCase().trim();
1071
+ return MARK_MOTIONS[k] || "pulse";
1072
+ }
1073
+
1074
+ // src/agent-chat/components.jsx
1075
+ import React, { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef, useState as useState2 } from "react";
1076
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1077
+ var DEFAULT_AGENT_LABELS = {
1078
+ starting: "Starting",
1079
+ thinking: "Thinking",
1080
+ writing: "Writing",
1081
+ tool: "Running a tool",
1082
+ thought: "Thought",
1083
+ thoughtFor: (t) => `Thought for ${t}`,
1084
+ workedFor: (t) => `Worked for ${t}`,
1085
+ worked: "Done",
1086
+ tokens: (n) => `${n} tokens`,
1087
+ stopped: "Stopped",
1088
+ stoppedAfter: (t) => `Stopped after ${t}`,
1089
+ failed: "Failed",
1090
+ failedAfter: (t) => `Failed after ${t}`,
1091
+ incomplete: "Stopped before finishing",
1092
+ input: "Input",
1093
+ output: "Output",
1094
+ noOutput: "No output",
1095
+ copy: "Copy",
1096
+ copied: "Copied",
1097
+ copyFailed: "Select and copy",
1098
+ moreLines: (n) => n === 1 ? "+1 line" : `+${n} lines`,
1099
+ fewerLines: "Show less",
1100
+ failedCalls: (n) => n === 1 ? "1 failed" : `${n} failed`,
1101
+ stoppedCall: "stopped",
1102
+ plan: "Plan",
1103
+ jump: "Jump to latest",
1104
+ send: "Send",
1105
+ stop: "Stop",
1106
+ stopping: "Stopping",
1107
+ attach: "Attach a file",
1108
+ remove: (name) => `Remove ${name}`,
1109
+ working: "Working"
1110
+ };
1111
+ var ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g;
1112
+ function cleanOutput(s) {
1113
+ return String(s ?? "").replace(ANSI, "").replace(/\r\n?/g, "\n");
1114
+ }
1115
+ function pretty(s) {
1116
+ const x = String(s || "").trim();
1117
+ if (!/^[[{]/.test(x)) return null;
1118
+ try {
1119
+ return JSON.stringify(JSON.parse(x), null, 2);
1120
+ } catch {
1121
+ return null;
1122
+ }
1123
+ }
1124
+ function firstLine(s, max = 220) {
1125
+ const l = cleanOutput(s).split("\n").map((x) => x.trim()).find(Boolean) || "";
1126
+ return l.length > max ? `${l.slice(0, max)}\u2026` : l;
1127
+ }
1128
+ function cls(...xs) {
1129
+ return xs.filter(Boolean).join(" ");
1130
+ }
1131
+ function WorkingMark(props) {
1132
+ const { mark, motion, size = 18, still = false } = props;
1133
+ const m = mark ? motion || "pulse" : "dots";
1134
+ return /* @__PURE__ */ jsxs("span", { className: cls("uac-mark", still && "is-still"), "data-motion": m, style: { "--uac-mark": `${size}px` }, "aria-hidden": "true", children: [
1135
+ /* @__PURE__ */ jsx("span", { className: "uac-mark-aura" }),
1136
+ /* @__PURE__ */ jsx("span", { className: "uac-mark-in", children: mark || /* @__PURE__ */ jsxs(Fragment, { children: [
1137
+ /* @__PURE__ */ jsx("i", {}),
1138
+ /* @__PURE__ */ jsx("i", {}),
1139
+ /* @__PURE__ */ jsx("i", {})
1140
+ ] }) })
1141
+ ] });
1142
+ }
1143
+ function WorkingIndicator(props) {
1144
+ const { mark, motion, start = null, end = null, label, onToggle, expanded, controls, className, shimmer = true, size } = props;
1145
+ const ms = useElapsed(start, end);
1146
+ const body = /* @__PURE__ */ jsxs(Fragment, { children: [
1147
+ /* @__PURE__ */ jsx(WorkingMark, { mark, motion, size }),
1148
+ ms != null ? /* @__PURE__ */ jsx("span", { className: "uac-elapsed", "aria-hidden": "true", children: formatElapsed(ms) }) : null,
1149
+ ms != null ? /* @__PURE__ */ jsx("span", { className: "uac-sep", "aria-hidden": "true", children: "\xB7" }) : null,
1150
+ /* @__PURE__ */ jsx("span", { className: cls("uac-verb", shimmer && "uac-shimmer"), "data-text": label, children: label }),
1151
+ onToggle ? /* @__PURE__ */ jsx("span", { className: "uac-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsx(Chevron, { dir: expanded ? "down" : "right", size: 12 }) }) : null
1152
+ ] });
1153
+ if (onToggle) {
1154
+ return /* @__PURE__ */ jsxs(
1155
+ "button",
1156
+ {
1157
+ type: "button",
1158
+ className: cls("uac-working", "is-button", className),
1159
+ "aria-expanded": !!expanded,
1160
+ "aria-controls": controls,
1161
+ onClick: onToggle,
1162
+ children: [
1163
+ /* @__PURE__ */ jsx("span", { className: "uac-sr", role: "status", children: label }),
1164
+ body
1165
+ ]
1166
+ }
1167
+ );
1168
+ }
1169
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-working", className), children: [
1170
+ /* @__PURE__ */ jsx("span", { className: "uac-sr", role: "status", children: label }),
1171
+ body
1172
+ ] });
1173
+ }
1174
+ function CopyButton(props) {
1175
+ const { text, labels = DEFAULT_AGENT_LABELS, label } = props;
1176
+ const [state, setState] = useState2("");
1177
+ useEffect2(() => {
1178
+ if (!state) return void 0;
1179
+ const t = setTimeout(() => setState(""), 1600);
1180
+ return () => clearTimeout(t);
1181
+ }, [state]);
1182
+ const copy = async (e) => {
1183
+ e.stopPropagation();
1184
+ try {
1185
+ await navigator.clipboard.writeText(String(text ?? ""));
1186
+ setState("ok");
1187
+ } catch {
1188
+ setState("no");
1189
+ }
1190
+ };
1191
+ const said = state === "ok" ? labels.copied : state === "no" ? labels.copyFailed : label || labels.copy;
1192
+ return /* @__PURE__ */ jsxs("button", { type: "button", className: cls("uac-copy", state && `is-${state}`), onClick: copy, "aria-label": label ? `${labels.copy} ${label}` : labels.copy, children: [
1193
+ /* @__PURE__ */ jsx("svg", { width: "13", height: "13", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.9", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: state === "ok" ? /* @__PURE__ */ jsx("path", { d: "M5 12l5 5L20 7" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1194
+ /* @__PURE__ */ jsx("rect", { x: "9", y: "9", width: "11", height: "11", rx: "2" }),
1195
+ /* @__PURE__ */ jsx("path", { d: "M5 15V6a2 2 0 0 1 2-2h9" })
1196
+ ] }) }),
1197
+ /* @__PURE__ */ jsx("span", { children: said })
1198
+ ] });
1199
+ }
1200
+ function DiffBadge(props) {
1201
+ const { diff } = props;
1202
+ if (!diff || !diff.added && !diff.removed && diff.added !== 0) return null;
1203
+ return /* @__PURE__ */ jsxs("span", { className: "uac-diff", "aria-label": `${diff.added} lines added, ${diff.removed} removed`, children: [
1204
+ /* @__PURE__ */ jsxs("span", { className: "uac-add", children: [
1205
+ "+",
1206
+ diff.added
1207
+ ] }),
1208
+ /* @__PURE__ */ jsxs("span", { className: "uac-del", children: [
1209
+ "\u2212",
1210
+ diff.removed
1211
+ ] })
1212
+ ] });
1213
+ }
1214
+ function LinesBlock(props) {
1215
+ const { lines, limit = 12, labels = DEFAULT_AGENT_LABELS, className, numbered = false } = props;
1216
+ const [all, setAll] = useState2(false);
1217
+ const more = Math.max(0, lines.length - limit);
1218
+ const shown = all || !more ? lines : lines.slice(0, limit);
1219
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-lines", className), children: [
1220
+ /* @__PURE__ */ jsx("pre", { children: shown.map((l, i) => /* @__PURE__ */ jsxs("span", { className: cls("uac-ln", l.cls), children: [
1221
+ numbered ? /* @__PURE__ */ jsx("span", { className: "uac-lno", children: i + 1 }) : null,
1222
+ l.text || " "
1223
+ ] }, i)) }),
1224
+ more ? /* @__PURE__ */ jsx("button", { type: "button", className: "uac-more", onClick: (e) => {
1225
+ e.stopPropagation();
1226
+ setAll((v) => !v);
1227
+ }, "aria-expanded": all, children: all ? labels.fewerLines : labels.moreLines(more) }) : null
1228
+ ] });
1229
+ }
1230
+ var asLines = (text, c) => String(text ?? "").replace(/\n$/, "").split("\n").map((t) => ({ text: t, cls: c }));
1231
+ var KIND_ICON = {
1232
+ shell: IcTerminal,
1233
+ shell_output: IcTerminal,
1234
+ read: IcScroll,
1235
+ write: IcDoc,
1236
+ edit: IcDoc,
1237
+ search: IcSearch,
1238
+ glob: IcSearch,
1239
+ list: IcList,
1240
+ web_search: IcGlobe,
1241
+ web_fetch: IcGlobe,
1242
+ agent: IcSpawn,
1243
+ todo: IcList,
1244
+ skill: IcSkill,
1245
+ think: IcThink,
1246
+ toolsearch: IcSearch,
1247
+ browser: IcGlobe,
1248
+ mcp: IcPlug,
1249
+ tool: IcTool
1250
+ };
1251
+ function StatusGlyph(props) {
1252
+ const { status, kind } = props;
1253
+ if (status === "running") return /* @__PURE__ */ jsx("span", { className: "uac-ring", "aria-hidden": "true" });
1254
+ if (status === "failed") return /* @__PURE__ */ jsx("span", { className: "uac-x", "aria-hidden": "true", children: /* @__PURE__ */ jsx(IcX, { size: 13 }) });
1255
+ if (status === "stopped") return /* @__PURE__ */ jsx("span", { className: "uac-stopped", "aria-hidden": "true" });
1256
+ const Ic = KIND_ICON[kind] || IcTool;
1257
+ return /* @__PURE__ */ jsx("span", { className: "uac-kind", "aria-hidden": "true", children: /* @__PURE__ */ jsx(Ic, {}) });
1258
+ }
1259
+ function inputLines(d, item) {
1260
+ const a = parseToolArgs(item.args);
1261
+ if (d.kind === "shell") {
1262
+ const cmd = d.mono ? d.target : d.note || d.targetFull;
1263
+ const out = asLines(`$ ${cmd || ""}`, "is-cmd");
1264
+ if (!d.mono && d.target) out.unshift({ text: d.target, cls: "is-note" });
1265
+ return { lines: out, copy: cmd };
1266
+ }
1267
+ if ((d.kind === "edit" || d.kind === "write") && d.diff) {
1268
+ const lines = [];
1269
+ const path = d.targetFull;
1270
+ if (path) lines.push({ text: path, cls: "is-path" });
1271
+ const edits = Array.isArray(a.edits) ? a.edits : [a];
1272
+ for (const e of edits) {
1273
+ const old = e.old_string ?? e.old_str ?? e.oldText ?? e.old_text;
1274
+ const neu = e.new_string ?? e.new_str ?? e.newText ?? e.new_text ?? e.content ?? e.file_text ?? e.contents;
1275
+ if (old != null && String(old)) lines.push(...asLines(old, "is-del").map((l) => ({ ...l, text: `- ${l.text}` })));
1276
+ if (neu != null && String(neu)) lines.push(...asLines(neu, "is-add").map((l) => ({ ...l, text: `+ ${l.text}` })));
1277
+ }
1278
+ const patch = a.patch ?? a.input ?? a._raw ?? a.diff;
1279
+ if (lines.length <= (path ? 1 : 0) && typeof patch === "string") {
1280
+ for (const l of patch.split("\n")) lines.push({ text: l, cls: /^\+(?!\+\+)/.test(l) ? "is-add" : /^-(?!--)/.test(l) ? "is-del" : "" });
1281
+ }
1282
+ if (lines.length > (path ? 1 : 0)) return { lines, copy: typeof item.args === "string" ? item.args : JSON.stringify(a, null, 2) };
1283
+ }
1284
+ if (a._raw != null) return { lines: asLines(a._raw), copy: a._raw };
1285
+ const keys = Object.keys(a);
1286
+ const flat = keys.length && keys.every((k) => a[k] == null || typeof a[k] !== "object");
1287
+ if (flat) {
1288
+ const lines = [];
1289
+ for (const k of keys) {
1290
+ const v = a[k] == null ? "" : String(a[k]);
1291
+ const vs = v.split("\n");
1292
+ lines.push({ text: `${k}: ${vs[0]}`, cls: "is-kv" });
1293
+ for (const more of vs.slice(1)) lines.push({ text: ` ${more}`, cls: "is-kv" });
1294
+ }
1295
+ return { lines, copy: typeof item.args === "string" ? item.args : JSON.stringify(a, null, 2) };
1296
+ }
1297
+ const js = keys.length ? JSON.stringify(a, null, 2) : "";
1298
+ return { lines: js ? asLines(js) : [], copy: js };
1299
+ }
1300
+ function StepDetail(props) {
1301
+ const { item, d, labels, id } = props;
1302
+ const input = inputLines(d, item);
1303
+ const out = item.output === void 0 ? null : cleanOutput(item.output);
1304
+ const outPretty = out != null ? pretty(out) || out : null;
1305
+ return /* @__PURE__ */ jsxs("div", { className: "uac-detail", id, children: [
1306
+ input.lines.length ? /* @__PURE__ */ jsxs("section", { className: "uac-sec", children: [
1307
+ /* @__PURE__ */ jsxs("header", { children: [
1308
+ /* @__PURE__ */ jsx("span", { children: labels.input }),
1309
+ /* @__PURE__ */ jsx(CopyButton, { text: input.copy, labels })
1310
+ ] }),
1311
+ /* @__PURE__ */ jsx(LinesBlock, { lines: input.lines, limit: d.kind === "write" || d.kind === "edit" ? 24 : 12, labels })
1312
+ ] }) : null,
1313
+ outPretty != null ? /* @__PURE__ */ jsxs("section", { className: cls("uac-sec", item.status === "failed" && "is-failed"), children: [
1314
+ /* @__PURE__ */ jsxs("header", { children: [
1315
+ /* @__PURE__ */ jsx("span", { children: labels.output }),
1316
+ outPretty ? /* @__PURE__ */ jsx(CopyButton, { text: outPretty, labels }) : null
1317
+ ] }),
1318
+ outPretty.trim() ? /* @__PURE__ */ jsx(LinesBlock, { lines: asLines(outPretty), labels }) : /* @__PURE__ */ jsx("p", { className: "uac-none", children: labels.noOutput }),
1319
+ item.truncated ? /* @__PURE__ */ jsx("p", { className: "uac-none", children: `${item.truncated} characters in all` }) : null
1320
+ ] }) : null
1321
+ ] });
1322
+ }
1323
+ function StepRow(props) {
1324
+ const { item, labels = DEFAULT_AGENT_LABELS, defaultOpen = false } = props;
1325
+ const d = useMemo(() => describeTool(item.name, item.args), [item.name, item.args]);
1326
+ const [open, setOpen] = useState2(defaultOpen);
1327
+ const uid = useRef(`uac-s-${Math.random().toString(36).slice(2, 9)}`).current;
1328
+ const running = item.status === "running";
1329
+ const runMs = useElapsed(running ? item.startedAt : null, null);
1330
+ const tookMs = !running && item.startedAt != null && item.endedAt != null ? item.endedAt - item.startedAt : null;
1331
+ const line = toolLine(d, running ? "running" : "done");
1332
+ const verb = running ? d.running : d.done;
1333
+ const hasTarget = d.target && line === `${verb} ${d.target}`;
1334
+ const note = !running && item.status !== "failed" ? resultNote(d.kind, item.output) : "";
1335
+ const hasDetail = !!(item.args && item.args !== "{}" && item.args !== '""') || item.output !== void 0;
1336
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-step", `is-${item.status}`), "data-kind": d.kind, children: [
1337
+ /* @__PURE__ */ jsxs(
1338
+ "button",
1339
+ {
1340
+ type: "button",
1341
+ className: "uac-step-h",
1342
+ "aria-expanded": hasDetail ? open : void 0,
1343
+ "aria-controls": hasDetail ? uid : void 0,
1344
+ disabled: !hasDetail,
1345
+ onClick: () => setOpen((v) => !v),
1346
+ title: d.targetFull || void 0,
1347
+ children: [
1348
+ /* @__PURE__ */ jsx(StatusGlyph, { status: item.status, kind: d.kind }),
1349
+ /* @__PURE__ */ jsxs("span", { className: "uac-step-t", children: [
1350
+ hasTarget ? /* @__PURE__ */ jsxs(Fragment, { children: [
1351
+ /* @__PURE__ */ jsx("span", { className: "uac-step-v", children: verb }),
1352
+ " ",
1353
+ /* @__PURE__ */ jsx("span", { className: cls("uac-step-o", d.mono && "is-mono"), children: d.target })
1354
+ ] }) : /* @__PURE__ */ jsx("span", { className: cls("uac-step-o", d.kind === "shell" && d.mono && "is-mono"), children: line }),
1355
+ d.note && d.kind === "agent" ? /* @__PURE__ */ jsx("span", { className: "uac-step-n", children: d.note }) : null
1356
+ ] }),
1357
+ /* @__PURE__ */ jsx(DiffBadge, { diff: item.status === "failed" ? null : d.diff }),
1358
+ note ? /* @__PURE__ */ jsx("span", { className: "uac-step-n", children: note }) : null,
1359
+ item.status === "stopped" ? /* @__PURE__ */ jsx("span", { className: "uac-step-n", children: labels.stoppedCall }) : null,
1360
+ running && runMs != null ? /* @__PURE__ */ jsx("span", { className: "uac-step-time", children: formatElapsed(runMs) }) : tookMs != null && tookMs >= 1e3 ? /* @__PURE__ */ jsx("span", { className: "uac-step-time", children: formatDuration(tookMs) }) : null,
1361
+ hasDetail ? /* @__PURE__ */ jsx("span", { className: "uac-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsx(Chevron, { dir: open ? "down" : "right", size: 12 }) }) : null
1362
+ ]
1363
+ }
1364
+ ),
1365
+ item.status === "failed" && item.output ? /* @__PURE__ */ jsx("div", { className: "uac-step-err", children: firstLine(item.output) }) : null,
1366
+ open && hasDetail ? /* @__PURE__ */ jsx(StepDetail, { item, d, labels, id: uid }) : null
1367
+ ] });
1368
+ }
1369
+ function ThinkingRow(props) {
1370
+ const { item, labels = DEFAULT_AGENT_LABELS } = props;
1371
+ const [open, setOpen] = useState2(false);
1372
+ const uid = useRef(`uac-t-${Math.random().toString(36).slice(2, 9)}`).current;
1373
+ const live = item.open && item.endedAt == null;
1374
+ const ms = !live && item.startedAt != null && item.endedAt != null ? item.endedAt - item.startedAt : null;
1375
+ const label = live ? labels.thinking : ms != null && ms >= 1e3 ? labels.thoughtFor(formatElapsed(ms)) : labels.thought;
1376
+ const has = !!String(item.text || "").trim();
1377
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-step", "is-thought", live && "is-running"), children: [
1378
+ /* @__PURE__ */ jsxs(
1379
+ "button",
1380
+ {
1381
+ type: "button",
1382
+ className: "uac-step-h",
1383
+ "aria-expanded": has ? open : void 0,
1384
+ "aria-controls": has ? uid : void 0,
1385
+ disabled: !has,
1386
+ onClick: () => setOpen((v) => !v),
1387
+ children: [
1388
+ /* @__PURE__ */ jsx("span", { className: "uac-kind", "aria-hidden": "true", children: /* @__PURE__ */ jsx(IcThink, {}) }),
1389
+ /* @__PURE__ */ jsx("span", { className: "uac-step-t", children: /* @__PURE__ */ jsx("span", { className: cls("uac-step-v", live && "uac-shimmer"), "data-text": label, children: label }) }),
1390
+ has ? /* @__PURE__ */ jsx("span", { className: "uac-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsx(Chevron, { dir: open ? "down" : "right", size: 12 }) }) : null
1391
+ ]
1392
+ }
1393
+ ),
1394
+ open && has ? /* @__PURE__ */ jsx("div", { className: "uac-thought", id: uid, children: item.text }) : null
1395
+ ] });
1396
+ }
1397
+ function sumDiff(tools) {
1398
+ let added = 0;
1399
+ let removed = 0;
1400
+ let any = false;
1401
+ for (const t of tools) {
1402
+ if (t.status === "failed") continue;
1403
+ const d = describeTool(t.name, t.args).diff;
1404
+ if (d) {
1405
+ any = true;
1406
+ added += d.added;
1407
+ removed += d.removed;
1408
+ }
1409
+ }
1410
+ return any ? { added, removed } : null;
1411
+ }
1412
+ function WorkGroup(props) {
1413
+ const { items, live = false, liveLabel, start = null, mark, motion, labels = DEFAULT_AGENT_LABELS, defaultOpen = false } = props;
1414
+ const [open, setOpen] = useState2(defaultOpen);
1415
+ const uid = useRef(`uac-g-${Math.random().toString(36).slice(2, 9)}`).current;
1416
+ const tools = items.filter((x) => x.kind === "tool");
1417
+ const thoughts = items.filter((x) => x.kind === "thinking");
1418
+ const failed = tools.filter((x) => x.status === "failed").length;
1419
+ let summary = "";
1420
+ if (tools.length) summary = summarizeCalls(tools);
1421
+ else if (thoughts.length) {
1422
+ const t = thoughts[0];
1423
+ const ms = t.startedAt != null && t.endedAt != null ? t.endedAt - t.startedAt : null;
1424
+ summary = ms != null && ms >= 1e3 ? labels.thoughtFor(formatElapsed(ms)) : labels.thought;
1425
+ }
1426
+ const diff = sumDiff(tools);
1427
+ if (!live && !tools.length && !thoughts.some((t) => String(t.text || "").trim())) return null;
1428
+ const body = open ? /* @__PURE__ */ jsx("div", { className: "uac-calls", id: uid, children: items.map((it) => it.kind === "tool" ? /* @__PURE__ */ jsx(StepRow, { item: it, labels }, it.id) : /* @__PURE__ */ jsx(ThinkingRow, { item: it, labels }, it.id)) }) : null;
1429
+ if (live) {
1430
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-group", "is-live", open && "is-open"), children: [
1431
+ /* @__PURE__ */ jsx(
1432
+ WorkingIndicator,
1433
+ {
1434
+ mark,
1435
+ motion,
1436
+ start,
1437
+ label: liveLabel,
1438
+ onToggle: () => setOpen((v) => !v),
1439
+ expanded: open,
1440
+ controls: uid
1441
+ }
1442
+ ),
1443
+ body
1444
+ ] });
1445
+ }
1446
+ return /* @__PURE__ */ jsxs("div", { className: cls("uac-group", open && "is-open", failed && "has-failed"), children: [
1447
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "uac-sum", "aria-expanded": open, "aria-controls": uid, onClick: () => setOpen((v) => !v), children: [
1448
+ /* @__PURE__ */ jsx("span", { className: "uac-sum-t", children: summary }),
1449
+ /* @__PURE__ */ jsx(DiffBadge, { diff }),
1450
+ failed ? /* @__PURE__ */ jsx("span", { className: "uac-fail-n", children: labels.failedCalls(failed) }) : null,
1451
+ /* @__PURE__ */ jsx("span", { className: "uac-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsx(Chevron, { dir: open ? "down" : "right", size: 12 }) })
1452
+ ] }),
1453
+ body
1454
+ ] });
1455
+ }
1456
+ function TodoCard(props) {
1457
+ const { todos, labels = DEFAULT_AGENT_LABELS, running = false } = props;
1458
+ if (!todos || !todos.length) return null;
1459
+ const done = todos.filter((t) => t.status === "completed").length;
1460
+ return /* @__PURE__ */ jsx("div", { className: "uac-todo", role: "group", "aria-label": `${labels.plan}: ${done} of ${todos.length} done`, children: todos.map((t, i) => /* @__PURE__ */ jsxs("div", { className: cls("uac-todo-i", `is-${t.status}`, !running && t.status === "in_progress" && "is-held"), children: [
1461
+ /* @__PURE__ */ jsx("span", { className: "uac-todo-m", "aria-hidden": "true", children: t.status === "completed" ? /* @__PURE__ */ jsx("svg", { width: "10", height: "10", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "3.4", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "M5 12l5 5L20 7" }) }) : null }),
1462
+ /* @__PURE__ */ jsx("span", { className: "uac-todo-t", children: t.text })
1463
+ ] }, i)) });
1464
+ }
1465
+ var REDUCED = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1466
+ function StreamingText(props) {
1467
+ const { text, active, render } = props;
1468
+ const on = !!active && !REDUCED;
1469
+ const [n, setN] = useState2(() => text ? text.length : 0);
1470
+ const textRef = useRef(text);
1471
+ textRef.current = text;
1472
+ const acc = useRef(text ? text.length : 0);
1473
+ useEffect2(() => {
1474
+ if (!on) {
1475
+ const l = textRef.current ? textRef.current.length : 0;
1476
+ acc.current = l;
1477
+ setN(l);
1478
+ return void 0;
1479
+ }
1480
+ let raf;
1481
+ let prev = null;
1482
+ const tick = (t) => {
1483
+ if (prev == null) prev = t;
1484
+ const dt = Math.min(0.1, (t - prev) / 1e3);
1485
+ prev = t;
1486
+ const len = textRef.current ? textRef.current.length : 0;
1487
+ const gap = len - acc.current;
1488
+ if (gap > 0) {
1489
+ acc.current = Math.min(len, acc.current + Math.max(40, gap / 1.2) * dt);
1490
+ setN(Math.floor(acc.current));
1491
+ } else if (gap < 0) {
1492
+ acc.current = len;
1493
+ setN(len);
1494
+ }
1495
+ raf = requestAnimationFrame(tick);
1496
+ };
1497
+ raf = requestAnimationFrame(tick);
1498
+ return () => cancelAnimationFrame(raf);
1499
+ }, [on]);
1500
+ const shown = on ? String(text || "").slice(0, n) : String(text || "");
1501
+ const rendering = on && n < String(text || "").length;
1502
+ return /* @__PURE__ */ jsx("div", { className: cls("uac-md", on && "is-streaming", rendering && "is-catching-up"), children: render ? render(shown) : /* @__PURE__ */ jsx("div", { className: "uac-plain", children: shown }) });
1503
+ }
1504
+ function UserBubble(props) {
1505
+ const { user, renderFile, extra } = props;
1506
+ if (!user) return null;
1507
+ const files = user.files || [];
1508
+ return /* @__PURE__ */ jsx("div", { className: "uac-user", children: /* @__PURE__ */ jsxs("div", { className: "uac-user-b", children: [
1509
+ extra,
1510
+ files.length ? /* @__PURE__ */ jsx("div", { className: "uac-user-files", children: files.map((f, i) => {
1511
+ if (renderFile) return /* @__PURE__ */ jsx(React.Fragment, { children: renderFile(f, i) }, i);
1512
+ const img = f.src && (/^data:image\//.test(f.src) || /\.(png|jpe?g|gif|webp|svg)$/i.test(f.name || ""));
1513
+ return img ? /* @__PURE__ */ jsx("img", { className: "uac-user-img", src: f.src, alt: f.name }, i) : /* @__PURE__ */ jsxs("span", { className: "uac-chip", children: [
1514
+ /* @__PURE__ */ jsx(IcPaperclip, { size: 12 }),
1515
+ /* @__PURE__ */ jsx("span", { children: f.name })
1516
+ ] }, i);
1517
+ }) }) : null,
1518
+ user.text ? /* @__PURE__ */ jsx("div", { className: "uac-user-t", children: user.text }) : null
1519
+ ] }) });
1520
+ }
1521
+ function TurnOutcome(props) {
1522
+ const { turn, labels = DEFAULT_AGENT_LABELS, describeIncomplete } = props;
1523
+ if (!turn || turn.status === "running") return null;
1524
+ const ms = turn.startedAt != null && turn.endedAt != null ? turn.endedAt - turn.startedAt : turn.elapsedMs;
1525
+ const time = ms != null && ms >= 0 ? formatElapsed(ms) : "";
1526
+ const tok = turn.usage && (turn.usage.total_tokens ?? (turn.usage.input_tokens || 0) + (turn.usage.output_tokens || 0));
1527
+ const tokens = tok ? labels.tokens(formatTokens(tok)) : "";
1528
+ if (turn.status === "done") {
1529
+ if (!time && !tokens) return null;
1530
+ return /* @__PURE__ */ jsx("div", { className: "uac-outcome", children: [time ? labels.workedFor(time) : labels.worked, tokens].filter(Boolean).join(" \xB7 ") });
1531
+ }
1532
+ if (turn.status === "cancelled") {
1533
+ return /* @__PURE__ */ jsx("div", { className: "uac-outcome is-stopped", children: time ? labels.stoppedAfter(time) : labels.stopped });
1534
+ }
1535
+ if (turn.status === "incomplete") {
1536
+ const why = describeIncomplete ? describeIncomplete(turn.incomplete || {}) : turn.incomplete && turn.incomplete.detail || "";
1537
+ return /* @__PURE__ */ jsxs("div", { className: "uac-outcome is-incomplete", children: [
1538
+ /* @__PURE__ */ jsxs("span", { children: [
1539
+ labels.incomplete,
1540
+ time ? ` \xB7 ${time}` : ""
1541
+ ] }),
1542
+ why ? /* @__PURE__ */ jsx("p", { className: "uac-outcome-why", children: why }) : null
1543
+ ] });
1544
+ }
1545
+ return /* @__PURE__ */ jsxs("div", { className: "uac-outcome is-failed", role: "status", children: [
1546
+ /* @__PURE__ */ jsx("span", { children: time ? labels.failedAfter(time) : labels.failed }),
1547
+ turn.error ? /* @__PURE__ */ jsx("p", { className: "uac-outcome-why", children: turn.error }) : null
1548
+ ] });
1549
+ }
1550
+ function AgentTurnView(props) {
1551
+ const {
1552
+ turn,
1553
+ renderMarkdown,
1554
+ mark,
1555
+ motion,
1556
+ labels: labelsIn,
1557
+ showUser = true,
1558
+ renderUserFile,
1559
+ userExtra,
1560
+ meta,
1561
+ renderFiles,
1562
+ actions,
1563
+ describeIncomplete,
1564
+ liveStart
1565
+ } = props;
1566
+ const labels = useMemo(() => ({ ...DEFAULT_AGENT_LABELS, ...labelsIn || {} }), [labelsIn]);
1567
+ if (!turn) return null;
1568
+ const running = turn.status === "running";
1569
+ const segs = segments(turn);
1570
+ const plan = latestPlan(turn, describeTool);
1571
+ const now = liveState(turn);
1572
+ const start = liveStart ?? turn.startedAt;
1573
+ const lastSeg = segs[segs.length - 1];
1574
+ const liveWork = running && lastSeg && lastSeg.type === "work";
1575
+ let liveLabel = labels.thinking;
1576
+ if (now) {
1577
+ if (now.phase === "tool" && now.tool) liveLabel = toolLine(describeTool(now.tool.name, now.tool.args), "running");
1578
+ else if (now.phase === "writing") liveLabel = labels.writing;
1579
+ else if (now.phase === "starting") liveLabel = labels.starting;
1580
+ }
1581
+ const lastTextIdx = (() => {
1582
+ for (let i = segs.length - 1; i >= 0; i--) if (segs[i].type === "text") return i;
1583
+ return -1;
1584
+ })();
1585
+ const files = renderFiles ? renderFiles(turn) : null;
1586
+ return /* @__PURE__ */ jsxs("article", { className: cls("uac-turn", `is-${turn.status}`), "data-status": turn.status, children: [
1587
+ showUser ? /* @__PURE__ */ jsx(UserBubble, { user: turn.user, renderFile: renderUserFile, extra: userExtra }) : null,
1588
+ /* @__PURE__ */ jsxs("div", { className: "uac-agent", children: [
1589
+ meta ? /* @__PURE__ */ jsx("div", { className: "uac-meta", children: meta }) : null,
1590
+ segs.map((s, i) => {
1591
+ const isLive = liveWork && i === segs.length - 1;
1592
+ if (isLive) {
1593
+ return /* @__PURE__ */ jsxs(React.Fragment, { children: [
1594
+ plan ? /* @__PURE__ */ jsx(TodoCard, { todos: plan, labels, running: true }) : null,
1595
+ /* @__PURE__ */ jsx(WorkGroup, { items: s.items, live: true, liveLabel, start, mark, motion, labels })
1596
+ ] }, `w${i}`);
1597
+ }
1598
+ if (s.type === "text") {
1599
+ return /* @__PURE__ */ jsx(
1600
+ StreamingText,
1601
+ {
1602
+ text: s.item.text,
1603
+ render: renderMarkdown,
1604
+ active: running && i === lastTextIdx && i === segs.length - 1
1605
+ },
1606
+ s.item.id || `t${i}`
1607
+ );
1608
+ }
1609
+ return /* @__PURE__ */ jsx(WorkGroup, { items: s.items, labels }, `w${i}-${s.items[0] && s.items[0].id}`);
1610
+ }),
1611
+ !liveWork && plan ? /* @__PURE__ */ jsx(TodoCard, { todos: plan, labels, running }) : null,
1612
+ running && !liveWork ? /* @__PURE__ */ jsx(WorkingIndicator, { mark, motion, start, label: liveLabel }) : null,
1613
+ files,
1614
+ /* @__PURE__ */ jsx(TurnOutcome, { turn, labels, describeIncomplete }),
1615
+ !running && actions ? /* @__PURE__ */ jsx("div", { className: "uac-actions", children: actions }) : null
1616
+ ] })
1617
+ ] });
1618
+ }
1619
+ function AgentComposer(props) {
1620
+ const {
1621
+ value,
1622
+ onChange,
1623
+ onSend,
1624
+ onStop,
1625
+ running = false,
1626
+ stopping = false,
1627
+ disabled = false,
1628
+ sendDisabled,
1629
+ placeholder,
1630
+ runningPlaceholder,
1631
+ attachments = [],
1632
+ onRemoveAttachment,
1633
+ onAttachFiles,
1634
+ accept,
1635
+ multiple = false,
1636
+ left,
1637
+ right,
1638
+ footer,
1639
+ inputId,
1640
+ inputRef,
1641
+ autoFocus,
1642
+ maxRows = 10,
1643
+ labels: labelsIn,
1644
+ ariaLabel,
1645
+ className
1646
+ } = props;
1647
+ const labels = { ...DEFAULT_AGENT_LABELS, ...labelsIn || {} };
1648
+ const own = useRef(null);
1649
+ const ta = inputRef || own;
1650
+ const fileIn = useRef(null);
1651
+ const root = useRef(null);
1652
+ const [dropping, setDropping] = useState2(false);
1653
+ const grow = useCallback(() => {
1654
+ const el = ta.current;
1655
+ if (!el) return;
1656
+ el.style.height = "auto";
1657
+ const cs = getComputedStyle(el);
1658
+ const lh = parseFloat(cs.lineHeight) || 22;
1659
+ const max = lh * maxRows + (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
1660
+ el.style.height = `${Math.min(el.scrollHeight, max)}px`;
1661
+ el.style.overflowY = el.scrollHeight > max ? "auto" : "hidden";
1662
+ }, [ta, maxRows]);
1663
+ useLayoutEffect(grow, [value, grow]);
1664
+ const blocked = sendDisabled ?? (!String(value || "").trim() && !attachments.length);
1665
+ const send = () => {
1666
+ if (!running && !disabled && !blocked) onSend && onSend();
1667
+ };
1668
+ const files = (list) => {
1669
+ if (list && list.length && onAttachFiles) onAttachFiles(list);
1670
+ };
1671
+ return /* @__PURE__ */ jsxs(
1672
+ "div",
1673
+ {
1674
+ ref: root,
1675
+ className: cls("uac-composer", running && "is-running", dropping && "is-dropping", disabled && "is-disabled", className),
1676
+ onDragOver: onAttachFiles ? (e) => {
1677
+ if (Array.from(e.dataTransfer.types || []).includes("Files")) {
1678
+ e.preventDefault();
1679
+ setDropping(true);
1680
+ }
1681
+ } : void 0,
1682
+ onDragLeave: onAttachFiles ? (e) => {
1683
+ if (!root.current || !root.current.contains(e.relatedTarget)) setDropping(false);
1684
+ } : void 0,
1685
+ onDrop: onAttachFiles ? (e) => {
1686
+ if (e.dataTransfer.files && e.dataTransfer.files.length) {
1687
+ e.preventDefault();
1688
+ setDropping(false);
1689
+ files(e.dataTransfer.files);
1690
+ }
1691
+ } : void 0,
1692
+ children: [
1693
+ attachments.length ? /* @__PURE__ */ jsx("div", { className: "uac-atts", children: attachments.map((f, i) => /* @__PURE__ */ jsxs("span", { className: cls("uac-att", f.status && `is-${f.status}`), children: [
1694
+ f.src && /^(data:image\/|blob:)/.test(f.src) ? /* @__PURE__ */ jsx("img", { src: f.src, alt: "" }) : /* @__PURE__ */ jsx(IcPaperclip, { size: 13 }),
1695
+ /* @__PURE__ */ jsx("span", { className: "uac-att-n", children: f.name }),
1696
+ onRemoveAttachment ? /* @__PURE__ */ jsx("button", { type: "button", "aria-label": labels.remove(f.name), onClick: () => onRemoveAttachment(i), children: /* @__PURE__ */ jsx(IcX, { size: 12 }) }) : null
1697
+ ] }, f.id || i)) }) : null,
1698
+ /* @__PURE__ */ jsx(
1699
+ "textarea",
1700
+ {
1701
+ id: inputId,
1702
+ ref: ta,
1703
+ rows: 1,
1704
+ value,
1705
+ autoFocus,
1706
+ disabled,
1707
+ placeholder: running && runningPlaceholder ? runningPlaceholder : placeholder,
1708
+ "aria-label": ariaLabel || placeholder,
1709
+ onChange: (e) => onChange && onChange(e.target.value),
1710
+ onPaste: onAttachFiles ? (e) => {
1711
+ const fl = e.clipboardData && e.clipboardData.files;
1712
+ if (fl && fl.length) {
1713
+ e.preventDefault();
1714
+ files(fl);
1715
+ }
1716
+ } : void 0,
1717
+ onKeyDown: (e) => {
1718
+ if (e.key !== "Enter" || e.shiftKey || e.nativeEvent && e.nativeEvent.isComposing) return;
1719
+ e.preventDefault();
1720
+ send();
1721
+ }
1722
+ }
1723
+ ),
1724
+ /* @__PURE__ */ jsxs("div", { className: "uac-composer-row", children: [
1725
+ onAttachFiles ? /* @__PURE__ */ jsxs(Fragment, { children: [
1726
+ /* @__PURE__ */ jsx(
1727
+ "button",
1728
+ {
1729
+ type: "button",
1730
+ className: "uac-icon-btn",
1731
+ "aria-label": labels.attach,
1732
+ title: labels.attach,
1733
+ disabled,
1734
+ onClick: () => fileIn.current && fileIn.current.click(),
1735
+ children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.1", strokeLinecap: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M12 5v14M5 12h14" }) })
1736
+ }
1737
+ ),
1738
+ /* @__PURE__ */ jsx(
1739
+ "input",
1740
+ {
1741
+ ref: fileIn,
1742
+ type: "file",
1743
+ hidden: true,
1744
+ accept,
1745
+ multiple,
1746
+ onChange: (e) => {
1747
+ files(e.target.files);
1748
+ e.target.value = "";
1749
+ }
1750
+ }
1751
+ )
1752
+ ] }) : null,
1753
+ left,
1754
+ /* @__PURE__ */ jsx("span", { className: "uac-composer-sp" }),
1755
+ right,
1756
+ running ? /* @__PURE__ */ jsx(
1757
+ "button",
1758
+ {
1759
+ type: "button",
1760
+ className: "uac-send is-stop",
1761
+ "aria-label": stopping ? labels.stopping : labels.stop,
1762
+ title: labels.stop,
1763
+ disabled: stopping || !onStop,
1764
+ onClick: () => onStop && onStop(),
1765
+ children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "14", height: "14", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ jsx("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2.5" }) })
1766
+ }
1767
+ ) : /* @__PURE__ */ jsx("button", { type: "button", className: "uac-send", "aria-label": labels.send, title: labels.send, disabled: disabled || blocked, onClick: send, children: /* @__PURE__ */ jsx(IcSend, {}) })
1768
+ ] }),
1769
+ footer ? /* @__PURE__ */ jsx("div", { className: "uac-composer-foot", children: footer }) : null
1770
+ ]
1771
+ }
1772
+ );
1773
+ }
1774
+ function nearestScroller(el) {
1775
+ let n = el && el.parentElement;
1776
+ while (n && n !== document.body && n !== document.documentElement) {
1777
+ const s = getComputedStyle(n);
1778
+ if (/(auto|scroll|overlay)/.test(s.overflowY)) return n;
1779
+ n = n.parentElement;
1780
+ }
1781
+ return null;
1782
+ }
1783
+ function useStickToBottom(contentRef, opts = {}) {
1784
+ const { scroller = null, anchorRef = null, followKey, threshold = 80, enabled = true } = opts;
1785
+ const stick = useRef(true);
1786
+ const [atBottom, setAtBottom] = useState2(true);
1787
+ const target = useRef(null);
1788
+ const resolve = useCallback(() => {
1789
+ target.current = scroller || (contentRef.current ? nearestScroller(contentRef.current) : null);
1790
+ return target.current;
1791
+ }, [scroller, contentRef]);
1792
+ const distance = () => {
1793
+ const a = anchorRef && anchorRef.current || contentRef.current;
1794
+ if (!a) return 0;
1795
+ const t = target.current;
1796
+ const viewBottom = t ? t.getBoundingClientRect().top + t.clientHeight : window.innerHeight;
1797
+ return a.getBoundingClientRect().bottom - viewBottom;
1798
+ };
1799
+ const toBottom = useCallback((smooth = false) => {
1800
+ const d = distance();
1801
+ if (Math.abs(d) < 1) return;
1802
+ const behavior = smooth && !REDUCED ? "smooth" : "auto";
1803
+ const t = target.current;
1804
+ if (t) t.scrollBy({ top: d, behavior });
1805
+ else window.scrollBy({ top: d, behavior });
1806
+ }, []);
1807
+ useEffect2(() => {
1808
+ if (!enabled) return void 0;
1809
+ const t = resolve();
1810
+ const on = () => {
1811
+ const at = distance() < threshold;
1812
+ stick.current = at;
1813
+ setAtBottom(at);
1814
+ };
1815
+ const el = t || window;
1816
+ el.addEventListener("scroll", on, { passive: true });
1817
+ on();
1818
+ return () => el.removeEventListener("scroll", on);
1819
+ }, [enabled, resolve, threshold]);
1820
+ useEffect2(() => {
1821
+ const el = contentRef.current;
1822
+ if (!enabled || !el || typeof ResizeObserver === "undefined") return void 0;
1823
+ let quietUntil = 0;
1824
+ const touched = () => {
1825
+ quietUntil = Date.now() + 600;
1826
+ };
1827
+ el.addEventListener("pointerdown", touched, true);
1828
+ el.addEventListener("keydown", touched, true);
1829
+ const ro = new ResizeObserver(() => {
1830
+ if (!target.current && scroller == null) resolve();
1831
+ if (Date.now() < quietUntil) {
1832
+ stick.current = distance() < threshold;
1833
+ setAtBottom(stick.current);
1834
+ return;
1835
+ }
1836
+ if (stick.current) toBottom(false);
1837
+ });
1838
+ ro.observe(el);
1839
+ return () => {
1840
+ ro.disconnect();
1841
+ el.removeEventListener("pointerdown", touched, true);
1842
+ el.removeEventListener("keydown", touched, true);
1843
+ };
1844
+ }, [enabled, contentRef, toBottom, resolve, scroller, threshold]);
1845
+ useEffect2(() => {
1846
+ if (!enabled || followKey === void 0) return;
1847
+ resolve();
1848
+ stick.current = true;
1849
+ setAtBottom(true);
1850
+ toBottom(false);
1851
+ }, [followKey]);
1852
+ return { atBottom, toBottom: () => {
1853
+ stick.current = true;
1854
+ setAtBottom(true);
1855
+ toBottom(true);
1856
+ } };
1857
+ }
1858
+ function AgentConversation(props) {
1859
+ const { children, composer, notice, running = false, mark, motion, mode = "pane", followKey, labels: labelsIn, className, empty } = props;
1860
+ const labels = { ...DEFAULT_AGENT_LABELS, ...labelsIn || {} };
1861
+ const rootRef = useRef(null);
1862
+ const scrollRef = useRef(null);
1863
+ const contentRef = useRef(null);
1864
+ const [scroller, setScroller] = useState2(null);
1865
+ useLayoutEffect(() => {
1866
+ if (mode === "pane") setScroller(scrollRef.current);
1867
+ }, [mode]);
1868
+ const { atBottom, toBottom } = useStickToBottom(contentRef, {
1869
+ scroller: mode === "pane" ? scroller : null,
1870
+ followKey,
1871
+ anchorRef: mode === "page" ? rootRef : null,
1872
+ enabled: mode === "page" || !!scroller
1873
+ });
1874
+ useLayoutEffect(() => {
1875
+ if (mode !== "page" || !rootRef.current) return void 0;
1876
+ const set = () => {
1877
+ const r = rootRef.current;
1878
+ if (!r) return;
1879
+ const sc = nearestScroller(r);
1880
+ const rect = r.getBoundingClientRect();
1881
+ const avail = sc ? sc.clientHeight - (rect.top - sc.getBoundingClientRect().top + sc.scrollTop) : window.innerHeight - (rect.top + window.scrollY);
1882
+ r.style.setProperty("--uac-fill", `${Math.max(240, Math.round(avail))}px`);
1883
+ };
1884
+ set();
1885
+ window.addEventListener("resize", set);
1886
+ const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(set) : null;
1887
+ if (ro && rootRef.current.parentElement) ro.observe(rootRef.current.parentElement);
1888
+ return () => {
1889
+ window.removeEventListener("resize", set);
1890
+ if (ro) ro.disconnect();
1891
+ };
1892
+ }, [mode]);
1893
+ return /* @__PURE__ */ jsxs("div", { ref: rootRef, className: cls("uac-convo", `is-${mode}`, className), children: [
1894
+ /* @__PURE__ */ jsx("div", { ref: scrollRef, className: "uac-scroll", children: /* @__PURE__ */ jsx("div", { ref: contentRef, className: "uac-thread", children: children || empty }) }),
1895
+ /* @__PURE__ */ jsxs("div", { className: "uac-dock", children: [
1896
+ !atBottom ? /* @__PURE__ */ jsx("button", { type: "button", className: "uac-jump", "aria-label": labels.jump, title: labels.jump, onClick: toBottom, children: running ? /* @__PURE__ */ jsx(WorkingMark, { mark, motion, size: 16 }) : /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M12 5v14M5 12l7 7 7-7" }) }) }) : null,
1897
+ notice ? /* @__PURE__ */ jsx("div", { className: "uac-notice", children: notice }) : null,
1898
+ composer
1899
+ ] })
1900
+ ] });
1901
+ }
1902
+ export {
1903
+ AgentComposer,
1904
+ AgentConversation,
1905
+ AgentTurnView,
1906
+ CopyButton,
1907
+ DEFAULT_AGENT_LABELS,
1908
+ DiffBadge,
1909
+ LinesBlock,
1910
+ MARK_MOTIONS,
1911
+ MOTIONS,
1912
+ StepRow,
1913
+ StreamingText,
1914
+ ThinkingRow,
1915
+ TodoCard,
1916
+ TurnOutcome,
1917
+ UserBubble,
1918
+ WorkGroup,
1919
+ WorkingIndicator,
1920
+ WorkingMark,
1921
+ baseNameOf,
1922
+ commandText,
1923
+ describeTool,
1924
+ diffOf,
1925
+ finish,
1926
+ formatDuration,
1927
+ formatElapsed,
1928
+ formatTokens,
1929
+ isTerminal,
1930
+ latestPlan,
1931
+ lineCount,
1932
+ liveState,
1933
+ motionFor,
1934
+ newTurn,
1935
+ parseToolArgs,
1936
+ patchStats,
1937
+ reduceTurn,
1938
+ resultNote,
1939
+ segments,
1940
+ summarizeCalls,
1941
+ todosOf,
1942
+ toolKind,
1943
+ toolLine,
1944
+ turnFromEvents,
1945
+ turnFromHistory,
1946
+ turnFromMessage,
1947
+ turnFromResponse,
1948
+ useElapsed,
1949
+ useNow,
1950
+ useStickToBottom
1951
+ };
1952
+ //# sourceMappingURL=agent-chat.js.map