reifyui 0.14.0 → 0.15.1

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