@seclai/handlers 0.0.2 → 0.0.3

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/README.md CHANGED
@@ -52,6 +52,9 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
52
52
  | `agentId` | Required | The agent to run |
53
53
  | `apiVersion` | `2026-10-28` | Dated API version. Must be `2026-10-16` or later |
54
54
  | `runTimeoutMs` | 11 minutes | How long a streaming run may take |
55
+ | `onEvent` | None | `(event, ctx)`: called with each run event before it is relayed. See [Run callbacks](#run-callbacks) |
56
+ | `onRunEnd` | None | `(outcome, ctx)`: called once per run with how it ended. See [Run callbacks](#run-callbacks) |
57
+ | `keepReadingAfterDisconnect` | `false` | Keep reading a run after the browser leaves, so `onRunEnd` gets its real outcome. See [Saving replies after a disconnect](#saving-replies-after-a-disconnect) |
55
58
  | `context` | None | `(req)`: your per-request context, such as the signed-in user, passed to every hook. See [Access control](#access-control) |
56
59
  | `authorizeRun` | None | `(req, body, ctx)`: refuse or rewrite a run. See [Access control](#access-control) |
57
60
  | `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
@@ -127,6 +130,78 @@ The context's type is inferred from the `context` option, or set as the type par
127
130
  - If the stream fails after it has started, it ends with an `error` event carrying `{ error }`.
128
131
  - When the browser disconnects, the upstream connection closes. **The run itself keeps going on Seclai** and may keep using credits.
129
132
 
133
+ ## Run callbacks
134
+
135
+ `onEvent` and `onRunEnd` let the server see each run, for example to store a chat's history without trusting the browser to report it. Both get a `ctx` of `{ body, request }`: the validated `run` request body and the `Request` itself. It is the same object for every call in a run.
136
+
137
+ ```ts
138
+ const seclai = createSeclaiHandlers({
139
+ apiKey: process.env.SECLAI_API_KEY!,
140
+ agentId: process.env.SECLAI_AGENT_ID!,
141
+ async onRunEnd(outcome, { body }) {
142
+ if (!body.sessionId) return;
143
+ await db.messages.insert({
144
+ sessionId: body.sessionId,
145
+ role: "assistant",
146
+ runId: outcome.runId,
147
+ status: outcome.status,
148
+ content: outcome.output,
149
+ attachments: outcome.attachments,
150
+ error: outcome.error,
151
+ });
152
+ },
153
+ });
154
+ ```
155
+
156
+ **`onEvent(event, ctx)`** gets each event as `{ event, data }`, with `data` parsed from JSON, in order. Each call is awaited before its event is relayed. It also sees the `error` event the handler sends when the upstream connection fails. The one event it can miss is a first event the browser never received because it disconnected straight away; that event still counts toward the outcome.
157
+
158
+ **`onRunEnd(outcome, ctx)`** is called exactly once for each run that started streaming. It is awaited before the final `done`, `error` or `timeout` event is relayed, so **whatever it stores is in place by the time the browser sees `done`**, and the browser can reload history right away. For `done`, `onEvent` runs first, then `onRunEnd`, then the event is relayed.
159
+
160
+ | `outcome` field | |
161
+ |---|---|
162
+ | `runId` | From `init` or `done`. `null` if the stream ended before either |
163
+ | `status` | `completed`, `failed` or `cancelled` |
164
+ | `output` | The run's output when it completed. Otherwise the text streamed in `stream_token` events so far |
165
+ | `attachments` | Files from `done`, as `{ id, name, mime }`. Fetch them with `download` |
166
+ | `error` | Why the run failed, or `null` |
167
+
168
+ | The run stream... | `status` | `error` |
169
+ |---|---|---|
170
+ | Sends `done` | `completed`, or `failed` if the run failed | The last attempt's error |
171
+ | Sends `error`, or the upstream connection fails | `failed` | The event's `error` |
172
+ | Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
173
+ | Ends with none of these | `failed` | `The stream ended without a result.` |
174
+ | Is cancelled by the browser | `cancelled`, unless `keepReadingAfterDisconnect` is on | `null` |
175
+
176
+ `cancelled` means the browser left. The run itself keeps going on Seclai. If the upstream connection fails or ends after the browser has left, that is reported as `cancelled` too, but an `error` or `timeout` event from the API is still `failed`. If the browser leaves while a callback is handling `done`, `error` or `timeout`, that event's outcome is reported.
177
+
178
+ When `runTimeoutMs` runs out, the stream gets an `error` event, `Timed out waiting for the agent run to finish.`, not `timeout`. The time spent awaiting your callbacks counts against `runTimeoutMs`.
179
+
180
+ If `onEvent` or `onRunEnd` throws or rejects, the handler logs the error with `console.error`, closes the upstream, and ends the stream with `event: error` carrying `{ "error": "The server could not process the run." }`, in place of the event it was handling. If `onRunEnd` hadn't been called yet, it is called once with `status: "failed"`, unless the browser had already disconnected, in which case the outcome is `cancelled` (with `keepReadingAfterDisconnect` on, it is `failed` either way). A throw during a cancel is only logged. A callback that never settles holds up the stream, and a cancel waits for a callback still running, so put a timeout on slow writes.
181
+
182
+ ### Saving replies after a disconnect
183
+
184
+ By default, when the browser leaves (it closes the tab, navigates to another chat, or aborts the request), the handler stops reading the run and `onRunEnd` reports `cancelled` with the text streamed so far. The run itself still finishes on Seclai and is billed, and a chat agent's memory keeps its reply, so an app that saves replies ends up with a turn the agent remembers but the app never showed.
185
+
186
+ Set `keepReadingAfterDisconnect: true` to keep reading the run in the background instead:
187
+
188
+ ```ts
189
+ const seclai = createSeclaiHandlers({
190
+ apiKey, agentId,
191
+ keepReadingAfterDisconnect: true,
192
+ onRunEnd: (outcome, { body }) => db.saveReply(body.sessionId, outcome),
193
+ });
194
+ ```
195
+
196
+ - **Callbacks.** The browser stops getting events, but `onEvent` still gets each one, and `onRunEnd` gets the run's real outcome with its output and files.
197
+ - **Outcomes.** A lost connection or a quiet end is reported as `failed`, since the browser leaving no longer stops the upstream, and `cancelled` doesn't occur. A callback that throws during the background reading is `failed` too.
198
+ - **Unread responses.** The handler also watches the request's signal, so it reads on even when the framework drops the response unread after the browser aborts. React Router does this when the browser leaves before the response starts.
199
+ - **Limits.** Reading the upstream stops at `runTimeoutMs` at the latest, and stops at once if a callback throws. A callback that never settles isn't bounded by it, so put a timeout on slow writes.
200
+ - **Show the reply when the user comes back.** For example, reload the conversation when it ends with a message that has no reply yet.
201
+ - **Serverless platforms** may freeze or end the function when the response closes, which cuts the background reading short. Use it on long-running servers, or check your platform's background-work support, such as `waitUntil`.
202
+
203
+ The option only takes effect with `onEvent` or `onRunEnd` set.
204
+
130
205
  ## Limits to know before deploying
131
206
 
132
207
  - **The endpoints have no auth by default.** Anyone who can reach them can run your agent on your credits. Use the [access-control hooks](#access-control) to check the caller, and put rate limiting in front of a public deployment. `attachment-references` has no hook, so guard that route yourself if the agent's accepted files are sensitive.
package/dist/index.cjs CHANGED
@@ -110,52 +110,296 @@ data: ${JSON.stringify(data)}
110
110
 
111
111
  `);
112
112
  }
113
- function relayRunEvents(first, events, abort) {
113
+ var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
114
+ function relayRunEvents(first, events, abort, observer, options = {}) {
115
+ const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
116
+ let pending = first;
114
117
  let closed = false;
118
+ let cancelled = false;
119
+ let closeReport;
120
+ let inflight;
115
121
  let keepalive;
122
+ let ctrl;
123
+ let draining = false;
124
+ let pulling;
116
125
  const finish = () => {
117
126
  closed = true;
118
127
  clearInterval(keepalive);
119
128
  };
120
- return new ReadableStream({
121
- start(controller) {
122
- if (!first) {
123
- finish();
124
- controller.close();
129
+ const stopUpstream = () => {
130
+ abort();
131
+ void events.return().catch(() => {
132
+ });
133
+ };
134
+ const call = async (hook) => {
135
+ try {
136
+ await hook();
137
+ return true;
138
+ } catch (err) {
139
+ try {
140
+ observer?.onError(err);
141
+ } catch {
142
+ }
143
+ return false;
144
+ }
145
+ };
146
+ const reportClose = (reason) => {
147
+ if (!observer) return Promise.resolve(true);
148
+ return closeReport ??= call(() => observer.onClose(reason));
149
+ };
150
+ const end = (controller, last) => {
151
+ if (cancelled) return;
152
+ if (last) controller.enqueue(last);
153
+ controller.close();
154
+ };
155
+ const fail = async (controller) => {
156
+ finish();
157
+ stopUpstream();
158
+ await reportClose("error");
159
+ end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
160
+ };
161
+ const relay = (controller, event, source = "upstream") => {
162
+ const work = (async () => {
163
+ if (observer && !await call(() => observer.onEvent(event, source))) {
164
+ if (!closed) await fail(controller);
125
165
  return;
126
166
  }
127
- controller.enqueue(frame(first.event, first.data));
128
- keepalive = setInterval(() => {
129
- if (!closed) controller.enqueue(encoder.encode(": keepalive\n\n"));
130
- }, KEEPALIVE_INTERVAL_MS);
131
- },
132
- async pull(controller) {
167
+ if (closed || cancelled) return;
168
+ controller.enqueue(frame(event.event, event.data));
169
+ })();
170
+ inflight = work;
171
+ return work;
172
+ };
173
+ const pullOnce = async (controller) => {
174
+ if (pending) {
175
+ const event = pending;
176
+ pending = void 0;
177
+ await relay(controller, event);
178
+ return;
179
+ }
180
+ let next;
181
+ try {
182
+ next = await events.next();
183
+ } catch (err) {
133
184
  if (closed) return;
185
+ await relay(
186
+ controller,
187
+ { event: "error", data: { error: streamErrorMessage(err) } },
188
+ "connection-lost"
189
+ );
190
+ if (closed) return;
191
+ finish();
192
+ await reportClose("end");
193
+ end(controller);
194
+ return;
195
+ }
196
+ if (closed) return;
197
+ if (next.done) {
198
+ finish();
199
+ const ok = await reportClose("end");
200
+ end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
201
+ return;
202
+ }
203
+ await relay(controller, next.value);
204
+ };
205
+ const drain = async (controller) => {
206
+ await pulling;
207
+ await inflight;
208
+ if (closed) return;
209
+ if (pending) {
210
+ const event = pending;
211
+ pending = void 0;
212
+ await relay(controller, event);
213
+ }
214
+ while (!closed) {
215
+ let next;
134
216
  try {
135
- const next = await events.next();
136
- if (closed) return;
137
- if (next.done) {
138
- finish();
139
- controller.close();
140
- return;
141
- }
142
- controller.enqueue(frame(next.value.event, next.value.data));
217
+ next = await events.next();
143
218
  } catch (err) {
144
219
  if (closed) return;
220
+ await relay(
221
+ controller,
222
+ { event: "error", data: { error: streamErrorMessage(err) } },
223
+ "connection-lost"
224
+ );
225
+ if (closed) return;
226
+ finish();
227
+ await reportClose("end");
228
+ return;
229
+ }
230
+ if (closed) return;
231
+ if (next.done) {
145
232
  finish();
146
- controller.enqueue(frame("error", { error: streamErrorMessage(err) }));
233
+ await reportClose("end");
234
+ return;
235
+ }
236
+ await relay(controller, next.value);
237
+ }
238
+ };
239
+ const startDrain = (fromCancel) => {
240
+ if (draining || closed || !ctrl) return;
241
+ draining = true;
242
+ cancelled = true;
243
+ clearInterval(keepalive);
244
+ const controller = ctrl;
245
+ if (!fromCancel) {
246
+ try {
147
247
  controller.close();
248
+ } catch {
249
+ }
250
+ }
251
+ try {
252
+ observer?.onDisconnect?.();
253
+ } catch {
254
+ }
255
+ void drain(controller).catch((err) => {
256
+ try {
257
+ observer?.onError(err);
258
+ } catch {
259
+ }
260
+ });
261
+ };
262
+ return new ReadableStream({
263
+ start(controller) {
264
+ ctrl = controller;
265
+ keepalive = setInterval(() => {
266
+ if (!closed && !cancelled) controller.enqueue(encoder.encode(": keepalive\n\n"));
267
+ }, KEEPALIVE_INTERVAL_MS);
268
+ if (keepReading && options.signal) {
269
+ const { signal } = options;
270
+ const onAbort = () => startDrain(false);
271
+ if (signal.aborted) queueMicrotask(onAbort);
272
+ else signal.addEventListener("abort", onAbort, { once: true });
148
273
  }
149
274
  },
150
- cancel() {
275
+ pull(controller) {
276
+ if (closed || draining) return;
277
+ const work = pullOnce(controller);
278
+ pulling = work;
279
+ return work;
280
+ },
281
+ async cancel() {
282
+ if (keepReading) {
283
+ startDrain(true);
284
+ return;
285
+ }
286
+ cancelled = true;
151
287
  finish();
152
- abort();
153
- void events.return().catch(() => {
154
- });
288
+ stopUpstream();
289
+ const unrelayed = pending;
290
+ pending = void 0;
291
+ if (unrelayed && observer?.onUnrelayed) {
292
+ await call(() => observer.onUnrelayed(unrelayed));
293
+ }
294
+ await inflight;
295
+ await reportClose("cancel");
155
296
  }
156
297
  });
157
298
  }
158
299
 
300
+ // src/run-callbacks.ts
301
+ var NO_RESULT_MESSAGE = "The stream ended without a result.";
302
+ var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
303
+ var FAILED_MESSAGE = "The run failed.";
304
+ function lastAttemptError(run) {
305
+ if (!Array.isArray(run.attempts)) return null;
306
+ for (let i = run.attempts.length - 1; i >= 0; i--) {
307
+ const error = run.attempts[i]?.error;
308
+ if (typeof error === "string" && error) return error;
309
+ }
310
+ return null;
311
+ }
312
+ function toAttachments(raw) {
313
+ if (!Array.isArray(raw)) return [];
314
+ return raw.flatMap(
315
+ (item) => typeof item?.id === "string" ? [
316
+ {
317
+ id: item.id,
318
+ name: typeof item.name === "string" ? item.name : null,
319
+ mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
320
+ }
321
+ ] : []
322
+ );
323
+ }
324
+ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
325
+ const { onEvent, onRunEnd } = callbacks;
326
+ const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
327
+ let runId = null;
328
+ let text = "";
329
+ let terminal;
330
+ let ended = false;
331
+ const outcome = (o) => ({
332
+ runId,
333
+ attachments: [],
334
+ ...o
335
+ });
336
+ const end = async (o) => {
337
+ if (ended) return;
338
+ ended = true;
339
+ await onRunEnd?.(o, ctx);
340
+ };
341
+ const failed = (error) => outcome({ status: "failed", output: text, error });
342
+ const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
343
+ const record = (event, source) => {
344
+ const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
345
+ if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
346
+ if (terminal) return;
347
+ switch (event.event) {
348
+ case "stream_token":
349
+ if (typeof payload.token === "string") text += payload.token;
350
+ return;
351
+ case "done": {
352
+ const run = payload;
353
+ if (typeof run.run_id === "string") runId = run.run_id;
354
+ const attachments = toAttachments(run.attachments);
355
+ terminal = run.status === "failed" ? outcome({
356
+ status: "failed",
357
+ output: text,
358
+ attachments,
359
+ error: lastAttemptError(run) ?? FAILED_MESSAGE
360
+ }) : outcome({
361
+ status: "completed",
362
+ // Agents with no streaming step send no tokens, so `output`
363
+ // may be the only text.
364
+ output: typeof run.output === "string" && run.output || text,
365
+ attachments,
366
+ error: null
367
+ });
368
+ return;
369
+ }
370
+ case "error":
371
+ terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
372
+ return;
373
+ case "timeout":
374
+ terminal = failed(TIMEOUT_MESSAGE);
375
+ return;
376
+ }
377
+ };
378
+ return {
379
+ async onEvent(event, source) {
380
+ record(event, source);
381
+ await onEvent?.(event, ctx);
382
+ if (terminal) await end(terminal);
383
+ },
384
+ onUnrelayed(event) {
385
+ record(event, "upstream");
386
+ },
387
+ async onClose(reason) {
388
+ switch (reason) {
389
+ case "end":
390
+ return end(terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE)));
391
+ case "error":
392
+ return end(failed(OBSERVER_ERROR_MESSAGE));
393
+ case "cancel":
394
+ return end(terminal ?? cancelled());
395
+ }
396
+ },
397
+ onError(err) {
398
+ console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
399
+ }
400
+ };
401
+ }
402
+
159
403
  // src/handlers.ts
160
404
  var MIN_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_16;
161
405
  var DEFAULT_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_28;
@@ -201,6 +445,9 @@ function createSeclaiHandlers(options) {
201
445
  agentId,
202
446
  apiVersion = DEFAULT_API_VERSION,
203
447
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
448
+ keepReadingAfterDisconnect = false,
449
+ onEvent,
450
+ onRunEnd,
204
451
  context,
205
452
  authorizeRun,
206
453
  authorizeUpload,
@@ -322,7 +569,8 @@ function createSeclaiHandlers(options) {
322
569
  }
323
570
  const upstream = new AbortController();
324
571
  const abort = () => upstream.abort();
325
- req.signal?.addEventListener("abort", abort, { once: true });
572
+ const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
573
+ if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
326
574
  const events = client.runStreamingAgent(
327
575
  agentId,
328
576
  {
@@ -334,8 +582,15 @@ function createSeclaiHandlers(options) {
334
582
  );
335
583
  try {
336
584
  const first = await events.next();
585
+ const observer = onEvent || onRunEnd ? createRunObserver({ onEvent, onRunEnd }, { body, request: req }, { keepReading }) : void 0;
337
586
  return new Response(
338
- relayRunEvents(first.done ? void 0 : first.value, events, abort),
587
+ relayRunEvents(
588
+ first.done ? void 0 : first.value,
589
+ events,
590
+ abort,
591
+ observer,
592
+ keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
593
+ ),
339
594
  { headers: SSE_HEADERS }
340
595
  );
341
596
  } catch (err) {
package/dist/index.d.cts CHANGED
@@ -1,5 +1,43 @@
1
1
  import { ApiVersion } from '@seclai/sdk';
2
2
 
3
+ /** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
4
+ interface RunEvent {
5
+ event: string;
6
+ data: unknown;
7
+ }
8
+ /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
9
+ interface RunCallbackContext {
10
+ /** The validated body of the `run` request. */
11
+ body: RunRequestBody;
12
+ /** The browser's request to the `run` handler. */
13
+ request: Request;
14
+ }
15
+ type RunOutcomeStatus = "completed" | "failed" | "cancelled";
16
+ /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
17
+ interface RunOutcomeAttachment {
18
+ id: string;
19
+ name: string | null;
20
+ mime: string;
21
+ }
22
+ /** How a run ended, as reported to `onRunEnd`. */
23
+ interface RunOutcome {
24
+ /** From `init` or `done`. `null` if the stream ended before either. */
25
+ runId: string | null;
26
+ /**
27
+ * `cancelled` means the browser went away before the run ended. The run
28
+ * itself may still finish on Seclai.
29
+ */
30
+ status: RunOutcomeStatus;
31
+ /** The run's output when it completed, otherwise the text streamed so far. */
32
+ output: string;
33
+ /** Files from `done`. Empty unless the run sent `done`. */
34
+ attachments: RunOutcomeAttachment[];
35
+ /** Why the run failed. `null` unless `status` is `failed`. */
36
+ error: string | null;
37
+ }
38
+ type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
39
+ type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
40
+
3
41
  /**
4
42
  * From this version uploads are `ready` at once and a run's `output` is plain
5
43
  * text with files in `attachments`. The handlers rely on both.
@@ -19,6 +57,35 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
19
57
  apiVersion?: ApiVersion;
20
58
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
21
59
  runTimeoutMs?: number;
60
+ /**
61
+ * Called with each event of a run stream, in order, and awaited before the
62
+ * event is relayed to the browser. If it throws, the stream ends with an
63
+ * `error` event.
64
+ */
65
+ onEvent?: RunEventCallback;
66
+ /**
67
+ * Called exactly once for each run that started streaming, with how it ended.
68
+ * Awaited before the final `done`, `error` or `timeout` event is relayed, so
69
+ * whatever it stores is in place when the browser sees the run end. If it
70
+ * throws, the browser gets an `error` event instead.
71
+ */
72
+ onRunEnd?: RunEndCallback;
73
+ /**
74
+ * What happens to a run when the browser disconnects: closes the tab, moves
75
+ * to another page, or aborts the request. The run itself always carries on at
76
+ * Seclai and uses credits.
77
+ *
78
+ * - `false` (default): the handler stops reading it. `onRunEnd` reports
79
+ * `cancelled` with what had streamed so far.
80
+ * - `true`: the handler keeps reading it in the background until it ends,
81
+ * still calling `onEvent` for each event, so `onRunEnd` gets the real
82
+ * outcome, with its output and files. Use it when `onRunEnd` saves replies.
83
+ * Reading stops at `runTimeoutMs` at the latest.
84
+ *
85
+ * Only takes effect with `onEvent` or `onRunEnd` set: without them there is
86
+ * nothing to read the rest of the run for.
87
+ */
88
+ keepReadingAfterDisconnect?: boolean;
22
89
  /**
23
90
  * Your app's per-request context (for example the signed-in user), passed to
24
91
  * each hook as its last argument. Called only when a hook is about to run.
@@ -137,4 +204,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
137
204
  context?: undefined;
138
205
  }): UnboundSeclaiHandlers<Ctx>;
139
206
 
140
- export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
207
+ export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,43 @@
1
1
  import { ApiVersion } from '@seclai/sdk';
2
2
 
3
+ /** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
4
+ interface RunEvent {
5
+ event: string;
6
+ data: unknown;
7
+ }
8
+ /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
9
+ interface RunCallbackContext {
10
+ /** The validated body of the `run` request. */
11
+ body: RunRequestBody;
12
+ /** The browser's request to the `run` handler. */
13
+ request: Request;
14
+ }
15
+ type RunOutcomeStatus = "completed" | "failed" | "cancelled";
16
+ /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
17
+ interface RunOutcomeAttachment {
18
+ id: string;
19
+ name: string | null;
20
+ mime: string;
21
+ }
22
+ /** How a run ended, as reported to `onRunEnd`. */
23
+ interface RunOutcome {
24
+ /** From `init` or `done`. `null` if the stream ended before either. */
25
+ runId: string | null;
26
+ /**
27
+ * `cancelled` means the browser went away before the run ended. The run
28
+ * itself may still finish on Seclai.
29
+ */
30
+ status: RunOutcomeStatus;
31
+ /** The run's output when it completed, otherwise the text streamed so far. */
32
+ output: string;
33
+ /** Files from `done`. Empty unless the run sent `done`. */
34
+ attachments: RunOutcomeAttachment[];
35
+ /** Why the run failed. `null` unless `status` is `failed`. */
36
+ error: string | null;
37
+ }
38
+ type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
39
+ type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
40
+
3
41
  /**
4
42
  * From this version uploads are `ready` at once and a run's `output` is plain
5
43
  * text with files in `attachments`. The handlers rely on both.
@@ -19,6 +57,35 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
19
57
  apiVersion?: ApiVersion;
20
58
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
21
59
  runTimeoutMs?: number;
60
+ /**
61
+ * Called with each event of a run stream, in order, and awaited before the
62
+ * event is relayed to the browser. If it throws, the stream ends with an
63
+ * `error` event.
64
+ */
65
+ onEvent?: RunEventCallback;
66
+ /**
67
+ * Called exactly once for each run that started streaming, with how it ended.
68
+ * Awaited before the final `done`, `error` or `timeout` event is relayed, so
69
+ * whatever it stores is in place when the browser sees the run end. If it
70
+ * throws, the browser gets an `error` event instead.
71
+ */
72
+ onRunEnd?: RunEndCallback;
73
+ /**
74
+ * What happens to a run when the browser disconnects: closes the tab, moves
75
+ * to another page, or aborts the request. The run itself always carries on at
76
+ * Seclai and uses credits.
77
+ *
78
+ * - `false` (default): the handler stops reading it. `onRunEnd` reports
79
+ * `cancelled` with what had streamed so far.
80
+ * - `true`: the handler keeps reading it in the background until it ends,
81
+ * still calling `onEvent` for each event, so `onRunEnd` gets the real
82
+ * outcome, with its output and files. Use it when `onRunEnd` saves replies.
83
+ * Reading stops at `runTimeoutMs` at the latest.
84
+ *
85
+ * Only takes effect with `onEvent` or `onRunEnd` set: without them there is
86
+ * nothing to read the rest of the run for.
87
+ */
88
+ keepReadingAfterDisconnect?: boolean;
22
89
  /**
23
90
  * Your app's per-request context (for example the signed-in user), passed to
24
91
  * each hook as its last argument. Called only when a hook is about to run.
@@ -137,4 +204,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
137
204
  context?: undefined;
138
205
  }): UnboundSeclaiHandlers<Ctx>;
139
206
 
140
- export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
207
+ export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
package/dist/index.js CHANGED
@@ -85,52 +85,296 @@ data: ${JSON.stringify(data)}
85
85
 
86
86
  `);
87
87
  }
88
- function relayRunEvents(first, events, abort) {
88
+ var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
89
+ function relayRunEvents(first, events, abort, observer, options = {}) {
90
+ const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
91
+ let pending = first;
89
92
  let closed = false;
93
+ let cancelled = false;
94
+ let closeReport;
95
+ let inflight;
90
96
  let keepalive;
97
+ let ctrl;
98
+ let draining = false;
99
+ let pulling;
91
100
  const finish = () => {
92
101
  closed = true;
93
102
  clearInterval(keepalive);
94
103
  };
95
- return new ReadableStream({
96
- start(controller) {
97
- if (!first) {
98
- finish();
99
- controller.close();
104
+ const stopUpstream = () => {
105
+ abort();
106
+ void events.return().catch(() => {
107
+ });
108
+ };
109
+ const call = async (hook) => {
110
+ try {
111
+ await hook();
112
+ return true;
113
+ } catch (err) {
114
+ try {
115
+ observer?.onError(err);
116
+ } catch {
117
+ }
118
+ return false;
119
+ }
120
+ };
121
+ const reportClose = (reason) => {
122
+ if (!observer) return Promise.resolve(true);
123
+ return closeReport ??= call(() => observer.onClose(reason));
124
+ };
125
+ const end = (controller, last) => {
126
+ if (cancelled) return;
127
+ if (last) controller.enqueue(last);
128
+ controller.close();
129
+ };
130
+ const fail = async (controller) => {
131
+ finish();
132
+ stopUpstream();
133
+ await reportClose("error");
134
+ end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
135
+ };
136
+ const relay = (controller, event, source = "upstream") => {
137
+ const work = (async () => {
138
+ if (observer && !await call(() => observer.onEvent(event, source))) {
139
+ if (!closed) await fail(controller);
100
140
  return;
101
141
  }
102
- controller.enqueue(frame(first.event, first.data));
103
- keepalive = setInterval(() => {
104
- if (!closed) controller.enqueue(encoder.encode(": keepalive\n\n"));
105
- }, KEEPALIVE_INTERVAL_MS);
106
- },
107
- async pull(controller) {
142
+ if (closed || cancelled) return;
143
+ controller.enqueue(frame(event.event, event.data));
144
+ })();
145
+ inflight = work;
146
+ return work;
147
+ };
148
+ const pullOnce = async (controller) => {
149
+ if (pending) {
150
+ const event = pending;
151
+ pending = void 0;
152
+ await relay(controller, event);
153
+ return;
154
+ }
155
+ let next;
156
+ try {
157
+ next = await events.next();
158
+ } catch (err) {
108
159
  if (closed) return;
160
+ await relay(
161
+ controller,
162
+ { event: "error", data: { error: streamErrorMessage(err) } },
163
+ "connection-lost"
164
+ );
165
+ if (closed) return;
166
+ finish();
167
+ await reportClose("end");
168
+ end(controller);
169
+ return;
170
+ }
171
+ if (closed) return;
172
+ if (next.done) {
173
+ finish();
174
+ const ok = await reportClose("end");
175
+ end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
176
+ return;
177
+ }
178
+ await relay(controller, next.value);
179
+ };
180
+ const drain = async (controller) => {
181
+ await pulling;
182
+ await inflight;
183
+ if (closed) return;
184
+ if (pending) {
185
+ const event = pending;
186
+ pending = void 0;
187
+ await relay(controller, event);
188
+ }
189
+ while (!closed) {
190
+ let next;
109
191
  try {
110
- const next = await events.next();
111
- if (closed) return;
112
- if (next.done) {
113
- finish();
114
- controller.close();
115
- return;
116
- }
117
- controller.enqueue(frame(next.value.event, next.value.data));
192
+ next = await events.next();
118
193
  } catch (err) {
119
194
  if (closed) return;
195
+ await relay(
196
+ controller,
197
+ { event: "error", data: { error: streamErrorMessage(err) } },
198
+ "connection-lost"
199
+ );
200
+ if (closed) return;
201
+ finish();
202
+ await reportClose("end");
203
+ return;
204
+ }
205
+ if (closed) return;
206
+ if (next.done) {
120
207
  finish();
121
- controller.enqueue(frame("error", { error: streamErrorMessage(err) }));
208
+ await reportClose("end");
209
+ return;
210
+ }
211
+ await relay(controller, next.value);
212
+ }
213
+ };
214
+ const startDrain = (fromCancel) => {
215
+ if (draining || closed || !ctrl) return;
216
+ draining = true;
217
+ cancelled = true;
218
+ clearInterval(keepalive);
219
+ const controller = ctrl;
220
+ if (!fromCancel) {
221
+ try {
122
222
  controller.close();
223
+ } catch {
224
+ }
225
+ }
226
+ try {
227
+ observer?.onDisconnect?.();
228
+ } catch {
229
+ }
230
+ void drain(controller).catch((err) => {
231
+ try {
232
+ observer?.onError(err);
233
+ } catch {
234
+ }
235
+ });
236
+ };
237
+ return new ReadableStream({
238
+ start(controller) {
239
+ ctrl = controller;
240
+ keepalive = setInterval(() => {
241
+ if (!closed && !cancelled) controller.enqueue(encoder.encode(": keepalive\n\n"));
242
+ }, KEEPALIVE_INTERVAL_MS);
243
+ if (keepReading && options.signal) {
244
+ const { signal } = options;
245
+ const onAbort = () => startDrain(false);
246
+ if (signal.aborted) queueMicrotask(onAbort);
247
+ else signal.addEventListener("abort", onAbort, { once: true });
123
248
  }
124
249
  },
125
- cancel() {
250
+ pull(controller) {
251
+ if (closed || draining) return;
252
+ const work = pullOnce(controller);
253
+ pulling = work;
254
+ return work;
255
+ },
256
+ async cancel() {
257
+ if (keepReading) {
258
+ startDrain(true);
259
+ return;
260
+ }
261
+ cancelled = true;
126
262
  finish();
127
- abort();
128
- void events.return().catch(() => {
129
- });
263
+ stopUpstream();
264
+ const unrelayed = pending;
265
+ pending = void 0;
266
+ if (unrelayed && observer?.onUnrelayed) {
267
+ await call(() => observer.onUnrelayed(unrelayed));
268
+ }
269
+ await inflight;
270
+ await reportClose("cancel");
130
271
  }
131
272
  });
132
273
  }
133
274
 
275
+ // src/run-callbacks.ts
276
+ var NO_RESULT_MESSAGE = "The stream ended without a result.";
277
+ var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
278
+ var FAILED_MESSAGE = "The run failed.";
279
+ function lastAttemptError(run) {
280
+ if (!Array.isArray(run.attempts)) return null;
281
+ for (let i = run.attempts.length - 1; i >= 0; i--) {
282
+ const error = run.attempts[i]?.error;
283
+ if (typeof error === "string" && error) return error;
284
+ }
285
+ return null;
286
+ }
287
+ function toAttachments(raw) {
288
+ if (!Array.isArray(raw)) return [];
289
+ return raw.flatMap(
290
+ (item) => typeof item?.id === "string" ? [
291
+ {
292
+ id: item.id,
293
+ name: typeof item.name === "string" ? item.name : null,
294
+ mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
295
+ }
296
+ ] : []
297
+ );
298
+ }
299
+ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
300
+ const { onEvent, onRunEnd } = callbacks;
301
+ const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
302
+ let runId = null;
303
+ let text = "";
304
+ let terminal;
305
+ let ended = false;
306
+ const outcome = (o) => ({
307
+ runId,
308
+ attachments: [],
309
+ ...o
310
+ });
311
+ const end = async (o) => {
312
+ if (ended) return;
313
+ ended = true;
314
+ await onRunEnd?.(o, ctx);
315
+ };
316
+ const failed = (error) => outcome({ status: "failed", output: text, error });
317
+ const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
318
+ const record = (event, source) => {
319
+ const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
320
+ if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
321
+ if (terminal) return;
322
+ switch (event.event) {
323
+ case "stream_token":
324
+ if (typeof payload.token === "string") text += payload.token;
325
+ return;
326
+ case "done": {
327
+ const run = payload;
328
+ if (typeof run.run_id === "string") runId = run.run_id;
329
+ const attachments = toAttachments(run.attachments);
330
+ terminal = run.status === "failed" ? outcome({
331
+ status: "failed",
332
+ output: text,
333
+ attachments,
334
+ error: lastAttemptError(run) ?? FAILED_MESSAGE
335
+ }) : outcome({
336
+ status: "completed",
337
+ // Agents with no streaming step send no tokens, so `output`
338
+ // may be the only text.
339
+ output: typeof run.output === "string" && run.output || text,
340
+ attachments,
341
+ error: null
342
+ });
343
+ return;
344
+ }
345
+ case "error":
346
+ terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
347
+ return;
348
+ case "timeout":
349
+ terminal = failed(TIMEOUT_MESSAGE);
350
+ return;
351
+ }
352
+ };
353
+ return {
354
+ async onEvent(event, source) {
355
+ record(event, source);
356
+ await onEvent?.(event, ctx);
357
+ if (terminal) await end(terminal);
358
+ },
359
+ onUnrelayed(event) {
360
+ record(event, "upstream");
361
+ },
362
+ async onClose(reason) {
363
+ switch (reason) {
364
+ case "end":
365
+ return end(terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE)));
366
+ case "error":
367
+ return end(failed(OBSERVER_ERROR_MESSAGE));
368
+ case "cancel":
369
+ return end(terminal ?? cancelled());
370
+ }
371
+ },
372
+ onError(err) {
373
+ console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
374
+ }
375
+ };
376
+ }
377
+
134
378
  // src/handlers.ts
135
379
  var MIN_API_VERSION = SeclaiApiVersion.V2026_10_16;
136
380
  var DEFAULT_API_VERSION = SeclaiApiVersion.V2026_10_28;
@@ -176,6 +420,9 @@ function createSeclaiHandlers(options) {
176
420
  agentId,
177
421
  apiVersion = DEFAULT_API_VERSION,
178
422
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
423
+ keepReadingAfterDisconnect = false,
424
+ onEvent,
425
+ onRunEnd,
179
426
  context,
180
427
  authorizeRun,
181
428
  authorizeUpload,
@@ -297,7 +544,8 @@ function createSeclaiHandlers(options) {
297
544
  }
298
545
  const upstream = new AbortController();
299
546
  const abort = () => upstream.abort();
300
- req.signal?.addEventListener("abort", abort, { once: true });
547
+ const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
548
+ if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
301
549
  const events = client.runStreamingAgent(
302
550
  agentId,
303
551
  {
@@ -309,8 +557,15 @@ function createSeclaiHandlers(options) {
309
557
  );
310
558
  try {
311
559
  const first = await events.next();
560
+ const observer = onEvent || onRunEnd ? createRunObserver({ onEvent, onRunEnd }, { body, request: req }, { keepReading }) : void 0;
312
561
  return new Response(
313
- relayRunEvents(first.done ? void 0 : first.value, events, abort),
562
+ relayRunEvents(
563
+ first.done ? void 0 : first.value,
564
+ events,
565
+ abort,
566
+ observer,
567
+ keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
568
+ ),
314
569
  { headers: SSE_HEADERS }
315
570
  );
316
571
  } catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Framework-free server handlers for running Seclai agents from a web app: upload, run with SSE relay, and download proxy.",
5
5
  "license": "MIT",
6
6
  "type": "module",