@seclai/handlers 0.0.3 → 0.0.5

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
@@ -59,6 +59,35 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
59
59
  | `authorizeRun` | None | `(req, body, ctx)`: refuse or rewrite a run. See [Access control](#access-control) |
60
60
  | `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
61
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.
62
91
 
63
92
  ### Access control
64
93
 
@@ -206,7 +235,7 @@ The option only takes effect with `onEvent` or `onRunEnd` set.
206
235
 
207
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.
208
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.
209
- - **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.
210
239
  - **Your platform's function duration limit** may end a long run before `runTimeoutMs` does.
211
240
 
212
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,
@@ -407,6 +408,35 @@ var DEFAULT_RUN_TIMEOUT_MS = 11 * 60 * 1e3;
407
408
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
408
409
  var ATTACHMENT_ID = /^[A-Za-z0-9_-]+={0,2}$/;
409
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
+ }
410
440
  var ROUTES = {
411
441
  "attachment-references": "attachmentReferences",
412
442
  upload: "upload",
@@ -439,12 +469,27 @@ function parseRunBody(body) {
439
469
  }
440
470
  return { input, uploadIds, sessionId };
441
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
+ }
442
486
  function createSeclaiHandlers(options) {
443
487
  const {
444
488
  apiKey,
445
489
  agentId,
446
490
  apiVersion = DEFAULT_API_VERSION,
447
491
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
492
+ upload: uploadOptions = {},
448
493
  keepReadingAfterDisconnect = false,
449
494
  onEvent,
450
495
  onRunEnd,
@@ -453,6 +498,7 @@ function createSeclaiHandlers(options) {
453
498
  authorizeUpload,
454
499
  authorizeDownload
455
500
  } = options;
501
+ const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
456
502
  if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
457
503
  if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
458
504
  if (apiVersion < MIN_API_VERSION) {
@@ -460,6 +506,9 @@ function createSeclaiHandlers(options) {
460
506
  `createSeclaiHandlers: \`apiVersion\` must be ${MIN_API_VERSION} or later, got ${apiVersion}.`
461
507
  );
462
508
  }
