@seclai/handlers 0.0.12 → 0.0.14

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
@@ -191,7 +204,7 @@ const seclai = createSeclaiHandlers({
191
204
 
192
205
  **`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.
193
206
 
194
- **`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.
207
+ **`onRunEnd(outcome, ctx)`** is called exactly once for each run, including one the API refuses before it streams (see below). For a run that streams, 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.
195
208
 
196
209
  | `outcome` field | |
197
210
  |---|---|
@@ -208,9 +221,12 @@ const seclai = createSeclaiHandlers({
208
221
  | Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
209
222
  | Ends with none of these | `failed` | `The stream ended without a result.` |
210
223
  | Is cancelled by the browser | `cancelled`, unless `keepReadingAfterDisconnect` is on | `null` |
224
+ | Is refused by the API before it streams, for example for no credits or a file the agent doesn't accept, or fails before its first event because the API can't be reached or `runTimeoutMs` runs out | `failed` | The `error` the browser gets in the error response |
211
225
 
212
226
  `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.
213
227
 
228
+ When the API refuses a run up front, or the run fails before its first event, `onRunEnd` is awaited before the handler returns the error response, so what it stores is in place by the time the browser sees the error. The outcome has `runId: null`, empty `output` and no `attachments`, and `onEvent` isn't called. After a timeout, the run may still have started and may still finish on Seclai, so the error says so: `Timed out waiting for the Seclai API. The run may still finish on Seclai.` If the browser left while the stream was connecting, the outcome is `cancelled` instead, with `error: null`, unless `keepReadingAfterDisconnect` is on. That includes a browser that left while `authorizeRun` or `context` ran: the run is then cancelled before it's sent to Seclai. If `onRunEnd` throws or rejects here, the error is logged like any other callback error (see below), and the browser still gets the original error response. A refusal from `authorizeRun`, `context` or the body check is your app's own decision, before the run is sent to the API, and doesn't call `onRunEnd`.
229
+
214
230
  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`.
215
231
 
216
232
  If `onEvent` or `onRunEnd` throws or rejects, the handler logs the error, with `logger.error` if you set a [`logger`](#logging) and `console.error` otherwise, 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.
package/dist/index.cjs CHANGED
@@ -58,37 +58,45 @@ function upstreamMessage(responseText) {
58
58
  }
59
59
  return void 0;
60
60
  }
61
- function toErrorResponse(err) {
61
+ function toErrorBody(err) {
62
62
  if (err instanceof import_sdk.SeclaiAPIValidationError) {
63
- return json(
64
- {
65
- error: "The Seclai API rejected this request as invalid.",
66
- status: 422,
67
- details: err.validationError
68
- },
69
- 422
70
- );
63
+ return {
64
+ error: "The Seclai API rejected this request as invalid.",
65
+ status: 422,
66
+ details: err.validationError
67
+ };
71
68
  }
72
69
  if (err instanceof import_sdk.SeclaiAPIStatusError) {
73
70
  const { statusCode } = err;
74
71
  if (statusCode === 401 || statusCode === 403) {
75
- return jsonError(
76
- 502,
77
- "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY."
78
- );
72
+ return {
73
+ error: "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY.",
74
+ status: 502
75
+ };
79
76
  }
80
77
  if (statusCode >= 400 && statusCode < 500) {
81
- return jsonError(
82
- statusCode,
83
- upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`
84
- );
78
+ return {
79
+ error: upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`,
80
+ status: statusCode
81
+ };
85
82
  }
86
- return jsonError(502, `The Seclai API returned status ${statusCode}.`);
83
+ return { error: `The Seclai API returned status ${statusCode}.`, status: 502 };
87
84
  }
88
85
  if (err instanceof import_sdk.SeclaiStreamingError) {
89
- return jsonError(504, "Timed out waiting for the Seclai API.");
86
+ return { error: "Timed out waiting for the Seclai API.", status: 504 };
90
87
  }
91
- return jsonError(502, "Could not reach the Seclai API.");
88
+ return { error: "Could not reach the Seclai API.", status: 502 };
89
+ }
90
+ function runErrorBody(err) {
91
+ const body = toErrorBody(err);
92
+ if (err instanceof import_sdk.SeclaiStreamingError) {
93
+ body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
94
+ }
95
+ return body;
96
+ }
97
+ function toErrorResponse(err) {
98
+ const body = toErrorBody(err);
99
+ return json(body, body.status);
92
100
  }
93
101
  function streamErrorMessage(err) {
94
102
  if (err instanceof import_sdk.SeclaiStreamingError) {
@@ -379,6 +387,20 @@ function toAttachments(raw) {
379
387
  ] : []
380
388
  );
381
389
  }
390
+ function reportCallbackError(log, err) {
391
+ if (log) log.callbackError(err);
392
+ else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
393
+ }
394
+ async function reportRefusedRun(callbacks, ctx, how) {
395
+ const { onRunEnd, log } = callbacks;
396
+ if (!onRunEnd) return;
397
+ const outcome = "error" in how ? { runId: null, status: "failed", output: "", attachments: [], error: how.error } : { runId: null, status: "cancelled", output: "", attachments: [], error: null };
398
+ try {
399
+ await onRunEnd(outcome, ctx);
400
+ } catch (err) {
401
+ reportCallbackError(log, err);
402
+ }
403
+ }
382
404
  function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
383
405
  const { onEvent, onRunEnd, log } = callbacks;
384
406
  const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
@@ -470,8 +492,7 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
470
492
  }
471
493
  },
472
494
  onError(err) {
473
- if (log) log.callbackError(err);
474
- else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
495
+ reportCallbackError(log, err);
475
496
  },
476
497
  onKeepalive: log && (() => log.keepalive()),
477
498
  onDisconnect: log && (() => log.readingOn()),
@@ -768,20 +789,22 @@ function createSeclaiHandlers(options) {
768
789
  // when called with any `this` but the global, so it can't be passed bare.
769
790
  fetch: (input, init) => globalThis.fetch(input, init)
770
791
  });
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;
792
+ let refsCache;
793
+ function remember(promise) {
794
+ const entry = { promise, expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS };
795
+ entry.promise.catch(() => {
796
+ if (refsCache === entry) refsCache = void 0;
797
+ });
798
+ refsCache = entry;
799
+ }
800
+ function cachedReferences() {
801
+ if (!refsCache || Date.now() >= refsCache.expires) {
802
+ remember(client.getAgentAttachmentReferences(agentId));
782
803
  }
783
- return slots.promise;
804
+ return refsCache.promise;
784
805
  }
806
+ const attachmentSlots = async () => (await cachedReferences()).accepted_attachments ?? [];
807
+ const getAttachmentReferences = async () => structuredClone(await cachedReferences());
785
808
  const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
786
809
  let warnedDownloadResult = false;
787
810
  async function callHook(name, req, resolveCtx, hook) {
@@ -810,7 +833,9 @@ function createSeclaiHandlers(options) {
810
833
  async attachmentReferences(req) {
811
834
  if (req.method !== "GET") return wrongMethod("GET");
812
835
  try {
813
- return json(await client.getAgentAttachmentReferences(agentId));
836
+ const refs = await client.getAgentAttachmentReferences(agentId);
837
+ remember(Promise.resolve(refs));
838
+ return json(refs);
814
839
  } catch (err) {
815
840
  return toErrorResponse(err);
816
841
  }
@@ -951,7 +976,10 @@ function createSeclaiHandlers(options) {
951
976
  const upstream = new AbortController();
952
977
  const abort = () => upstream.abort();
953
978
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
954
- if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
979
+ if (!keepReading) {
980
+ if (req.signal?.aborted) abort();
981
+ else req.signal?.addEventListener("abort", abort, { once: true });
982
+ }
955
983
  const log = logger && startRunLog(logger, {
956
984
  sessionId: body.sessionId,
957
985
  uploads: body.uploadIds?.length ?? 0,
@@ -988,10 +1016,16 @@ function createSeclaiHandlers(options) {
988
1016
  { headers: SSE_HEADERS }
989
1017
  );
990
1018
  } catch (err) {
991
- const res = toErrorResponse(err);
992
- if (!keepReading && req.signal?.aborted) log?.disconnected();
993
- else log?.rejected(err, res.status);
994
- return res;
1019
+ const error = runErrorBody(err);
1020
+ const browserLeft = upstream.signal.aborted;
1021
+ await reportRefusedRun(
1022
+ { onRunEnd, log },
1023
+ { body, request: req, context: runContext },
1024
+ browserLeft ? { cancelled: true } : { error: error.error }
1025
+ );
1026
+ if (browserLeft) log?.disconnected();
1027
+ else log?.rejected(err, error.status);
1028
+ return json(error, error.status);
995
1029
  }
996
1030
  },
997
1031
  async download(req) {
@@ -1067,6 +1101,7 @@ function createSeclaiHandlers(options) {
1067
1101
  };
1068
1102
  return {
1069
1103
  ...handlers,
1104
+ getAttachmentReferences,
1070
1105
  async handle(req) {
1071
1106
  const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
1072
1107
  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
  *
@@ -146,10 +148,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
146
148
  */
147
149
  onEvent?: RunEventCallback<Ctx>;
148
150
  /**
149
- * Called exactly once for each run that started streaming, with how it ended.
150
- * Awaited before the final `done`, `error` or `timeout` event is relayed, so
151
- * whatever it stores is in place when the browser sees the run end. If it
152
- * throws, the browser gets an `error` event instead.
151
+ * Called exactly once for each run, with how it ended. Awaited before the
152
+ * final `done`, `error` or `timeout` event is relayed, so whatever it stores
153
+ * is in place when the browser sees the run end. If it throws, the browser
154
+ * gets an `error` event instead.
155
+ *
156
+ * Also called, with `status: "failed"`, when the API refuses the run before
157
+ * it streams, or it fails before its first event (the API can't be reached,
158
+ * or `runTimeoutMs` runs out), and awaited before the error response is
159
+ * returned. The status is `cancelled` instead if the browser left while the
160
+ * stream was connecting. A throw there is only logged. Not called when
161
+ * `authorizeRun`, `context` or the body check refuses the run.
153
162
  */
154
163
  onRunEnd?: RunEndCallback<Ctx>;
155
164
  /**
@@ -230,8 +239,10 @@ interface RunRequestBody {
230
239
  sessionId?: string;
231
240
  }
232
241
  type SeclaiHandler = (req: Request) => Promise<Response>;
242
+ /** Which files the agent accepts: the `attachmentReferences` handler's JSON body. */
243
+ type AttachmentReferences = AgentAttachmentRefsApiResponse;
233
244
  interface SeclaiHandlers {
234
- /** `GET`: which files the agent accepts. */
245
+ /** `GET`: which files the agent accepts. Always a fresh lookup. */
235
246
  attachmentReferences: SeclaiHandler;
236
247
  /** `POST` multipart form data with a `file` field: returns the upload's `id`. */
237
248
  upload: SeclaiHandler;
@@ -246,8 +257,24 @@ interface SeclaiHandlers {
246
257
  */
247
258
  handle: SeclaiHandler;
248
259
  }
260
+ /**
261
+ * Server-side lookups offered next to the handlers. They need no request or
262
+ * context, so they're available both before and after `withContext`.
263
+ */
264
+ interface SeclaiLookups {
265
+ /**
266
+ * Which files the agent accepts, for server-side code such as a loader that
267
+ * sets a composer's file limit. The same value as the `attachmentReferences`
268
+ * handler's body, reused for {@link ATTACHMENT_SLOTS_TTL_MS} and shared with
269
+ * `upload.checkContentType`. Each call gets its own copy.
270
+ *
271
+ * Rejects if the lookup fails, with the SDK's error. A failure isn't reused:
272
+ * the next call tries again.
273
+ */
274
+ getAttachmentReferences(): Promise<AttachmentReferences>;
275
+ }
249
276
  /** What {@link createSeclaiHandlers} adds to the handlers. */
250
- interface WithContext<Ctx> {
277
+ interface WithContext<Ctx> extends SeclaiLookups {
251
278
  /**
252
279
  * The same handlers, with `ctx` passed to the hooks instead of calling the
253
280
  * `context` option. Use it when your framework already knows the user:
@@ -257,7 +284,7 @@ interface WithContext<Ctx> {
257
284
  * seclai.withContext({ userId: context.get(user).id }).handle(request);
258
285
  * ```
259
286
  */
260
- withContext(ctx: Ctx): SeclaiHandlers;
287
+ withContext(ctx: Ctx): SeclaiHandlers & SeclaiLookups;
261
288
  }
262
289
  /**
263
290
  * A refusal for a hook to return or throw: the `{ error, status }` JSON the
@@ -293,4 +320,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
293
320
  context?: undefined;
294
321
  }): UnboundSeclaiHandlers<Ctx>;
295
322
 
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 };
323
+ 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
  *
@@ -146,10 +148,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
146
148
  */
147
149
  onEvent?: RunEventCallback<Ctx>;
148
150
  /**
149
- * Called exactly once for each run that started streaming, with how it ended.
150
- * Awaited before the final `done`, `error` or `timeout` event is relayed, so
151
- * whatever it stores is in place when the browser sees the run end. If it
152
- * throws, the browser gets an `error` event instead.
151
+ * Called exactly once for each run, with how it ended. Awaited before the
152
+ * final `done`, `error` or `timeout` event is relayed, so whatever it stores
153
+ * is in place when the browser sees the run end. If it throws, the browser
154
+ * gets an `error` event instead.
155
+ *
156
+ * Also called, with `status: "failed"`, when the API refuses the run before
157
+ * it streams, or it fails before its first event (the API can't be reached,
158
+ * or `runTimeoutMs` runs out), and awaited before the error response is
159
+ * returned. The status is `cancelled` instead if the browser left while the
160
+ * stream was connecting. A throw there is only logged. Not called when
161
+ * `authorizeRun`, `context` or the body check refuses the run.
153
162
  */
154
163
  onRunEnd?: RunEndCallback<Ctx>;
155
164
  /**
@@ -230,8 +239,10 @@ interface RunRequestBody {
230
239
  sessionId?: string;
231
240
  }
232
241
  type SeclaiHandler = (req: Request) => Promise<Response>;
242
+ /** Which files the agent accepts: the `attachmentReferences` handler's JSON body. */
243
+ type AttachmentReferences = AgentAttachmentRefsApiResponse;
233
244
  interface SeclaiHandlers {
234
- /** `GET`: which files the agent accepts. */
245
+ /** `GET`: which files the agent accepts. Always a fresh lookup. */
235
246
  attachmentReferences: SeclaiHandler;
236
247
  /** `POST` multipart form data with a `file` field: returns the upload's `id`. */
237
248
  upload: SeclaiHandler;
@@ -246,8 +257,24 @@ interface SeclaiHandlers {
246
257
  */
247
258
  handle: SeclaiHandler;
248
259
  }
260
+ /**
261
+ * Server-side lookups offered next to the handlers. They need no request or
262
+ * context, so they're available both before and after `withContext`.
263
+ */
264
+ interface SeclaiLookups {
265
+ /**
266
+ * Which files the agent accepts, for server-side code such as a loader that
267
+ * sets a composer's file limit. The same value as the `attachmentReferences`
268
+ * handler's body, reused for {@link ATTACHMENT_SLOTS_TTL_MS} and shared with
269
+ * `upload.checkContentType`. Each call gets its own copy.
270
+ *
271
+ * Rejects if the lookup fails, with the SDK's error. A failure isn't reused:
272
+ * the next call tries again.
273
+ */
274
+ getAttachmentReferences(): Promise<AttachmentReferences>;
275
+ }
249
276
  /** What {@link createSeclaiHandlers} adds to the handlers. */
250
- interface WithContext<Ctx> {
277
+ interface WithContext<Ctx> extends SeclaiLookups {
251
278
  /**
252
279
  * The same handlers, with `ctx` passed to the hooks instead of calling the
253
280
  * `context` option. Use it when your framework already knows the user:
@@ -257,7 +284,7 @@ interface WithContext<Ctx> {
257
284
  * seclai.withContext({ userId: context.get(user).id }).handle(request);
258
285
  * ```
259
286
  */
260
- withContext(ctx: Ctx): SeclaiHandlers;
287
+ withContext(ctx: Ctx): SeclaiHandlers & SeclaiLookups;
261
288
  }
262
289
  /**
263
290
  * A refusal for a hook to return or throw: the `{ error, status }` JSON the
@@ -293,4 +320,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
293
320
  context?: undefined;
294
321
  }): UnboundSeclaiHandlers<Ctx>;
295
322
 
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 };
323
+ 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
@@ -34,37 +34,45 @@ function upstreamMessage(responseText) {
34
34
  }
35
35
  return void 0;
36
36
  }
37
- function toErrorResponse(err) {
37
+ function toErrorBody(err) {
38
38
  if (err instanceof SeclaiAPIValidationError) {
39
- return json(
40
- {
41
- error: "The Seclai API rejected this request as invalid.",
42
- status: 422,
43
- details: err.validationError
44
- },
45
- 422
46
- );
39
+ return {
40
+ error: "The Seclai API rejected this request as invalid.",
41
+ status: 422,
42
+ details: err.validationError
43
+ };
47
44
  }
48
45
  if (err instanceof SeclaiAPIStatusError) {
49
46
  const { statusCode } = err;
50
47
  if (statusCode === 401 || statusCode === 403) {
51
- return jsonError(
52
- 502,
53
- "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY."
54
- );
48
+ return {
49
+ error: "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY.",
50
+ status: 502
51
+ };
55
52
  }
56
53
  if (statusCode >= 400 && statusCode < 500) {
57
- return jsonError(
58
- statusCode,
59
- upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`
60
- );
54
+ return {
55
+ error: upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`,
56
+ status: statusCode
57
+ };
61
58
  }
62
- return jsonError(502, `The Seclai API returned status ${statusCode}.`);
59
+ return { error: `The Seclai API returned status ${statusCode}.`, status: 502 };
63
60
  }
64
61
  if (err instanceof SeclaiStreamingError) {
65
- return jsonError(504, "Timed out waiting for the Seclai API.");
62
+ return { error: "Timed out waiting for the Seclai API.", status: 504 };
66
63
  }
67
- return jsonError(502, "Could not reach the Seclai API.");
64
+ return { error: "Could not reach the Seclai API.", status: 502 };
65
+ }
66
+ function runErrorBody(err) {
67
+ const body = toErrorBody(err);
68
+ if (err instanceof SeclaiStreamingError) {
69
+ body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
70
+ }
71
+ return body;
72
+ }
73
+ function toErrorResponse(err) {
74
+ const body = toErrorBody(err);
75
+ return json(body, body.status);
68
76
  }
69
77
  function streamErrorMessage(err) {
70
78
  if (err instanceof SeclaiStreamingError) {
@@ -355,6 +363,20 @@ function toAttachments(raw) {
355
363
  ] : []
356
364
  );
357
365
  }
366
+ function reportCallbackError(log, err) {
367
+ if (log) log.callbackError(err);
368
+ else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
369
+ }
370
+ async function reportRefusedRun(callbacks, ctx, how) {
371
+ const { onRunEnd, log } = callbacks;
372
+ if (!onRunEnd) return;
373
+ const outcome = "error" in how ? { runId: null, status: "failed", output: "", attachments: [], error: how.error } : { runId: null, status: "cancelled", output: "", attachments: [], error: null };
374
+ try {
375
+ await onRunEnd(outcome, ctx);
376
+ } catch (err) {
377
+ reportCallbackError(log, err);
378
+ }
379
+ }
358
380
  function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
359
381
  const { onEvent, onRunEnd, log } = callbacks;
360
382
  const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
@@ -446,8 +468,7 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
446
468
  }
447
469
  },
448
470
  onError(err) {
449
- if (log) log.callbackError(err);
450
- else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
471
+ reportCallbackError(log, err);
451
472
  },
452
473
  onKeepalive: log && (() => log.keepalive()),
453
474
  onDisconnect: log && (() => log.readingOn()),
@@ -744,20 +765,22 @@ function createSeclaiHandlers(options) {
744
765
  // when called with any `this` but the global, so it can't be passed bare.
745
766
  fetch: (input, init) => globalThis.fetch(input, init)
746
767
  });
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;
768
+ let refsCache;
769
+ function remember(promise) {
770
+ const entry = { promise, expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS };
771
+ entry.promise.catch(() => {
772
+ if (refsCache === entry) refsCache = void 0;
773
+ });
774
+ refsCache = entry;
775
+ }
776
+ function cachedReferences() {
777
+ if (!refsCache || Date.now() >= refsCache.expires) {
778
+ remember(client.getAgentAttachmentReferences(agentId));
758
779
  }
759
- return slots.promise;
780
+ return refsCache.promise;
760
781
  }
782
+ const attachmentSlots = async () => (await cachedReferences()).accepted_attachments ?? [];
783
+ const getAttachmentReferences = async () => structuredClone(await cachedReferences());
761
784
  const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
762
785
  let warnedDownloadResult = false;
763
786
  async function callHook(name, req, resolveCtx, hook) {
@@ -786,7 +809,9 @@ function createSeclaiHandlers(options) {
786
809
  async attachmentReferences(req) {
787
810
  if (req.method !== "GET") return wrongMethod("GET");
788
811
  try {
789
- return json(await client.getAgentAttachmentReferences(agentId));
812
+ const refs = await client.getAgentAttachmentReferences(agentId);
813
+ remember(Promise.resolve(refs));
814
+ return json(refs);
790
815
  } catch (err) {
791
816
  return toErrorResponse(err);
792
817
  }
@@ -927,7 +952,10 @@ function createSeclaiHandlers(options) {
927
952
  const upstream = new AbortController();
928
953
  const abort = () => upstream.abort();
929
954
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
930
- if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
955
+ if (!keepReading) {
956
+ if (req.signal?.aborted) abort();
957
+ else req.signal?.addEventListener("abort", abort, { once: true });
958
+ }
931
959
  const log = logger && startRunLog(logger, {
932
960
  sessionId: body.sessionId,
933
961
  uploads: body.uploadIds?.length ?? 0,
@@ -964,10 +992,16 @@ function createSeclaiHandlers(options) {
964
992
  { headers: SSE_HEADERS }
965
993
  );
966
994
  } catch (err) {
967
- const res = toErrorResponse(err);
968
- if (!keepReading && req.signal?.aborted) log?.disconnected();
969
- else log?.rejected(err, res.status);
970
- return res;
995
+ const error = runErrorBody(err);
996
+ const browserLeft = upstream.signal.aborted;
997
+ await reportRefusedRun(
998
+ { onRunEnd, log },
999
+ { body, request: req, context: runContext },
1000
+ browserLeft ? { cancelled: true } : { error: error.error }
1001
+ );
1002
+ if (browserLeft) log?.disconnected();
1003
+ else log?.rejected(err, error.status);
1004
+ return json(error, error.status);
971
1005
  }
972
1006
  },
973
1007
  async download(req) {
@@ -1043,6 +1077,7 @@ function createSeclaiHandlers(options) {
1043
1077
  };
1044
1078
  return {
1045
1079
  ...handlers,
1080
+ getAttachmentReferences,
1046
1081
  async handle(req) {
1047
1082
  const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
1048
1083
  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.12",
3
+ "version": "0.0.14",
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",