@seclai/handlers 0.0.2 → 0.0.4

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,10 +52,42 @@ 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 |
58
61
  | `authorizeDownload` | None | `(req, { runId, attachmentId }, ctx)`: return `true` to serve the file |
62
+ | `upload` | None | Size limit, content-type check and hook for `upload`, below |
63
+
64
+ ### Upload options
65
+
66
+ ```ts
67
+ const seclai = createSeclaiHandlers({
68
+ apiKey: process.env.SECLAI_API_KEY!,
69
+ agentId: process.env.SECLAI_AGENT_ID!,
70
+ upload: {
71
+ maxBytes: 4 * 1024 * 1024,
72
+ checkContentType: true,
73
+ async onUpload(file, result, req) {
74
+ await saveCopy(result.id, file);
75
+ },
76
+ },
77
+ });
78
+ ```
79
+
80
+ | Option | Default | |
81
+ |---|---|---|
82
+ | `maxBytes` | No limit | Largest file accepted, in bytes. A bigger one gets a 413 |
83
+ | `checkContentType` | `false` | Give a 415 to a file whose type none of the agent's attachment slots accepts |
84
+ | `onUpload(file, result, req)` | None | Called after a successful upload. Return a `Response` to replace the default JSON |
85
+
86
+ The size checks and the content-type check refuse a file before it reaches the API, and `onUpload` runs only after the API has accepted one. In order, `upload` checks the size, then calls [`authorizeUpload`](#access-control), then checks the content type, so a refused caller never triggers the slot lookup.
87
+
88
+ - **`maxBytes`** is checked against `content-length` first, so a request that declares an oversized body is refused before it's read. Without `content-length`, as with a chunked body, the bytes are counted as they stream and reading stops with a 413 once they pass the limit. Both checks allow 64 KB for the multipart envelope, and the file's own size is checked once the form is read.
89
+ - **`checkContentType`** reads the slots with `getAgentAttachmentReferences` and reuses them for 60 seconds, so an edit to the agent's slots takes up to a minute to apply. A slot type is exact, like `application/pdf`, or a wildcard, like `image/*`. A slot with no types accepts every file. A file of unknown type isn't checked and goes on to the API, which decides: browsers send no type for `.md`, some `.csv` files or HEIC on Windows, and such a file arrives as `application/octet-stream`. An agent with no slots takes no typed files, so they all get a 415. If the lookup fails, the upload is refused with the error from the API, usually a 502, and the next upload tries again. Slots' `name_pattern` isn't checked here: the API checks it when the run starts. The slots are kept per `createSeclaiHandlers` instance, so where the handlers are created per request, as on Cloudflare Workers, every upload makes its own lookup.
90
+ - **`onUpload`** receives the `File`, the `{ id, status, filename, content_type, file_size }` the handler would return, and the `Request`, whose body has already been read. Returning nothing keeps the default response. If it throws, the browser gets a 500 with a generic message. The file is already on Seclai by then.
59
91
 
60
92
  ### Access control
61
93
 
@@ -127,11 +159,83 @@ The context's type is inferred from the `context` option, or set as the type par
127
159
  - If the stream fails after it has started, it ends with an `error` event carrying `{ error }`.
128
160
  - When the browser disconnects, the upstream connection closes. **The run itself keeps going on Seclai** and may keep using credits.
129
161
 
162
+ ## Run callbacks
163
+
164
+ `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.
165
+
166
+ ```ts
167
+ const seclai = createSeclaiHandlers({
168
+ apiKey: process.env.SECLAI_API_KEY!,
169
+ agentId: process.env.SECLAI_AGENT_ID!,
170
+ async onRunEnd(outcome, { body }) {
171
+ if (!body.sessionId) return;
172
+ await db.messages.insert({
173
+ sessionId: body.sessionId,
174
+ role: "assistant",
175
+ runId: outcome.runId,
176
+ status: outcome.status,
177
+ content: outcome.output,
178
+ attachments: outcome.attachments,
179
+ error: outcome.error,
180
+ });
181
+ },
182
+ });
183
+ ```
184
+
185
+ **`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.
186
+
187
+ **`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.
188
+
189
+ | `outcome` field | |
190
+ |---|---|
191
+ | `runId` | From `init` or `done`. `null` if the stream ended before either |
192
+ | `status` | `completed`, `failed` or `cancelled` |
193
+ | `output` | The run's output when it completed. Otherwise the text streamed in `stream_token` events so far |
194
+ | `attachments` | Files from `done`, as `{ id, name, mime }`. Fetch them with `download` |
195
+ | `error` | Why the run failed, or `null` |
196
+
197
+ | The run stream... | `status` | `error` |
198
+ |---|---|---|
199
+ | Sends `done` | `completed`, or `failed` if the run failed | The last attempt's error |
200
+ | Sends `error`, or the upstream connection fails | `failed` | The event's `error` |
201
+ | Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
202
+ | Ends with none of these | `failed` | `The stream ended without a result.` |
203
+ | Is cancelled by the browser | `cancelled`, unless `keepReadingAfterDisconnect` is on | `null` |
204
+
205
+ `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.
206
+
207
+ 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`.
208
+
209
+ 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.
210
+
211
+ ### Saving replies after a disconnect
212
+
213
+ 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.
214
+
215
+ Set `keepReadingAfterDisconnect: true` to keep reading the run in the background instead:
216
+
217
+ ```ts
218
+ const seclai = createSeclaiHandlers({
219
+ apiKey, agentId,
220
+ keepReadingAfterDisconnect: true,
221
+ onRunEnd: (outcome, { body }) => db.saveReply(body.sessionId, outcome),
222
+ });
223
+ ```
224
+
225
+ - **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.
226
+ - **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.
227
+ - **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.
228
+ - **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.
229
+ - **Show the reply when the user comes back.** For example, reload the conversation when it ends with a message that has no reply yet.
230
+ - **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`.
231
+
232
+ The option only takes effect with `onEvent` or `onRunEnd` set.
233
+
130
234
  ## Limits to know before deploying
131
235
 
132
236
  - **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.
133
237
  - **The API key is account-wide.** `download` checks that ids are well formed, but the API only checks that a run belongs to the account, not to this agent. Without [`authorizeDownload`](#access-control), anyone holding a run's id and a file's id from the same account could fetch that file. Run ids are random UUIDs, so they can't be guessed, but only your app knows which runs a caller may read.
134
- - **Uploads pass through your function**, so your platform's body limit applies, not the API's 200 MB: about 4.5 MB on Vercel and 6 MB on Netlify. The API has no CORS, so the browser can't upload to it directly.
238
+ - **Uploads pass through your function**, so your platform's body limit applies, not the API's 200 MB: about 4.5 MB on Vercel and 6 MB on Netlify. The API has no CORS, so the browser can't upload to it directly. Set `upload.maxBytes` below that limit so the browser gets a clear 413 instead of the platform's error, and `upload.checkContentType` to refuse files the agent can't use before they're sent on.
135
239
  - **Your platform's function duration limit** may end a long run before `runTimeoutMs` does.
136
240
 
137
241
  ## Runtimes
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ATTACHMENT_SLOTS_TTL_MS: () => ATTACHMENT_SLOTS_TTL_MS,
23
24
  DEFAULT_API_VERSION: () => DEFAULT_API_VERSION,
24
25
  MIN_API_VERSION: () => MIN_API_VERSION,
25
26
  createSeclaiHandlers: () => createSeclaiHandlers,
@@ -110,52 +111,296 @@ data: ${JSON.stringify(data)}
110
111
 
111
112
  `);
112
113
  }
113
- function relayRunEvents(first, events, abort) {
114
+ var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
115
+ function relayRunEvents(first, events, abort, observer, options = {}) {
116
+ const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
117
+ let pending = first;
114
118
  let closed = false;
119
+ let cancelled = false;
120
+ let closeReport;
121
+ let inflight;
115
122
  let keepalive;
123
+ let ctrl;
124
+ let draining = false;
125
+ let pulling;
116
126
  const finish = () => {
117
127
  closed = true;
118
128
  clearInterval(keepalive);
119
129
  };
120
- return new ReadableStream({
121
- start(controller) {
122
- if (!first) {
123
- finish();
124
- controller.close();
130
+ const stopUpstream = () => {
131
+ abort();
132
+ void events.return().catch(() => {
133
+ });
134
+ };
135
+ const call = async (hook) => {
136
+ try {
137
+ await hook();
138
+ return true;
139
+ } catch (err) {
140
+ try {
141
+ observer?.onError(err);
142
+ } catch {
143
+ }
144
+ return false;
145
+ }
146
+ };
147
+ const reportClose = (reason) => {
148
+ if (!observer) return Promise.resolve(true);
149
+ return closeReport ??= call(() => observer.onClose(reason));
150
+ };
151
+ const end = (controller, last) => {
152
+ if (cancelled) return;
153
+ if (last) controller.enqueue(last);
154
+ controller.close();
155
+ };
156
+ const fail = async (controller) => {
157
+ finish();
158
+ stopUpstream();
159
+ await reportClose("error");
160
+ end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
161
+ };
162
+ const relay = (controller, event, source = "upstream") => {
163
+ const work = (async () => {
164
+ if (observer && !await call(() => observer.onEvent(event, source))) {
165
+ if (!closed) await fail(controller);
125
166
  return;
126
167
  }
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) {
168
+ if (closed || cancelled) return;
169
+ controller.enqueue(frame(event.event, event.data));
170
+ })();
171
+ inflight = work;
172
+ return work;
173
+ };
174
+ const pullOnce = async (controller) => {
175
+ if (pending) {
176
+ const event = pending;
177
+ pending = void 0;
178
+ await relay(controller, event);
179
+ return;
180
+ }
181
+ let next;
182
+ try {
183
+ next = await events.next();
184
+ } catch (err) {
133
185
  if (closed) return;
186
+ await relay(
187
+ controller,
188
+ { event: "error", data: { error: streamErrorMessage(err) } },
189
+ "connection-lost"
190
+ );
191
+ if (closed) return;
192
+ finish();
193
+ await reportClose("end");
194
+ end(controller);
195
+ return;
196
+ }
197
+ if (closed) return;
198
+ if (next.done) {
199
+ finish();
200
+ const ok = await reportClose("end");
201
+ end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
202
+ return;
203
+ }
204
+ await relay(controller, next.value);
205
+ };
206
+ const drain = async (controller) => {
207
+ await pulling;
208
+ await inflight;
209
+ if (closed) return;
210
+ if (pending) {
211
+ const event = pending;
212
+ pending = void 0;
213
+ await relay(controller, event);
214
+ }
215
+ while (!closed) {
216
+ let next;
134
217
  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));
218
+ next = await events.next();
143
219
  } catch (err) {
220
+ if (closed) return;
221
+ await relay(
222
+ controller,
223
+ { event: "error", data: { error: streamErrorMessage(err) } },
224
+ "connection-lost"
225
+ );
144
226
  if (closed) return;
145
227
  finish();
146
- controller.enqueue(frame("error", { error: streamErrorMessage(err) }));
228
+ await reportClose("end");
229
+ return;
230
+ }
231
+ if (closed) return;
232
+ if (next.done) {
233
+ finish();
234
+ await reportClose("end");
235
+ return;
236
+ }
237
+ await relay(controller, next.value);
238
+ }
239
+ };
240
+ const startDrain = (fromCancel) => {
241
+ if (draining || closed || !ctrl) return;
242
+ draining = true;
243
+ cancelled = true;
244
+ clearInterval(keepalive);
245
+ const controller = ctrl;
246
+ if (!fromCancel) {
247
+ try {
147
248
  controller.close();
249
+ } catch {
250
+ }
251
+ }
252
+ try {
253
+ observer?.onDisconnect?.();
254
+ } catch {
255
+ }
256
+ void drain(controller).catch((err) => {
257
+ try {
258
+ observer?.onError(err);
259
+ } catch {
260
+ }
261
+ });
262
+ };
263
+ return new ReadableStream({
264
+ start(controller) {
265
+ ctrl = controller;
266
+ keepalive = setInterval(() => {
267
+ if (!closed && !cancelled) controller.enqueue(encoder.encode(": keepalive\n\n"));
268
+ }, KEEPALIVE_INTERVAL_MS);
269
+ if (keepReading && options.signal) {
270
+ const { signal } = options;
271
+ const onAbort = () => startDrain(false);
272
+ if (signal.aborted) queueMicrotask(onAbort);
273
+ else signal.addEventListener("abort", onAbort, { once: true });
148
274
  }
149
275
  },
150
- cancel() {
276
+ pull(controller) {
277
+ if (closed || draining) return;
278
+ const work = pullOnce(controller);
279
+ pulling = work;
280
+ return work;
281
+ },
282
+ async cancel() {
283
+ if (keepReading) {
284
+ startDrain(true);
285
+ return;
286
+ }
287
+ cancelled = true;
151
288
  finish();
152
- abort();
153
- void events.return().catch(() => {
154
- });
289
+ stopUpstream();
290
+ const unrelayed = pending;
291
+ pending = void 0;
292
+ if (unrelayed && observer?.onUnrelayed) {
293
+ await call(() => observer.onUnrelayed(unrelayed));
294
+ }
295
+ await inflight;
296
+ await reportClose("cancel");
155
297
  }
156
298
  });
157
299
  }
158
300
 
301
+ // src/run-callbacks.ts
302
+ var NO_RESULT_MESSAGE = "The stream ended without a result.";
303
+ var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
304
+ var FAILED_MESSAGE = "The run failed.";
305
+ function lastAttemptError(run) {
306
+ if (!Array.isArray(run.attempts)) return null;
307
+ for (let i = run.attempts.length - 1; i >= 0; i--) {
308
+ const error = run.attempts[i]?.error;
309
+ if (typeof error === "string" && error) return error;
310
+ }
311
+ return null;
312
+ }
313
+ function toAttachments(raw) {
314
+ if (!Array.isArray(raw)) return [];
315
+ return raw.flatMap(
316
+ (item) => typeof item?.id === "string" ? [
317
+ {
318
+ id: item.id,
319
+ name: typeof item.name === "string" ? item.name : null,
320
+ mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
321
+ }
322
+ ] : []
323
+ );
324
+ }
325
+ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
326
+ const { onEvent, onRunEnd } = callbacks;
327
+ const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
328
+ let runId = null;
329
+ let text = "";
330
+ let terminal;
331
+ let ended = false;
332
+ const outcome = (o) => ({
333
+ runId,
334
+ attachments: [],
335
+ ...o
336
+ });
337
+ const end = async (o) => {
338
+ if (ended) return;
339
+ ended = true;
340
+ await onRunEnd?.(o, ctx);
341
+ };
342
+ const failed = (error) => outcome({ status: "failed", output: text, error });
343
+ const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
344
+ const record = (event, source) => {
345
+ const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
346
+ if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
347
+ if (terminal) return;
348
+ switch (event.event) {
349
+ case "stream_token":
350
+ if (typeof payload.token === "string") text += payload.token;
351
+ return;
352
+ case "done": {
353
+ const run = payload;
354
+ if (typeof run.run_id === "string") runId = run.run_id;
355
+ const attachments = toAttachments(run.attachments);
356
+ terminal = run.status === "failed" ? outcome({
357
+ status: "failed",
358
+ output: text,
359
+ attachments,
360
+ error: lastAttemptError(run) ?? FAILED_MESSAGE
361
+ }) : outcome({
362
+ status: "completed",
363
+ // Agents with no streaming step send no tokens, so `output`
364
+ // may be the only text.
365
+ output: typeof run.output === "string" && run.output || text,
366
+ attachments,
367
+ error: null
368
+ });
369
+ return;
370
+ }
371
+ case "error":
372
+ terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
373
+ return;
374
+ case "timeout":
375
+ terminal = failed(TIMEOUT_MESSAGE);
376
+ return;
377
+ }
378
+ };
379
+ return {
380
+ async onEvent(event, source) {
381
+ record(event, source);
382
+ await onEvent?.(event, ctx);
383
+ if (terminal) await end(terminal);
384
+ },
385
+ onUnrelayed(event) {
386
+ record(event, "upstream");
387
+ },
388
+ async onClose(reason) {
389
+ switch (reason) {
390
+ case "end":
391
+ return end(terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE)));
392
+ case "error":
393
+ return end(failed(OBSERVER_ERROR_MESSAGE));
394
+ case "cancel":
395
+ return end(terminal ?? cancelled());
396
+ }
397
+ },
398
+ onError(err) {
399
+ console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
400
+ }
401
+ };
402
+ }
403
+
159
404
  // src/handlers.ts
160
405
  var MIN_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_16;
161
406
  var DEFAULT_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_28;
@@ -163,6 +408,35 @@ var DEFAULT_RUN_TIMEOUT_MS = 11 * 60 * 1e3;
163
408
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
164
409
  var ATTACHMENT_ID = /^[A-Za-z0-9_-]+={0,2}$/;
165
410
  var MAX_DOWNLOAD_NAME_LENGTH = 255;
411
+ var ATTACHMENT_SLOTS_TTL_MS = 60 * 1e3;
412
+ var MULTIPART_OVERHEAD_BYTES = 64 * 1024;
413
+ async function readLimitedForm(req, limit) {
414
+ if (!req.body) return req.formData();
415
+ let received = 0;
416
+ let exceeded = false;
417
+ const counted = req.body.pipeThrough(
418
+ new TransformStream({
419
+ transform(chunk, controller) {
420
+ received += chunk.byteLength;
421
+ if (received > limit) {
422
+ exceeded = true;
423
+ controller.error(new Error("The request body is over the size limit."));
424
+ return;
425
+ }
426
+ controller.enqueue(chunk);
427
+ }
428
+ })
429
+ );
430
+ const headers = new Headers();
431
+ const contentType = req.headers.get("content-type");
432
+ if (contentType) headers.set("content-type", contentType);
433
+ try {
434
+ return await new Response(counted, { headers }).formData();
435
+ } catch (err) {
436
+ if (exceeded) return "too-large";
437
+ throw err;
438
+ }
439
+ }
166
440
  var ROUTES = {
167
441
  "attachment-references": "attachmentReferences",
168
442
  upload: "upload",
@@ -195,17 +469,36 @@ function parseRunBody(body) {
195
469
  }
196
470
  return { input, uploadIds, sessionId };
197
471
  }
472
+ var UNKNOWN_TYPES = /* @__PURE__ */ new Set(["", "application/octet-stream"]);
473
+ function essence(type) {
474
+ return type.split(";")[0].trim().toLowerCase();
475
+ }
476
+ function slotAllows(slot, type) {
477
+ const patterns = slot.content_types ?? [];
478
+ if (patterns.length === 0) return true;
479
+ return patterns.some((raw) => {
480
+ const pattern = essence(raw);
481
+ if (pattern === "*" || pattern === "*/*") return true;
482
+ if (pattern.endsWith("/*")) return type.startsWith(pattern.slice(0, -1));
483
+ return pattern === type;
484
+ });
485
+ }
198
486
  function createSeclaiHandlers(options) {
199
487
  const {
200
488
  apiKey,
201
489
  agentId,
202
490
  apiVersion = DEFAULT_API_VERSION,
203
491
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
492
+ upload: uploadOptions = {},
493
+ keepReadingAfterDisconnect = false,
494
+ onEvent,
495
+ onRunEnd,
204
496
  context,
205
497
  authorizeRun,
206
498
  authorizeUpload,
207
499
  authorizeDownload
208
500
  } = options;
501
+ const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
209
502
  if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
210
503
  if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
211
504
  if (apiVersion < MIN_API_VERSION) {
@@ -213,6 +506,9 @@ function createSeclaiHandlers(options) {
213
506
  `createSeclaiHandlers: \`apiVersion\` must be ${MIN_API_VERSION} or later, got ${apiVersion}.`
214
507
  );
215
508
  }
