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