@openlegion/platform 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1189 -2
  3. package/dist/body.d.ts +9 -0
  4. package/dist/body.js +28 -0
  5. package/dist/chat-history.d.ts +53 -0
  6. package/dist/chat-history.js +11 -0
  7. package/dist/client.d.ts +217 -0
  8. package/dist/client.js +367 -0
  9. package/dist/core.d.ts +47 -0
  10. package/dist/core.js +1 -0
  11. package/dist/crypto.d.ts +25 -0
  12. package/dist/crypto.js +81 -0
  13. package/dist/errors.d.ts +111 -0
  14. package/dist/errors.js +134 -0
  15. package/dist/events.d.ts +131 -0
  16. package/dist/events.js +5 -0
  17. package/dist/generated/api.d.ts +5505 -0
  18. package/dist/generated/api.js +446 -0
  19. package/dist/handler.d.ts +201 -0
  20. package/dist/handler.js +682 -0
  21. package/dist/index.d.ts +24 -0
  22. package/dist/index.js +12 -0
  23. package/dist/kit-agents.d.ts +95 -0
  24. package/dist/kit-agents.js +280 -0
  25. package/dist/kit-codes.d.ts +279 -0
  26. package/dist/kit-codes.js +44 -0
  27. package/dist/kit-connections.d.ts +21 -0
  28. package/dist/kit-connections.js +189 -0
  29. package/dist/kit-files.d.ts +8 -0
  30. package/dist/kit-files.js +117 -0
  31. package/dist/kit-model-keys.d.ts +8 -0
  32. package/dist/kit-model-keys.js +86 -0
  33. package/dist/kit-threads.d.ts +3 -0
  34. package/dist/kit-threads.js +92 -0
  35. package/dist/kit-tools.d.ts +21 -0
  36. package/dist/kit-tools.js +47 -0
  37. package/dist/kit.d.ts +130 -0
  38. package/dist/kit.js +155 -0
  39. package/dist/mcp-server.d.ts +27 -0
  40. package/dist/mcp-server.js +166 -0
  41. package/dist/next.d.ts +24 -0
  42. package/dist/next.js +6 -0
  43. package/dist/ol-signed.d.ts +82 -0
  44. package/dist/ol-signed.js +115 -0
  45. package/dist/react/add-server.d.ts +90 -0
  46. package/dist/react/add-server.js +183 -0
  47. package/dist/react/agent-chat.d.ts +925 -0
  48. package/dist/react/agent-chat.js +1917 -0
  49. package/dist/react/agent-editor.d.ts +133 -0
  50. package/dist/react/agent-editor.js +222 -0
  51. package/dist/react/agent-kit.d.ts +160 -0
  52. package/dist/react/agent-kit.js +279 -0
  53. package/dist/react/agent-list.d.ts +247 -0
  54. package/dist/react/agent-list.js +248 -0
  55. package/dist/react/approval-card.d.ts +272 -0
  56. package/dist/react/approval-card.js +372 -0
  57. package/dist/react/artifact-card.d.ts +38 -0
  58. package/dist/react/artifact-card.js +39 -0
  59. package/dist/react/avatar.d.ts +21 -0
  60. package/dist/react/avatar.js +33 -0
  61. package/dist/react/card-ledger.d.ts +30 -0
  62. package/dist/react/card-ledger.js +49 -0
  63. package/dist/react/chat-timing.d.ts +121 -0
  64. package/dist/react/chat-timing.js +229 -0
  65. package/dist/react/computer-view.d.ts +309 -0
  66. package/dist/react/computer-view.js +543 -0
  67. package/dist/react/computer-viewer.d.ts +175 -0
  68. package/dist/react/computer-viewer.js +555 -0
  69. package/dist/react/computer-wire.d.ts +178 -0
  70. package/dist/react/computer-wire.js +244 -0
  71. package/dist/react/connect-button.d.ts +145 -0
  72. package/dist/react/connect-button.js +212 -0
  73. package/dist/react/connection-request.d.ts +16 -0
  74. package/dist/react/connection-request.js +18 -0
  75. package/dist/react/connections-list.d.ts +90 -0
  76. package/dist/react/connections-list.js +76 -0
  77. package/dist/react/errors.d.ts +250 -0
  78. package/dist/react/errors.js +146 -0
  79. package/dist/react/files.d.ts +41 -0
  80. package/dist/react/files.js +78 -0
  81. package/dist/react/index.d.ts +35 -0
  82. package/dist/react/index.js +26 -0
  83. package/dist/react/limit-words.d.ts +80 -0
  84. package/dist/react/limit-words.js +53 -0
  85. package/dist/react/markdown.d.ts +42 -0
  86. package/dist/react/markdown.js +56 -0
  87. package/dist/react/md-parse.d.ts +106 -0
  88. package/dist/react/md-parse.js +638 -0
  89. package/dist/react/model-keys-card.d.ts +94 -0
  90. package/dist/react/model-keys-card.js +123 -0
  91. package/dist/react/reload.d.ts +211 -0
  92. package/dist/react/reload.js +339 -0
  93. package/dist/react/reveal.d.ts +17 -0
  94. package/dist/react/reveal.js +22 -0
  95. package/dist/react/schedule-editor.d.ts +107 -0
  96. package/dist/react/schedule-editor.js +172 -0
  97. package/dist/react/schedule-time.d.ts +66 -0
  98. package/dist/react/schedule-time.js +90 -0
  99. package/dist/react/styles.css +1274 -0
  100. package/dist/react/transport.d.ts +49 -0
  101. package/dist/react/transport.js +380 -0
  102. package/dist/react/use-connections.d.ts +155 -0
  103. package/dist/react/use-connections.js +231 -0
  104. package/dist/react/use-model-keys.d.ts +47 -0
  105. package/dist/react/use-model-keys.js +57 -0
  106. package/dist/react/use-threads.d.ts +63 -0
  107. package/dist/react/use-threads.js +73 -0
  108. package/dist/react/vault-form.d.ts +92 -0
  109. package/dist/react/vault-form.js +151 -0
  110. package/dist/schema.d.ts +47 -0
  111. package/dist/schema.js +16 -0
  112. package/dist/secrets.d.ts +15 -0
  113. package/dist/secrets.js +18 -0
  114. package/dist/stream.d.ts +129 -0
  115. package/dist/stream.js +192 -0
  116. package/dist/testing.d.ts +33 -0
  117. package/dist/testing.js +40 -0
  118. package/dist/webhooks.d.ts +31 -0
  119. package/dist/webhooks.js +72 -0
  120. package/package.json +85 -3
