@seclai/handlers 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -85,52 +85,296 @@ data: ${JSON.stringify(data)}
85
85
 
86
86
  `);
87
87
  }
88
- function relayRunEvents(first, events, abort) {
88
+ var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
89
+ function relayRunEvents(first, events, abort, observer, options = {}) {
90
+ const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
91
+ let pending = first;
89
92
  let closed = false;
93
+ let cancelled = false;
94
+ let closeReport;
95
+ let inflight;
90
96
  let keepalive;
97
+ let ctrl;
98
+ let draining = false;
99
+ let pulling;
91
100
  const finish = () => {
92
101
  closed = true;
93
102
  clearInterval(keepalive);
94
103
  };
95
- return new ReadableStream({
96
- start(controller) {
97
- if (!first) {
98
- finish();
99
- controller.close();
104
+ const stopUpstream = () => {
105
+ abort();
106
+ void events.return().catch(() => {
107
+ });
108
+ };
109
+ const call = async (hook) => {
110
+ try {
111
+ await hook();
112
+ return true;
113
+ } catch (err) {
114
+ try {
115
+ observer?.onError(err);
116
+ } catch {
117
+ }
118
+ return false;
119
+ }
120
+ };
121
+ const reportClose = (reason) => {
122
+ if (!observer) return Promise.resolve(true);
123
+ return closeReport ??= call(() => observer.onClose(reason));
124
+ };
125
+ const end = (controller, last) => {
126
+ if (cancelled) return;
127
+ if (last) controller.enqueue(last);
128
+ controller.close();
129
+ };
130
+ const fail = async (controller) => {
131
+ finish();
132
+ stopUpstream();
133
+ await reportClose("error");
134
+ end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
135
+ };
136
+ const relay = (controller, event, source = "upstream") => {
137
+ const work = (async () => {
138
+ if (observer && !await call(() => observer.onEvent(event, source))) {
139
+ if (!closed) await fail(controller);
100
140
  return;
101
141
  }
102
- controller.enqueue(frame(first.event, first.data));
103
- keepalive = setInterval(() => {
104
- if (!closed) controller.enqueue(encoder.encode(": keepalive\n\n"));
105
- }, KEEPALIVE_INTERVAL_MS);
106
- },
107
- async pull(controller) {
142
+ if (closed || cancelled) return;
143
+ controller.enqueue(frame(event.event, event.data));
144
+ })();
145
+ inflight = work;
146
+ return work;
147
+ };
148
+ const pullOnce = async (controller) => {
149
+ if (pending) {
150
+ const event = pending;
151
+ pending = void 0;
152
+ await relay(controller, event);
153
+ return;
154
+ }
155
+ let next;
156
+ try {
157
+ next = await events.next();
158
+ } catch (err) {
159
+ if (closed) return;
160
+ await relay(
161
+ controller,
162
+ { event: "error", data: { error: streamErrorMessage(err) } },
163
+ "connection-lost"
164
+ );
108
165
  if (closed) return;
166
+ finish();
167
+ await reportClose("end");
168
+ end(controller);
169
+ return;
170
+ }
171
+ if (closed) return;
172
+ if (next.done) {
173
+ finish();
174
+ const ok = await reportClose("end");
175
+ end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
176
+ return;
177
+ }
178
+ await relay(controller, next.value);
179
+ };
180
+ const drain = async (controller) => {
181
+ await pulling;
182
+ await inflight;
183
+ if (closed) return;
184
+ if (pending) {
185
+ const event = pending;
186
+ pending = void 0;
187
+ await relay(controller, event);
188
+ }
189
+ while (!closed) {
190
+ let next;
109
191
  try {
110
- const next = await events.next();
111
- if (closed) return;
112
- if (next.done) {
113
- finish();
114
- controller.close();
115
- return;
116
- }
117
- controller.enqueue(frame(next.value.event, next.value.data));
192
+ next = await events.next();
118
193
  } catch (err) {
194
+ if (closed) return;
195
+ await relay(
196
+ controller,
197
+ { event: "error", data: { error: streamErrorMessage(err) } },
198
+ "connection-lost"
199
+ );
119
200
  if (closed) return;
120
201
  finish();
121
- controller.enqueue(frame("error", { error: streamErrorMessage(err) }));
202
+ await reportClose("end");
203
+ return;
204
+ }
205
+ if (closed) return;
206
+ if (next.done) {
207
+ finish();
208
+ await reportClose("end");
209
+ return;
210
+ }
211
+ await relay(controller, next.value);
212
+ }
213
+ };
214
+ const startDrain = (fromCancel) => {
215
+ if (draining || closed || !ctrl) return;
216
+ draining = true;
217
+ cancelled = true;
218
+ clearInterval(keepalive);
219
+ const controller = ctrl;
220
+ if (!fromCancel) {
221
+ try {
122
222
  controller.close();
223
+ } catch {
224
+ }
225
+ }
226
+ try {
227
+ observer?.onDisconnect?.();
228
+ } catch {
229
+ }
230
+ void drain(controller).catch((err) => {
231
+ try {
232
+ observer?.onError(err);
233
+ } catch {
234
+ }
235
+ });
236
+ };
237
+ return new ReadableStream({
238
+ start(controller) {
239
+ ctrl = controller;
240
+ keepalive = setInterval(() => {
241
+ if (!closed && !cancelled) controller.enqueue(encoder.encode(": keepalive\n\n"));
242
+ }, KEEPALIVE_INTERVAL_MS);
243
+ if (keepReading && options.signal) {
244
+ const { signal } = options;
245
+ const onAbort = () => startDrain(false);
246
+ if (signal.aborted) queueMicrotask(onAbort);
247
+ else signal.addEventListener("abort", onAbort, { once: true });
123
248
  }
124
249
  },
125
- cancel() {
250
+ pull(controller) {
251
+ if (closed || draining) return;
252
+ const work = pullOnce(controller);
253
+ pulling = work;
254
+ return work;
255
+ },
256
+ async cancel() {
257
+ if (keepReading) {
258
+ startDrain(true);
259
+ return;
260
+ }
261
+ cancelled = true;
126
262
  finish();
127
- abort();
128
- void events.return().catch(() => {
129
- });
263
+ stopUpstream();
264
+ const unrelayed = pending;
265
+ pending = void 0;
266
+ if (unrelayed && observer?.onUnrelayed) {
267
+ await call(() => observer.onUnrelayed(unrelayed));
268
+ }
269
+ await inflight;
270
+ await reportClose("cancel");
130
271
  }
131
272
  });
132
273
  }
133
274
 
275
+ // src/run-callbacks.ts
276
+ var NO_RESULT_MESSAGE = "The stream ended without a result.";
277
+ var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
278
+ var FAILED_MESSAGE = "The run failed.";
279
+ function lastAttemptError(run) {
280
+ if (!Array.isArray(run.attempts)) return null;
281
+ for (let i = run.attempts.length - 1; i >= 0; i--) {
282
+ const error = run.attempts[i]?.error;
283
+ if (typeof error === "string" && error) return error;
284
+ }
285
+ return null;
286
+ }
287
+ function toAttachments(raw) {
288
+ if (!Array.isArray(raw)) return [];
289
+ return raw.flatMap(
290
+ (item) => typeof item?.id === "string" ? [
291
+ {
292
+ id: item.id,
293
+ name: typeof item.name === "string" ? item.name : null,
294
+ mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
295
+ }
296
+ ] : []
297
+ );
298
+ }
299
+ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
300
+ const { onEvent, onRunEnd } = callbacks;
301
+ const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
302
+ let runId = null;
303
+ let text = "";
304
+ let terminal;
305
+ let ended = false;
306
+ const outcome = (o) => ({
307
+ runId,
308
+ attachments: [],
309
+ ...o
310
+ });
311
+ const end = async (o) => {
312
+ if (ended) return;
313
+ ended = true;
314
+ await onRunEnd?.(o, ctx);
315
+ };
316
+ const failed = (error) => outcome({ status: "failed", output: text, error });
317
+ const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
318
+ const record = (event, source) => {
319
+ const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
320
+ if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
321
+ if (terminal) return;
322
+ switch (event.event) {
323
+ case "stream_token":
324
+ if (typeof payload.token === "string") text += payload.token;
325
+ return;
326
+ case "done": {
327
+ const run = payload;
328
+ if (typeof run.run_id === "string") runId = run.run_id;
329
+ const attachments = toAttachments(run.attachments);
330
+ terminal = run.status === "failed" ? outcome({
331
+ status: "failed",
332
+ output: text,
333
+ attachments,
334
+ error: lastAttemptError(run) ?? FAILED_MESSAGE
335
+ }) : outcome({
336
+ status: "completed",
337
+ // Agents with no streaming step send no tokens, so `output`
338
+ // may be the only text.
339
+ output: typeof run.output === "string" && run.output || text,
340
+ attachments,
341
+ error: null
342
+ });
343
+ return;
344
+ }
345
+ case "error":
346
+ terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
347
+ return;
348
+ case "timeout":
349
+ terminal = failed(TIMEOUT_MESSAGE);
350
+ return;
351
+ }
352
+ };
353
+ return {
354
+ async onEvent(event, source) {
355
+ record(event, source);
356
+ await onEvent?.(event, ctx);
357
+ if (terminal) await end(terminal);
358
+ },
359
+ onUnrelayed(event) {
360
+ record(event, "upstream");
361
+ },
362
+ async onClose(reason) {
363
+ switch (reason) {
364
+ case "end":
365
+ return end(terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE)));
366
+ case "error":
367
+ return end(failed(OBSERVER_ERROR_MESSAGE));
368
+ case "cancel":
369
+ return end(terminal ?? cancelled());
370
+ }
371
+ },
372
+ onError(err) {
373
+ console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
374
+ }
375
+ };
376
+ }
377
+
134
378
  // src/handlers.ts
135
379
  var MIN_API_VERSION = SeclaiApiVersion.V2026_10_16;
136
380
  var DEFAULT_API_VERSION = SeclaiApiVersion.V2026_10_28;
@@ -147,6 +391,10 @@ var ROUTES = {
147
391
  function wrongMethod(allow) {
148
392
  return jsonError(405, "Method not allowed.", { allow });
149
393
  }
394
+ var NOT_AUTHORIZED = "Could not authorize this request.";
395
+ function deny(status, message, headers) {
396
+ return jsonError(status, message, headers);
397
+ }
150
398
  function parseRunBody(body) {
151
399
  if (typeof body !== "object" || body === null || Array.isArray(body)) {
152
400
  return "The request body must be a JSON object.";
@@ -171,7 +419,14 @@ function createSeclaiHandlers(options) {
171
419
  apiKey,
172
420
  agentId,
173
421
  apiVersion = DEFAULT_API_VERSION,
174
- runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS
422
+ runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
423
+ keepReadingAfterDisconnect = false,
424
+ onEvent,
425
+ onRunEnd,
426
+ context,
427
+ authorizeRun,
428
+ authorizeUpload,
429
+ authorizeDownload
175
430
  } = options;
176
431
  if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
177
432
  if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
@@ -187,127 +442,211 @@ function createSeclaiHandlers(options) {
187
442
  // when called with any `this` but the global, so it can't be passed bare.
188
443
  fetch: (input, init) => globalThis.fetch(input, init)
189
444
  });
190
- const handlers = {
191
- async attachmentReferences(req) {
192
- if (req.method !== "GET") return wrongMethod("GET");
193
- try {
194
- return json(await client.getAgentAttachmentReferences(agentId));
195
- } catch (err) {
196
- return toErrorResponse(err);
197
- }
198
- },
199
- async upload(req) {
200
- if (req.method !== "POST") return wrongMethod("POST");
201
- let form;
202
- try {
203
- form = await req.formData();
204
- } catch {
205
- return jsonError(400, "The request body must be multipart form data.");
206
- }
207
- const file = form.get("file");
208
- if (file === null || typeof file === "string") {
209
- return jsonError(400, "The form must include a `file` field holding a file.");
210
- }
211
- try {
212
- const upload = await client.uploadAgentInput(agentId, {
213
- file,
214
- fileName: file.name,
215
- mimeType: file.type || void 0
216
- });
217
- return json({
218
- id: upload.id,
219
- status: upload.status,
220
- filename: upload.filename,
221
- content_type: upload.content_type,
222
- file_size: upload.file_size
223
- });
224
- } catch (err) {
225
- return toErrorResponse(err);
226
- }
227
- },
228
- async run(req) {
229
- if (req.method !== "POST") return wrongMethod("POST");
230
- let raw;
231
- try {
232
- raw = await req.json();
233
- } catch {
234
- return jsonError(400, "The request body must be JSON.");
235
- }
236
- const body = parseRunBody(raw);
237
- if (typeof body === "string") return jsonError(400, body);
238
- const upstream = new AbortController();
239
- const abort = () => upstream.abort();
240
- req.signal?.addEventListener("abort", abort, { once: true });
241
- const events = client.runStreamingAgent(
242
- agentId,
243
- {
244
- ...body.input ? { input: body.input } : {},
245
- ...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
246
- ...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
247
- },
248
- { timeoutMs: runTimeoutMs, signal: upstream.signal }
249
- );
250
- try {
251
- const first = await events.next();
252
- return new Response(
253
- relayRunEvents(first.done ? void 0 : first.value, events, abort),
254
- { headers: SSE_HEADERS }
445
+ let warnedDownloadResult = false;
446
+ async function callHook(name, req, resolveCtx, hook) {
447
+ let ctx;
448
+ try {
449
+ ctx = await resolveCtx(req);
450
+ return { value: await hook(ctx) };
451
+ } catch (err) {
452
+ if (err instanceof Response) return { response: err };
453
+ const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
454
+ console.error(`[seclai] ${name} threw, so the request got a 500.${hint}`, err);
455
+ return { response: jsonError(500, NOT_AUTHORIZED) };
456
+ }
457
+ }
458
+ const build = (resolveCtx) => {
459
+ const handlers = {
460
+ async attachmentReferences(req) {
461
+ if (req.method !== "GET") return wrongMethod("GET");
462
+ try {
463
+ return json(await client.getAgentAttachmentReferences(agentId));
464
+ } catch (err) {
465
+ return toErrorResponse(err);
466
+ }
467
+ },
468
+ async upload(req) {
469
+ if (req.method !== "POST") return wrongMethod("POST");
470
+ let form;
471
+ try {
472
+ form = await req.formData();
473
+ } catch {
474
+ return jsonError(400, "The request body must be multipart form data.");
475
+ }
476
+ const file = form.get("file");
477
+ if (file === null || typeof file === "string") {
478
+ return jsonError(400, "The form must include a `file` field holding a file.");
479
+ }
480
+ if (authorizeUpload) {
481
+ const result = await callHook(
482
+ "authorizeUpload",
483
+ req,
484
+ resolveCtx,
485
+ (ctx) => authorizeUpload(req, file, ctx)
486
+ );
487
+ if ("response" in result) return result.response;
488
+ const allowed = result.value;
489
+ if (allowed instanceof Response) return allowed;
490
+ if (allowed === false) return jsonError(403, "This upload isn't allowed.");
491
+ if (allowed !== void 0 && allowed !== true) {
492
+ console.error("[seclai] authorizeUpload returned something other than true, false, nothing or a Response, so the request got a 500.", allowed);
493
+ return jsonError(500, NOT_AUTHORIZED);
494
+ }
495
+ }
496
+ try {
497
+ const upload = await client.uploadAgentInput(agentId, {
498
+ file,
499
+ fileName: file.name,
500
+ mimeType: file.type || void 0
501
+ });
502
+ return json({
503
+ id: upload.id,
504
+ status: upload.status,
505
+ filename: upload.filename,
506
+ content_type: upload.content_type,
507
+ file_size: upload.file_size
508
+ });
509
+ } catch (err) {
510
+ return toErrorResponse(err);
511
+ }
512
+ },
513
+ async run(req) {
514
+ if (req.method !== "POST") return wrongMethod("POST");
515
+ let raw;
516
+ try {
517
+ raw = await req.json();
518
+ } catch {
519
+ return jsonError(400, "The request body must be JSON.");
520
+ }
521
+ const parsed = parseRunBody(raw);
522
+ if (typeof parsed === "string") return jsonError(400, parsed);
523
+ let body = parsed;
524
+ if (authorizeRun) {
525
+ const result = await callHook(
526
+ "authorizeRun",
527
+ req,
528
+ resolveCtx,
529
+ (ctx) => authorizeRun(req, parsed, ctx)
530
+ );
531
+ if ("response" in result) return result.response;
532
+ const verdict = result.value;
533
+ if (verdict instanceof Response) return verdict;
534
+ if (verdict === false) return jsonError(403, "This request isn't allowed.");
535
+ const kept = verdict === void 0 || verdict === true;
536
+ const rewritten = parseRunBody(kept ? parsed : verdict);
537
+ if (typeof rewritten === "string") {
538
+ console.error(
539
+ kept ? `[seclai] authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `[seclai] authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
540
+ );
541
+ return jsonError(500, NOT_AUTHORIZED);
542
+ }
543
+ body = rewritten;
544
+ }
545
+ const upstream = new AbortController();
546
+ const abort = () => upstream.abort();
547
+ const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
548
+ if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
549
+ const events = client.runStreamingAgent(
550
+ agentId,
551
+ {
552
+ ...body.input ? { input: body.input } : {},
553
+ ...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
554
+ ...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
555
+ },
556
+ { timeoutMs: runTimeoutMs, signal: upstream.signal }
255
557
  );
256
- } catch (err) {
257
- return toErrorResponse(err);
258
- }
259
- },
260
- async download(req) {
261
- if (req.method !== "GET") return wrongMethod("GET");
262
- const params = new URL(req.url).searchParams;
263
- const runId = params.get("runId") ?? "";
264
- const attachmentId = params.get("attachmentId") ?? "";
265
- const name = params.get("name") ?? void 0;
266
- if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
267
- if (!ATTACHMENT_ID.test(attachmentId)) {
268
- return jsonError(400, "`attachmentId` is not valid.");
269
- }
270
- if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
271
- return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
272
- }
273
- try {
274
- const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
275
- ...name ? { downloadName: name } : {},
276
- signal: req.signal
277
- });
278
- const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
279
- const headers = new Headers({
280
- "content-type": contentType,
281
- "cache-control": "private, no-store",
282
- "x-content-type-options": "nosniff"
283
- });
284
- const disposition = upstream.headers.get("content-disposition");
285
- if (disposition) headers.set("content-disposition", disposition);
286
- const length = upstream.headers.get("content-length");
287
- if (length && !upstream.headers.has("content-encoding")) {
288
- headers.set("content-length", length);
558
+ try {
559
+ const first = await events.next();
560
+ const observer = onEvent || onRunEnd ? createRunObserver({ onEvent, onRunEnd }, { body, request: req }, { keepReading }) : void 0;
561
+ return new Response(
562
+ relayRunEvents(
563
+ first.done ? void 0 : first.value,
564
+ events,
565
+ abort,
566
+ observer,
567
+ keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
568
+ ),
569
+ { headers: SSE_HEADERS }
570
+ );
571
+ } catch (err) {
572
+ return toErrorResponse(err);
289
573
  }
290
- if (!contentType.toLowerCase().startsWith("application/pdf")) {
291
- headers.set("content-security-policy", "sandbox; default-src 'none'");
574
+ },
575
+ async download(req) {
576
+ if (req.method !== "GET") return wrongMethod("GET");
577
+ const params = new URL(req.url).searchParams;
578
+ const runId = params.get("runId") ?? "";
579
+ const attachmentId = params.get("attachmentId") ?? "";
580
+ const name = params.get("name") ?? void 0;
581
+ if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
582
+ if (!ATTACHMENT_ID.test(attachmentId)) {
583
+ return jsonError(400, "`attachmentId` is not valid.");
584
+ }
585
+ if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
586
+ return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
587
+ }
588
+ if (authorizeDownload) {
589
+ const result = await callHook(
590
+ "authorizeDownload",
591
+ req,
592
+ resolveCtx,
593
+ (ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
594
+ );
595
+ if ("response" in result) return result.response;
596
+ const allowed = result.value;
597
+ if (allowed instanceof Response) return allowed;
598
+ if (allowed !== true && allowed !== false && !warnedDownloadResult) {
599
+ warnedDownloadResult = true;
600
+ console.warn(
601
+ `[seclai] authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`
602
+ );
603
+ }
604
+ if (allowed !== true) return jsonError(404, "Not found.");
605
+ }
606
+ try {
607
+ const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
608
+ ...name ? { downloadName: name } : {},
609
+ signal: req.signal
610
+ });
611
+ const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
612
+ const headers = new Headers({
613
+ "content-type": contentType,
614
+ "cache-control": "private, no-store",
615
+ "x-content-type-options": "nosniff"
616
+ });
617
+ const disposition = upstream.headers.get("content-disposition");
618
+ if (disposition) headers.set("content-disposition", disposition);
619
+ const length = upstream.headers.get("content-length");
620
+ if (length && !upstream.headers.has("content-encoding")) {
621
+ headers.set("content-length", length);
622
+ }
623
+ if (!contentType.toLowerCase().startsWith("application/pdf")) {
624
+ headers.set("content-security-policy", "sandbox; default-src 'none'");
625
+ }
626
+ return new Response(upstream.body, { status: upstream.status, headers });
627
+ } catch (err) {
628
+ return toErrorResponse(err);
292
629
  }
293
- return new Response(upstream.body, { status: upstream.status, headers });
294
- } catch (err) {
295
- return toErrorResponse(err);
296
630
  }
297
- }
298
- };
299
- return {
300
- ...handlers,
301
- async handle(req) {
302
- const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
303
- const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
304
- if (!name) return jsonError(404, "Not found.");
305
- return handlers[name](req);
306
- }
631
+ };
632
+ return {
633
+ ...handlers,
634
+ async handle(req) {
635
+ const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
636
+ const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
637
+ if (!name) return jsonError(404, "Not found.");
638
+ return handlers[name](req);
639
+ }
640
+ };
307
641
  };
642
+ const unbound = build(
643
+ context ? async (req) => context(req) : async () => void 0
644
+ );
645
+ return { ...unbound, withContext: (ctx) => build(async () => ctx) };
308
646
  }
309
647
  export {
310
648
  DEFAULT_API_VERSION,
311
649
  MIN_API_VERSION,
312
- createSeclaiHandlers
650
+ createSeclaiHandlers,
651
+ deny
313
652
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Framework-free server handlers for running Seclai agents from a web app: upload, run with SSE relay, and download proxy.",
5
5
  "license": "MIT",
6
6
  "type": "module",