509
+ if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes > 0)) {
510
+ throw new Error("createSeclaiHandlers: `upload.maxBytes` must be a positive number.");
511
+ }
216
512
  const client = new import_sdk2.Seclai({
217
513
  apiKey,
218
514
  apiVersion,
@@ -220,6 +516,21 @@ function createSeclaiHandlers(options) {
220
516
  // when called with any `this` but the global, so it can't be passed bare.
221
517
  fetch: (input, init) => globalThis.fetch(input, init)
222
518
  });
519
+ let slots;
520
+ function attachmentSlots() {
521
+ if (!slots || Date.now() >= slots.expires) {
522
+ const entry = {
523
+ promise: client.getAgentAttachmentReferences(agentId).then((refs) => refs.accepted_attachments ?? []),
524
+ expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS
525
+ };
526
+ entry.promise.catch(() => {
527
+ if (slots === entry) slots = void 0;
528
+ });
529
+ slots = entry;
530
+ }
531
+ return slots.promise;
532
+ }
533
+ const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
223
534
  let warnedDownloadResult = false;
224
535
  async function callHook(name, req, resolveCtx, hook) {
225
536
  let ctx;
@@ -245,9 +556,16 @@ function createSeclaiHandlers(options) {
245
556
  },
246
557
  async upload(req) {
247
558
  if (req.method !== "POST") return wrongMethod("POST");
559
+ const bodyLimit = maxBytes === void 0 ? void 0 : maxBytes + MULTIPART_OVERHEAD_BYTES;
560
+ if (bodyLimit !== void 0) {
561
+ const length = Number(req.headers.get("content-length"));
562
+ if (length > bodyLimit) return tooLarge();
563
+ }
248
564
  let form;
249
565
  try {
250
- form = await req.formData();
566
+ const read = bodyLimit === void 0 ? await req.formData() : await readLimitedForm(req, bodyLimit);
567
+ if (read === "too-large") return tooLarge();
568
+ form = read;
251
569
  } catch {
252
570
  return jsonError(400, "The request body must be multipart form data.");
253
571
  }
@@ -255,15 +573,16 @@ function createSeclaiHandlers(options) {
255
573
  if (file === null || typeof file === "string") {
256
574
  return jsonError(400, "The form must include a `file` field holding a file.");
257
575
  }
576
+ if (maxBytes !== void 0 && file.size > maxBytes) return tooLarge();
258
577
  if (authorizeUpload) {
259
- const result = await callHook(
578
+ const result2 = await callHook(
260
579
  "authorizeUpload",
261
580
  req,
262
581
  resolveCtx,
263
582
  (ctx) => authorizeUpload(req, file, ctx)
264
583
  );
265
- if ("response" in result) return result.response;
266
- const allowed = result.value;
584
+ if ("response" in result2) return result2.response;
585
+ const allowed = result2.value;
267
586
  if (allowed instanceof Response) return allowed;
268
587
  if (allowed === false) return jsonError(403, "This upload isn't allowed.");
269
588
  if (allowed !== void 0 && allowed !== true) {
@@ -271,22 +590,39 @@ function createSeclaiHandlers(options) {
271
590
  return jsonError(500, NOT_AUTHORIZED);
272
591
  }
273
592
  }
593
+ let result;
274
594
  try {
595
+ const type = essence(file.type);
596
+ if (checkContentType && !UNKNOWN_TYPES.has(type)) {
597
+ const accepted = await attachmentSlots();
598
+ if (!accepted.some((slot) => slotAllows(slot, type))) {
599
+ return jsonError(415, `This agent does not accept files of type ${type}.`);
600
+ }
601
+ }
275
602
  const upload = await client.uploadAgentInput(agentId, {
276
603
  file,
277
604
  fileName: file.name,
278
605
  mimeType: file.type || void 0
279
606
  });
280
- return json({
607
+ result = {
281
608
  id: upload.id,
282
609
  status: upload.status,
283
610
  filename: upload.filename,
284
611
  content_type: upload.content_type,
285
612
  file_size: upload.file_size
286
- });
613
+ };
287
614
  } catch (err) {
288
615
  return toErrorResponse(err);
289
616
  }
617
+ if (onUpload) {
618
+ try {
619
+ const replacement = await onUpload(file, result, req);
620
+ if (replacement instanceof Response) return replacement;
621
+ } catch {
622
+ return jsonError(500, "The server failed to finish handling the upload.");
623
+ }
624
+ }
625
+ return json(result);
290
626
  },
291
627
  async run(req) {
292
628
  if (req.method !== "POST") return wrongMethod("POST");
@@ -322,7 +658,8 @@ function createSeclaiHandlers(options) {
322
658
  }
323
659
  const upstream = new AbortController();
324
660
  const abort = () => upstream.abort();
325
- req.signal?.addEventListener("abort", abort, { once: true });
661
+ const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
662
+ if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
326
663
  const events = client.runStreamingAgent(
327
664
  agentId,
328
665
  {
@@ -334,8 +671,15 @@ function createSeclaiHandlers(options) {
334
671
  );
335
672
  try {
336
673
  const first = await events.next();
674
+ const observer = onEvent || onRunEnd ? createRunObserver({ onEvent, onRunEnd }, { body, request: req }, { keepReading }) : void 0;
337
675
  return new Response(
338
- relayRunEvents(first.done ? void 0 : first.value, events, abort),
676
+ relayRunEvents(
677
+ first.done ? void 0 : first.value,
678
+ events,
679
+ abort,
680
+ observer,
681
+ keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
682
+ ),
339
683
  { headers: SSE_HEADERS }
340
684
  );
341
685
  } catch (err) {
@@ -416,6 +760,7 @@ function createSeclaiHandlers(options) {
416
760
  }
417
761
  // Annotate the CommonJS export names for ESM import in node:
418
762
  0 && (module.exports = {
763
+ ATTACHMENT_SLOTS_TTL_MS,
419
764
  DEFAULT_API_VERSION,
420
765
  MIN_API_VERSION,
421
766
  createSeclaiHandlers,