@@ -0,0 +1,1917 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useChat } from "@ai-sdk/react";
4
+ import { generateId } from "ai";
5
+ import { Fragment, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
+ import { limitOf, refusalWords } from "./limit-words.js";
7
+ import { ApprovalCard } from "./approval-card.js";
8
+ import { AgentChatError, agentChatErrorText, attachErrorText, decisionRefusalWords, DEFAULT_LABELS, isInterrupted, queuedText } from "./errors.js";
9
+ import { KIT_SCHEDULE_DONE, KIT_TOOL_LINES as BUILT_IN_TOOLS } from "../kit-tools.js";
10
+ import { afterReconnect, answeredBy, kitBaseFor, loadHistoryState, mergeReread, missedReplies, placeEarlier, readEarlier, readThreadHistory, reconcileReply, replyOf, rereadOnLoad, runSettled, runStillUnanswered, runStopped, sentMessageIds, sentMessageOf, unansweredRuns } from "./reload.js";
11
+ import { createAgentChatTransport } from "./transport.js";
12
+ import { vaultRequestOf, VaultSecretForm } from "./vault-form.js";
13
+ import { cardLedger, CardLedgerContext, connectKey } from "./card-ledger.js";
14
+ import { ConnectButton, connectLabelsOf } from "./connect-button.js";
15
+ import { connectionRequestOf } from "./connection-request.js";
16
+ import { markSeen } from "./agent-list.js";
17
+ import { ArtifactCard } from "./artifact-card.js";
18
+ import { BrowserControlContext, computerPlaces, ComputerPointer, ComputerRow, ComputerRowsContext, controlAfter, DEFAULT_COMPUTER_VIEW_LABELS } from "./computer-view.js";
19
+ import { MarkdownText } from "./markdown.js";
20
+ import { Avatar } from "./avatar.js";
21
+ import { artifactDownloadHref, artifactOf, ATTACHMENT_ACCEPT, attachmentsOf, listKitArtifacts, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, readKitArtifactText, sizeText, uploadKitFile } from "./files.js";
22
+ import { decisionWatch, lookAfterDecision, noticeLooks, settleLedger, stopStateAfter } from "./chat-timing.js";
23
+ export { decisionWatch, followUpWaits, lookAfterDecision, noticeLooks, stopStateAfter } from "./chat-timing.js";
24
+ export function isMessageTainted(m) {
25
+ const fromStream = m.metadata?.tainted;
26
+ const fromApi = m.tainted;
27
+ const said = typeof fromStream === "boolean" ? fromStream : typeof fromApi === "boolean" ? fromApi : null;
28
+ return m.role === "assistant" ? said !== false : said === true;
29
+ }
30
+ function startedBySchedule(m) {
31
+ return m.role === "assistant" && m.trigger === "schedule";
32
+ }
33
+ export function isMessageStopped(m) {
34
+ return m.role === "assistant" && m.stopped === true;
35
+ }
36
+ const STOP_EARLY = new Set(["run_budget_exhausted", "run_step_limit"]);
37
+ function refusalCode(part) {
38
+ if (part?.type !== "data-refusal")
39
+ return null;
40
+ const code = part.data?.code;
41
+ return typeof code === "string" ? code : "";
42
+ }
43
+ export function replyFailed(m) {
44
+ if (m.role !== "assistant")
45
+ return false;
46
+ return m.parts.some((p) => {
47
+ const code = refusalCode(p);
48
+ return code !== null && !STOP_EARLY.has(code);
49
+ });
50
+ }
51
+ function outcomeFailed(outcome) {
52
+ return outcome.refusal !== null && !STOP_EARLY.has(outcome.refusal.code ?? "");
53
+ }
54
+ export function stopAlreadySaid(parts, i, labels) {
55
+ const code = refusalCode(parts[i]);
56
+ if (code === null || !STOP_EARLY.has(code) || labels.refusals?.[code] !== undefined)
57
+ return false;
58
+ for (let j = i - 1; j >= 0; j--) {
59
+ const p = parts[j];
60
+ if (p.type === "step-start" || p.type === "reasoning" || p.type === "tool-agent_finish")
61
+ continue;
62
+ if (p.type === "text" && p.text.trim() === "")
63
+ continue;
64
+ return p.type === "text";
65
+ }
66
+ return false;
67
+ }
68
+ export function finishStatus(message, isAbort, isError) {
69
+ if (isAbort || isMessageStopped(message))
70
+ return "stopped";
71
+ return isError || replyFailed(message) ? "failed" : "finished";
72
+ }
73
+ function agentWords(messages) {
74
+ let n = 0;
75
+ for (const m of messages)
76
+ if (m.role === "assistant")
77
+ for (const p of m.parts)
78
+ if (p.type === "text")
79
+ n += p.text.length;
80
+ return n;
81
+ }
82
+ export function seenWatch(report, now = () => new Date()) {
83
+ const told = new Set();
84
+ return {
85
+ update(o) {
86
+ if (o.newest === null || told.has(o.newest) || !o.inView || !o.visible || !o.focused || o.writing)
87
+ return;
88
+ told.add(o.newest);
89
+ report({ message: o.newest, at: now().toISOString() });
90
+ },
91
+ };
92
+ }
93
+ export function seenMarks(post) {
94
+ const stored = new Map();
95
+ let owed = null;
96
+ return {
97
+ seen(id) {
98
+ const mark = MESSAGE_ID_RE.test(id) ? id : stored.get(id);
99
+ owed = mark === undefined ? id : null;
100
+ if (mark !== undefined)
101
+ post(mark);
102
+ },
103
+ known(liveId, id) {
104
+ if (!MESSAGE_ID_RE.test(id) || stored.get(liveId) === id)
105
+ return;
106
+ stored.set(liveId, id);
107
+ if (owed === liveId) {
108
+ owed = null;
109
+ post(id);
110
+ }
111
+ },
112
+ };
113
+ }
114
+ export function seenPoster(o) {
115
+ let off = false;
116
+ return async (message) => {
117
+ if (off)
118
+ return;
119
+ try {
120
+ await markSeen(o.thread, message, { api: o.base, fetch: o.fetch });
121
+ }
122
+ catch (err) {
123
+ if (err.code === "subject_required")
124
+ off = true;
125
+ else
126
+ o.onError()?.(err instanceof Error ? err : new Error(String(err)));
127
+ }
128
+ };
129
+ }
130
+ const NOTICE_EVERY_MS = 30_000;
131
+ export function stampMoved(was, now) {
132
+ return typeof was === "string" && typeof now === "string" && now !== was;
133
+ }
134
+ export function stampLedger() {
135
+ let at = undefined;
136
+ let first = true;
137
+ return {
138
+ wants: (now, noticing) => first || (noticing && stampMoved(at, now)),
139
+ heard(now) {
140
+ first = false;
141
+ at = now;
142
+ },
143
+ };
144
+ }
145
+ export function unsentAfterError(messages, err) {
146
+ const last = messages[messages.length - 1];
147
+ if (!last || last.role !== "user")
148
+ return null;
149
+ if (!(err instanceof AgentChatError) || err.code === "stream_interrupted" || err.run !== null)
150
+ return null;
151
+ return last.id;
152
+ }
153
+ export function unsentReason(err) {
154
+ if (!(err instanceof AgentChatError) || err.type !== "refusal")
155
+ return "failed";
156
+ return err.code === "cap_reached" ? "limit" : "refused";
157
+ }
158
+ export function resendOf(m) {
159
+ const text = m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join("\n");
160
+ const files = m.parts.flatMap((p) => (p.type === "data-attachments" ? attachmentsOf(p.data) : []));
161
+ return { text, files };
162
+ }
163
+ export function mayHaveArrived(err) {
164
+ if (!(err instanceof AgentChatError))
165
+ return false;
166
+ if (err.code === "network" || err.code === "idempotency_in_flight")
167
+ return true;
168
+ return err.status !== null && err.status >= 500;
169
+ }
170
+ export function againOf(m, err) {
171
+ return { id: mayHaveArrived(err) ? m.id : null, ...resendOf(m) };
172
+ }
173
+ export function latestFetch(ref) {
174
+ return (input, init) => (ref.current ?? globalThis.fetch)(input, init);
175
+ }
176
+ export function withWaiting(messages, waiting) {
177
+ if (waiting.length === 0)
178
+ return { messages, waiting: new Set() };
179
+ const placed = new Set(messages.map((m) => m.id));
180
+ const still = waiting.filter((m) => !placed.has(m.id));
181
+ return { messages: still.length === 0 ? messages : [...messages, ...still], waiting: new Set(still.map((m) => m.id)) };
182
+ }
183
+ export function placeAnswered(messages, answered, later) {
184
+ const last = messages[messages.length - 1];
185
+ if (answered.length === 0 || last?.role !== "assistant")
186
+ return [...messages, ...answered, ...later];
187
+ return [...messages.slice(0, -1), ...answered, last, ...later];
188
+ }
189
+ function outgoingParts(text, files) {
190
+ const parts = [{ type: "text", text }];
191
+ if (files.length > 0)
192
+ parts.push({ type: "data-attachments", data: { files: files.slice(0, MAX_ATTACHMENTS) } });
193
+ return parts;
194
+ }
195
+ export const SETTLE_RETRY_MS = 1500;
196
+ const STOP_CHECK_RETRY_MS = 1000;
197
+ export function atEndAfterScroll(was, before, el, seen = {}) {
198
+ if (el.scrollHeight - el.scrollTop - el.clientHeight < 48)
199
+ return true;
200
+ if (el.scrollTop < before && seen.person === true)
201
+ return false;
202
+ return was;
203
+ }
204
+ export const QUIET_FRAMES = 3;
205
+ function afterFrames(frames, fn) {
206
+ if (typeof requestAnimationFrame !== "function") {
207
+ setTimeout(fn, 16 * frames);
208
+ return;
209
+ }
210
+ const next = (left) => {
211
+ requestAnimationFrame(() => (left <= 1 ? fn() : next(left - 1)));
212
+ };
213
+ next(frames);
214
+ }
215
+ export function scrollJudge(later = afterFrames) {
216
+ let changes = 0;
217
+ let recent = 0;
218
+ let lastTop = 0;
219
+ return {
220
+ resized() {
221
+ changes++;
222
+ recent++;
223
+ later(QUIET_FRAMES, () => {
224
+ recent--;
225
+ });
226
+ },
227
+ took() {
228
+ changes++;
229
+ },
230
+ scrolled(atEnd, el, person) {
231
+ const up = el.scrollTop < lastTop;
232
+ const next = atEndAfterScroll(atEnd, lastTop, el, { person });
233
+ lastTop = el.scrollTop;
234
+ if (!takesEndBack(next, el))
235
+ return { atEnd: next, then: "none" };
236
+ return { atEnd: next, then: recent === 0 && up ? { confirm: changes } : "back" };
237
+ },
238
+ quiet(mark) {
239
+ return changes === mark;
240
+ },
241
+ };
242
+ }
243
+ export function takesEndBack(atEnd, el) {
244
+ return atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 48;
245
+ }
246
+ const SCROLL_KEYS = new Set(["PageUp", "PageDown", "ArrowUp", "ArrowDown", "Home", "End"]);
247
+ const TYPED_IN = new Set(["INPUT", "TEXTAREA", "SELECT"]);
248
+ export function isScrollInput(e, el) {
249
+ if (e.type === "wheel" || e.type === "touchmove")
250
+ return true;
251
+ const t = e.target;
252
+ if (e.type === "focusin") {
253
+ if (!t || typeof t.matches !== "function")
254
+ return false;
255
+ try {
256
+ return t.matches(":focus-visible") === true;
257
+ }
258
+ catch {
259
+ return false;
260
+ }
261
+ }
262
+ if (e.type === "keydown") {
263
+ if (!t || (typeof t.tagName === "string" && TYPED_IN.has(t.tagName)) || t.isContentEditable === true)
264
+ return false;
265
+ return SCROLL_KEYS.has(e.key ?? "") || e.key === "Tab" || (e.key === " " && t === el);
266
+ }
267
+ if (e.type === "pointerdown")
268
+ return t === el && ((e.offsetX ?? 0) >= el.clientWidth || (e.offsetY ?? 0) >= el.clientHeight);
269
+ return false;
270
+ }
271
+ export function approvalBarCount(all, view) {
272
+ const buttons = all.filter((b) => b.deciding !== true);
273
+ const inView = buttons.some((b) => b.top >= view.top - 1 && b.bottom <= view.bottom + 1);
274
+ return inView ? 0 : buttons.length;
275
+ }
276
+ function shownPart(el) {
277
+ const screen = { top: 0, bottom: window.innerHeight };
278
+ if (el.scrollHeight <= el.clientHeight + 1)
279
+ return screen;
280
+ const box = el.getBoundingClientRect();
281
+ return { top: Math.max(box.top, screen.top), bottom: Math.min(box.bottom, screen.bottom) };
282
+ }
283
+ export const EARLIER_REACH_PX = 200;
284
+ const MESSAGE_ID_RE = /^msg_[0-9A-Za-z]{1,64}$/;
285
+ const EARLIER_HUSH_MS = 500;
286
+ export function earlierFrom(messages, threadId) {
287
+ const oldest = messages[0];
288
+ return threadId && oldest && MESSAGE_ID_RE.test(oldest.id) ? oldest.id : null;
289
+ }
290
+ export function wantsEarlier(at) {
291
+ if (at.earlier !== "more" || !at.scrollBox)
292
+ return false;
293
+ return !at.overflowing || (!at.atEnd && at.top <= EARLIER_REACH_PX);
294
+ }
295
+ export function rowsAbove(messages, first) {
296
+ const at = first === null ? -1 : messages.findIndex((m) => m.id === first);
297
+ return at > 0 ? messages.slice(0, at).map((m) => m.id) : [];
298
+ }
299
+ function readingPlace(el) {
300
+ const box = el.getBoundingClientRect().top;
301
+ for (const row of Array.from(el.querySelectorAll(":scope > [data-ol-message-id]"))) {
302
+ const r = row.getBoundingClientRect();
303
+ if (r.bottom > box)
304
+ return { id: row.getAttribute("data-ol-message-id") ?? "", offset: r.top - box };
305
+ }
306
+ return null;
307
+ }
308
+ export function keepReadingPlace(el, place) {
309
+ const row = el.querySelector(`:scope > [data-ol-message-id="${CSS.escape(place.id)}"]`);
310
+ if (!row)
311
+ return;
312
+ const shift = row.getBoundingClientRect().top - el.getBoundingClientRect().top - place.offset;
313
+ if (Math.abs(shift) >= 0.5)
314
+ el.scrollTop += shift;
315
+ }
316
+ export function goToTarget(el, id, letGo) {
317
+ const card = APPROVAL_ID_RE.test(id);
318
+ const attr = card ? "data-ol-approval-id" : "data-ol-message-id";
319
+ const target = Array.from(el.querySelectorAll(`[${attr}]`)).find((n) => n.getAttribute(attr) === id);
320
+ if (!target)
321
+ return false;
322
+ const part = shownPart(el);
323
+ const fits = target.getBoundingClientRect().height <= part.bottom - part.top;
324
+ const buttons = card && !fits ? target.querySelector("[data-ol-approval-actions]") : null;
325
+ letGo();
326
+ if (buttons)
327
+ buttons.scrollIntoView({ block: "nearest" });
328
+ else
329
+ target.scrollIntoView({ block: fits ? "nearest" : "start" });
330
+ return true;
331
+ }
332
+ export function openTargetLoaded(messages, outcomes, id) {
333
+ if (!APPROVAL_ID_RE.test(id))
334
+ return messages.some((m) => m.id === id);
335
+ if (messages.some((m) => m.parts.some((p) => approvalOfPart(p) === id)))
336
+ return true;
337
+ return Object.values(outcomes ?? {}).some((o) => o.tools.some((t) => t.approval === id));
338
+ }
339
+ export function openAtMissing(at) {
340
+ const id = at.openAt;
341
+ if (!id || at.historyLoaded !== true || at.fired.has(id))
342
+ return null;
343
+ return openTargetLoaded(at.messages, at.outcomes, id) ? null : id;
344
+ }
345
+ export function chatHandle(transcript, letGo) {
346
+ return {
347
+ bringIntoView: (id) => {
348
+ const el = transcript();
349
+ return el !== null && goToTarget(el, id, letGo);
350
+ },
351
+ };
352
+ }
353
+ export function decisionTakesEnd(was, before, now) {
354
+ for (const apr of now.keys())
355
+ if (!before.has(apr))
356
+ return true;
357
+ return was;
358
+ }
359
+ const HIDDEN_FROM_VIEW = { position: "absolute", width: "1px", height: "1px", margin: "-1px", padding: 0, border: 0, overflow: "hidden", clipPath: "inset(50%)", whiteSpace: "nowrap" };
360
+ const OFF_CONTROL = { inert: true, disabled: true, tabIndex: -1, "aria-hidden": true, style: { visibility: "hidden" } };
361
+ export function approvalsToAnnounce(cards, said, initial) {
362
+ return cards.filter((c) => !said.has(c.id) && !(c.message !== null && initial.has(c.message))).map(({ id, title }) => ({ id, title }));
363
+ }
364
+ export function ApprovalBar(props) {
365
+ const words = props.count > 1 ? props.labels.approvalBarMany.replace("{count}", String(props.count)) : props.labels.approvalBar;
366
+ return (_jsxs("div", { "data-ol-approval-bar": true, role: "status", children: [_jsx("span", { children: words }), " ", _jsx("button", { type: "button", "data-ol-approval-review": true, onClick: props.onReview, children: props.labels.approvalReview })] }));
367
+ }
368
+ export function stepAfterStop(at, m, i) {
369
+ const p = m.parts[i];
370
+ if (!at || !p || !(p.type.startsWith("tool-") || p.type === "dynamic-tool"))
371
+ return false;
372
+ return at.id !== m.id || i >= at.parts;
373
+ }
374
+ function noResult(p) {
375
+ if (p.state === "input-streaming" || p.state === "input-available")
376
+ return true;
377
+ const out = p.output;
378
+ return p.state === "output-available" && out !== null && typeof out === "object" && out.action === null && out.status === null;
379
+ }
380
+ export function useAgentChat(opts) {
381
+ const [queued, setQueued] = useState(null);
382
+ const [queuedReason, setQueuedReason] = useState(null);
383
+ const resuming = useRef(opts.resume !== false);
384
+ const resumeRef = useRef(null);
385
+ const onErrorRef = useRef(opts.onError);
386
+ onErrorRef.current = opts.onError;
387
+ const onFinishRef = useRef(opts.onFinish);
388
+ onFinishRef.current = opts.onFinish;
389
+ const onIdleRef = useRef(null);
390
+ const [unsent, setUnsent] = useState(() => new Set());
391
+ const unsentWhy = useRef(new Map());
392
+ const unsentReasons = useMemo(() => new Map([...unsent].map((id) => [id, unsentReason(unsentWhy.current.get(id))])), [unsent]);
393
+ const [failedSend, setFailedSend] = useState(null);
394
+ const [stopState, setStopState] = useState(null);
395
+ const stopStateRef = useRef(null);
396
+ stopStateRef.current = stopState;
397
+ const streamStopped = useRef(false);
398
+ const [awaitingReply, setAwaitingReply] = useState(false);
399
+ const wordsAtDecision = useRef(0);
400
+ const replyEnds = useRef({ n: 0, next: [] });
401
+ const openAtDecision = useRef(null);
402
+ const followUpRef = useRef(() => Promise.resolve());
403
+ const stopRunRef = useRef(() => Promise.resolve());
404
+ const [watch] = useState(() => decisionWatch({
405
+ show: (on) => {
406
+ setAwaitingReply(on);
407
+ if (!on && !busyRef.current)
408
+ setStopState((s) => stopStateAfter(s, { type: "gone" }));
409
+ },
410
+ follow: () => void followUpRef.current(),
411
+ stop: () => void stopRunRef.current(),
412
+ }));
413
+ useEffect(() => () => watch.dispose(), [watch]);
414
+ const fetchRef = useRef(opts.fetch);
415
+ fetchRef.current = opts.fetch;
416
+ const [kitFetch] = useState(() => latestFetch(fetchRef));
417
+ const [transport] = useState(() => createAgentChatTransport({
418
+ ...(opts.api ? { api: opts.api } : {}),
419
+ fetch: kitFetch,
420
+ onQueued: (position, reason) => {
421
+ setQueued(position);
422
+ setQueuedReason(reason);
423
+ },
424
+ onIdle: (lastMessageAt) => onIdleRef.current?.(lastMessageAt),
425
+ onStopped: () => {
426
+ streamStopped.current = true;
427
+ setStopState((s) => stopStateAfter(s, { type: "stream-stopped" }));
428
+ },
429
+ }));
430
+ const [waiting, setWaitingState] = useState([]);
431
+ const waitingRef = useRef([]);
432
+ const setWaiting = (next) => {
433
+ waitingRef.current = next;
434
+ setWaitingState(next);
435
+ };
436
+ const posting = useRef(0);
437
+ const accepted = useRef(new Map());
438
+ const placing = useRef(false);
439
+ const [waitingError, setWaitingError] = useState(undefined);
440
+ const inFlight = useRef(0);
441
+ const notice = useRef(null);
442
+ const flushRef = useRef(() => undefined);
443
+ const track = (request) => {
444
+ inFlight.current += 1;
445
+ return request
446
+ .then(() => undefined, () => undefined)
447
+ .finally(() => {
448
+ inFlight.current -= 1;
449
+ flushRef.current();
450
+ queueMicrotask(() => notice.current?.settled());
451
+ });
452
+ };
453
+ const followed = useRef(false);
454
+ const mounted = useRef(true);
455
+ useEffect(() => {
456
+ mounted.current = true;
457
+ return () => {
458
+ mounted.current = false;
459
+ };
460
+ }, []);
461
+ const confirmStopped = async (id, run) => {
462
+ const from = loadFrom.current;
463
+ const ask = () => runStopped({ base: from.base, fetch: from.fetch }, run);
464
+ let said = await ask();
465
+ if (said === "again") {
466
+ await new Promise((r) => setTimeout(r, STOP_CHECK_RETRY_MS));
467
+ said = await ask();
468
+ }
469
+ const c = chatRef.current;
470
+ if (said !== "stopped" || !c || !mounted.current)
471
+ return;
472
+ c.setMessages((ms) => (ms.some((m) => m.id === id && !isMessageStopped(m)) ? ms.map((m) => (m.id === id ? { ...m, stopped: true } : m)) : ms));
473
+ };
474
+ const settleRef = useRef(() => Promise.resolve(undefined));
475
+ const drawnRuns = useRef(new Set());
476
+ const [owedReads] = useState(settleLedger);
477
+ const onFinish = ({ message, messages, isAbort, isError }) => {
478
+ const run = transport.followedRun(opts.threadId);
479
+ if (streamStopped.current && message?.role === "assistant") {
480
+ const marked = { ...message, stopped: true };
481
+ chatRef.current?.setMessages((ms) => (ms.some((m) => m.id === message.id) ? ms.map((m) => (m.id === message.id ? { ...m, stopped: true } : m)) : [...ms, { ...marked, parts: [] }]));
482
+ }
483
+ const askedNotSaid = stopStateRef.current === "stopping" && !streamStopped.current && run !== null && message?.role === "assistant";
484
+ streamStopped.current = false;
485
+ if (run && message?.role === "assistant") {
486
+ drawnRuns.current.add(run);
487
+ owedReads.ended(run, message.id);
488
+ }
489
+ const settled = run && message?.role === "assistant" ? settleRef.current(message.id, run) : Promise.resolve(undefined);
490
+ if (askedNotSaid && run && message)
491
+ void settled.then(() => confirmStopped(message.id, run));
492
+ if (message) {
493
+ void settled.then((now) => {
494
+ const drawn = now?.find((m) => m.id === message.id) ?? message;
495
+ onFinishRef.current?.({ message: drawn, status: finishStatus(drawn, isAbort, isError) });
496
+ });
497
+ }
498
+ setQueued(null);
499
+ setQueuedReason(null);
500
+ setStopState((s) => stopStateAfter(s, { type: "ended" }));
501
+ followed.current = true;
502
+ if (openAtDecision.current === replyEnds.current.n)
503
+ wordsAtDecision.current = agentWords(messages);
504
+ watch.ended();
505
+ replyEnds.current.n += 1;
506
+ for (const tell of replyEnds.current.next.splice(0))
507
+ tell();
508
+ if (resuming.current && !isAbort && !isError && resumeRef.current)
509
+ void track(resumeRef.current());
510
+ };
511
+ const chat = useChat({
512
+ id: opts.threadId,
513
+ ...(opts.initialMessages ? { messages: [...opts.initialMessages] } : {}),
514
+ transport,
515
+ resume: opts.resume !== false,
516
+ onError: (err) => {
517
+ onErrorRef.current?.(err);
518
+ setFailedSend({ err });
519
+ },
520
+ onFinish,
521
+ });
522
+ resumeRef.current = chat.resumeStream;
523
+ const busy = chat.status === "submitted" || chat.status === "streaming";
524
+ const busyRef = useRef(busy);
525
+ busyRef.current = busy;
526
+ useEffect(() => {
527
+ if (busy)
528
+ watch.attached();
529
+ }, [busy, watch]);
530
+ flushRef.current = () => {
531
+ const moved = waitingRef.current;
532
+ if (!mounted.current || busy || placing.current || inFlight.current > 0 || posting.current > 0 || moved.length === 0 || isInterrupted(chat.error))
533
+ return;
534
+ const place = (answered) => {
535
+ const all = waitingRef.current;
536
+ const later = all.filter((m) => !answered.has(m.id));
537
+ setWaiting([]);
538
+ chat.setMessages((ms) => placeAnswered(ms, all.filter((m) => answered.has(m.id)), later));
539
+ if (!later.some((m) => accepted.current.has(m.id))) {
540
+ transport.forgetWaiting(opts.threadId);
541
+ return;
542
+ }
543
+ resuming.current = true;
544
+ reread.current = false;
545
+ void track(chat.resumeStream());
546
+ };
547
+ const followed = transport.followedRun(opts.threadId);
548
+ const withRuns = moved.flatMap((m) => {
549
+ const run = accepted.current.get(m.id);
550
+ return run ? [{ message: m.id, run }] : [];
551
+ });
552
+ if (!followed || withRuns.length === 0)
553
+ return place(new Set());
554
+ placing.current = true;
555
+ const from = loadFrom.current;
556
+ void answeredBy({ base: from.base, fetch: from.fetch }, followed, withRuns)
557
+ .then((answered) => answered, () => new Set())
558
+ .then((answered) => {
559
+ placing.current = false;
560
+ if (mounted.current && !busyRef.current && inFlight.current === 0)
561
+ place(answered);
562
+ });
563
+ };
564
+ useEffect(() => {
565
+ if (!busy && waiting.length > 0)
566
+ flushRef.current();
567
+ }, [busy, waiting, chat.error]);
568
+ const sendAs = (text, files, id) => {
569
+ resuming.current = false;
570
+ reread.current = false;
571
+ setWaitingError(undefined);
572
+ const startsReply = !busy && inFlight.current === 0 && waitingRef.current.length === 0;
573
+ setStopState((s) => stopStateAfter(s, { type: "send", startsReply }));
574
+ if (startsReply) {
575
+ streamStopped.current = false;
576
+ if (id !== null)
577
+ return track(chat.sendMessage({ id, role: "user", parts: outgoingParts(text, files) }));
578
+ return track(files.length === 0 ? chat.sendMessage({ text }) : chat.sendMessage({ parts: outgoingParts(text, files) }));
579
+ }
580
+ const message = { id: id ?? generateId(), role: "user", parts: outgoingParts(text, files) };
581
+ setWaiting([...waitingRef.current, message]);
582
+ posting.current += 1;
583
+ return transport
584
+ .sendWaiting(opts.threadId, message)
585
+ .then((run) => void accepted.current.set(message.id, run), (err) => {
586
+ const error = err instanceof Error ? err : new Error(String(err));
587
+ onErrorRef.current?.(error);
588
+ if (!mounted.current)
589
+ return;
590
+ unsentWhy.current.set(message.id, err);
591
+ setUnsent((had) => new Set([...had, message.id]));
592
+ setWaitingError(error);
593
+ })
594
+ .finally(() => {
595
+ posting.current -= 1;
596
+ flushRef.current();
597
+ });
598
+ };
599
+ const send = (text, files = []) => sendAs(text, files, null);
600
+ useEffect(() => {
601
+ if (!failedSend)
602
+ return;
603
+ const id = unsentAfterError(chat.messages, failedSend.err);
604
+ if (id) {
605
+ unsentWhy.current.set(id, failedSend.err);
606
+ setUnsent((had) => new Set([...had, id]));
607
+ }
608
+ setFailedSend(null);
609
+ }, [failedSend, chat.messages]);
610
+ const [runOutcomes, setRunOutcomes] = useState({});
611
+ const loadParts = useRef({ reread: false, outcomes: false }).current;
612
+ const [historyLoaded, setHistoryLoaded] = useState(false);
613
+ const markLoaded = () => {
614
+ if (loadParts.reread && loadParts.outcomes)
615
+ setHistoryLoaded(true);
616
+ };
617
+ const [savedAsks, setSavedAsks] = useState(() => new Set());
618
+ const history = useRef(opts.initialMessages ? [...opts.initialMessages] : []);
619
+ const loadFrom = useRef({ threadId: opts.threadId, base: kitBaseFor(opts.api), vaultApi: opts.vaultApi ?? `${kitBaseFor(opts.api)}/vault`, fetch: kitFetch });
620
+ const [marks] = useState(() => {
621
+ const from = loadFrom.current;
622
+ const post = seenPoster({ thread: from.threadId, base: from.base, fetch: from.fetch, onError: () => onErrorRef.current });
623
+ return seenMarks((message) => void post(message));
624
+ });
625
+ const reread = useRef(true);
626
+ const chatRef = useRef(null);
627
+ chatRef.current = chat;
628
+ onIdleRef.current = (lastMessageAt) => {
629
+ heardIdle.current = true;
630
+ readOut.current = Promise.resolve(true);
631
+ const load = reread.current;
632
+ if (!stamps.wants(lastMessageAt, noticing.current))
633
+ return;
634
+ if (!load && !noticing.current)
635
+ return stamps.heard(lastMessageAt);
636
+ readOut.current = readArrived(lastMessageAt, load);
637
+ };
638
+ const noticing = useRef(false);
639
+ const heardIdle = useRef(false);
640
+ const [stamps] = useState(stampLedger);
641
+ const reading = useRef(false);
642
+ const readOut = useRef(Promise.resolve(true));
643
+ const readArrived = async (stamp, load) => {
644
+ if (reading.current)
645
+ return true;
646
+ reading.current = true;
647
+ try {
648
+ const from = loadFrom.current;
649
+ const read = await readThreadHistory({ base: from.base, threadId: from.threadId, fetch: from.fetch }).catch(() => null);
650
+ const c = chatRef.current;
651
+ if (!c || !mounted.current)
652
+ return true;
653
+ if (!read)
654
+ return false;
655
+ const free = !busyRef.current && waitingRef.current.length === 0;
656
+ const next = load ? (free ? rereadOnLoad(c.messages, history.current.length, read, drawnRuns.current, (id) => transport.runOfSend(id)) : mergeReread(c.messages, history.current.length, read)) : free ? missedReplies(c.messages, read, drawnRuns.current, (id) => transport.runOfSend(id)) : c.messages;
657
+ if (next !== c.messages) {
658
+ c.setMessages(next);
659
+ if (load) {
660
+ const open = new Set(unansweredRuns(next).map((u) => u.message));
661
+ setRunOutcomes((had) => Object.fromEntries(Object.entries(had).filter(([id]) => open.has(id))));
662
+ }
663
+ }
664
+ if (!free)
665
+ return false;
666
+ stamps.heard(stamp);
667
+ if (load)
668
+ reread.current = false;
669
+ return true;
670
+ }
671
+ finally {
672
+ reading.current = false;
673
+ if (load) {
674
+ loadParts.reread = true;
675
+ markLoaded();
676
+ }
677
+ }
678
+ };
679
+ const idleRef = useRef(() => false);
680
+ idleRef.current = () => mounted.current && chat.status === "ready" && !awaitingReply && deciding.current === 0 && inFlight.current === 0 && posting.current === 0 && !placing.current && waitingRef.current.length === 0 && stopStateRef.current !== "stopping";
681
+ const lookEvery = opts.lookEveryMs ?? NOTICE_EVERY_MS;
682
+ const [looks, setLooks] = useState(0);
683
+ useEffect(() => {
684
+ if (typeof document === "undefined" || typeof window === "undefined")
685
+ return;
686
+ const n = noticeLooks({
687
+ everyMs: lookEvery,
688
+ visible: () => document.visibilityState === "visible",
689
+ idle: () => idleRef.current(),
690
+ look: () => {
691
+ const look = resumeRef.current;
692
+ if (!look)
693
+ return;
694
+ setLooks((n) => n + 1);
695
+ noticing.current = true;
696
+ heardIdle.current = false;
697
+ readOut.current = Promise.resolve(true);
698
+ return track(look())
699
+ .finally(() => {
700
+ noticing.current = false;
701
+ })
702
+ .then(() => (heardIdle.current ? readOut.current : false))
703
+ .then((ok) => (ok ? readOwed() : false));
704
+ },
705
+ });
706
+ notice.current = n;
707
+ const poke = () => n.poke();
708
+ document.addEventListener("visibilitychange", poke);
709
+ window.addEventListener("focus", poke);
710
+ return () => {
711
+ n.dispose();
712
+ notice.current = null;
713
+ document.removeEventListener("visibilitychange", poke);
714
+ window.removeEventListener("focus", poke);
715
+ };
716
+ }, [lookEvery]);
717
+ useEffect(() => {
718
+ notice.current?.settled();
719
+ });
720
+ settleRef.current = (liveId, run) => {
721
+ const from = loadFrom.current;
722
+ const look = (tries) => readThreadHistory({ base: from.base, threadId: from.threadId, fetch: from.fetch }).then((read) => {
723
+ const c = chatRef.current;
724
+ if (!read || !c || !mounted.current || isInterrupted(c.error))
725
+ return;
726
+ const streaming = busyRef.current && c.messages[c.messages.length - 1]?.id === liveId;
727
+ if (streaming)
728
+ return;
729
+ const sent = sentMessageIds(c.messages.find((m) => m.id === liveId)?.parts ?? []);
730
+ const stored = replyOf(read, run, sent);
731
+ if (stored)
732
+ marks.known(liveId, stored.id);
733
+ if (runSettled(read, run, sent))
734
+ owedReads.settled(run);
735
+ const next = reconcileReply(c.messages, liveId, run, read, (id) => transport.runOfSend(id));
736
+ if (next !== c.messages) {
737
+ c.setMessages(next);
738
+ return next;
739
+ }
740
+ if (tries > 0 && !runSettled(read, run, sent)) {
741
+ return new Promise((done) => setTimeout(() => void look(tries - 1).then(done), SETTLE_RETRY_MS));
742
+ }
743
+ return c.messages;
744
+ });
745
+ return look(1)
746
+ .catch(() => undefined)
747
+ .then((now) => {
748
+ owedReads.missed(run);
749
+ return now;
750
+ });
751
+ };
752
+ const readOwed = async () => {
753
+ for (const { run, liveId } of owedReads.owed())
754
+ await settleRef.current(liveId, run);
755
+ return owedReads.owed().length === 0;
756
+ };
757
+ const [artifacts, setArtifacts] = useState([]);
758
+ const settled = chat.status === "ready" || chat.status === "error";
759
+ const readsFiles = opts.showFiles === true;
760
+ useEffect(() => {
761
+ if (!settled || !readsFiles)
762
+ return;
763
+ let live = true;
764
+ const from = loadFrom.current;
765
+ void listKitArtifacts(from.base, from.threadId, from.fetch).then((list) => {
766
+ if (live && list)
767
+ setArtifacts(list);
768
+ });
769
+ return () => {
770
+ live = false;
771
+ };
772
+ }, [settled, readsFiles]);
773
+ const readStateOf = (list, live, only) => {
774
+ const from = loadFrom.current;
775
+ return loadHistoryState(list, { threadId: from.threadId, base: from.base, vaultApi: from.vaultApi, fetch: from.fetch }, {
776
+ outcome: (message, outcome) => {
777
+ const c = chatRef.current;
778
+ if (live() && (!c || runStillUnanswered(c.messages, message)))
779
+ setRunOutcomes((had) => ({ ...had, [message]: outcome }));
780
+ },
781
+ saved: (key) => {
782
+ if (live())
783
+ setSavedAsks((had) => new Set([...had, key]));
784
+ },
785
+ }, only);
786
+ };
787
+ useEffect(() => {
788
+ let live = true;
789
+ void readStateOf(history.current, () => live).then(() => {
790
+ if (!live)
791
+ return;
792
+ loadParts.outcomes = true;
793
+ markLoaded();
794
+ });
795
+ return () => {
796
+ live = false;
797
+ };
798
+ }, []);
799
+ const [earlierAt, setEarlierAt] = useState({ state: "idle", at: null, next: null });
800
+ const earlierNow = useRef(earlierAt);
801
+ earlierNow.current = earlierAt;
802
+ const oldestStored = earlierFrom(chat.messages, opts.threadId);
803
+ const earlier = oldestStored === null ? undefined : earlierAt.state === "loading" ? "loading" : earlierAt.at !== oldestStored || earlierAt.state === "idle" ? "more" : earlierAt.state;
804
+ const readingEarlier = useRef(false);
805
+ const loadEarlier = async () => {
806
+ const c = chatRef.current;
807
+ const oldest = c ? earlierFrom(c.messages, opts.threadId) : null;
808
+ if (readingEarlier.current || !c || oldest === null)
809
+ return;
810
+ const was = earlierNow.current;
811
+ const before = was.at === oldest && was.next !== null ? was.next : oldest;
812
+ readingEarlier.current = true;
813
+ setEarlierAt({ state: "loading", at: oldest, next: before });
814
+ try {
815
+ const page = await readEarlier(loadFrom.current, before);
816
+ const now = chatRef.current;
817
+ if (!mounted.current || !now)
818
+ return;
819
+ if (!page)
820
+ return setEarlierAt({ state: "failed", at: oldest, next: before });
821
+ let placed = [];
822
+ let fresh = [];
823
+ now.setMessages((ms) => {
824
+ placed = placeEarlier(ms, page.messages);
825
+ fresh = placed.slice(0, placed.length - ms.length);
826
+ return placed;
827
+ });
828
+ if (fresh.length > 0)
829
+ history.current = [...fresh, ...history.current];
830
+ setEarlierAt({ state: page.next === null ? "end" : "idle", at: earlierFrom(placed, opts.threadId), next: page.next });
831
+ if (fresh.length > 0)
832
+ void readStateOf(placed, () => mounted.current, new Set(fresh.map((m) => m.id)));
833
+ }
834
+ finally {
835
+ readingEarlier.current = false;
836
+ }
837
+ };
838
+ const listed = useMemo(() => withWaiting(chat.messages, waiting), [chat.messages, waiting]);
839
+ stopRunRef.current = async () => {
840
+ try {
841
+ if (!(await transport.stop(opts.threadId)))
842
+ setStopState((s) => stopStateAfter(s, { type: "no-run" }));
843
+ }
844
+ catch (err) {
845
+ onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));
846
+ setStopState((s) => stopStateAfter(s, { type: "refused", busy: busyRef.current }));
847
+ }
848
+ };
849
+ const deciding = useRef(0);
850
+ const followUp = () => {
851
+ deciding.current += 1;
852
+ return lookAfterDecision({
853
+ replyOpen: openAtDecision.current !== null && openAtDecision.current === replyEnds.current.n ? new Promise((r) => replyEnds.current.next.push(r)) : null,
854
+ begin: () => {
855
+ resuming.current = true;
856
+ followed.current = false;
857
+ },
858
+ look: () => resumeRef.current?.() ?? Promise.resolve(),
859
+ followed: () => followed.current,
860
+ here: () => mounted.current,
861
+ missed: async () => {
862
+ const from = loadFrom.current;
863
+ const read = await readThreadHistory({ base: from.base, threadId: from.threadId, fetch: from.fetch }).catch(() => null);
864
+ const c = chatRef.current;
865
+ if (!read || !c || !mounted.current || busyRef.current || followed.current)
866
+ return false;
867
+ const next = missedReplies(c.messages, read, drawnRuns.current, (id) => transport.runOfSend(id));
868
+ if (next === c.messages)
869
+ return false;
870
+ c.setMessages(next);
871
+ followed.current = true;
872
+ watch.attached();
873
+ watch.ended();
874
+ return true;
875
+ },
876
+ }).finally(() => {
877
+ deciding.current -= 1;
878
+ });
879
+ };
880
+ followUpRef.current = followUp;
881
+ return {
882
+ ...chat,
883
+ messages: listed.messages,
884
+ error: chat.error ?? waitingError,
885
+ waiting: listed.waiting,
886
+ stop: async () => {
887
+ setStopState((s) => stopStateAfter(s, { type: "tap" }));
888
+ if (!busyRef.current && watch.stopEarly())
889
+ return;
890
+ await stopRunRef.current();
891
+ },
892
+ stopState,
893
+ awaitingReply,
894
+ afterDecision: (taken) => {
895
+ wordsAtDecision.current = agentWords(chat.messages);
896
+ openAtDecision.current = busyRef.current ? replyEnds.current.n : null;
897
+ watch.decided(taken, busyRef.current);
898
+ },
899
+ awaitingWords: awaitingReply && agentWords(chat.messages) <= wordsAtDecision.current,
900
+ looks,
901
+ historyLoaded,
902
+ earlier,
903
+ loadEarlier: () => void loadEarlier(),
904
+ seen: (s) => marks.seen(s.message),
905
+ runOutcomes,
906
+ savedAsks,
907
+ unsent,
908
+ unsentReasons,
909
+ sendAgain: (id) => {
910
+ const waited = waitingRef.current.find((x) => x.id === id);
911
+ const m = waited ?? chat.messages.find((x) => x.id === id);
912
+ if (!m)
913
+ return;
914
+ const again = againOf(m, unsentWhy.current.get(id));
915
+ unsentWhy.current.delete(id);
916
+ if (waited)
917
+ setWaiting(waitingRef.current.filter((x) => x.id !== id));
918
+ else
919
+ chat.setMessages(chat.messages.filter((x) => x.id !== id));
920
+ setUnsent((had) => new Set([...had].filter((x) => x !== id)));
921
+ chat.clearError();
922
+ void sendAs(again.text, again.files, again.id);
923
+ },
924
+ queued,
925
+ queuedReason,
926
+ artifacts,
927
+ artifactHref: (id) => artifactDownloadHref(loadFrom.current.base, loadFrom.current.threadId, id),
928
+ artifactText: (id) => readKitArtifactText(loadFrom.current.base, loadFrom.current.threadId, id, loadFrom.current.fetch),
929
+ attach: (file) => uploadKitFile(loadFrom.current.base, loadFrom.current.threadId, file, loadFrom.current.fetch),
930
+ send,
931
+ reconnect: async () => {
932
+ const err = chat.error;
933
+ const lastMessage = chat.messages[chat.messages.length - 1];
934
+ const dropped = isInterrupted(err) && err.run && lastMessage?.role === "assistant" ? lastMessage : null;
935
+ if (dropped)
936
+ chat.setMessages(chat.messages.slice(0, -1));
937
+ chat.clearError();
938
+ resuming.current = true;
939
+ await chat.resumeStream();
940
+ if (dropped)
941
+ chat.setMessages((ms) => afterReconnect(ms, dropped));
942
+ },
943
+ };
944
+ }
945
+ export function composerIsOff(spec, error, refused) {
946
+ if (!spec)
947
+ return false;
948
+ return spec.now !== false || refused || refusedForOff(spec, error);
949
+ }
950
+ function refusedForOff(spec, error) {
951
+ return spec?.code !== undefined && error instanceof Error && error.code === spec.code;
952
+ }
953
+ function connectedWords(l, app, appName) {
954
+ return app.startsWith("custom-") ? l.doneCustom : l.done.replaceAll("{app}", appName);
955
+ }
956
+ export function agentChatViewProps(chat, props) {
957
+ const l = { ...DEFAULT_LABELS, ...props.labels };
958
+ return {
959
+ messages: chat.messages,
960
+ threadId: props.threadId,
961
+ busy: chat.status === "submitted" || chat.status === "streaming" || chat.awaitingReply === true,
962
+ awaitingWords: chat.awaitingWords === true,
963
+ error: chat.error,
964
+ queued: chat.queued,
965
+ queuedReason: chat.queuedReason,
966
+ labels: props.labels,
967
+ renderText: props.renderText,
968
+ showToolCalls: props.showToolCalls,
969
+ showFiles: props.showFiles,
970
+ steps: props.steps,
971
+ approvalFields: props.approvalFields,
972
+ className: props.className,
973
+ suggestions: props.suggestions,
974
+ suggestionsAt: props.suggestionsAt,
975
+ autoFocus: props.autoFocus,
976
+ approvalBar: props.approvalBar,
977
+ fromSchedule: props.fromSchedule,
978
+ agentName: props.agentName,
979
+ avatar: props.avatar,
980
+ onSeen: (s) => {
981
+ chat.seen(s);
982
+ props.onSeen?.(s);
983
+ },
984
+ openAt: props.openAt,
985
+ historyLoaded: chat.historyLoaded,
986
+ earlier: chat.earlier,
987
+ onLoadEarlier: chat.loadEarlier,
988
+ onOpenAtMissing: props.onOpenAtMissing,
989
+ ref: props.ref,
990
+ beforeComposer: props.beforeComposer,
991
+ afterComposer: props.afterComposer,
992
+ composerOff: props.composerOff,
993
+ computer: props.computer,
994
+ onSend: (text, files) => void chat.send(text, files),
995
+ waiting: chat.waiting,
996
+ onStop: () => void chat.stop(),
997
+ stopState: chat.stopState,
998
+ onAttach: chat.attach,
999
+ artifacts: chat.artifacts,
1000
+ artifactHref: chat.artifactHref,
1001
+ artifactText: chat.artifactText,
1002
+ onReconnect: () => void chat.reconnect(),
1003
+ vaultApi: props.vaultApi ?? `${kitBaseFor(props.api)}/vault`,
1004
+ vaultLabels: props.vaultLabels,
1005
+ runOutcomes: chat.runOutcomes,
1006
+ savedAsks: chat.savedAsks,
1007
+ unsent: chat.unsent,
1008
+ unsentReasons: chat.unsentReasons,
1009
+ onSendAgain: chat.sendAgain,
1010
+ onVaultSaved: () => void chat.send(l.vaultSaved),
1011
+ onVaultError: props.onError,
1012
+ connect: { api: kitBaseFor(props.api), labels: props.connectLabels, onError: props.onError, onConnected: (app, name) => void chat.send(connectedWords(connectLabelsOf(props.connectLabels), app, name)) },
1013
+ approvalBase: kitBaseFor(props.api),
1014
+ approvalLook: chat.looks,
1015
+ onApprovalDeciding: (_decision, taken) => chat.afterDecision(taken),
1016
+ fetch: props.fetch,
1017
+ };
1018
+ }
1019
+ export function AgentChat(props) {
1020
+ return _jsx(ThreadChat, { ...props }, props.threadId);
1021
+ }
1022
+ function ThreadChat(props) {
1023
+ return _jsx(AgentChatView, { ...agentChatViewProps(useAgentChat(props), props) });
1024
+ }
1025
+ const MCP_TOOL_PREFIX = /^mcp_[a-z][a-z0-9]{1,15}_/;
1026
+ function yourTool(name, l) {
1027
+ return l.tools?.[name] ?? l.tools?.[name.replace(MCP_TOOL_PREFIX, "")];
1028
+ }
1029
+ function toolLabel(name, l) {
1030
+ const yours = yourTool(name, l);
1031
+ if (typeof yours === "string" && yours)
1032
+ return yours;
1033
+ if (typeof yours === "object" && yours.running)
1034
+ return yours.running;
1035
+ const own = name.replace(MCP_TOOL_PREFIX, "");
1036
+ const words = own.replace(/[_.-]+/g, " ").trim();
1037
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : name;
1038
+ }
1039
+ function isHeld(part) {
1040
+ return part["state"] === "output-available" && part["output"]?.status === "requires_approval";
1041
+ }
1042
+ function scheduled(part) {
1043
+ const repeats = part["output"]?.repeats;
1044
+ if (typeof repeats === "string" && repeats !== "")
1045
+ return repeats === "once" ? "once" : "repeats";
1046
+ const input = part["input"];
1047
+ if (!input || typeof input !== "object" || Array.isArray(input))
1048
+ return null;
1049
+ const cron = input.cron;
1050
+ return typeof cron === "string" && cron.trim() !== "" ? "repeats" : "once";
1051
+ }
1052
+ function toolLine(part, l, failed = true) {
1053
+ const type = String(part["type"]);
1054
+ const name = type === "dynamic-tool" ? String(part["toolName"] ?? "tool") : type.startsWith("tool-") ? type.slice(5) : null;
1055
+ if (name === null || name === "agent_finish")
1056
+ return null;
1057
+ const state = String(part["state"] ?? "");
1058
+ if (name === "agent_note_to_user" && state === "output-available" && !isHeld(part))
1059
+ return null;
1060
+ const label = toolLabel(name, l);
1061
+ const yours = yourTool(name, l);
1062
+ if (state === "output-error" && !failed) {
1063
+ const own = yours ? undefined : BUILT_IN_TOOLS[name];
1064
+ return { text: own ? own[2] : l.toolSkipped.replace("{tool}", label), state, recovered: true };
1065
+ }
1066
+ const sentence = state === "output-error" && typeof part["errorText"] === "string" ? part["errorText"].trim().slice(0, 500) : "";
1067
+ if (sentence)
1068
+ return { text: sentence, state };
1069
+ const held = isHeld(part);
1070
+ const builtIn = yours ? undefined : BUILT_IN_TOOLS[name];
1071
+ if (builtIn && !held && state !== "output-error" && state !== "output-denied") {
1072
+ const kind = name === "agent_schedule" && state === "output-available" ? scheduled(part) : null;
1073
+ return { text: state === "output-available" ? (kind ? KIT_SCHEDULE_DONE[kind] : builtIn[1]) : `${builtIn[0]}…`, state };
1074
+ }
1075
+ if (typeof yours === "object" && !held && state !== "output-error" && state !== "output-denied") {
1076
+ return { text: state === "output-available" ? yours.done : yours.running, state };
1077
+ }
1078
+ const words = held ? l.toolWaiting : state === "output-available" ? l.toolDone : state === "output-error" ? l.toolFailed : state === "output-denied" ? l.toolDenied : l.toolCalling;
1079
+ return { text: words.replace("{tool}", builtIn ? builtIn[0] : label), state, ...(held ? { waiting: true } : {}) };
1080
+ }
1081
+ export function refusalAfterDecision(decision, runRefused) {
1082
+ return decision === "approve" ? runRefused : null;
1083
+ }
1084
+ const APPROVAL_ID_RE = /^apr_[0-9A-Za-z]{1,64}$/;
1085
+ export function carriedOn(was, now) {
1086
+ const s = was ?? { working: new Set(), settled: new Set() };
1087
+ if (now.busy) {
1088
+ const fresh = [...now.decided].filter((a) => !s.working.has(a) && !s.settled.has(a));
1089
+ return fresh.length === 0 ? s : { working: new Set([...s.working, ...fresh]), settled: s.settled };
1090
+ }
1091
+ if (s.working.size === 0)
1092
+ return s;
1093
+ return { working: new Set(), settled: new Set([...s.settled, ...s.working]) };
1094
+ }
1095
+ const ACTION_ID_RE = /^act_[0-9A-Za-z]{1,64}$/;
1096
+ function actionOfPart(part) {
1097
+ const action = part["output"]?.action;
1098
+ if (typeof action === "string" && ACTION_ID_RE.test(action))
1099
+ return action;
1100
+ const id = part["toolCallId"];
1101
+ return typeof id === "string" && ACTION_ID_RE.test(id) ? id : null;
1102
+ }
1103
+ export function chatBubbles(parts, o) {
1104
+ const out = [];
1105
+ const once = new Set(o.drawn);
1106
+ let run = [];
1107
+ let split = false;
1108
+ parts.forEach((p, i) => {
1109
+ if (p.type !== "data-message") {
1110
+ run.push(i);
1111
+ return;
1112
+ }
1113
+ const message = sentMessageOf(p);
1114
+ if (!message || once.has(message.id))
1115
+ return;
1116
+ once.add(message.id);
1117
+ split = true;
1118
+ if (run.some(o.says)) {
1119
+ out.push({ kind: "parts", parts: run, reply: false });
1120
+ run = [];
1121
+ }
1122
+ out.push({ kind: "message", part: i, message });
1123
+ });
1124
+ if (!split)
1125
+ return [{ kind: "parts", parts: run, reply: true }];
1126
+ if (run.length > 0 && (o.tail || run.some(o.shows)))
1127
+ out.push({ kind: "parts", parts: run, reply: true });
1128
+ return out;
1129
+ }
1130
+ function repeatedParts(parts) {
1131
+ const seen = new Set();
1132
+ const again = new Set();
1133
+ parts.forEach((p, i) => {
1134
+ const data = p.data;
1135
+ const key = p.type === "data-artifact" ? (artifactOf(data)?.id ?? null) : p.type === "data-model-note" && modelNoteOf(data) ? "model-note" : null;
1136
+ if (key === null)
1137
+ return;
1138
+ if (seen.has(key))
1139
+ again.add(i);
1140
+ else
1141
+ seen.add(key);
1142
+ });
1143
+ return again;
1144
+ }
1145
+ function modelNoteOf(data) {
1146
+ const d = data;
1147
+ if (!d || typeof d !== "object" || d.object !== "model_note")
1148
+ return null;
1149
+ return { reason: typeof d.reason === "string" ? d.reason : null, message: typeof d.message === "string" && d.message.trim() !== "" ? d.message : null };
1150
+ }
1151
+ function modelNoteWords(note, labels) {
1152
+ return ((note.reason !== null ? labels.modelNotes?.[note.reason] : undefined) ?? note.message ?? labels.modelNote).slice(0, 500);
1153
+ }
1154
+ export function partKeys(parts, cardOf) {
1155
+ const met = new Map();
1156
+ return parts.map((part, i) => {
1157
+ const p = part;
1158
+ const before = i > 0 ? parts[i - 1] : null;
1159
+ const askedBy = (tool) => (before && before["type"] === tool ? actionOfPart(before) : null);
1160
+ const card = cardOf(i);
1161
+ let key = part.type;
1162
+ if (card !== null)
1163
+ key = `approval:${card}`;
1164
+ else if (part.type.startsWith("tool-") || part.type === "dynamic-tool") {
1165
+ const action = actionOfPart(p);
1166
+ key = action ? `action:${action}` : `call:${String(p["toolCallId"] ?? "")}`;
1167
+ }
1168
+ else if (part.type === "data-connection-request") {
1169
+ const r = connectionRequestOf(p["data"]);
1170
+ key = `connect:${askedBy("tool-connections_request") ?? (r ? connectKey(r) : "")}`;
1171
+ }
1172
+ else if (part.type === "data-vault-request") {
1173
+ key = `vault:${askedBy("tool-vault_ask_user") ?? vaultRequestOf(p["data"])?.name ?? ""}`;
1174
+ }
1175
+ else if (part.type === "data-artifact") {
1176
+ const a = artifactOf(p["data"]);
1177
+ if (a)
1178
+ key = `artifact:${a.id}`;
1179
+ }
1180
+ const n = met.get(key) ?? 0;
1181
+ met.set(key, n + 1);
1182
+ return n === 0 ? key : `${key}#${n}`;
1183
+ });
1184
+ }
1185
+ export function approvalOfPart(part) {
1186
+ const output = part["output"];
1187
+ const id = output?.approval ?? part["approval"];
1188
+ return typeof id === "string" && APPROVAL_ID_RE.test(id) ? id : null;
1189
+ }
1190
+ export function approvalPlaces(messages, outcomes, decidedIn) {
1191
+ const shownIds = new Set(messages.map((m) => m.id));
1192
+ const stayAt = (apr) => {
1193
+ const at = decidedIn?.get(apr);
1194
+ return at !== undefined && shownIds.has(at) ? at : null;
1195
+ };
1196
+ const actions = new Set();
1197
+ const cardOf = new Map();
1198
+ const named = [];
1199
+ for (const m of messages) {
1200
+ m.parts.forEach((p, i) => {
1201
+ const id = p.type.startsWith("tool-") || p.type === "dynamic-tool" ? approvalOfPart(p) : null;
1202
+ if (!id)
1203
+ return;
1204
+ const key = `${m.id}:${i}`;
1205
+ const call = p.toolCallId;
1206
+ const outAction = (p.output ?? null)?.action;
1207
+ const action = typeof outAction === "string" && outAction !== "" ? outAction : typeof call === "string" && call !== "" ? call : key;
1208
+ const held = isHeld(p);
1209
+ const at = stayAt(id);
1210
+ if (at !== null) {
1211
+ actions.add(action);
1212
+ if (m.id === at)
1213
+ cardOf.set(id, key);
1214
+ }
1215
+ else if (!actions.has(action) || held) {
1216
+ actions.add(action);
1217
+ cardOf.set(id, key);
1218
+ }
1219
+ named.push({ apr: id, key, part: true, held });
1220
+ });
1221
+ for (const t of outcomes?.[m.id]?.tools ?? []) {
1222
+ if (!t.approval)
1223
+ continue;
1224
+ const action = t.action ?? `${m.id}:${t.approval}`;
1225
+ if (actions.has(action))
1226
+ continue;
1227
+ actions.add(action);
1228
+ const at = stayAt(t.approval);
1229
+ if (at === null || at === m.id)
1230
+ cardOf.set(t.approval, `${m.id}:${t.approval}`);
1231
+ named.push({ apr: t.approval, key: `${m.id}:${t.approval}`, part: false, held: false });
1232
+ }
1233
+ }
1234
+ const cards = new Set(cardOf.values());
1235
+ const below = new Set();
1236
+ const after = new Set();
1237
+ const spent = new Set();
1238
+ for (const { apr, key, part, held } of named) {
1239
+ if (key === cardOf.get(apr))
1240
+ after.add(apr);
1241
+ else if (part && !after.has(apr))
1242
+ below.add(key);
1243
+ else if (part && held && stayAt(apr) !== null)
1244
+ spent.add(key);
1245
+ }
1246
+ return { cards, below, spent };
1247
+ }
1248
+ function cardFollows(part, next, saved) {
1249
+ if (!next)
1250
+ return false;
1251
+ const data = next.data;
1252
+ if (part.type === "tool-connections_request")
1253
+ return next.type === "data-connection-request" && connectionRequestOf(data) !== null;
1254
+ if (part.type === "tool-vault_ask_user")
1255
+ return next.type === "data-vault-request" && !saved && vaultRequestOf(data) !== null;
1256
+ return false;
1257
+ }
1258
+ function stepLineOf(part, labels, saved, carded, card) {
1259
+ const p = part;
1260
+ if (carded || card !== null)
1261
+ return null;
1262
+ return toolLine(p, labels);
1263
+ }
1264
+ function toolWords(part, labels) {
1265
+ const type = String(part["type"]);
1266
+ const name = type === "dynamic-tool" ? String(part["toolName"] ?? "tool") : type.slice(5);
1267
+ const builtIn = yourTool(name, labels) ? undefined : BUILT_IN_TOOLS[name];
1268
+ return builtIn ? builtIn[0] : toolLabel(name, labels);
1269
+ }
1270
+ function heldTitle(part, labels) {
1271
+ return toolLine({ type: part["type"], toolName: part["toolName"], state: "output-available", output: { status: "requires_approval" } }, labels)?.text ?? labels.toolWaiting.replace("{tool}", "");
1272
+ }
1273
+ function decidedLine(part, labels) {
1274
+ const status = part["output"]?.status;
1275
+ if (part["state"] === "output-available" && status === "requires_approval")
1276
+ return undefined;
1277
+ return toolLine(part, labels)?.text;
1278
+ }
1279
+ function Part({ part, info, labels, renderText, showToolCalls, vault, saved, approval, connect, fetch: kitFetch, ask, carded, files, card, below, failed, streaming, computer, computerAt, computerPointer }) {
1280
+ if (part.type === "text") {
1281
+ if (renderText)
1282
+ return _jsx("div", { "data-ol-text": true, children: renderText(part.text, info) });
1283
+ return info.role === "assistant" ? (_jsx("div", { "data-ol-text": true, children: _jsx(MarkdownText, { text: part.text, ended: !streaming, tainted: info.tainted }) })) : (_jsx("div", { "data-ol-text": true, style: { whiteSpace: "pre-wrap" }, children: part.text }));
1284
+ }
1285
+ if (part.type === "data-attachments") {
1286
+ const files = attachmentsOf(part.data);
1287
+ return files.length > 0 ? _jsx(FileChips, { files: files }) : null;
1288
+ }
1289
+ if (part.type === "data-model-note") {
1290
+ const note = modelNoteOf(part.data);
1291
+ return note ? (_jsx("p", { "data-ol-model-note": true, role: "note", children: modelNoteWords(note, labels) })) : null;
1292
+ }
1293
+ if (part.type === "data-refusal") {
1294
+ const data = part.data;
1295
+ return _jsx(RefusalNote, { code: typeof data?.code === "string" ? data.code : null, message: typeof data?.message === "string" ? data.message : null, limit: limitOf(data?.limit), labels: labels });
1296
+ }
1297
+ if (part.type === "data-computer")
1298
+ return computerAt ? _jsx(ComputerRow, { session: computerAt, computer: computer }) : computerPointer ? _jsx(ComputerPointer, { session: computerPointer, computer: computer }) : null;
1299
+ if (part.type === "data-artifact") {
1300
+ const a = artifactOf(part.data);
1301
+ const href = a ? files.artifactHref?.(a.id) : undefined;
1302
+ const read = files.artifactText;
1303
+ return a && href ? _jsx(ArtifactCard, { artifact: a, href: href, labels: labels, renderText: renderText, ...(read ? { loadText: () => read(a.id) } : {}) }) : null;
1304
+ }
1305
+ if (part.type === "data-connection-request") {
1306
+ const r = connectionRequestOf(part.data);
1307
+ return r ? _jsx(ConnectButton, { app: r.app, appName: r.appName, reason: r.reason, agent: r.agent, reconnect: r.reconnect, tainted: r.tainted, ...(connect?.api ? { api: connect.api } : {}), ...(kitFetch ? { fetch: kitFetch } : {}), labels: connect?.labels, onConnected: connect?.onConnected, onError: connect?.onError }) : null;
1308
+ }
1309
+ if (part.type === "data-vault-request" && !saved) {
1310
+ const request = vaultRequestOf(part.data);
1311
+ if (request) {
1312
+ return (_jsx(VaultSecretForm, { request: request, ...(vault.vaultApi ? { api: vault.vaultApi } : {}), ...(vault.vaultLabels ? { labels: vault.vaultLabels } : {}), ...(vault.onVaultSaved ? { onSaved: vault.onVaultSaved } : {}), ...(vault.onVaultError ? { onError: vault.onVaultError } : {}), ...(ask ? { ask } : {}), ...(kitFetch ? { fetch: kitFetch } : {}) }));
1313
+ }
1314
+ }
1315
+ if (part.type === "data-vault-request")
1316
+ return null;
1317
+ if (card) {
1318
+ return _jsx(ChatApprovalCard, { id: card, approval: approval, labels: labels, fallbackTitle: heldTitle(part, labels), loadingTitle: decidedLine(part, labels) });
1319
+ }
1320
+ if (below) {
1321
+ return (_jsx("div", { "data-ol-tool": true, "data-ol-tool-state": String(part.state ?? ""), "data-ol-approval-below": true, ...(isHeld(part) ? { "data-ol-tool-waiting": "true" } : {}), children: labels.toolApprovalBelow.replace("{tool}", toolWords(part, labels)) }));
1322
+ }
1323
+ if (showToolCalls && !carded) {
1324
+ const t = toolLine(part, labels, failed);
1325
+ if (t) {
1326
+ return (_jsx("div", { "data-ol-tool": true, "data-ol-tool-state": t.state, ...(t.recovered ? { "data-ol-tool-recovered": "true" } : {}), ...(t.waiting ? { "data-ol-tool-waiting": "true" } : {}), children: t.text }));
1327
+ }
1328
+ }
1329
+ return null;
1330
+ }
1331
+ function FileChips({ files, onRemove, removeLabel }) {
1332
+ return (_jsx("ul", { "data-ol-attachments": true, children: files.map((f) => (_jsxs("li", { "data-ol-attachment": true, children: [_jsx("span", { "data-ol-attachment-name": true, children: f.name }), onRemove ? (_jsx("button", { type: "button", "data-ol-attachment-remove": true, "aria-label": (removeLabel ?? "Remove {file}").replace("{file}", f.name), onClick: () => onRemove(f.id), children: "\u00D7" })) : null] }, f.id))) }));
1333
+ }
1334
+ function DeliveredFiles({ artifacts, href, labels }) {
1335
+ return (_jsxs("section", { "data-ol-files": true, "aria-label": labels.files, children: [_jsx("h2", { "data-ol-files-heading": true, children: labels.files }), _jsx("ul", { "data-ol-files-list": true, children: artifacts.map((a) => (_jsxs("li", { "data-ol-file": true, "data-ol-tainted": a.tainted ? "true" : "false", children: [_jsx("a", { "data-ol-file-link": true, href: href(a.id), download: a.name, children: a.name }), " ", _jsx("span", { "data-ol-file-size": true, children: sizeText(a.size_bytes) }), a.tainted ? (_jsx("span", { "data-ol-file-note": true, children: labels.fileUntrusted })) : null] }, a.id))) })] }));
1336
+ }
1337
+ const noSubscribe = () => () => undefined;
1338
+ function useLive() {
1339
+ return useSyncExternalStore(noSubscribe, () => true, () => false);
1340
+ }
1341
+ function RefusalNote({ code, message, limit, labels, alert = false }) {
1342
+ const live = useLive();
1343
+ const [, rerender] = useState(0);
1344
+ const at = limit?.resetsAt ? Date.parse(limit.resetsAt) : null;
1345
+ useEffect(() => {
1346
+ if (!live || at === null)
1347
+ return;
1348
+ const wait = at - Date.now();
1349
+ if (wait <= 0)
1350
+ return;
1351
+ const t = setTimeout(() => rerender((n) => n + 1), Math.min(wait + 1000, 2_147_483_647));
1352
+ return () => clearTimeout(t);
1353
+ }, [live, at]);
1354
+ const text = refusalWords({ code, message, limit }, labels, live);
1355
+ if (text === null)
1356
+ return null;
1357
+ const raise = code === "cap_reached" && limit ? labels.limits?.raise : undefined;
1358
+ const reset = live && at !== null && at <= Date.now();
1359
+ return (_jsxs(_Fragment, { children: [alert ? (_jsx("p", { role: "alert", "data-ol-refusal": true, children: text.slice(0, 500) })) : (_jsx("p", { "data-ol-refusal": true, role: "note", children: text.slice(0, 500) })), raise && !reset ? (_jsx("p", { "data-ol-limit-raise": true, children: _jsx("a", { href: raise.href, children: raise.text }) })) : null] }));
1360
+ }
1361
+ function sendHeldUntil(error) {
1362
+ if (!(error instanceof AgentChatError) || error.code !== "cap_reached" || !error.limit?.resetsAt)
1363
+ return null;
1364
+ const at = Date.parse(error.limit.resetsAt);
1365
+ return Number.isNaN(at) ? null : at;
1366
+ }
1367
+ function outcomeParts(outcome, labels, showToolCalls, isCard = () => true) {
1368
+ const carded = (t) => t.approval !== undefined && isCard(t.approval);
1369
+ const cards = outcome.tools.flatMap((t) => (t.approval && carded(t) ? [{ id: t.approval, title: heldTitle({ type: `tool-${t.tool}` }, labels) }] : []));
1370
+ const lines = showToolCalls ? outcome.tools.filter((t) => !carded(t)).map((t) => toolLine({ type: `tool-${t.tool}`, state: t.state }, labels, outcomeFailed(outcome))).filter((t) => t !== null) : [];
1371
+ const r = outcome.refusal;
1372
+ const text = r ? ((r.code !== null ? labels.refusals?.[r.code] : undefined) ?? r.message) : null;
1373
+ return { cards, lines, text, stopped: outcome.stopped === true };
1374
+ }
1375
+ function hasOutcome(outcome, labels, showToolCalls, isCard) {
1376
+ const { cards, lines, text, stopped } = outcomeParts(outcome, labels, showToolCalls, isCard);
1377
+ return cards.length > 0 || lines.length > 0 || text !== null || stopped;
1378
+ }
1379
+ export function chatGoOn(opts) {
1380
+ if (opts.busy || opts.off)
1381
+ return null;
1382
+ return () => opts.onSend(opts.message);
1383
+ }
1384
+ export function ChatApprovalCard({ id, approval, labels, fallbackTitle, loadingTitle }) {
1385
+ const control = useContext(BrowserControlContext);
1386
+ const refused = approval.refused?.(id);
1387
+ const kept = refused ? decisionRefusalWords(refused.code, labels) : undefined;
1388
+ const noteLabels = refused && kept !== undefined ? { ...labels, refusals: { ...labels.refusals, [refused.code]: kept } } : labels;
1389
+ return (_jsxs(_Fragment, { children: [_jsx(ApprovalCard, { id: id, base: approval.approvalBase ?? "/api/openlegion", fallbackTitle: fallbackTitle, ...(loadingTitle !== undefined ? { loadingTitle } : {}), labels: labels, fields: approval.approvalFields, ...(approval.fetch ? { fetch: approval.fetch } : {}), onDecided: (decision, after) => approval.tookHere?.(id, refusalAfterDecision(decision, after.runRefused)), decidedHere: approval.decidedHere?.(id) === true, settled: approval.settled?.(id) === true || refused !== undefined, ...(approval.onApprovalDeciding ? { onDeciding: approval.onApprovalDeciding } : {}), look: approval.approvalLook, heldSessions: control?.held }), refused ? _jsx(RefusalNote, { code: refused.code, message: refused.message, limit: refused.limit, labels: noteLabels }) : null] }));
1390
+ }
1391
+ function Outcome({ outcome, labels, showToolCalls, approval, isCard }) {
1392
+ const { cards, lines, text, stopped } = outcomeParts(outcome, labels, showToolCalls, isCard);
1393
+ if (cards.length === 0 && lines.length === 0 && text === null && !stopped)
1394
+ return null;
1395
+ return (_jsxs("div", { "data-ol-run-outcome": true, children: [cards.map((c) => (_jsx(ChatApprovalCard, { id: c.id, approval: approval, labels: labels, fallbackTitle: c.title }, c.id))), lines.map((t, i) => (_jsx("div", { "data-ol-tool": true, "data-ol-tool-state": t.state, ...(t.recovered ? { "data-ol-tool-recovered": "true" } : {}), ...(t.waiting ? { "data-ol-tool-waiting": "true" } : {}), children: t.text }, i))), text !== null && outcome.refusal ? _jsx(RefusalNote, { code: outcome.refusal.code, message: outcome.refusal.message, limit: outcome.refusal.limit ?? null, labels: labels }) : null, stopped ? (_jsx("p", { role: "status", "data-ol-stopped": true, children: labels.stopped })) : null] }));
1396
+ }
1397
+ export function submitAction(text, uploading) {
1398
+ if (text.trim() === "")
1399
+ return "none";
1400
+ return uploading > 0 ? "hold" : "send";
1401
+ }
1402
+ export function heldSendNext(s) {
1403
+ if (s.failed)
1404
+ return "cancel";
1405
+ return s.uploading > 0 ? "wait" : "send";
1406
+ }
1407
+ export function composerAction(s) {
1408
+ return s.busy && s.canStop && s.stopAsked !== true && s.text.trim() === "" ? "stop" : "send";
1409
+ }
1410
+ export function AgentChatView(props) {
1411
+ const l = { ...DEFAULT_LABELS, ...props.labels };
1412
+ const agentName = props.agentName?.trim() ? props.agentName.trim() : null;
1413
+ const agentAuthor = agentName ? (_jsxs("span", { "data-ol-author": true, children: [_jsx(Avatar, { agent: { name: agentName }, name: agentName, draw: props.avatar }), _jsx("span", { children: agentName })] })) : (_jsx("span", { "data-ol-author": true, children: l.agent }));
1414
+ const [input, setInput] = useState("");
1415
+ const [cards] = useState(cardLedger);
1416
+ const [attached, setAttached] = useState([]);
1417
+ const [uploading, setUploading] = useState(0);
1418
+ const [attachError, setAttachError] = useState(null);
1419
+ const [held, setHeld] = useState(null);
1420
+ const offSpec = props.composerOff;
1421
+ const [offLatch, setOffLatch] = useState({ now: offSpec?.now, refused: false });
1422
+ if (offLatch.now !== offSpec?.now)
1423
+ setOffLatch({ now: offSpec?.now, refused: false });
1424
+ else if (!offLatch.refused && refusedForOff(offSpec, props.error))
1425
+ setOffLatch({ now: offLatch.now, refused: true });
1426
+ const off = composerIsOff(offSpec, props.error, offLatch.now === offSpec?.now && offLatch.refused);
1427
+ const offNow = useRef(off);
1428
+ offNow.current = off;
1429
+ const error = offSpec && refusedForOff(offSpec, props.error) ? undefined : props.error;
1430
+ const limitUntil = sendHeldUntil(error);
1431
+ const [, redraw] = useState(0);
1432
+ useEffect(() => {
1433
+ if (limitUntil === null)
1434
+ return;
1435
+ const t = setTimeout(() => redraw((n) => n + 1), Math.min(Math.max(0, limitUntil - Date.now()) + 1000, 2_147_483_647));
1436
+ return () => clearTimeout(t);
1437
+ }, [limitUntil]);
1438
+ const limitHolds = limitUntil !== null && limitUntil > Date.now();
1439
+ const unsentWhyOf = (id) => props.unsentReasons?.get(id) ?? (error !== undefined ? unsentReason(error) : "failed");
1440
+ const picker = useRef(null);
1441
+ const onAttach = props.onAttach;
1442
+ const pick = (list) => {
1443
+ if (!onAttach || !list)
1444
+ return;
1445
+ setAttachError(null);
1446
+ const room = MAX_ATTACHMENTS - attached.length - uploading;
1447
+ for (const file of Array.from(list).slice(0, Math.max(0, room))) {
1448
+ if (file.size > MAX_ATTACHMENT_BYTES) {
1449
+ setAttachError(l.fileTooLarge);
1450
+ continue;
1451
+ }
1452
+ setUploading((n) => n + 1);
1453
+ onAttach(file)
1454
+ .then((f) => setAttached((had) => (had.length < MAX_ATTACHMENTS ? [...had, f] : had)))
1455
+ .catch((err) => {
1456
+ setAttachError(attachErrorText(err, l));
1457
+ setHeld((h) => (h ? { failed: true } : h));
1458
+ })
1459
+ .finally(() => setUploading((n) => n - 1));
1460
+ }
1461
+ if (picker.current)
1462
+ picker.current.value = "";
1463
+ };
1464
+ const showToolCalls = props.showToolCalls !== false;
1465
+ const onVaultSaved = offSpec && props.onVaultSaved ? (handle, request) => (offNow.current ? undefined : props.onVaultSaved?.(handle, request)) : props.onVaultSaved;
1466
+ const vault = { vaultApi: props.vaultApi, vaultLabels: props.vaultLabels, onVaultSaved, onVaultError: props.onVaultError };
1467
+ const connect = offSpec && props.connect?.onConnected ? { ...props.connect, onConnected: (app, appName) => (offNow.current ? undefined : props.connect?.onConnected?.(app, appName)) } : props.connect;
1468
+ const [decidedIn, setDecidedIn] = useState(() => new Map());
1469
+ const [refusedIn, setRefusedIn] = useState(() => new Map());
1470
+ const [carry, setCarry] = useState(undefined);
1471
+ useEffect(() => {
1472
+ setCarry((was) => carriedOn(was, { busy: props.busy, decided: decidedIn.keys() }));
1473
+ }, [props.busy, decidedIn]);
1474
+ const approval = { approvalBase: props.approvalBase, onApprovalDeciding: props.onApprovalDeciding, fetch: props.fetch, approvalFields: props.approvalFields, approvalLook: props.approvalLook, decidedHere: (apr) => decidedIn.has(apr), settled: (apr) => carry?.settled.has(apr) === true, refused: (apr) => refusedIn.get(apr) };
1475
+ const approvalIn = (row) => ({
1476
+ ...approval,
1477
+ tookHere: (apr, refused) => {
1478
+ setDecidedIn((had) => (had.get(apr) === row ? had : new Map(had).set(apr, row)));
1479
+ if (refused)
1480
+ setRefusedIn((had) => (had.get(apr) === refused ? had : new Map(had).set(apr, refused)));
1481
+ },
1482
+ });
1483
+ const files = { artifactHref: props.artifactHref, artifactText: props.artifactText };
1484
+ const [heldBrowsers, setHeldBrowsers] = useState(() => new Set());
1485
+ const goOnMessage = props.computer?.labels?.goOnMessage ?? DEFAULT_COMPUTER_VIEW_LABELS.goOnMessage;
1486
+ const onSendRef = useRef(props.onSend);
1487
+ onSendRef.current = props.onSend;
1488
+ const busyNow = props.busy === true;
1489
+ const browserControl = useMemo(() => ({
1490
+ held: heldBrowsers,
1491
+ report: (session, held) => setHeldBrowsers((had) => controlAfter(had, session, held)),
1492
+ goOn: chatGoOn({
1493
+ busy: busyNow,
1494
+ off,
1495
+ message: goOnMessage,
1496
+ onSend: (text) => {
1497
+ atEnd.current = true;
1498
+ onSendRef.current(text);
1499
+ },
1500
+ }),
1501
+ }), [heldBrowsers, busyNow, off, goOnMessage]);
1502
+ const computers = useMemo(() => computerPlaces(props.messages), [props.messages]);
1503
+ const rowShows = useRef(new Map());
1504
+ const computerRows = useMemo(() => ({
1505
+ add: (id, show) => {
1506
+ rowShows.current.set(id, show);
1507
+ return () => {
1508
+ if (rowShows.current.get(id) === show)
1509
+ rowShows.current.delete(id);
1510
+ };
1511
+ },
1512
+ show: (id) => rowShows.current.get(id)?.(),
1513
+ newestIn: (id) => computers.newestIn(id),
1514
+ }), [computers]);
1515
+ const shown = props.messages.filter((m) => m.role === "user" || m.role === "assistant");
1516
+ const drawnSoFar = new Set(shown.map((m) => m.id));
1517
+ const places = approvalPlaces(shown, props.runOutcomes, decidedIn);
1518
+ const cardsAt = places.cards;
1519
+ const isWaiting = (m) => m.role === "user" && props.waiting?.has(m.id) === true;
1520
+ const last = shown.filter((m) => !isWaiting(m)).at(-1);
1521
+ const newest = shown.at(-1) ?? null;
1522
+ const newestWriting = newest !== null && props.busy && newest === last && newest.role === "assistant";
1523
+ const onSeenRef = useRef(props.onSeen);
1524
+ onSeenRef.current = props.onSeen;
1525
+ const seen = useRef(null);
1526
+ const wantsSeen = props.onSeen !== undefined;
1527
+ useEffect(() => {
1528
+ if (!wantsSeen || newest === null || typeof document === "undefined" || typeof IntersectionObserver === "undefined")
1529
+ return;
1530
+ seen.current ??= seenWatch((s) => onSeenRef.current?.(s));
1531
+ const watch = seen.current;
1532
+ const rows = transcript.current?.querySelectorAll(`[data-ol-part-of="${CSS.escape(newest.id)}"]`);
1533
+ const row = (rows && rows.length > 0 ? rows[rows.length - 1] : null) ?? transcript.current?.querySelector(`[data-ol-message-id="${CSS.escape(newest.id)}"]`) ?? null;
1534
+ if (!row)
1535
+ return;
1536
+ let inView = false;
1537
+ const check = () => watch.update({ newest: newest.id, inView, visible: document.visibilityState === "visible", focused: document.hasFocus(), writing: newestWriting });
1538
+ const io = new IntersectionObserver((entries) => {
1539
+ inView = entries.some((e) => e.isIntersecting);
1540
+ check();
1541
+ });
1542
+ io.observe(row);
1543
+ document.addEventListener("visibilitychange", check);
1544
+ window.addEventListener("focus", check);
1545
+ return () => {
1546
+ io.disconnect();
1547
+ document.removeEventListener("visibilitychange", check);
1548
+ window.removeEventListener("focus", check);
1549
+ };
1550
+ }, [wantsSeen, newest?.id, newestWriting]);
1551
+ const stopAsked = props.stopState === "stopping" || props.stopState === "stopped";
1552
+ const stopMark = useRef(null);
1553
+ if (!(stopAsked && props.busy))
1554
+ stopMark.current = null;
1555
+ else if (stopMark.current === null)
1556
+ stopMark.current = last?.role === "assistant" ? { id: last.id, parts: last.parts.length } : { id: null, parts: 0 };
1557
+ const unrun = (m, i) => {
1558
+ const p = m.parts[i];
1559
+ if (!p || !(p.type.startsWith("tool-") || p.type === "dynamic-tool"))
1560
+ return false;
1561
+ if (places.spent.has(`${m.id}:${i}`))
1562
+ return true;
1563
+ if (isMessageStopped(m) || (stopAsked && m === last && m.role === "assistant")) {
1564
+ if (noResult(p))
1565
+ return true;
1566
+ }
1567
+ return m === last && stepAfterStop(stopMark.current, m, i);
1568
+ };
1569
+ const stopLine = (props.stopState === "stopping" && props.busy) || (props.stopState === "stopped" && !(last !== undefined && isMessageStopped(last))) ? props.stopState : null;
1570
+ const stopNote = stopLine === null ? null : (_jsx("p", { role: "status", ...(stopLine === "stopping" ? { "data-ol-stopping": "true" } : { "data-ol-stopped": "true" }), children: stopLine === "stopping" ? l.stopping : l.stopped }));
1571
+ const thinking = props.busy && props.queued === null && !stopAsked && (props.awaitingWords === true || !(last?.role === "assistant" && last.parts.some((p) => (p.type === "text" && p.text.trim() !== "") || sentMessageOf(p) !== null)));
1572
+ const transcript = useRef(null);
1573
+ const atEnd = useRef(true);
1574
+ const [judge] = useState(scrollJudge);
1575
+ const gestureAt = useRef(-Infinity);
1576
+ const dragging = useRef(false);
1577
+ const judging = useRef(0);
1578
+ const stay = () => {
1579
+ const el = transcript.current;
1580
+ if (!el)
1581
+ return;
1582
+ if (atEnd.current)
1583
+ el.scrollTop = el.scrollHeight;
1584
+ };
1585
+ useEffect(stay, [props.messages, thinking]);
1586
+ const [scrollBox, setScrollBox] = useState(false);
1587
+ const drawnAny = shown.length > 0;
1588
+ useLayoutEffect(() => {
1589
+ const el = transcript.current;
1590
+ if (el)
1591
+ setScrollBox(/^(auto|scroll)$/.test(getComputedStyle(el).overflowY));
1592
+ }, [drawnAny]);
1593
+ const earlierShown = props.earlier;
1594
+ const earlierNow = () => {
1595
+ const el = transcript.current;
1596
+ if (el && wantsEarlier({ earlier: props.earlier, scrollBox, overflowing: el.scrollHeight > el.clientHeight + 1, atEnd: atEnd.current, top: el.scrollTop }))
1597
+ props.onLoadEarlier?.();
1598
+ };
1599
+ useEffect(earlierNow, [props.earlier, scrollBox, shown.length]);
1600
+ const loadingEarlier = props.earlier === "loading";
1601
+ const [hushedAfter, setHushedAfter] = useState(false);
1602
+ useEffect(() => {
1603
+ if (loadingEarlier)
1604
+ return setHushedAfter(true);
1605
+ const t = setTimeout(() => setHushedAfter(false), EARLIER_HUSH_MS);
1606
+ return () => clearTimeout(t);
1607
+ }, [loadingEarlier]);
1608
+ const hushed = loadingEarlier || hushedAfter;
1609
+ const topKey = `${earlierShown ?? ""}|${shown[0]?.id ?? ""}`;
1610
+ const place = useRef({ key: topKey, at: null });
1611
+ if (place.current.key !== topKey)
1612
+ place.current = { key: topKey, at: transcript.current && !atEnd.current ? readingPlace(transcript.current) : null };
1613
+ useLayoutEffect(() => {
1614
+ const at = place.current.at;
1615
+ place.current.at = null;
1616
+ const el = transcript.current;
1617
+ if (el && at && !atEnd.current)
1618
+ keepReadingPlace(el, at);
1619
+ }, [topKey]);
1620
+ const decidedBefore = useRef(decidedIn);
1621
+ useEffect(() => {
1622
+ if (decisionTakesEnd(false, decidedBefore.current, decidedIn))
1623
+ judge.took();
1624
+ atEnd.current = decisionTakesEnd(atEnd.current, decidedBefore.current, decidedIn);
1625
+ decidedBefore.current = decidedIn;
1626
+ stay();
1627
+ }, [decidedIn]);
1628
+ useEffect(() => {
1629
+ const el = transcript.current;
1630
+ if (!el || typeof ResizeObserver !== "function")
1631
+ return;
1632
+ const resized = () => {
1633
+ judge.resized();
1634
+ stay();
1635
+ };
1636
+ const sizes = new ResizeObserver((entries) => {
1637
+ if (entries.some((e) => e.target !== el))
1638
+ resized();
1639
+ else if (judging.current === 0)
1640
+ stay();
1641
+ });
1642
+ for (const row of Array.from(el.children))
1643
+ sizes.observe(row);
1644
+ const list = typeof MutationObserver === "function"
1645
+ ? new MutationObserver((changes) => {
1646
+ for (const change of changes) {
1647
+ for (const node of Array.from(change.addedNodes))
1648
+ if (node instanceof Element)
1649
+ sizes.observe(node);
1650
+ for (const node of Array.from(change.removedNodes))
1651
+ if (node instanceof Element)
1652
+ sizes.unobserve(node);
1653
+ }
1654
+ resized();
1655
+ })
1656
+ : null;
1657
+ list?.observe(el, { childList: true });
1658
+ sizes.observe(el);
1659
+ const hand = (e) => {
1660
+ if (!isScrollInput(e, el))
1661
+ return;
1662
+ gestureAt.current = performance.now();
1663
+ if (e.type === "pointerdown")
1664
+ dragging.current = true;
1665
+ };
1666
+ const letGo = () => {
1667
+ dragging.current = false;
1668
+ };
1669
+ const gestures = ["wheel", "touchmove", "keydown", "pointerdown", "focusin"];
1670
+ for (const g of gestures)
1671
+ el.addEventListener(g, hand, { passive: true });
1672
+ window.addEventListener("pointerup", letGo);
1673
+ window.addEventListener("pointercancel", letGo);
1674
+ return () => {
1675
+ sizes.disconnect();
1676
+ list?.disconnect();
1677
+ for (const g of gestures)
1678
+ el.removeEventListener(g, hand);
1679
+ window.removeEventListener("pointerup", letGo);
1680
+ window.removeEventListener("pointercancel", letGo);
1681
+ };
1682
+ }, []);
1683
+ const [announced, setAnnounced] = useState("");
1684
+ const openedWith = useRef(null);
1685
+ openedWith.current ??= new Set(props.messages.map((m) => m.id));
1686
+ const firstDrawn = useRef(props.messages[0]?.id ?? null);
1687
+ for (const id of rowsAbove(props.messages, firstDrawn.current))
1688
+ openedWith.current.add(id);
1689
+ firstDrawn.current = props.messages[0]?.id ?? null;
1690
+ useEffect(() => {
1691
+ const el = transcript.current;
1692
+ if (!el || typeof MutationObserver !== "function")
1693
+ return;
1694
+ const said = new Set();
1695
+ const look = () => {
1696
+ const cards = Array.from(el.querySelectorAll('[data-ol-approval][data-ol-approval-status="pending"]'), (c) => ({
1697
+ id: c.getAttribute("data-ol-approval-id") ?? "",
1698
+ title: c.querySelector("[data-ol-approval-title]")?.textContent?.trim() ?? "",
1699
+ message: c.closest("[data-ol-message-id]")?.getAttribute("data-ol-message-id") ?? null,
1700
+ })).filter((c) => c.id !== "");
1701
+ const next = approvalsToAnnounce(cards, said, openedWith.current ?? new Set());
1702
+ for (const c of cards)
1703
+ said.add(c.id);
1704
+ if (next.length > 0)
1705
+ setAnnounced(next.map((c) => l.approvalAnnounce.replace("{title}", c.title)).join(" "));
1706
+ };
1707
+ const changes = new MutationObserver(look);
1708
+ changes.observe(el, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-ol-approval-status"] });
1709
+ look();
1710
+ return () => changes.disconnect();
1711
+ }, []);
1712
+ const [waitingOut, setWaitingOut] = useState(0);
1713
+ const barOn = props.approvalBar !== false;
1714
+ useEffect(() => {
1715
+ const el = transcript.current;
1716
+ if (!barOn || !el || typeof requestAnimationFrame !== "function")
1717
+ return;
1718
+ let frame = 0;
1719
+ const look = () => {
1720
+ frame = 0;
1721
+ const buttons = Array.from(el.querySelectorAll("[data-ol-approval-actions]"), (b) => {
1722
+ const r = b.getBoundingClientRect();
1723
+ return { top: r.top, bottom: r.bottom, deciding: b.closest("[data-ol-approval]")?.hasAttribute("data-ol-approval-deciding") === true };
1724
+ });
1725
+ setWaitingOut(buttons.length === 0 ? 0 : approvalBarCount(buttons, shownPart(el)));
1726
+ };
1727
+ const soon = () => {
1728
+ if (frame === 0)
1729
+ frame = requestAnimationFrame(look);
1730
+ };
1731
+ const sizes = typeof ResizeObserver === "function" ? new ResizeObserver(soon) : null;
1732
+ sizes?.observe(el);
1733
+ const changes = typeof MutationObserver === "function" ? new MutationObserver(soon) : null;
1734
+ changes?.observe(el, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-ol-approval-status", "data-ol-approval-deciding"] });
1735
+ el.addEventListener("scroll", soon, { passive: true });
1736
+ window.addEventListener("scroll", soon, { passive: true });
1737
+ window.addEventListener("resize", soon);
1738
+ soon();
1739
+ return () => {
1740
+ if (frame !== 0)
1741
+ cancelAnimationFrame(frame);
1742
+ sizes?.disconnect();
1743
+ changes?.disconnect();
1744
+ el.removeEventListener("scroll", soon);
1745
+ window.removeEventListener("scroll", soon);
1746
+ window.removeEventListener("resize", soon);
1747
+ };
1748
+ }, [barOn]);
1749
+ const review = () => {
1750
+ const el = transcript.current;
1751
+ const buttons = el ? Array.from(el.querySelectorAll("[data-ol-approval]:not([data-ol-approval-deciding]) [data-ol-approval-actions]")) : [];
1752
+ const actions = buttons[buttons.length - 1];
1753
+ const card = actions?.closest("[data-ol-approval]");
1754
+ if (!el || !actions || !card)
1755
+ return;
1756
+ const part = shownPart(el);
1757
+ atEnd.current = false;
1758
+ (card.getBoundingClientRect().height <= part.bottom - part.top ? card : actions).scrollIntoView({ block: "nearest" });
1759
+ card.focus({ preventScroll: true });
1760
+ };
1761
+ const letGo = () => {
1762
+ atEnd.current = false;
1763
+ };
1764
+ useImperativeHandle(props.ref, () => chatHandle(() => transcript.current, letGo), []);
1765
+ useEffect(() => {
1766
+ const el = transcript.current;
1767
+ const id = props.openAt;
1768
+ if (!el || !id)
1769
+ return;
1770
+ if (goToTarget(el, id, letGo) || typeof MutationObserver !== "function")
1771
+ return;
1772
+ const since = performance.now();
1773
+ const watch = new MutationObserver(() => {
1774
+ if (gestureAt.current >= since || goToTarget(el, id, letGo))
1775
+ watch.disconnect();
1776
+ });
1777
+ watch.observe(el, { childList: true, subtree: true });
1778
+ return () => watch.disconnect();
1779
+ }, [props.openAt]);
1780
+ const missingSaid = useRef(new Set());
1781
+ useEffect(() => {
1782
+ const missing = openAtMissing({ openAt: props.openAt, historyLoaded: props.historyLoaded, messages: props.messages, outcomes: props.runOutcomes, fired: missingSaid.current });
1783
+ if (missing === null)
1784
+ return;
1785
+ missingSaid.current.add(missing);
1786
+ props.onOpenAtMissing?.(missing);
1787
+ }, [props.openAt, props.historyLoaded, props.messages, props.runOutcomes]);
1788
+ const submit = (e) => {
1789
+ e?.preventDefault();
1790
+ if (off)
1791
+ return;
1792
+ const text = input.trim();
1793
+ const action = submitAction(text, uploading);
1794
+ if (action === "hold") {
1795
+ setHeld((h) => h ?? { failed: false });
1796
+ return;
1797
+ }
1798
+ setHeld(null);
1799
+ if (action === "none")
1800
+ return;
1801
+ atEnd.current = true;
1802
+ props.onSend(text, attached);
1803
+ setInput("");
1804
+ setAttached([]);
1805
+ setAttachError(null);
1806
+ };
1807
+ const onKeyDown = (e) => {
1808
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
1809
+ e.preventDefault();
1810
+ submit();
1811
+ }
1812
+ else if (e.key === "Escape" && held) {
1813
+ e.preventDefault();
1814
+ setHeld(null);
1815
+ }
1816
+ };
1817
+ const submitRef = useRef(submit);
1818
+ submitRef.current = submit;
1819
+ useEffect(() => {
1820
+ if (!held)
1821
+ return;
1822
+ const next = heldSendNext({ uploading, failed: held.failed });
1823
+ if (next === "cancel")
1824
+ setHeld(null);
1825
+ else if (next === "send")
1826
+ submitRef.current();
1827
+ }, [held, uploading]);
1828
+ const suggestions = !off && shown.length === 0 && !props.busy && props.suggestions && props.suggestions.length > 0 ? (_jsx("ul", { "data-ol-suggestions": true, children: props.suggestions.map((text, i) => (_jsx("li", { children: _jsx("button", { type: "button", "data-ol-suggestion": true, onClick: () => props.onSend(text), children: text }) }, i))) })) : null;
1829
+ return (_jsx(CardLedgerContext.Provider, { value: cards, children: _jsx(BrowserControlContext.Provider, { value: browserControl, children: _jsx(ComputerRowsContext.Provider, { value: computerRows, children: _jsxs("div", { className: props.className, "data-ol-chat": true, children: [shown.length === 0 && !props.busy ? (_jsx("p", { "data-ol-empty": true, children: l.empty })) : null, props.suggestionsAt !== "end" ? suggestions : null, _jsxs("ol", { ref: transcript, "data-ol-transcript": true, "aria-live": hushed ? "off" : "polite", "aria-busy": props.busy, style: shown.length === 0 ? HIDDEN_FROM_VIEW : undefined, onScroll: (e) => {
1830
+ const el = e.currentTarget;
1831
+ const seen = judge.scrolled(atEnd.current, el, dragging.current || performance.now() - gestureAt.current < 1000);
1832
+ atEnd.current = seen.atEnd;
1833
+ earlierNow();
1834
+ if (seen.then === "back")
1835
+ stay();
1836
+ else if (seen.then !== "none") {
1837
+ const mark = seen.then.confirm;
1838
+ judging.current++;
1839
+ afterFrames(QUIET_FRAMES, () => {
1840
+ judging.current--;
1841
+ if (!judge.quiet(mark))
1842
+ return stay();
1843
+ if (atEnd.current && takesEndBack(true, el))
1844
+ atEnd.current = false;
1845
+ earlierNow();
1846
+ });
1847
+ }
1848
+ }, children: [earlierShown ? (_jsx("li", { "data-ol-earlier": earlierShown, role: "status", children: earlierShown === "loading" ? (l.earlierLoading) : earlierShown === "end" ? (l.earlierStart) : earlierShown === "failed" ? (_jsxs(_Fragment, { children: [l.earlierFailed, " ", _jsx("button", { type: "button", "data-ol-earlier-retry": true, onClick: () => props.onLoadEarlier?.(), children: l.earlierRetry })] })) : scrollBox ? null : (_jsx("button", { type: "button", "data-ol-earlier-show": true, onClick: () => props.onLoadEarlier?.(), children: l.earlierShow })) })) : null, shown.map((m) => {
1849
+ const info = { tainted: isMessageTainted(m), role: m.role };
1850
+ const failed = replyFailed(m);
1851
+ const notSent = m.role === "user" && props.unsent?.has(m.id) === true;
1852
+ const waits = isWaiting(m);
1853
+ const ran = m.role === "user" ? props.runOutcomes?.[m.id] : undefined;
1854
+ const isSaved = (i) => props.savedAsks?.has(`${m.id}:${i}`) === true;
1855
+ const carded = (i) => cardFollows(m.parts[i], m.parts[i + 1], isSaved(i + 1));
1856
+ const isBelow = (i) => places.below.has(`${m.id}:${i}`);
1857
+ const cardOf = (i) => (cardsAt.has(`${m.id}:${i}`) ? approvalOfPart(m.parts[i]) : null);
1858
+ const live = props.busy && props.awaitingWords !== true && m === last && m.role === "assistant" && !failed;
1859
+ const folds = m.role === "assistant" && showToolCalls && props.steps !== "list";
1860
+ const plain = live || folds ? m.parts.flatMap((p, i) => (!unrun(m, i) && !isBelow(i) && stepLineOf(p, l, isSaved(i), carded(i), cardOf(i)) ? [i] : [])) : [];
1861
+ const steps = live ? plain : [];
1862
+ const wordsArriving = (i) => props.busy && m === last && m.role === "assistant" && m.parts[i].state !== "done";
1863
+ const keys = partKeys(m.parts, cardOf);
1864
+ const again = repeatedParts(m.parts);
1865
+ const draw = (p, i) => {
1866
+ if (again.has(i))
1867
+ return null;
1868
+ const retried = live && (p.type.startsWith("tool-") || p.type === "dynamic-tool") && p.state === "output-error";
1869
+ if (retried && i !== steps[steps.length - 1])
1870
+ return null;
1871
+ const part = retried ? { ...p, state: "input-available", errorText: undefined } : p;
1872
+ return _jsx(Part, { part: part, info: info, labels: l, renderText: props.renderText, showToolCalls: showToolCalls, vault: vault, saved: isSaved(i), approval: approvalIn(m.id), connect: connect, fetch: props.fetch, ask: props.threadId ? { thread: props.threadId, message: m.id } : undefined, carded: carded(i), files: files, card: cardOf(i), below: isBelow(i), failed: failed, streaming: wordsArriving(i), computer: props.computer, computerAt: part.type === "data-computer" ? computers.row(m.id, i, part.data) : null, computerPointer: part.type === "data-computer" ? computers.pointer(m.id, i, part.data) : null }, keys[i]);
1873
+ };
1874
+ const outcomeCard = (apr) => cardsAt.has(`${m.id}:${apr}`);
1875
+ const says = (i) => {
1876
+ const p = m.parts[i];
1877
+ if (p.type === "text")
1878
+ return p.text.trim() !== "";
1879
+ if (again.has(i))
1880
+ return false;
1881
+ if (p.type === "data-model-note")
1882
+ return modelNoteOf(p.data) !== null;
1883
+ if (p.type === "data-computer")
1884
+ return computers.row(m.id, i, p.data) !== null || computers.pointer(m.id, i, p.data) !== null;
1885
+ return (p.type.startsWith("data-") && p.type !== "data-message") || p.type === "file" || cardOf(i) !== null || isBelow(i);
1886
+ };
1887
+ const shows = (i) => says(i) || (showToolCalls && !unrun(m, i) && stepLineOf(m.parts[i], l, isSaved(i), carded(i), cardOf(i)) !== null);
1888
+ const stopHere = isMessageStopped(m) || (m === last && m.role === "assistant" && stopNote !== null);
1889
+ const bubbles = m.role === "assistant" && m.parts.some((p) => p.type === "data-message") ? chatBubbles(m.parts, { drawn: drawnSoFar, says, shows, tail: stopHere }) : [{ kind: "parts", parts: m.parts.map((_, i) => i), reply: true }];
1890
+ const split = bubbles.length > 1 || bubbles[0]?.kind === "message";
1891
+ for (const b of bubbles)
1892
+ if (b.kind === "message")
1893
+ drawnSoFar.add(b.message.id);
1894
+ const partsRow = (b, first) => {
1895
+ const stepAt = folds ? plain.filter((i) => b.parts.includes(i)) : [];
1896
+ const mode = stepAt.length < 2 ? "list" : props.busy && m === last && b.reply ? "current" : b.parts.some((i) => { const p = m.parts[i]; return p.type === "text" && p.text.trim() !== ""; }) ? "fold" : "list";
1897
+ return (_jsxs("li", { "data-ol-message": true, "data-ol-role": m.role, "data-ol-tainted": info.tainted ? "true" : "false", ...(failed ? { "data-ol-reply-failed": "true" } : {}), ...(notSent ? { "data-ol-unsent": "true" } : {}), ...(waits ? { "data-ol-waiting": "true" } : {}), ...(b.reply ? { "data-ol-message-id": m.id } : {}), ...(split ? { "data-ol-part-of": m.id } : {}), children: [first && props.fromSchedule !== false && startedBySchedule(m) ? _jsx("p", { "data-ol-from-schedule": true, children: l.fromSchedule }) : null, m.role === "user" ? _jsx("span", { "data-ol-author": true, children: l.you }) : agentAuthor, b.parts.map((i) => {
1898
+ const p = m.parts[i];
1899
+ if (stopAlreadySaid(m.parts, i, l) || unrun(m, i))
1900
+ return null;
1901
+ if (mode === "list" || !stepAt.includes(i))
1902
+ return draw(p, i);
1903
+ if (mode === "current")
1904
+ return i === stepAt[stepAt.length - 1] ? draw(p, i) : null;
1905
+ return i === stepAt[0] ? (_jsxs("details", { "data-ol-steps": true, children: [_jsx("summary", { "data-ol-steps-summary": true, children: l.steps.replace("{count}", String(stepAt.length)) }), stepAt.map((j) => draw(m.parts[j], j))] }, "steps")) : null;
1906
+ }), notSent ? (_jsxs("p", { "data-ol-unsent-note": true, role: "note", "data-ol-unsent-why": unsentWhyOf(m.id), children: [_jsx("span", { children: l.notSent }), " ", props.onSendAgain && !off && !(limitHolds && unsentWhyOf(m.id) === "limit") ? (_jsx("button", { type: "button", "data-ol-send-again": true, onClick: () => props.onSendAgain?.(m.id), children: l.sendAgain })) : null] })) : waits ? (_jsx("p", { role: "status", "data-ol-waiting-note": true, children: queuedText("thread_busy", props.labels) })) : null, !b.reply ? null : isMessageStopped(m) ? (_jsx("p", { role: "status", "data-ol-stopped": true, children: l.stopped })) : m === last && m.role === "assistant" ? (stopNote) : null] }, b.reply ? m.id : `${m.id}:${b.parts[0] ?? 0}`));
1907
+ };
1908
+ const messageRow = (b, first) => {
1909
+ const said = { tainted: b.message.tainted, role: "assistant" };
1910
+ return (_jsxs("li", { "data-ol-message": true, "data-ol-role": "assistant", "data-ol-tainted": b.message.tainted ? "true" : "false", "data-ol-message-id": b.message.id, "data-ol-part-of": m.id, children: [first && props.fromSchedule !== false && startedBySchedule(m) ? _jsx("p", { "data-ol-from-schedule": true, children: l.fromSchedule }) : null, agentAuthor, _jsx(Part, { part: { type: "text", text: b.message.text, state: "done" }, info: said, labels: l, renderText: props.renderText, showToolCalls: showToolCalls, vault: vault, saved: false, approval: approvalIn(m.id), connect: connect, fetch: props.fetch, ask: undefined, carded: false, files: files, card: null, below: false, failed: false, streaming: false })] }, b.message.id));
1911
+ };
1912
+ return (_jsxs(Fragment, { children: [bubbles.map((b, k) => (b.kind === "message" ? messageRow(b, k === 0) : partsRow(b, k === 0))), ran && hasOutcome(ran, l, showToolCalls, outcomeCard) ? (_jsxs("li", { "data-ol-message": true, "data-ol-role": "assistant", "data-ol-tainted": "false", ...(outcomeFailed(ran) ? { "data-ol-reply-failed": "true" } : {}), children: [agentAuthor, _jsx(Outcome, { outcome: ran, labels: l, showToolCalls: showToolCalls, approval: approvalIn(m.id), isCard: outcomeCard })] })) : null, stopNote !== null && m === last && m.role !== "assistant" ? (_jsxs("li", { "data-ol-message": true, "data-ol-role": "assistant", "data-ol-tainted": "false", children: [agentAuthor, stopNote] })) : null] }, m.id));
1913
+ })] }), _jsx("p", { "data-ol-announce": true, role: "status", style: HIDDEN_FROM_VIEW, children: announced }), thinking ? (_jsx("p", { role: "status", "data-ol-thinking": true, children: l.thinking })) : null, props.queued !== null ? (_jsx("p", { role: "status", "data-ol-queued": true, children: queuedText(props.queuedReason ?? null, props.labels) })) : null, props.stopState === "failed" ? (_jsx("p", { role: "status", "data-ol-stop-failed": true, children: l.stopFailed })) : null, error instanceof AgentChatError && error.type === "refusal" && error.code === "cap_reached" && error.limit ? (_jsx(RefusalNote, { code: error.code, message: error.displayMessage, limit: error.limit, labels: l, alert: true })) : error ? (_jsxs("p", { role: "alert", "data-ol-error": true, children: [agentChatErrorText(error, l), isInterrupted(error) ? (_jsxs(_Fragment, { children: [" ", _jsx("button", { type: "button", "data-ol-reconnect": true, onClick: props.onReconnect, children: l.reconnect })] })) : null] })) : null, props.showFiles === true && props.artifacts && props.artifacts.length > 0 && props.artifactHref ? _jsx(DeliveredFiles, { artifacts: props.artifacts, href: props.artifactHref, labels: l }) : null, attached.length > 0 ? (_jsx(FileChips, { files: attached, removeLabel: l.removeFile, onRemove: (id) => {
1914
+ setHeld(null);
1915
+ setAttached((had) => had.filter((f) => f.id !== id));
1916
+ } })) : null, uploading > 0 && held ? (_jsx("p", { role: "status", "data-ol-uploading": true, "data-ol-send-held": true, children: l.sendWhenUploaded })) : uploading > 0 ? (_jsx("p", { role: "status", "data-ol-uploading": true, children: l.uploading })) : null, attachError ? (_jsx("p", { role: "alert", "data-ol-attach-error": true, children: attachError })) : null, props.beforeComposer, barOn && waitingOut > 0 ? _jsx(ApprovalBar, { count: waitingOut, labels: l, onReview: review }) : null, off && offSpec ? (_jsxs("form", { "data-ol-composer": true, "data-ol-composer-off": true, onSubmit: submit, children: [onAttach ? (_jsx("button", { type: "button", "data-ol-attach": true, ...OFF_CONTROL, children: l.attach })) : null, _jsx("textarea", { "data-ol-input": true, "aria-label": l.input, placeholder: l.placeholder, rows: 2, value: "", readOnly: true, ...OFF_CONTROL }), _jsx("button", { type: "submit", "data-ol-send": true, ...OFF_CONTROL, children: l.send }), _jsxs("p", { "data-ol-composer-note": true, role: "status", children: [offSpec.text, offSpec.link ? (_jsxs(_Fragment, { children: [offSpec.text ? " " : null, _jsx("a", { "data-ol-composer-link": true, href: offSpec.link.href, children: offSpec.link.text })] })) : null] })] })) : (_jsxs("form", { "data-ol-composer": true, onSubmit: submit, children: [onAttach ? (_jsxs(_Fragment, { children: [_jsx("input", { ref: picker, type: "file", accept: ATTACHMENT_ACCEPT, multiple: true, hidden: true, "data-ol-file-input": true, onChange: (e) => pick(e.target.files) }), _jsx("button", { type: "button", "data-ol-attach": true, disabled: attached.length + uploading >= MAX_ATTACHMENTS, onClick: () => picker.current?.click(), children: l.attach })] })) : null, _jsx("textarea", { "data-ol-input": true, "aria-label": l.input, placeholder: l.placeholder, rows: 2, value: input, onChange: (e) => setInput(e.target.value), onKeyDown: onKeyDown, autoFocus: props.autoFocus === true }), composerAction({ busy: props.busy, canStop: props.onStop !== undefined, text: input, stopAsked }) === "stop" ? (_jsx("button", { type: "button", "data-ol-stop": true, onClick: props.onStop, children: l.stop })) : (_jsx("button", { type: "submit", "data-ol-send": true, disabled: held !== null || submitAction(input, uploading) === "none", children: l.send }))] })), props.suggestionsAt === "end" ? suggestions : null, props.afterComposer] }) }) }) }));
1917
+ }