@seclai/react 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,484 @@
1
+ "use client";
2
+
3
+ // src/AgentChat.tsx
4
+ import { useRef as useRef2, useState as useState2 } from "react";
5
+
6
+ // src/placeholders/MarkdownContent.tsx
7
+ import { jsx } from "react/jsx-runtime";
8
+ function MarkdownContent({ content }) {
9
+ return /* @__PURE__ */ jsx("div", { className: "seclai-markdown", children: content });
10
+ }
11
+
12
+ // src/placeholders/MediaPreview.tsx
13
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
14
+ function MediaPreview({ attachment }) {
15
+ const name = attachment.name ?? attachment.id;
16
+ return /* @__PURE__ */ jsxs("figure", { className: "seclai-media", children: [
17
+ attachment.mime.startsWith("image/") && /* @__PURE__ */ jsx2("img", { src: attachment.url, alt: name }),
18
+ /* @__PURE__ */ jsx2("figcaption", { children: /* @__PURE__ */ jsx2("a", { href: attachment.url, download: name, children: name }) })
19
+ ] });
20
+ }
21
+
22
+ // src/useAgentRun.ts
23
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
24
+
25
+ // src/endpoints.ts
26
+ var DEFAULT_BASE_PATH = "/api/seclai";
27
+ function createEndpoints({
28
+ basePath = DEFAULT_BASE_PATH,
29
+ agentId
30
+ } = {}) {
31
+ const trimmed = basePath.replace(/\/+$/, "");
32
+ const base = agentId ? `${trimmed}/${encodeURIComponent(agentId)}` : trimmed;
33
+ return {
34
+ attachmentReferences: `${base}/attachment-references`,
35
+ upload: `${base}/upload`,
36
+ run: `${base}/run`,
37
+ download(runId, attachmentId, name) {
38
+ const params = new URLSearchParams({ runId, attachmentId });
39
+ if (name) params.set("name", name);
40
+ return `${base}/download?${params}`;
41
+ }
42
+ };
43
+ }
44
+ async function readErrorMessage(res) {
45
+ try {
46
+ const body = await res.json();
47
+ if (typeof body.error === "string" && body.error) return body.error;
48
+ } catch {
49
+ }
50
+ return `The request failed with status ${res.status}.`;
51
+ }
52
+ async function readJson(res) {
53
+ if (!res.ok) throw new Error(await readErrorMessage(res));
54
+ return await res.json();
55
+ }
56
+ async function fetchAttachmentReferences(endpoints, signal) {
57
+ return readJson(await fetch(endpoints.attachmentReferences, { signal }));
58
+ }
59
+ async function uploadFile(endpoints, file) {
60
+ const form = new FormData();
61
+ form.set("file", file);
62
+ return readJson(await fetch(endpoints.upload, { method: "POST", body: form }));
63
+ }
64
+
65
+ // src/sse.ts
66
+ function parseData(data) {
67
+ try {
68
+ return JSON.parse(data);
69
+ } catch {
70
+ return data;
71
+ }
72
+ }
73
+ async function* readSseStream(stream) {
74
+ const reader = stream.getReader();
75
+ const decoder = new TextDecoder();
76
+ let buffer = "";
77
+ let event = "message";
78
+ let dataLines = [];
79
+ function takeEvent() {
80
+ const parsed = dataLines.length ? { event, data: parseData(dataLines.join("\n")) } : void 0;
81
+ event = "message";
82
+ dataLines = [];
83
+ return parsed;
84
+ }
85
+ function* drain(final) {
86
+ while (true) {
87
+ const match = /\r\n|\n|\r/.exec(buffer);
88
+ if (!match) return;
89
+ if (match[0] === "\r" && match.index === buffer.length - 1 && !final) return;
90
+ const line = buffer.slice(0, match.index);
91
+ buffer = buffer.slice(match.index + match[0].length);
92
+ if (line === "") {
93
+ const parsed = takeEvent();
94
+ if (parsed) yield parsed;
95
+ continue;
96
+ }
97
+ if (line.startsWith(":")) continue;
98
+ const colon = line.indexOf(":");
99
+ const field = colon === -1 ? line : line.slice(0, colon);
100
+ let value = colon === -1 ? "" : line.slice(colon + 1);
101
+ if (value.startsWith(" ")) value = value.slice(1);
102
+ if (field === "event") event = value;
103
+ else if (field === "data") dataLines.push(value);
104
+ }
105
+ }
106
+ try {
107
+ while (true) {
108
+ const { value, done } = await reader.read();
109
+ if (done) break;
110
+ buffer += decoder.decode(value, { stream: true });
111
+ yield* drain(false);
112
+ }
113
+ buffer += decoder.decode();
114
+ buffer += "\n\n";
115
+ yield* drain(true);
116
+ } finally {
117
+ void reader.cancel().catch(() => {
118
+ });
119
+ }
120
+ }
121
+
122
+ // src/useAgentRun.ts
123
+ var IDLE = {
124
+ status: "idle",
125
+ text: "",
126
+ steps: [],
127
+ attachments: [],
128
+ error: null,
129
+ runId: null
130
+ };
131
+ function toAttachments(files, runId, endpoints) {
132
+ if (!files || !runId) return [];
133
+ return files.map(({ id, name, mime, bytes }) => ({
134
+ id,
135
+ name,
136
+ mime,
137
+ bytes,
138
+ url: endpoints.download(runId, id, name)
139
+ }));
140
+ }
141
+ function lastAttemptError(run) {
142
+ for (const attempt of [...run.attempts ?? []].reverse()) {
143
+ if (attempt.error) return attempt.error;
144
+ }
145
+ return null;
146
+ }
147
+ function applyEvent(state, { event, data }, endpoints) {
148
+ const payload = typeof data === "object" && data !== null ? data : {};
149
+ switch (event) {
150
+ case "init":
151
+ return { ...state, runId: typeof payload.run_id === "string" ? payload.run_id : state.runId };
152
+ case "stream_token":
153
+ return typeof payload.token === "string" ? { ...state, text: state.text + payload.token } : state;
154
+ case "step_progress": {
155
+ if (typeof payload.step_id !== "string") return state;
156
+ const step = {
157
+ id: payload.step_id,
158
+ name: typeof payload.step_name === "string" ? payload.step_name : payload.step_id,
159
+ message: typeof payload.message === "string" ? payload.message : ""
160
+ };
161
+ const known = state.steps.some((s) => s.id === step.id);
162
+ return {
163
+ ...state,
164
+ steps: known ? state.steps.map((s) => s.id === step.id ? step : s) : [...state.steps, step]
165
+ };
166
+ }
167
+ case "done": {
168
+ const run = payload;
169
+ const runId = run.run_id ?? state.runId ?? void 0;
170
+ const attachments = toAttachments(run.attachments, runId, endpoints);
171
+ if (run.status === "failed") {
172
+ return {
173
+ ...state,
174
+ status: "failed",
175
+ runId: runId ?? null,
176
+ attachments,
177
+ error: lastAttemptError(run) ?? "The run failed."
178
+ };
179
+ }
180
+ return {
181
+ ...state,
182
+ status: "completed",
183
+ runId: runId ?? null,
184
+ attachments,
185
+ // `output` wins over the tokens, which are only a progress channel. Agents
186
+ // with no streaming step send no tokens, so this is their only text.
187
+ text: run.output || state.text
188
+ };
189
+ }
190
+ case "error":
191
+ return {
192
+ ...state,
193
+ status: "failed",
194
+ error: typeof payload.error === "string" ? payload.error : "The run failed."
195
+ };
196
+ case "timeout":
197
+ return {
198
+ ...state,
199
+ status: "failed",
200
+ error: "Stopped waiting for the run. It may still finish on Seclai."
201
+ };
202
+ default:
203
+ return state;
204
+ }
205
+ }
206
+ function useAgentRun(options = {}) {
207
+ const { basePath, agentId } = options;
208
+ const endpoints = useMemo(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
209
+ const [state, setState] = useState(IDLE);
210
+ const active = useRef(null);
211
+ useEffect(() => () => active.current?.abort(), []);
212
+ const start = useCallback(
213
+ async ({ input, uploadIds, sessionId }) => {
214
+ active.current?.abort();
215
+ const controller = new AbortController();
216
+ active.current = controller;
217
+ let current = { ...IDLE, status: "running" };
218
+ const update = (next) => {
219
+ current = next;
220
+ if (active.current === controller) setState(next);
221
+ };
222
+ update(current);
223
+ try {
224
+ const res = await fetch(endpoints.run, {
225
+ method: "POST",
226
+ headers: { "content-type": "application/json" },
227
+ body: JSON.stringify({ input, uploadIds, sessionId }),
228
+ signal: controller.signal
229
+ });
230
+ if (!res.ok) {
231
+ update({ ...current, status: "failed", error: await readErrorMessage(res) });
232
+ return current;
233
+ }
234
+ if (!res.body) {
235
+ update({ ...current, status: "failed", error: "The response had no body to stream." });
236
+ return current;
237
+ }
238
+ for await (const event of readSseStream(res.body)) {
239
+ update(applyEvent(current, event, endpoints));
240
+ if (current.status !== "running") break;
241
+ }
242
+ if (current.status === "running") {
243
+ update({
244
+ ...current,
245
+ status: "failed",
246
+ error: "The connection closed before the run finished."
247
+ });
248
+ }
249
+ } catch (err) {
250
+ if (controller.signal.aborted) {
251
+ update({ ...current, status: "cancelled" });
252
+ } else {
253
+ update({
254
+ ...current,
255
+ status: "failed",
256
+ error: err instanceof Error ? err.message : "The run failed."
257
+ });
258
+ }
259
+ }
260
+ return current;
261
+ },
262
+ [endpoints]
263
+ );
264
+ const cancel = useCallback(() => active.current?.abort(), []);
265
+ return { ...state, start, cancel };
266
+ }
267
+
268
+ // src/AgentChat.tsx
269
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
270
+ function createSessionId() {
271
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
272
+ return Array.from(
273
+ crypto.getRandomValues(new Uint8Array(16)),
274
+ (byte) => byte.toString(16).padStart(2, "0")
275
+ ).join("");
276
+ }
277
+ function Turn({ turn }) {
278
+ return /* @__PURE__ */ jsxs2("li", { className: `seclai-turn seclai-turn-${turn.role}`, children: [
279
+ turn.text && /* @__PURE__ */ jsx3(MarkdownContent, { content: turn.text }),
280
+ turn.attachments?.map((attachment) => /* @__PURE__ */ jsx3(MediaPreview, { attachment }, attachment.id)),
281
+ turn.error && /* @__PURE__ */ jsx3("p", { className: "seclai-error", role: "alert", children: turn.error }),
282
+ turn.cancelled && /* @__PURE__ */ jsx3("p", { className: "seclai-notice", children: "Stopped." })
283
+ ] });
284
+ }
285
+ function AgentChat({ basePath, agentId, placeholder = "Send a message" }) {
286
+ const run = useAgentRun({ basePath, agentId });
287
+ const [turns, setTurns] = useState2([]);
288
+ const [message, setMessage] = useState2("");
289
+ const sessionId = useRef2(null);
290
+ const nextTurnId = useRef2(0);
291
+ const running = run.status === "running";
292
+ async function send() {
293
+ const text = message.trim();
294
+ if (!text || running) return;
295
+ sessionId.current ??= createSessionId();
296
+ setMessage("");
297
+ setTurns((prev) => [...prev, { id: nextTurnId.current++, role: "user", text }]);
298
+ const result = await run.start({ input: text, sessionId: sessionId.current });
299
+ setTurns((prev) => [
300
+ ...prev,
301
+ {
302
+ id: nextTurnId.current++,
303
+ role: "assistant",
304
+ text: result.text,
305
+ attachments: result.attachments,
306
+ error: result.error,
307
+ cancelled: result.status === "cancelled"
308
+ }
309
+ ]);
310
+ }
311
+ function onSubmit(event) {
312
+ event.preventDefault();
313
+ void send();
314
+ }
315
+ function onKeyDown(event) {
316
+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
317
+ event.preventDefault();
318
+ void send();
319
+ }
320
+ }
321
+ return /* @__PURE__ */ jsxs2("div", { className: "seclai-agent seclai-chat", children: [
322
+ /* @__PURE__ */ jsxs2("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": running, children: [
323
+ turns.map((turn) => /* @__PURE__ */ jsx3(Turn, { turn }, turn.id)),
324
+ running && /* @__PURE__ */ jsx3("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ jsx3(MarkdownContent, { content: run.text }) : /* @__PURE__ */ jsx3("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
325
+ ] }),
326
+ /* @__PURE__ */ jsxs2("form", { className: "seclai-form", onSubmit, children: [
327
+ /* @__PURE__ */ jsx3(
328
+ "textarea",
329
+ {
330
+ rows: 2,
331
+ "aria-label": "Message",
332
+ placeholder,
333
+ value: message,
334
+ onChange: (e) => setMessage(e.target.value),
335
+ onKeyDown
336
+ }
337
+ ),
338
+ /* @__PURE__ */ jsxs2("div", { className: "seclai-actions", children: [
339
+ /* @__PURE__ */ jsx3(
340
+ "button",
341
+ {
342
+ type: "submit",
343
+ className: "seclai-button seclai-button-primary",
344
+ disabled: running || !message.trim(),
345
+ children: "Send"
346
+ }
347
+ ),
348
+ running && /* @__PURE__ */ jsx3("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
349
+ ] })
350
+ ] })
351
+ ] });
352
+ }
353
+
354
+ // src/AgentRunForm.tsx
355
+ import { useEffect as useEffect2, useMemo as useMemo2, useState as useState3 } from "react";
356
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
357
+ function slotProblem(slot, count) {
358
+ const label = slot.label ?? slot.name;
359
+ const min = slot.min ?? 0;
360
+ if (count < min) return `${label} needs at least ${min} file${min === 1 ? "" : "s"}.`;
361
+ if (slot.max != null && count > slot.max) {
362
+ return `${label} takes at most ${slot.max} file${slot.max === 1 ? "" : "s"}.`;
363
+ }
364
+ return null;
365
+ }
366
+ function AgentRunForm({ basePath, agentId, inputLabel = "Input", onFinish }) {
367
+ const endpoints = useMemo2(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
368
+ const run = useAgentRun({ basePath, agentId });
369
+ const [slots, setSlots] = useState3(null);
370
+ const [loadError, setLoadError] = useState3(null);
371
+ const [input, setInput] = useState3("");
372
+ const [files, setFiles] = useState3({});
373
+ const [uploading, setUploading] = useState3(false);
374
+ const [formError, setFormError] = useState3(null);
375
+ useEffect2(() => {
376
+ const controller = new AbortController();
377
+ setSlots(null);
378
+ setLoadError(null);
379
+ fetchAttachmentReferences(endpoints, controller.signal).then((refs) => setSlots(refs.accepted_attachments ?? [])).catch((err) => {
380
+ if (controller.signal.aborted) return;
381
+ setLoadError(err instanceof Error ? err.message : "Could not load this agent.");
382
+ });
383
+ return () => controller.abort();
384
+ }, [endpoints]);
385
+ const selected = Object.values(files).flat();
386
+ const busy = uploading || run.status === "running";
387
+ async function submit(event) {
388
+ event.preventDefault();
389
+ if (busy || !slots) return;
390
+ const problem = slots.map((slot) => slotProblem(slot, files[slot.name]?.length ?? 0)).find(Boolean);
391
+ if (problem) {
392
+ setFormError(problem);
393
+ return;
394
+ }
395
+ if (!input.trim() && selected.length === 0) {
396
+ setFormError("Enter some text or choose a file.");
397
+ return;
398
+ }
399
+ setFormError(null);
400
+ setUploading(true);
401
+ let uploadIds;
402
+ try {
403
+ const uploads = await Promise.all(selected.map((file) => uploadFile(endpoints, file)));
404
+ uploadIds = uploads.map((upload) => upload.id);
405
+ } catch (err) {
406
+ setFormError(err instanceof Error ? err.message : "The upload failed.");
407
+ return;
408
+ } finally {
409
+ setUploading(false);
410
+ }
411
+ const result = await run.start({
412
+ input: input.trim() || void 0,
413
+ uploadIds: uploadIds.length ? uploadIds : void 0
414
+ });
415
+ onFinish?.(result);
416
+ }
417
+ if (loadError) {
418
+ return /* @__PURE__ */ jsx4("div", { className: "seclai-agent", children: /* @__PURE__ */ jsx4("p", { className: "seclai-error", role: "alert", children: loadError }) });
419
+ }
420
+ if (!slots) {
421
+ return /* @__PURE__ */ jsxs3("div", { className: "seclai-agent", children: [
422
+ /* @__PURE__ */ jsx4("p", { className: "seclai-notice", children: "Loading\u2026" }),
423
+ /* @__PURE__ */ jsxs3("div", { className: "seclai-skeleton", "aria-hidden": "true", children: [
424
+ /* @__PURE__ */ jsx4("span", {}),
425
+ /* @__PURE__ */ jsx4("span", {})
426
+ ] })
427
+ ] });
428
+ }
429
+ const error = formError ?? run.error;
430
+ return /* @__PURE__ */ jsxs3("div", { className: "seclai-agent", children: [
431
+ /* @__PURE__ */ jsxs3("form", { className: "seclai-form", onSubmit: submit, children: [
432
+ /* @__PURE__ */ jsxs3("label", { className: "seclai-field", children: [
433
+ /* @__PURE__ */ jsx4("span", { children: inputLabel }),
434
+ /* @__PURE__ */ jsx4("textarea", { rows: 4, value: input, onChange: (e) => setInput(e.target.value) })
435
+ ] }),
436
+ slots.map((slot) => /* @__PURE__ */ jsxs3("label", { className: "seclai-field", children: [
437
+ /* @__PURE__ */ jsxs3("span", { children: [
438
+ slot.label ?? slot.name,
439
+ (slot.min ?? 0) > 0 ? " (required)" : ""
440
+ ] }),
441
+ /* @__PURE__ */ jsx4(
442
+ "input",
443
+ {
444
+ type: "file",
445
+ name: slot.name,
446
+ accept: slot.content_types?.length ? slot.content_types.join(",") : void 0,
447
+ multiple: slot.max == null || slot.max > 1,
448
+ onChange: (e) => setFiles((prev) => ({ ...prev, [slot.name]: Array.from(e.target.files ?? []) }))
449
+ }
450
+ )
451
+ ] }, slot.name)),
452
+ /* @__PURE__ */ jsxs3("div", { className: "seclai-actions", children: [
453
+ /* @__PURE__ */ jsx4("button", { type: "submit", className: "seclai-button seclai-button-primary", disabled: busy, children: uploading ? "Uploading\u2026" : "Run" }),
454
+ run.status === "running" && /* @__PURE__ */ jsx4("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
455
+ ] })
456
+ ] }),
457
+ run.steps.length > 0 && /* @__PURE__ */ jsx4("ul", { className: "seclai-steps", children: run.steps.map((step) => /* @__PURE__ */ jsxs3("li", { children: [
458
+ step.name,
459
+ ": ",
460
+ step.message
461
+ ] }, step.id)) }),
462
+ error && /* @__PURE__ */ jsx4("p", { className: "seclai-error", role: "alert", children: error }),
463
+ run.status === "cancelled" && /* @__PURE__ */ jsx4("p", { className: "seclai-notice", children: "Stopped." }),
464
+ (run.text || run.attachments.length > 0) && /* @__PURE__ */ jsxs3("div", { className: "seclai-output", "aria-live": "polite", "aria-busy": run.status === "running", children: [
465
+ run.text && /* @__PURE__ */ jsx4(MarkdownContent, { content: run.text }),
466
+ run.attachments.map((attachment) => /* @__PURE__ */ jsx4(MediaPreview, { attachment }, attachment.id))
467
+ ] })
468
+ ] });
469
+ }
470
+
471
+ // src/SeclaiAgent.tsx
472
+ import { jsx as jsx5 } from "react/jsx-runtime";
473
+ function SeclaiAgent({ mode, basePath, agentId }) {
474
+ return mode === "chat" ? /* @__PURE__ */ jsx5(AgentChat, { basePath, agentId }) : /* @__PURE__ */ jsx5(AgentRunForm, { basePath, agentId });
475
+ }
476
+ export {
477
+ AgentChat,
478
+ AgentRunForm,
479
+ DEFAULT_BASE_PATH,
480
+ MarkdownContent,
481
+ MediaPreview,
482
+ SeclaiAgent,
483
+ useAgentRun
484
+ };