@seclai/handlers 0.0.11 → 0.0.13

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
@@ -44,6 +44,19 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
44
44
 
45
45
  `run` needs `input`, `uploadIds`, or both. `sessionId` reaches the agent as `metadata.session_id`, which is what chat agents key a conversation on.
46
46
 
47
+ ### Attachment references on the server
48
+
49
+ A server-rendered page can read the agent's accepted files directly, for example to set a composer's file limit and `accept` types in a loader:
50
+
51
+ ```ts
52
+ const refs = await seclai.getAttachmentReferences();
53
+ // { requires_uploads, accepted_attachments: [{ name, min, max, content_types, ... }] }
54
+ ```
55
+
56
+ It returns the same value as the `attachmentReferences` handler's JSON body, and needs no request or context, so it's also on what `withContext(ctx)` returns. The result is reused for 60 seconds (`ATTACHMENT_SLOTS_TTL_MS`) and shared with [`checkContentType`](#upload-options), so a page load and the uploads after it make one lookup, and concurrent calls share one that's in flight. Each call gets its own copy. If the lookup fails, it rejects with the SDK's error, so you choose the fallback. A failure isn't reused: the next call tries again.
57
+
58
+ The `attachmentReferences` handler always looks up afresh, and a successful lookup refreshes the shared copy.
59
+
47
60
  ### Options
48
61
 
49
62
  | Option | Default | |
@@ -87,7 +100,7 @@ const seclai = createSeclaiHandlers({
87
100
  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.
88
101
 
89
102
  - **`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.
90
- - **`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.
103
+ - **`checkContentType`** reads the slots with `getAgentAttachmentReferences` and reuses them for 60 seconds, sharing them with [`getAttachmentReferences`](#attachment-references-on-the-server), 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.
91
104
  - **`onUpload`** receives the `File`, the `{ id, status, filename, content_type, file_size }` the handler would return, the `Request`, whose body has already been read, and the app's [context](#access-control), the same value the access-control hooks get. The context is resolved before the file is uploaded, so a `context` that refuses does so before the file reaches Seclai. 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.
92
105
 
93
106
  ### Access control
package/dist/index.cjs CHANGED
@@ -768,20 +768,22 @@ function createSeclaiHandlers(options) {
768
768
  // when called with any `this` but the global, so it can't be passed bare.
769
769
  fetch: (input, init) => globalThis.fetch(input, init)
770
770
  });
771
- let slots;
772
- function attachmentSlots() {
773
- if (!slots || Date.now() >= slots.expires) {
774
- const entry = {
775
- promise: client.getAgentAttachmentReferences(agentId).then((refs) => refs.accepted_attachments ?? []),
776
- expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS
777
- };
778
- entry.promise.catch(() => {
779
- if (slots === entry) slots = void 0;
780
- });
781
- slots = entry;
771
+ let refsCache;
772
+ function remember(promise) {
773
+ const entry = { promise, expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS };
774
+ entry.promise.catch(() => {
775
+ if (refsCache === entry) refsCache = void 0;
776
+ });
777
+ refsCache = entry;
778
+ }
779
+ function cachedReferences() {
780
+ if (!refsCache || Date.now() >= refsCache.expires) {
781
+ remember(client.getAgentAttachmentReferences(agentId));
782
782
  }
783
- return slots.promise;
783
+ return refsCache.promise;
784
784
  }
785
+ const attachmentSlots = async () => (await cachedReferences()).accepted_attachments ?? [];
786
+ const getAttachmentReferences = async () => structuredClone(await cachedReferences());
785
787
  const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
786
788
  let warnedDownloadResult = false;
787
789
  async function callHook(name, req, resolveCtx, hook) {
@@ -810,7 +812,9 @@ function createSeclaiHandlers(options) {
810
812
  async attachmentReferences(req) {
811
813
  if (req.method !== "GET") return wrongMethod("GET");
812
814
  try {
813
- return json(await client.getAgentAttachmentReferences(agentId));
815
+ const refs = await client.getAgentAttachmentReferences(agentId);
816
+ remember(Promise.resolve(refs));
817
+ return json(refs);
814
818
  } catch (err) {
815
819
  return toErrorResponse(err);
816
820
  }
@@ -1067,6 +1071,7 @@ function createSeclaiHandlers(options) {
1067
1071
  };
1068
1072
  return {
1069
1073
  ...handlers,
1074
+ getAttachmentReferences,
1070
1075
  async handle(req) {
1071
1076
  const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
1072
1077
  const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApiVersion } from '@seclai/sdk';
1
+ import { AgentAttachmentRefsApiResponse, ApiVersion } from '@seclai/sdk';
2
2
 
3
3
  /** Structured details of a log line: ids, timings and counts. */
4
4
  type SeclaiLogFields = Record<string, unknown>;
@@ -80,9 +80,10 @@ declare const MIN_API_VERSION: "2026-10-16";
80
80
  */
81
81
  declare const DEFAULT_API_VERSION: "2026-10-28";
82
82
  /**
83
- * How long `upload.checkContentType` reuses the agent's attachment slots. Short,
84
- * so a slot edited on Seclai takes effect within a minute, but long enough that a
85
- * burst of uploads makes one lookup.
83
+ * How long the agent's attachment references are reused by
84
+ * `getAttachmentReferences` and `upload.checkContentType`, which share them.
85
+ * Short, so a slot edited on Seclai takes effect within a minute, but long enough
86
+ * that a page load and a burst of uploads make one lookup.
86
87
  */
87
88
  declare const ATTACHMENT_SLOTS_TTL_MS: number;
88
89
  /** What the `upload` handler returns, and what `upload.onUpload` receives. */
@@ -108,7 +109,8 @@ interface SeclaiUploadOptions<Ctx = undefined> {
108
109
  * agent's accepted attachment slots allows. A file of unknown type (none, or
109
110
  * `application/octet-stream`, which a typeless file arrives as) isn't checked:
110
111
  * the API decides. The slots are read with
111
- * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS}.
112
+ * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS},
113
+ * sharing the lookup with {@link SeclaiLookups.getAttachmentReferences}.
112
114
  * An agent with no slots accepts nothing, and a failed lookup refuses the
113
115
  * upload.
114
116
  *
@@ -230,8 +232,10 @@ interface RunRequestBody {
230
232
  sessionId?: string;
231
233
  }
232
234
  type SeclaiHandler = (req: Request) => Promise<Response>;
235
+ /** Which files the agent accepts: the `attachmentReferences` handler's JSON body. */
236
+ type AttachmentReferences = AgentAttachmentRefsApiResponse;
233
237
  interface SeclaiHandlers {
234
- /** `GET`: which files the agent accepts. */
238
+ /** `GET`: which files the agent accepts. Always a fresh lookup. */
235
239
  attachmentReferences: SeclaiHandler;
236
240
  /** `POST` multipart form data with a `file` field: returns the upload's `id`. */
237
241
  upload: SeclaiHandler;
@@ -246,8 +250,24 @@ interface SeclaiHandlers {
246
250
  */
247
251
  handle: SeclaiHandler;
248
252
  }
253
+ /**
254
+ * Server-side lookups offered next to the handlers. They need no request or
255
+ * context, so they're available both before and after `withContext`.
256
+ */
257
+ interface SeclaiLookups {
258
+ /**
259
+ * Which files the agent accepts, for server-side code such as a loader that
260
+ * sets a composer's file limit. The same value as the `attachmentReferences`
261
+ * handler's body, reused for {@link ATTACHMENT_SLOTS_TTL_MS} and shared with
262
+ * `upload.checkContentType`. Each call gets its own copy.
263
+ *
264
+ * Rejects if the lookup fails, with the SDK's error. A failure isn't reused:
265
+ * the next call tries again.
266
+ */
267
+ getAttachmentReferences(): Promise<AttachmentReferences>;
268
+ }
249
269
  /** What {@link createSeclaiHandlers} adds to the handlers. */
250
- interface WithContext<Ctx> {
270
+ interface WithContext<Ctx> extends SeclaiLookups {
251
271
  /**
252
272
  * The same handlers, with `ctx` passed to the hooks instead of calling the
253
273
  * `context` option. Use it when your framework already knows the user:
@@ -257,7 +277,7 @@ interface WithContext<Ctx> {
257
277
  * seclai.withContext({ userId: context.get(user).id }).handle(request);
258
278
  * ```
259
279
  */
260
- withContext(ctx: Ctx): SeclaiHandlers;
280
+ withContext(ctx: Ctx): SeclaiHandlers & SeclaiLookups;
261
281
  }
262
282
  /**
263
283
  * A refusal for a hook to return or throw: the `{ error, status }` JSON the
@@ -293,4 +313,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
293
313
  context?: undefined;
294
314
  }): UnboundSeclaiHandlers<Ctx>;
295
315
 
296
- 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
316
+ export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApiVersion } from '@seclai/sdk';
1
+ import { AgentAttachmentRefsApiResponse, ApiVersion } from '@seclai/sdk';
2
2
 
3
3
  /** Structured details of a log line: ids, timings and counts. */
4
4
  type SeclaiLogFields = Record<string, unknown>;
@@ -80,9 +80,10 @@ declare const MIN_API_VERSION: "2026-10-16";
80
80
  */
81
81
  declare const DEFAULT_API_VERSION: "2026-10-28";
82
82
  /**
83
- * How long `upload.checkContentType` reuses the agent's attachment slots. Short,
84
- * so a slot edited on Seclai takes effect within a minute, but long enough that a
85
- * burst of uploads makes one lookup.
83
+ * How long the agent's attachment references are reused by
84
+ * `getAttachmentReferences` and `upload.checkContentType`, which share them.
85
+ * Short, so a slot edited on Seclai takes effect within a minute, but long enough
86
+ * that a page load and a burst of uploads make one lookup.
86
87
  */
87
88
  declare const ATTACHMENT_SLOTS_TTL_MS: number;
88
89
  /** What the `upload` handler returns, and what `upload.onUpload` receives. */
@@ -108,7 +109,8 @@ interface SeclaiUploadOptions<Ctx = undefined> {
108
109
  * agent's accepted attachment slots allows. A file of unknown type (none, or
109
110
  * `application/octet-stream`, which a typeless file arrives as) isn't checked:
110
111
  * the API decides. The slots are read with
111
- * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS}.
112
+ * `getAgentAttachmentReferences` and reused for {@link ATTACHMENT_SLOTS_TTL_MS},
113
+ * sharing the lookup with {@link SeclaiLookups.getAttachmentReferences}.
112
114
  * An agent with no slots accepts nothing, and a failed lookup refuses the
113
115
  * upload.
114
116
  *
@@ -230,8 +232,10 @@ interface RunRequestBody {
230
232
  sessionId?: string;
231
233
  }
232
234
  type SeclaiHandler = (req: Request) => Promise<Response>;
235
+ /** Which files the agent accepts: the `attachmentReferences` handler's JSON body. */
236
+ type AttachmentReferences = AgentAttachmentRefsApiResponse;
233
237
  interface SeclaiHandlers {
234
- /** `GET`: which files the agent accepts. */
238
+ /** `GET`: which files the agent accepts. Always a fresh lookup. */
235
239
  attachmentReferences: SeclaiHandler;
236
240
  /** `POST` multipart form data with a `file` field: returns the upload's `id`. */
237
241
  upload: SeclaiHandler;
@@ -246,8 +250,24 @@ interface SeclaiHandlers {
246
250
  */
247
251
  handle: SeclaiHandler;
248
252
  }
253
+ /**
254
+ * Server-side lookups offered next to the handlers. They need no request or
255
+ * context, so they're available both before and after `withContext`.
256
+ */
257
+ interface SeclaiLookups {
258
+ /**
259
+ * Which files the agent accepts, for server-side code such as a loader that
260
+ * sets a composer's file limit. The same value as the `attachmentReferences`
261
+ * handler's body, reused for {@link ATTACHMENT_SLOTS_TTL_MS} and shared with
262
+ * `upload.checkContentType`. Each call gets its own copy.
263
+ *
264
+ * Rejects if the lookup fails, with the SDK's error. A failure isn't reused:
265
+ * the next call tries again.
266
+ */
267
+ getAttachmentReferences(): Promise<AttachmentReferences>;
268
+ }
249
269
  /** What {@link createSeclaiHandlers} adds to the handlers. */
250
- interface WithContext<Ctx> {
270
+ interface WithContext<Ctx> extends SeclaiLookups {
251
271
  /**
252
272
  * The same handlers, with `ctx` passed to the hooks instead of calling the
253
273
  * `context` option. Use it when your framework already knows the user:
@@ -257,7 +277,7 @@ interface WithContext<Ctx> {
257
277
  * seclai.withContext({ userId: context.get(user).id }).handle(request);
258
278
  * ```
259
279
  */
260
- withContext(ctx: Ctx): SeclaiHandlers;
280
+ withContext(ctx: Ctx): SeclaiHandlers & SeclaiLookups;
261
281
  }
262
282
  /**
263
283
  * A refusal for a hook to return or throw: the `{ error, status }` JSON the
@@ -293,4 +313,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
293
313
  context?: undefined;
294
314
  }): UnboundSeclaiHandlers<Ctx>;
295
315
 
296
- 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
316
+ export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
package/dist/index.js CHANGED
@@ -744,20 +744,22 @@ function createSeclaiHandlers(options) {
744
744
  // when called with any `this` but the global, so it can't be passed bare.
745
745
  fetch: (input, init) => globalThis.fetch(input, init)
746
746
  });
747
- let slots;
748
- function attachmentSlots() {
749
- if (!slots || Date.now() >= slots.expires) {
750
- const entry = {
751
- promise: client.getAgentAttachmentReferences(agentId).then((refs) => refs.accepted_attachments ?? []),
752
- expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS
753
- };
754
- entry.promise.catch(() => {
755
- if (slots === entry) slots = void 0;
756
- });
757
- slots = entry;
747
+ let refsCache;
748
+ function remember(promise) {
749
+ const entry = { promise, expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS };
750
+ entry.promise.catch(() => {
751
+ if (refsCache === entry) refsCache = void 0;
752
+ });
753
+ refsCache = entry;
754
+ }
755
+ function cachedReferences() {
756
+ if (!refsCache || Date.now() >= refsCache.expires) {
757
+ remember(client.getAgentAttachmentReferences(agentId));
758
758
  }
759
- return slots.promise;
759
+ return refsCache.promise;
760
760
  }
761
+ const attachmentSlots = async () => (await cachedReferences()).accepted_attachments ?? [];
762
+ const getAttachmentReferences = async () => structuredClone(await cachedReferences());
761
763
  const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
762
764
  let warnedDownloadResult = false;
763
765
  async function callHook(name, req, resolveCtx, hook) {
@@ -786,7 +788,9 @@ function createSeclaiHandlers(options) {
786
788
  async attachmentReferences(req) {
787
789
  if (req.method !== "GET") return wrongMethod("GET");
788
790
  try {
789
- return json(await client.getAgentAttachmentReferences(agentId));
791
+ const refs = await client.getAgentAttachmentReferences(agentId);
792
+ remember(Promise.resolve(refs));
793
+ return json(refs);
790
794
  } catch (err) {
791
795
  return toErrorResponse(err);
792
796
  }
@@ -1043,6 +1047,7 @@ function createSeclaiHandlers(options) {
1043
1047
  };
1044
1048
  return {
1045
1049
  ...handlers,
1050
+ getAttachmentReferences,
1046
1051
  async handle(req) {
1047
1052
  const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
1048
1053
  const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
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",