509
+ if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes > 0)) {
510
+ throw new Error("createSeclaiHandlers: `upload.maxBytes` must be a positive number.");
511
+ }
463
512
  const client = new import_sdk2.Seclai({
464
513
  apiKey,
465
514
  apiVersion,
@@ -467,6 +516,21 @@ function createSeclaiHandlers(options) {
467
516
  // when called with any `this` but the global, so it can't be passed bare.
468
517
  fetch: (input, init) => globalThis.fetch(input, init)
469
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.`);
470
534
  let warnedDownloadResult = false;
471
535
  async function callHook(name, req, resolveCtx, hook) {
472
536
  let ctx;
@@ -492,9 +556,16 @@ function createSeclaiHandlers(options) {
492
556
  },
493
557
  async upload(req) {
494
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
+ }
495
564
  let form;
496
565
  try {
497
- 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;
498
569
  } catch {
499
570
  return jsonError(400, "The request body must be multipart form data.");
500
571
  }
@@ -502,15 +573,16 @@ function createSeclaiHandlers(options) {
502
573
  if (file === null || typeof file === "string") {
503
574
  return jsonError(400, "The form must include a `file` field holding a file.");
504
575
  }
576
+ if (maxBytes !== void 0 && file.size > maxBytes) return tooLarge();
505
577
  if (authorizeUpload) {
506
- const result = await callHook(
578
+ const result2 = await callHook(
507
579
  "authorizeUpload",
508
580
  req,
509
581
  resolveCtx,
510
582
  (ctx) => authorizeUpload(req, file, ctx)
511
583
  );
512
- if ("response" in result) return result.response;
513
- const allowed = result.value;
584
+ if ("response" in result2) return result2.response;
585
+ const allowed = result2.value;
514
586
  if (allowed instanceof Response) return allowed;
515
587
  if (allowed === false) return jsonError(403, "This upload isn't allowed.");
516
588
  if (allowed !== void 0 && allowed !== true) {
@@ -518,22 +590,39 @@ function createSeclaiHandlers(options) {
518
590
  return jsonError(500, NOT_AUTHORIZED);
519
591
  }
520
592
  }
593
+ let result;
521
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
+ }
522
602
  const upload = await client.uploadAgentInput(agentId, {
523
603
  file,
524
604
  fileName: file.name,
525
605
  mimeType: file.type || void 0
526
606
  });
527
- return json({
607
+ result = {
528
608
  id: upload.id,
529
609
  status: upload.status,
530
610
  filename: upload.filename,
531
611
  content_type: upload.content_type,
532
612
  file_size: upload.file_size
533
- });
613
+ };
534
614
  } catch (err) {
535
615
  return toErrorResponse(err);
536
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);
537
626
  },
538
627
  async run(req) {
539
628
  if (req.method !== "POST") return wrongMethod("POST");
@@ -671,6 +760,7 @@ function createSeclaiHandlers(options) {
671
760
  }
672
761
  // Annotate the CommonJS export names for ESM import in node:
673
762
  0 && (module.exports = {
763
+ ATTACHMENT_SLOTS_TTL_MS,
674
764
  DEFAULT_API_VERSION,
675
765
  MIN_API_VERSION,
676
766
  createSeclaiHandlers,
package/dist/index.d.cts CHANGED
@@ -48,6 +48,51 @@ declare const MIN_API_VERSION: "2026-10-16";
48
48
  * and could change response shapes underneath a deployed app.
49
49
  */
50
50
  declare const DEFAULT_API_VERSION: "2026-10-28";
51
+ /**
52
+ * How long `upload.checkContentType` reuses the agent's attachment slots. Short,
53
+ * so a slot edited on Seclai takes effect within a minute, but long enough that a
54
+ * burst of uploads makes one lookup.
55
+ */
56
+ declare const ATTACHMENT_SLOTS_TTL_MS: number;
57
+ /** What the `upload` handler returns, and what `upload.onUpload` receives. */
58
+ interface UploadResult {
59
+ /** Pass this in `uploadIds` to the `run` handler. */
60
+ id: string;
61
+ status: string;
62
+ filename: string;
63
+ content_type: string;
64
+ file_size: number;
65
+ }
66
+ /** Checks and a hook for the `upload` handler. All are off by default. */
67
+ interface SeclaiUploadOptions {
68
+ /**
69
+ * Largest file accepted, in bytes. Anything bigger gets a 413 without reaching
70
+ * the API. A request whose `content-length` is too big is refused before its
71
+ * body is read; otherwise the body is counted as it streams and reading stops
72
+ * once it passes the limit plus 64 KB for the multipart envelope.
73
+ */
74
+ maxBytes?: number;
75
+ /**
76
+ * Refuse with a 415, without reaching the API, a file whose type none of the
77
+ * agent's accepted attachment slots allows. A file of unknown type (none, or
78
+ * `application/octet-stream`, which a typeless file arrives as) isn't checked:
79
+ * the API decides. The slots are read with
80
+ * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS}.
81
+ * An agent with no slots accepts nothing, and a failed lookup refuses the
82
+ * upload.
83
+ *
84
+ * The reused slots belong to this `createSeclaiHandlers` instance. Where the
85
+ * handlers are created per request, as on Cloudflare Workers, every upload makes
86
+ * its own lookup.
87
+ */
88
+ checkContentType?: boolean;
89
+ /**
90
+ * Called after a successful upload, for example to keep a copy of the file or
91
+ * record which session it belongs to. Return a `Response` to send it instead of
92
+ * the default JSON. `req`'s body has already been read. A throw becomes a 500.
93
+ */
94
+ onUpload?(file: File, result: UploadResult, req: Request): void | Response | Promise<void | Response>;
95
+ }
51
96
  interface SeclaiHandlersOptions<Ctx = undefined> {
52
97
  /** Seclai API key. Server-side only: never expose it to the browser. */
53
98
  apiKey: string;
@@ -57,6 +102,8 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
57
102
  apiVersion?: ApiVersion;
58
103
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
59
104
  runTimeoutMs?: number;
105
+ /** Size limit, content-type check and hook for the `upload` handler. */
106
+ upload?: SeclaiUploadOptions;
60
107
  /**
61
108
  * Called with each event of a run stream, in order, and awaited before the
62
109
  * event is relayed to the browser. If it throws, the stream ends with an
@@ -204,4 +251,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
204
251
  context?: undefined;
205
252
  }): UnboundSeclaiHandlers<Ctx>;
206
253
 
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 };
254
+ export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, createSeclaiHandlers, deny };
package/dist/index.d.ts CHANGED
@@ -48,6 +48,51 @@ declare const MIN_API_VERSION: "2026-10-16";
48
48
  * and could change response shapes underneath a deployed app.
49
49
  */
50
50
  declare const DEFAULT_API_VERSION: "2026-10-28";
51
+ /**
52
+ * How long `upload.checkContentType` reuses the agent's attachment slots. Short,
53
+ * so a slot edited on Seclai takes effect within a minute, but long enough that a
54
+ * burst of uploads makes one lookup.
55
+ */
56
+ declare const ATTACHMENT_SLOTS_TTL_MS: number;
57
+ /** What the `upload` handler returns, and what `upload.onUpload` receives. */
58
+ interface UploadResult {
59
+ /** Pass this in `uploadIds` to the `run` handler. */
60
+ id: string;
61
+ status: string;
62
+ filename: string;
63
+ content_type: string;
64
+ file_size: number;
65
+ }
66
+ /** Checks and a hook for the `upload` handler. All are off by default. */
67
+ interface SeclaiUploadOptions {
68
+ /**
69
+ * Largest file accepted, in bytes. Anything bigger gets a 413 without reaching
70
+ * the API. A request whose `content-length` is too big is refused before its
71
+ * body is read; otherwise the body is counted as it streams and reading stops
72
+ * once it passes the limit plus 64 KB for the multipart envelope.
73
+ */
74
+ maxBytes?: number;
75
+ /**
76
+ * Refuse with a 415, without reaching the API, a file whose type none of the
77
+ * agent's accepted attachment slots allows. A file of unknown type (none, or
78
+ * `application/octet-stream`, which a typeless file arrives as) isn't checked:
79
+ * the API decides. The slots are read with
80
+ * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS}.
81
+ * An agent with no slots accepts nothing, and a failed lookup refuses the
82
+ * upload.
83
+ *
84
+ * The reused slots belong to this `createSeclaiHandlers` instance. Where the
85
+ * handlers are created per request, as on Cloudflare Workers, every upload makes
86
+ * its own lookup.
87
+ */
88
+ checkContentType?: boolean;
89
+ /**
90
+ * Called after a successful upload, for example to keep a copy of the file or
91
+ * record which session it belongs to. Return a `Response` to send it instead of
92
+ * the default JSON. `req`'s body has already been read. A throw becomes a 500.
93
+ */
94
+ onUpload?(file: File, result: UploadResult, req: Request): void | Response | Promise<void | Response>;
95
+ }
51
96
  interface SeclaiHandlersOptions<Ctx = undefined> {
52
97
  /** Seclai API key. Server-side only: never expose it to the browser. */
53
98
  apiKey: string;
@@ -57,6 +102,8 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
57
102
  apiVersion?: ApiVersion;
58
103
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
59
104
  runTimeoutMs?: number;
105
+ /** Size limit, content-type check and hook for the `upload` handler. */
106
+ upload?: SeclaiUploadOptions;
60
107
  /**
61
108
  * Called with each event of a run stream, in order, and awaited before the
62
109
  * event is relayed to the browser. If it throws, the stream ends with an
@@ -204,4 +251,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
204
251
  context?: undefined;
205
252
  }): UnboundSeclaiHandlers<Ctx>;
206
253
 
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 };
254
+ export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, createSeclaiHandlers, deny };
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  // src/handlers.ts
2
- import { Seclai, SeclaiApiVersion } from "@seclai/sdk";
2
+ import {
3
+ Seclai,
4
+ SeclaiApiVersion
5
+ } from "@seclai/sdk";
3
6
 
4
7
  // src/errors.ts
5
8
  import {
@@ -382,6 +385,35 @@ var DEFAULT_RUN_TIMEOUT_MS = 11 * 60 * 1e3;
382
385
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
383
386
  var ATTACHMENT_ID = /^[A-Za-z0-9_-]+={0,2}$/;
384
387
  var MAX_DOWNLOAD_NAME_LENGTH = 255;
388
+ var ATTACHMENT_SLOTS_TTL_MS = 60 * 1e3;
389
+ var MULTIPART_OVERHEAD_BYTES = 64 * 1024;
390
+ async function readLimitedForm(req, limit) {
391
+ if (!req.body) return req.formData();
392
+ let received = 0;
393
+ let exceeded = false;
394
+ const counted = req.body.pipeThrough(
395
+ new TransformStream({
396
+ transform(chunk, controller) {
397
+ received += chunk.byteLength;
398
+ if (received > limit) {
399
+ exceeded = true;
400
+ controller.error(new Error("The request body is over the size limit."));
401
+ return;
402
+ }
403
+ controller.enqueue(chunk);
404
+ }
405
+ })
406
+ );
407
+ const headers = new Headers();
408
+ const contentType = req.headers.get("content-type");
409
+ if (contentType) headers.set("content-type", contentType);
410
+ try {
411
+ return await new Response(counted, { headers }).formData();
412
+ } catch (err) {
413
+ if (exceeded) return "too-large";
414
+ throw err;
415
+ }
416
+ }
385
417
  var ROUTES = {
386
418
  "attachment-references": "attachmentReferences",
387
419
  upload: "upload",
@@ -414,12 +446,27 @@ function parseRunBody(body) {
414
446
  }
415
447
  return { input, uploadIds, sessionId };
416
448
  }
449
+ var UNKNOWN_TYPES = /* @__PURE__ */ new Set(["", "application/octet-stream"]);
450
+ function essence(type) {
451
+ return type.split(";")[0].trim().toLowerCase();
452
+ }
453
+ function slotAllows(slot, type) {
454
+ const patterns = slot.content_types ?? [];
455
+ if (patterns.length === 0) return true;
456
+ return patterns.some((raw) => {
457
+ const pattern = essence(raw);
458
+ if (pattern === "*" || pattern === "*/*") return true;
459
+ if (pattern.endsWith("/*")) return type.startsWith(pattern.slice(0, -1));
460
+ return pattern === type;
461
+ });
462
+ }
417
463
  function createSeclaiHandlers(options) {
418
464
  const {
419
465
  apiKey,
420
466
  agentId,
421
467
  apiVersion = DEFAULT_API_VERSION,
422
468
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
469
+ upload: uploadOptions = {},
423
470
  keepReadingAfterDisconnect = false,
424
471
  onEvent,
425
472
  onRunEnd,
@@ -428,6 +475,7 @@ function createSeclaiHandlers(options) {
428
475
  authorizeUpload,
429
476
  authorizeDownload
430
477
  } = options;
478
+ const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
431
479
  if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
432
480
  if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
433
481
  if (apiVersion < MIN_API_VERSION) {
@@ -435,6 +483,9 @@ function createSeclaiHandlers(options) {
435
483
  `createSeclaiHandlers: \`apiVersion\` must be ${MIN_API_VERSION} or later, got ${apiVersion}.`
436
484
  );
437
485
  }
486
+ if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes > 0)) {
487
+ throw new Error("createSeclaiHandlers: `upload.maxBytes` must be a positive number.");
488
+ }
438
489
  const client = new Seclai({
439
490
  apiKey,
440
491
  apiVersion,
@@ -442,6 +493,21 @@ function createSeclaiHandlers(options) {
442
493
  // when called with any `this` but the global, so it can't be passed bare.
443
494
  fetch: (input, init) => globalThis.fetch(input, init)
444
495
  });
496
+ let slots;
497
+ function attachmentSlots() {
498
+ if (!slots || Date.now() >= slots.expires) {
499
+ const entry = {
500
+ promise: client.getAgentAttachmentReferences(agentId).then((refs) => refs.accepted_attachments ?? []),
501
+ expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS
502
+ };
503
+ entry.promise.catch(() => {
504
+ if (slots === entry) slots = void 0;
505
+ });
506
+ slots = entry;
507
+ }
508
+ return slots.promise;
509
+ }
510
+ const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
445
511
  let warnedDownloadResult = false;
446
512
  async function callHook(name, req, resolveCtx, hook) {
447
513
  let ctx;
@@ -467,9 +533,16 @@ function createSeclaiHandlers(options) {
467
533
  },
468
534
  async upload(req) {
469
535
  if (req.method !== "POST") return wrongMethod("POST");
536
+ const bodyLimit = maxBytes === void 0 ? void 0 : maxBytes + MULTIPART_OVERHEAD_BYTES;
537
+ if (bodyLimit !== void 0) {
538
+ const length = Number(req.headers.get("content-length"));
539
+ if (length > bodyLimit) return tooLarge();
540
+ }
470
541
  let form;
471
542
  try {
472
- form = await req.formData();
543
+ const read = bodyLimit === void 0 ? await req.formData() : await readLimitedForm(req, bodyLimit);
544
+ if (read === "too-large") return tooLarge();
545
+ form = read;
473
546
  } catch {
474
547
  return jsonError(400, "The request body must be multipart form data.");
475
548
  }
@@ -477,15 +550,16 @@ function createSeclaiHandlers(options) {
477
550
  if (file === null || typeof file === "string") {
478
551
  return jsonError(400, "The form must include a `file` field holding a file.");
479
552
  }
553
+ if (maxBytes !== void 0 && file.size > maxBytes) return tooLarge();
480
554
  if (authorizeUpload) {
481
- const result = await callHook(
555
+ const result2 = await callHook(
482
556
  "authorizeUpload",
483
557
  req,
484
558
  resolveCtx,
485
559
  (ctx) => authorizeUpload(req, file, ctx)
486
560
  );
487
- if ("response" in result) return result.response;
488
- const allowed = result.value;
561
+ if ("response" in result2) return result2.response;
562
+ const allowed = result2.value;
489
563
  if (allowed instanceof Response) return allowed;
490
564
  if (allowed === false) return jsonError(403, "This upload isn't allowed.");
491
565
  if (allowed !== void 0 && allowed !== true) {
@@ -493,22 +567,39 @@ function createSeclaiHandlers(options) {
493
567
  return jsonError(500, NOT_AUTHORIZED);
494
568
  }
495
569
  }
570
+ let result;
496
571
  try {
572
+ const type = essence(file.type);
573
+ if (checkContentType && !UNKNOWN_TYPES.has(type)) {
574
+ const accepted = await attachmentSlots();
575
+ if (!accepted.some((slot) => slotAllows(slot, type))) {
576
+ return jsonError(415, `This agent does not accept files of type ${type}.`);
577
+ }
578
+ }
497
579
  const upload = await client.uploadAgentInput(agentId, {
498
580
  file,
499
581
  fileName: file.name,
500
582
  mimeType: file.type || void 0
501
583
  });
502
- return json({
584
+ result = {
503
585
  id: upload.id,
504
586
  status: upload.status,
505
587
  filename: upload.filename,
506
588
  content_type: upload.content_type,
507
589
  file_size: upload.file_size
508
- });
590
+ };
509
591
  } catch (err) {
510
592
  return toErrorResponse(err);
511
593
  }
594
+ if (onUpload) {
595
+ try {
596
+ const replacement = await onUpload(file, result, req);
597
+ if (replacement instanceof Response) return replacement;
598
+ } catch {
599
+ return jsonError(500, "The server failed to finish handling the upload.");
600
+ }
601
+ }
602
+ return json(result);
512
603
  },
513
604
  async run(req) {
514
605
  if (req.method !== "POST") return wrongMethod("POST");
@@ -645,6 +736,7 @@ function createSeclaiHandlers(options) {
645
736
  return { ...unbound, withContext: (ctx) => build(async () => ctx) };
646
737
  }
647
738
  export {
739
+ ATTACHMENT_SLOTS_TTL_MS,
648
740
  DEFAULT_API_VERSION,
649
741
  MIN_API_VERSION,
650
742
  createSeclaiHandlers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
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",