@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,372 @@
1
+ "use client";
2
+ import { jsxs as _jsxs, Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { DEFAULT_KIT_BASE } from "./agent-kit.js";
5
+ import { isComputerSessionId } from "./computer-wire.js";
6
+ import { DEFAULT_LABELS } from "./errors.js";
7
+ import { limitOf } from "./limit-words.js";
8
+ const OUTCOMES = ["succeeded", "failed", "refused", "unknown"];
9
+ function actionOf(raw) {
10
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
11
+ return null;
12
+ const r = raw;
13
+ if (typeof r["status"] !== "string" || !(r["outcome"] === null || OUTCOMES.includes(String(r["outcome"]))))
14
+ return null;
15
+ return { status: r["status"], outcome: r["outcome"], message: typeof r["message"] === "string" && r["message"].trim() !== "" ? r["message"] : null };
16
+ }
17
+ function runRefusedOf(raw) {
18
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
19
+ return null;
20
+ const r = raw;
21
+ if (typeof r["code"] !== "string" || r["code"] === "" || typeof r["message"] !== "string")
22
+ return null;
23
+ return { code: r["code"], message: r["message"], limit: limitOf(r["limit"]) };
24
+ }
25
+ const APPROVAL_RE = /^apr_[0-9A-Za-z]{1,64}$/;
26
+ const STATUSES = ["pending", "approved", "rejected", "expired"];
27
+ export function approvalCardOf(body) {
28
+ if (!body || typeof body !== "object")
29
+ return null;
30
+ const b = body;
31
+ if (b["object"] !== "approval" || typeof b["id"] !== "string" || !APPROVAL_RE.test(b["id"]) || !STATUSES.includes(String(b["status"])))
32
+ return null;
33
+ const fields = Array.isArray(b["fields"])
34
+ ? b["fields"].flatMap((f) => {
35
+ const o = f && typeof f === "object" ? f : {};
36
+ return typeof o["label"] === "string" && typeof o["value"] === "string" ? [{ label: o["label"], value: o["value"], ...(o["detail"] === true ? { detail: true } : {}), ...(o["truncated"] === true ? { truncated: true } : {}), ...(o["from_page"] === true ? { from_page: true } : {}) }] : [];
37
+ })
38
+ : [];
39
+ const runRefused = runRefusedOf(b["run_refused"]);
40
+ const action = actionOf(b["action"]);
41
+ return {
42
+ id: b["id"],
43
+ status: b["status"],
44
+ title: typeof b["title"] === "string" && b["title"] !== "" ? b["title"] : null,
45
+ fields,
46
+ action_hash: typeof b["action_hash"] === "string" ? b["action_hash"] : null,
47
+ can_decide: typeof b["can_decide"] === "boolean" ? b["can_decide"] : null,
48
+ ...(isComputerSessionId(b["computer_session"]) ? { computer_session: b["computer_session"] } : {}),
49
+ ...(runRefused ? { run_refused: runRefused } : {}),
50
+ ...(action ? { action } : {}),
51
+ };
52
+ }
53
+ export async function readApproval(opts) {
54
+ try {
55
+ const res = await opts.fetch(`${opts.base}/approvals/${encodeURIComponent(opts.id)}`);
56
+ return res.ok ? approvalCardOf(await res.json()) : null;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ function refusalSaid(status, error) {
63
+ if (status < 400 || status > 499 || !(status === 402 || status === 409 || error?.type === "refusal"))
64
+ return undefined;
65
+ const said = typeof error?.message === "string" ? error.message.trim() : "";
66
+ return said === "" ? undefined : said;
67
+ }
68
+ export async function decideApproval(opts) {
69
+ try {
70
+ const res = await opts.fetch(`${opts.base}/approvals/${encodeURIComponent(opts.id)}/decide`, {
71
+ method: "POST",
72
+ headers: { "content-type": "application/json" },
73
+ body: JSON.stringify({ decision: opts.decision, action_hash: opts.actionHash }),
74
+ });
75
+ const body = (await res.json().catch(() => null));
76
+ if (res.ok) {
77
+ const card = approvalCardOf(body);
78
+ return card ? { ok: true, card } : { ok: false, code: "invalid_answer" };
79
+ }
80
+ const error = body && typeof body === "object" ? body.error : undefined;
81
+ const code = typeof error?.code === "string" ? error.code : `http_${res.status}`;
82
+ const said = refusalSaid(res.status, error && typeof error === "object" ? error : undefined);
83
+ return said === undefined ? { ok: false, code } : { ok: false, code, said };
84
+ }
85
+ catch {
86
+ return { ok: false, code: "network" };
87
+ }
88
+ }
89
+ const READ_AGAIN = new Set(["action_changed", "approval_not_pending", "approval_expired"]);
90
+ export function afterRefusal(code, labels, said) {
91
+ if (code === "insufficient_role")
92
+ return { notice: null, waiting: true, readAgain: false };
93
+ if (code === "action_changed")
94
+ return { notice: labels.approvalChanged, waiting: false, readAgain: true };
95
+ if (READ_AGAIN.has(code))
96
+ return { notice: null, waiting: false, readAgain: true };
97
+ return { notice: said ? said.slice(0, 500) : labels.generic, waiting: false, readAgain: false };
98
+ }
99
+ export function heldBackFor(card, held) {
100
+ return card.status === "pending" && card.computer_session !== undefined && held?.has(card.computer_session) === true;
101
+ }
102
+ const FACTS_SHOWN = 2;
103
+ export const VALUE_LINES = 6;
104
+ export function mayRunLong(value) {
105
+ let lines = 0;
106
+ for (const line of value.split("\n"))
107
+ lines += Math.max(1, Math.ceil(line.length / 40));
108
+ return lines > VALUE_LINES;
109
+ }
110
+ function Value({ value, labels, fromPage }) {
111
+ const long = mayRunLong(value);
112
+ const [open, setOpen] = useState(false);
113
+ const [fits, setFits] = useState(false);
114
+ const ref = useRef(null);
115
+ useEffect(() => {
116
+ const el = ref.current;
117
+ if (!long || open || !el)
118
+ return;
119
+ const measure = () => setFits(el.scrollHeight <= el.clientHeight + 1);
120
+ measure();
121
+ if (typeof ResizeObserver !== "function")
122
+ return;
123
+ const watch = new ResizeObserver(measure);
124
+ watch.observe(el);
125
+ return () => watch.disconnect();
126
+ }, [long, open]);
127
+ const clamped = long && !open;
128
+ return (_jsxs("dd", { ...(fromPage ? { "data-ol-approval-from-page": "" } : {}), children: [_jsx("span", { ref: ref, "data-ol-approval-value": true, ...(clamped ? { "data-ol-approval-value-clamped": true } : {}), style: { whiteSpace: "pre-wrap", wordBreak: "break-word", ...(clamped ? { display: "-webkit-box", WebkitBoxOrient: "vertical", WebkitLineClamp: `var(--ol-approval-lines, ${VALUE_LINES})`, overflow: "hidden" } : { display: "block" }) }, children: fromPage ? (_jsxs(_Fragment, { children: [_jsxs("span", { style: PAGE_WORDS_HIDDEN, children: [labels.pageWords, ": "] }), "\u201C", value, "\u201D"] })) : (value) }), long && !(fits && !open) ? (_jsx("button", { type: "button", "data-ol-approval-show-all": true, "aria-expanded": open, onClick: () => setOpen((was) => !was), children: open ? labels.showLess : labels.showAll })) : null] }));
129
+ }
130
+ const PAGE_WORDS_HIDDEN = { position: "absolute", width: "1px", height: "1px", margin: "-1px", padding: 0, border: 0, overflow: "hidden", clipPath: "inset(50%)", whiteSpace: "nowrap" };
131
+ function Facts({ fields, extra, labels }) {
132
+ return (_jsx("dl", { ...(extra ? { "data-ol-approval-more": true } : { "data-ol-approval-fields": true }), children: fields.map((f, i) => (_jsxs("div", { "data-ol-approval-field": true, children: [_jsx("dt", { children: f.label }), _jsx(Value, { value: f.value, labels: labels, fromPage: f.from_page === true })] }, i))) }));
133
+ }
134
+ export function valueCutText(label, value, template) {
135
+ const shown = (value.endsWith("…") ? value.length - 1 : value.length).toLocaleString("en-US");
136
+ return template.replaceAll("{field}", label).replaceAll("{shown}", shown);
137
+ }
138
+ export function focusAfterDecision(card, hadFocus, active, body) {
139
+ if (!card || !hadFocus || (active !== null && active !== body))
140
+ return false;
141
+ card.focus({ preventScroll: true });
142
+ return true;
143
+ }
144
+ function actionDidNotWork(card) {
145
+ return card.status === "approved" && card.action != null && card.action.outcome !== null && card.action.outcome !== "succeeded";
146
+ }
147
+ export function ApprovalCardView(props) {
148
+ const { card, labels: l } = props;
149
+ const heldBack = props.heldBack === true;
150
+ const heldLine = useId();
151
+ const waiting = props.waiting === true || card.can_decide === false;
152
+ const earlier = props.earlier === true;
153
+ const failed = actionDidNotWork(card);
154
+ const why = failed && card.action?.message ? card.action.message.slice(0, 500) : null;
155
+ const outcome = failed ? (why ? l.actionFailedWith.replace("{message}", () => why) : l.actionFailed) : card.status === "approved" ? (earlier || props.settled === true || card.run_refused ? l.wasApproved : l.approved) : card.status === "rejected" ? (earlier ? l.wasRejected : l.rejected) : card.status === "expired" ? l.approvalExpired : waiting ? l.approvalNotAllowed : null;
156
+ const [detailsOpen, setDetailsOpen] = useState(false);
157
+ const marked = card.fields.some((f) => f.detail === true);
158
+ const shown = props.fields === "all" ? card.fields : marked ? card.fields.filter((f) => f.detail !== true) : card.fields.slice(0, FACTS_SHOWN);
159
+ const more = props.fields === "all" ? [] : marked ? card.fields.filter((f) => f.detail === true) : card.fields.slice(FACTS_SHOWN);
160
+ return (_jsxs("div", { ref: props.rootRef, "data-ol-approval": true, "data-ol-approval-status": card.status, ...(props.busy ? { "data-ol-approval-deciding": "true" } : {}), tabIndex: -1, "data-ol-approval-id": card.id, children: [_jsx("strong", { "data-ol-approval-title": true, children: card.title ?? props.fallbackTitle }), shown.length > 0 ? _jsx(Facts, { fields: shown, labels: l }) : null, more.length > 0 ? (_jsxs("details", { "data-ol-approval-details": true, open: detailsOpen, onToggle: (e) => setDetailsOpen(e.currentTarget.open), children: [_jsx("summary", { "data-ol-approval-details-summary": true, children: detailsOpen ? l.hideDetails : l.details }), _jsx(Facts, { fields: more, extra: true, labels: l })] })) : null, card.fields
161
+ .filter((f) => f.truncated === true)
162
+ .map((f, i) => (_jsx("p", { "data-ol-approval-cut": true, children: valueCutText(f.label, f.value, l.approvalValueCut) }, i))), props.notice ? (_jsx("p", { "data-ol-approval-notice": true, role: "alert", children: props.notice })) : null, outcome !== null ? (_jsx("p", { "data-ol-approval-outcome": true, ...(failed ? { "data-ol-approval-failed": "true" } : {}), role: "status", children: outcome })) : props.busy && props.deciding ? (_jsx("p", { "data-ol-approval-progress": true, role: "status", children: props.deciding === "approve" ? l.approving : l.rejecting })) : (_jsxs(_Fragment, { children: [heldBack ? (_jsx("p", { id: heldLine, "data-ol-approval-held": true, children: l.approveHeldBack ?? DEFAULT_LABELS.approveHeldBack })) : null, _jsxs("div", { "data-ol-approval-actions": true, children: [_jsx("button", { type: "button", "data-ol-approval-approve": true, disabled: props.busy || heldBack, ...(heldBack ? { "aria-describedby": heldLine } : {}), onClick: () => props.onDecide("approve"), children: l.approve }), _jsx("button", { type: "button", "data-ol-approval-reject": true, disabled: props.busy, onClick: () => props.onDecide("reject"), children: l.reject })] })] }))] }));
163
+ }
164
+ export function ApprovalReadView(props) {
165
+ if (!props.failed) {
166
+ return (_jsx("div", { "data-ol-approval-loading": true, "aria-busy": "true", children: props.loadingTitle ?? props.fallbackTitle }));
167
+ }
168
+ return (_jsxs("p", { "data-ol-approval-error": true, role: "alert", children: [props.labels.approvalUnavailable, " ", _jsx("button", { type: "button", "data-ol-approval-retry": true, onClick: props.onRetry, children: props.labels.retry })] }));
169
+ }
170
+ export async function sendDecision(decision, post, onDeciding) {
171
+ let taken;
172
+ const took = new Promise((r) => (taken = r));
173
+ onDeciding?.(decision, took);
174
+ const r = await post();
175
+ taken(r.ok && !r.card.run_refused);
176
+ return r;
177
+ }
178
+ export function readsAsEarlier(status, decidedHere) {
179
+ return status !== "pending" && !decidedHere;
180
+ }
181
+ export function followsAction(card) {
182
+ return card.status === "approved" && card.action != null && card.action.outcome === null && card.run_refused === undefined;
183
+ }
184
+ export const FOLLOW_DELAYS_MS = [1_000, 2_000, 3_000, 5_000, 8_000, 13_000, 20_000];
185
+ export const FOLLOW_FOR_MS = 10 * 60_000;
186
+ export function followAction(env) {
187
+ let gone = false;
188
+ let timer;
189
+ let spent = 0;
190
+ let n = 0;
191
+ const next = () => {
192
+ const wait = FOLLOW_DELAYS_MS[Math.min(n, FOLLOW_DELAYS_MS.length - 1)];
193
+ if (gone || spent + wait > FOLLOW_FOR_MS)
194
+ return;
195
+ n += 1;
196
+ spent += wait;
197
+ timer = setTimeout(() => {
198
+ void env
199
+ .read()
200
+ .catch(() => null)
201
+ .then((card) => {
202
+ if (gone)
203
+ return;
204
+ if (card)
205
+ env.onRead(card);
206
+ if (!card || followsAction(card))
207
+ next();
208
+ });
209
+ }, wait);
210
+ };
211
+ next();
212
+ return {
213
+ dispose() {
214
+ gone = true;
215
+ if (timer !== undefined)
216
+ clearTimeout(timer);
217
+ },
218
+ };
219
+ }
220
+ export const APPROVAL_REREAD_GAP_MS = 2_000;
221
+ export function approvalRereads(env) {
222
+ const now = env.now ?? Date.now;
223
+ const gap = env.gapMs ?? APPROVAL_REREAD_GAP_MS;
224
+ let out = false;
225
+ let gone = false;
226
+ let began = Number.NEGATIVE_INFINITY;
227
+ return {
228
+ poke() {
229
+ if (gone || out || now() - began < gap)
230
+ return;
231
+ out = true;
232
+ began = now();
233
+ void env
234
+ .read()
235
+ .catch(() => undefined)
236
+ .finally(() => {
237
+ out = false;
238
+ });
239
+ },
240
+ dispose() {
241
+ gone = true;
242
+ },
243
+ };
244
+ }
245
+ export function onTabBack(win, doc, poke) {
246
+ const shown = () => {
247
+ if (doc.visibilityState === "visible")
248
+ poke();
249
+ };
250
+ win.addEventListener("focus", poke);
251
+ doc.addEventListener("visibilitychange", shown);
252
+ return () => {
253
+ win.removeEventListener("focus", poke);
254
+ doc.removeEventListener("visibilitychange", shown);
255
+ };
256
+ }
257
+ export function afterReread(current, read, decidedHere) {
258
+ if (!read || current.status !== "pending")
259
+ return null;
260
+ return { card: read, earlier: read.status === "pending" ? null : readsAsEarlier(read.status, decidedHere) };
261
+ }
262
+ export function ApprovalCard(props) {
263
+ const base = props.base ?? DEFAULT_KIT_BASE;
264
+ const labels = { ...DEFAULT_LABELS, ...props.labels };
265
+ const [card, setCard] = useState(null);
266
+ const [busy, setBusy] = useState(false);
267
+ const [out, setOut] = useState(null);
268
+ const [notice, setNotice] = useState(null);
269
+ const [waiting, setWaiting] = useState(false);
270
+ const [reads, setReads] = useState(0);
271
+ const [failed, setFailed] = useState(false);
272
+ const [earlier, setEarlier] = useState(null);
273
+ const doFetch = props.fetch ?? ((input, init) => fetch(input, init));
274
+ const root = useRef(null);
275
+ const refocus = useRef(false);
276
+ useEffect(() => {
277
+ if (!refocus.current || typeof document === "undefined")
278
+ return;
279
+ refocus.current = false;
280
+ focusAfterDecision(root.current, true, document.activeElement, document.body);
281
+ });
282
+ useEffect(() => {
283
+ let live = true;
284
+ void readApproval({ base: base, id: props.id, fetch: doFetch }).then((read) => {
285
+ if (!live)
286
+ return;
287
+ if (read) {
288
+ setCard(read);
289
+ setEarlier((was) => was ?? readsAsEarlier(read.status, props.decidedHere === true));
290
+ }
291
+ else
292
+ setFailed(true);
293
+ });
294
+ return () => {
295
+ live = false;
296
+ };
297
+ }, [props.id, base, reads]);
298
+ const cardNow = useRef(card);
299
+ cardNow.current = card;
300
+ const deciding = useRef(false);
301
+ deciding.current = busy;
302
+ const rereads = useRef(null);
303
+ const pending = card?.status === "pending";
304
+ useEffect(() => {
305
+ if (!pending || typeof window === "undefined" || typeof document === "undefined")
306
+ return;
307
+ let live = true;
308
+ const w = approvalRereads({
309
+ read: () => readApproval({ base: base, id: props.id, fetch: doFetch }).then((read) => {
310
+ const now = cardNow.current;
311
+ if (!live || deciding.current || !now)
312
+ return;
313
+ const next = afterReread(now, read, props.decidedHere === true);
314
+ if (!next)
315
+ return;
316
+ setCard(next.card);
317
+ if (next.earlier !== null)
318
+ setEarlier(next.earlier);
319
+ }),
320
+ });
321
+ rereads.current = w;
322
+ const off = onTabBack(window, document, () => w.poke());
323
+ return () => {
324
+ live = false;
325
+ off();
326
+ w.dispose();
327
+ rereads.current = null;
328
+ };
329
+ }, [pending, props.id, base]);
330
+ const following = card !== null && followsAction(card);
331
+ useEffect(() => {
332
+ if (!following)
333
+ return;
334
+ const f = followAction({ read: () => readApproval({ base: base, id: props.id, fetch: doFetch }), onRead: (read) => setCard((now) => (now && now.status === "approved" && read.status === "approved" ? read : now)) });
335
+ return () => f.dispose();
336
+ }, [following, props.id, base]);
337
+ const firstLook = useRef(props.look);
338
+ useEffect(() => {
339
+ if (props.look === firstLook.current)
340
+ return;
341
+ firstLook.current = props.look;
342
+ rereads.current?.poke();
343
+ }, [props.look]);
344
+ if (!card) {
345
+ return (_jsx(ApprovalReadView, { failed: failed, fallbackTitle: props.fallbackTitle, loadingTitle: props.loadingTitle, labels: labels, onRetry: () => {
346
+ setFailed(false);
347
+ setReads((n) => n + 1);
348
+ } }));
349
+ }
350
+ const decide = async (decision) => {
351
+ const hadFocus = typeof document !== "undefined" && root.current?.contains(document.activeElement) === true;
352
+ refocus.current = hadFocus;
353
+ setBusy(true);
354
+ setOut(decision);
355
+ setNotice(null);
356
+ const r = await sendDecision(decision, () => decideApproval({ base: base, id: card.id, decision, actionHash: card.action_hash, fetch: doFetch }), props.onDeciding);
357
+ setBusy(false);
358
+ setOut(null);
359
+ if (r.ok) {
360
+ refocus.current = hadFocus;
361
+ setCard(r.card);
362
+ props.onDecided?.(decision, { runRefused: r.card.run_refused ?? null });
363
+ return;
364
+ }
365
+ const next = afterRefusal(r.code, labels, r.said);
366
+ setNotice(next.notice);
367
+ setWaiting(next.waiting);
368
+ if (next.readAgain)
369
+ setReads((n) => n + 1);
370
+ };
371
+ return _jsx(ApprovalCardView, { card: card, fallbackTitle: props.fallbackTitle, labels: labels, busy: busy, deciding: out, notice: notice, waiting: waiting, earlier: earlier === true, settled: props.settled === true, fields: props.fields, heldBack: heldBackFor(card, props.heldSessions), onDecide: (d) => void decide(d), rootRef: root });
372
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `<ArtifactCard>`: a file the agent delivered, drawn where it delivered it. `<AgentChat>` draws one for each
3
+ * `data-artifact` part, which follows the tool call that delivered the file:
4
+ *
5
+ * <ArtifactCard artifact={artifactOf(part.data)} href={chat.artifactHref(id)} loadText={() => chat.artifactText(id)} />
6
+ *
7
+ * The card names the file as its download link, with its size, and says when the agent wrote it after reading
8
+ * content from outside. A PREVIEW BY TYPE, and only these: an image (PNG, JPEG, WebP, GIF) is shown at once; a PDF
9
+ * and a Markdown or plain-text file wait behind a Preview button, so nothing is loaded that was not asked for.
10
+ * Every other type is the card alone.
11
+ *
12
+ * NOTHING IN A FILE IS EVER INTERPRETED HERE. An image is an `<img>` (never SVG), a PDF is the browser's own
13
+ * viewer, and text is text: drawn through your `renderText` (told whether the file is tainted), else a Markdown
14
+ * file by the chat's safe subset (`<MarkdownText>`: no HTML, no image loaded) and a plain-text file as it is.
15
+ */
16
+ import { type ReactNode } from "react";
17
+ import { type AgentChatLabels } from "./errors.ts";
18
+ import { type KitArtifactRef } from "./files.ts";
19
+ /** Which preview a file's type gets: `image`, `pdf` or `text`; null for none. */
20
+ export declare function previewKindOf(mime: string): "image" | "pdf" | "text" | null;
21
+ export interface ArtifactCardProps {
22
+ /** The file (`artifactOf(part.data)`). */
23
+ artifact: KitArtifactRef;
24
+ /** The link that downloads it (`useAgentChat().artifactHref(id)`). */
25
+ href: string;
26
+ /** Reads a text file's words for its preview (`useAgentChat().artifactText(id)`); null when they can't be shown. Absent, a text file has no preview. */
27
+ loadText?: (() => Promise<string | null>) | undefined;
28
+ /** Your markdown renderer, as `<AgentChat>`'s. When `info.tainted`, render no remote images and link only to hosts you allow. */
29
+ renderText?: ((text: string, info: {
30
+ tainted: boolean;
31
+ role: "assistant";
32
+ }) => ReactNode) | undefined;
33
+ labels?: Partial<AgentChatLabels> | undefined;
34
+ /** Start with the preview open. Default: an image is open, a PDF and a text file are closed. */
35
+ defaultOpen?: boolean | undefined;
36
+ className?: string | undefined;
37
+ }
38
+ export declare function ArtifactCard(props: ArtifactCardProps): import("react").JSX.Element;
@@ -0,0 +1,39 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { DEFAULT_LABELS } from "./errors.js";
5
+ import { sizeText } from "./files.js";
6
+ import { MarkdownText } from "./markdown.js";
7
+ export function previewKindOf(mime) {
8
+ const type = mime.split(";")[0].trim().toLowerCase();
9
+ if (type === "image/png" || type === "image/jpeg" || type === "image/webp" || type === "image/gif")
10
+ return "image";
11
+ if (type === "application/pdf")
12
+ return "pdf";
13
+ if (type === "text/markdown" || type === "text/plain")
14
+ return "text";
15
+ return null;
16
+ }
17
+ export function ArtifactCard(props) {
18
+ const l = { ...DEFAULT_LABELS, ...props.labels };
19
+ const a = props.artifact;
20
+ const found = previewKindOf(a.mime);
21
+ const kind = found === "text" && !props.loadText ? null : found;
22
+ const [open, setOpen] = useState(props.defaultOpen ?? kind === "image");
23
+ const isMarkdown = a.mime.split(";")[0].trim().toLowerCase() === "text/markdown";
24
+ const [text, setText] = useState(null);
25
+ const loadText = useRef(props.loadText);
26
+ loadText.current = props.loadText;
27
+ const wanted = open && kind === "text" && text === null && props.loadText !== undefined;
28
+ useEffect(() => {
29
+ const load = loadText.current;
30
+ if (!wanted || !load)
31
+ return;
32
+ let live = true;
33
+ load().then((words) => live && setText({ words }), () => live && setText({ words: null }));
34
+ return () => {
35
+ live = false;
36
+ };
37
+ }, [wanted]);
38
+ return (_jsxs("section", { "data-ol-artifact": true, "data-ol-tainted": a.tainted ? "true" : "false", "aria-label": a.name, className: props.className, children: [_jsxs("div", { "data-ol-artifact-file": true, children: [_jsx("a", { "data-ol-file-link": true, href: props.href, 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: l.fileUntrusted }) : null, kind === "pdf" || kind === "text" ? (_jsx("button", { type: "button", "data-ol-artifact-toggle": true, "aria-expanded": open, onClick: () => setOpen((was) => !was), children: open ? l.hidePreview : l.preview })) : null, open && kind === "image" ? _jsx("img", { "data-ol-artifact-preview": "image", src: props.href, alt: a.name, loading: "lazy" }) : null, open && kind === "pdf" ? (_jsx("object", { "data-ol-artifact-preview": "pdf", type: "application/pdf", data: props.href, "aria-label": a.name, children: _jsx("p", { "data-ol-artifact-fallback": true, children: l.previewFailed }) })) : null, open && kind === "text" ? (_jsx("div", { "data-ol-artifact-preview": "text", children: text === null ? l.previewLoading : text.words === null ? l.previewFailed : props.renderText ? props.renderText(text.words, { tainted: a.tainted, role: "assistant" }) : isMarkdown ? _jsx(MarkdownText, { text: text.words }) : _jsx("pre", { "data-ol-artifact-text": true, children: text.words }) })) : null] }));
39
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * An agent's picture beside its name (`<AgentList avatar>`, `<AgentChat avatar>`). The art is yours, never the kit's:
3
+ * `avatar={(agent) => <img src={…} alt="" />}` draws your own; without it, the name's first letter in a circle;
4
+ * `avatar={null}` draws nothing. Your function answering null draws the letter, and so does a picture of yours that
5
+ * fails to load (an image, video or picture inside the box): an agent always has a face.
6
+ *
7
+ * THE BOX IS FIXED (`--ol-avatar-size`, 1.75rem by default; set on the element itself, so even without the kit's
8
+ * stylesheet): nothing beside it moves when your image loads, or fails. Hidden from screen readers: the row or the
9
+ * message already says the name.
10
+ */
11
+ import { type ReactNode } from "react";
12
+ /** What a row or a message draws for an agent: your function, absent for the kit's letter, null for nothing. */
13
+ export type AvatarFor<A> = ((agent: A) => ReactNode) | null | undefined;
14
+ /** The name's first letter as a person reads it (one grapheme: an accent or an emoji stays whole), upper case. */
15
+ export declare function agentInitial(name: string): string;
16
+ /** The avatar's box, with yours or the letter in it; nothing when `draw` is null. */
17
+ export declare function Avatar<A>(p: {
18
+ agent: A;
19
+ name: string;
20
+ draw: AvatarFor<A>;
21
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,33 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { isValidElement, useLayoutEffect, useRef, useState } from "react";
3
+ export function agentInitial(name) {
4
+ const t = name.trim();
5
+ if (t === "")
6
+ return "";
7
+ const first = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(t)[Symbol.iterator]().next().value?.segment : Array.from(t)[0];
8
+ return (first ?? "").toLocaleUpperCase();
9
+ }
10
+ const BOX = { display: "inline-flex", flex: "none", alignItems: "center", justifyContent: "center", width: "var(--ol-avatar-size, 1.75rem)", height: "var(--ol-avatar-size, 1.75rem)", overflow: "hidden" };
11
+ export function Avatar(p) {
12
+ const box = useRef(null);
13
+ const own = p.draw ? p.draw(p.agent) : null;
14
+ const which = isValidElement(own) ? String(own.props.src ?? p.name) : p.name;
15
+ const [failed, setFailed] = useState(null);
16
+ const drawn = own !== null && own !== undefined && failed !== which ? own : null;
17
+ useLayoutEffect(() => {
18
+ const el = box.current;
19
+ if (!el || drawn === null)
20
+ return;
21
+ const lost = (e) => {
22
+ if (e.target !== el)
23
+ setFailed(which);
24
+ };
25
+ el.addEventListener("error", lost, true);
26
+ if (Array.from(el.querySelectorAll("img")).some((i) => i.complete && i.naturalWidth === 0 && i.getAttribute("src")))
27
+ setFailed(which);
28
+ return () => el.removeEventListener("error", lost, true);
29
+ }, [drawn === null, which]);
30
+ if (p.draw === null)
31
+ return null;
32
+ return (_jsx("span", { ref: box, "data-ol-avatar": drawn === null ? "initial" : "own", "aria-hidden": "true", style: BOX, children: drawn === null ? agentInitial(p.name) : drawn }));
33
+ }
@@ -0,0 +1,30 @@
1
+ /** Where a vault form stands. */
2
+ export type VaultFormState = "idle" | "saving" | "saved" | "failed" | "notYours" | "notYet";
3
+ export interface CardLedger {
4
+ /** A Connect card for `key` started a connect: `session` answers its id, or null when it did not start. */
5
+ connectStarted(key: string, session: Promise<string | null>): void;
6
+ /** For a card just drawn: the connect a card for `key` started and that has not ended yet, else null. */
7
+ connectInFlight(key: string): Promise<string | null> | null;
8
+ /**
9
+ * A session a card for `key` started has ended (`completed`, or not). True once, for a completed one: the carry-on
10
+ * is still to send. After it, a card for `key` drawn anew starts clean.
11
+ */
12
+ connectEnded(key: string, session: string, completed: boolean): boolean;
13
+ /** A vault form's state, by `vaultKey`. */
14
+ vaultState(key: string): VaultFormState | undefined;
15
+ vaultSet(key: string, state: VaultFormState): void;
16
+ /** Hear each change of `key`'s state from now on. Returns stop(). */
17
+ vaultWatch(key: string, fn: (state: VaultFormState) => void): () => void;
18
+ }
19
+ /** A Connect card is its app and the agent it asked for. */
20
+ export declare function connectKey(c: {
21
+ app: string;
22
+ agent: string | null;
23
+ }): string;
24
+ /** A vault form is the ask it answers: the agent's message, and the handle asked for. */
25
+ export declare function vaultKey(ask: {
26
+ message: string;
27
+ }, handle: string): string;
28
+ export declare function cardLedger(): CardLedger;
29
+ /** The conversation's ledger, from `AgentChatView`; null outside a chat. */
30
+ export declare const CardLedgerContext: import("react").Context<CardLedger | null>;
@@ -0,0 +1,49 @@
1
+ "use client";
2
+ import { createContext } from "react";
3
+ export function connectKey(c) {
4
+ return `${c.app}|${c.agent ?? ""}`;
5
+ }
6
+ export function vaultKey(ask, handle) {
7
+ return `${ask.message}|${handle}`;
8
+ }
9
+ export function cardLedger() {
10
+ const connects = new Map();
11
+ const carried = new Set();
12
+ const vault = new Map();
13
+ const watchers = new Map();
14
+ const release = (key, pending, session) => {
15
+ void pending.then((id) => {
16
+ if (id === session && connects.get(key) === pending)
17
+ connects.delete(key);
18
+ });
19
+ };
20
+ return {
21
+ connectStarted(key, session) {
22
+ connects.set(key, session);
23
+ release(key, session, null);
24
+ },
25
+ connectInFlight: (key) => connects.get(key) ?? null,
26
+ connectEnded(key, session, completed) {
27
+ const pending = connects.get(key);
28
+ if (pending)
29
+ release(key, pending, session);
30
+ if (!completed || carried.has(session))
31
+ return false;
32
+ carried.add(session);
33
+ return true;
34
+ },
35
+ vaultState: (key) => vault.get(key),
36
+ vaultSet(key, state) {
37
+ vault.set(key, state);
38
+ for (const fn of watchers.get(key) ?? [])
39
+ fn(state);
40
+ },
41
+ vaultWatch(key, fn) {
42
+ const set = watchers.get(key) ?? new Set();
43
+ watchers.set(key, set);
44
+ set.add(fn);
45
+ return () => void set.delete(fn);
46
+ },
47
+ };
48
+ }
49
+ export const CardLedgerContext = createContext(null);