@seclai/handlers 0.0.10 → 0.0.12

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
@@ -82,13 +82,13 @@ const seclai = createSeclaiHandlers({
82
82
  |---|---|---|
83
83
  | `maxBytes` | No limit | Largest file accepted, in bytes. A bigger one gets a 413 |
84
84
  | `checkContentType` | `false` | Give a 415 to a file whose type none of the agent's attachment slots accepts |
85
- | `onUpload(file, result, req)` | None | Called after a successful upload. Return a `Response` to replace the default JSON |
85
+ | `onUpload(file, result, req, context)` | None | Called after a successful upload. Return a `Response` to replace the default JSON |
86
86
 
87
87
  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
88
 
89
89
  - **`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
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.
91
- - **`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.
91
+ - **`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
92
 
93
93
  ### Access control
94
94
 
@@ -162,7 +162,13 @@ The context's type is inferred from the `context` option, or set as the type par
162
162
 
163
163
  ## Run callbacks
164
164
 
165
- `onEvent` and `onRunEnd` let the server see each run, for example to store a chat's history without trusting the browser to report it. Both get a `ctx` of `{ body, request }`: the validated `run` request body and the `Request` itself. It is the same object for every call in a run.
165
+ `onEvent` and `onRunEnd` let the server see each run, for example to store a chat's history without trusting the browser to report it. Both get a `ctx` of `{ body, request, context }`:
166
+
167
+ - `body` is the validated `run` request body, after any `authorizeRun` rewrite.
168
+ - `request` is the `Request` itself.
169
+ - `context` is the app's [context](#access-control), the same value the access-control hooks get, so a callback can save a reply for the signed-in user without working out who they are again.
170
+
171
+ `ctx` is the same object for every call in a run. The context is resolved once per request and before the run starts, so a `context` that refuses does so before any credits are used.
166
172
 
167
173
  ```ts
168
174
  const seclai = createSeclaiHandlers({
package/dist/index.cjs CHANGED
@@ -797,6 +797,15 @@ function createSeclaiHandlers(options) {
797
797
  }
798
798
  }
799
799
  const build = (resolveCtx) => {
800
+ const resolved = /* @__PURE__ */ new WeakMap();
801
+ const resolve = (req) => {
802
+ let ctx = resolved.get(req);
803
+ if (!ctx) {
804
+ ctx = resolveCtx(req);
805
+ resolved.set(req, ctx);
806
+ }
807
+ return ctx;
808
+ };
800
809
  const handlers = {
801
810
  async attachmentReferences(req) {
802
811
  if (req.method !== "GET") return wrongMethod("GET");
@@ -833,7 +842,7 @@ function createSeclaiHandlers(options) {
833
842
  const result2 = await callHook(
834
843
  "authorizeUpload",
835
844
  req,
836
- resolveCtx,
845
+ resolve,
837
846
  (ctx) => authorizeUpload(req, file, ctx)
838
847
  );
839
848
  if ("response" in result2) return refused("upload", result2.response, fileFields);
@@ -848,6 +857,7 @@ function createSeclaiHandlers(options) {
848
857
  }
849
858
  }
850
859
  let result;
860
+ let uploadContext;
851
861
  try {
852
862
  const type = essence(file.type);
853
863
  if (checkContentType && !UNKNOWN_TYPES.has(type)) {
@@ -856,6 +866,11 @@ function createSeclaiHandlers(options) {
856
866
  return refused("upload", jsonError(415, `This agent does not accept files of type ${type}.`), fileFields);
857
867
  }
858
868
  }
869
+ if (onUpload) {
870
+ const ctx = await callHook("context", req, resolve, (c) => c);
871
+ if ("response" in ctx) return refused("upload", ctx.response, fileFields);
872
+ uploadContext = ctx.value;
873
+ }
859
874
  const upload = await client.uploadAgentInput(agentId, {
860
875
  file,
861
876
  fileName: file.name,
@@ -886,7 +901,7 @@ function createSeclaiHandlers(options) {
886
901
  }
887
902
  if (onUpload) {
888
903
  try {
889
- const replacement = await onUpload(file, result, req);
904
+ const replacement = await onUpload(file, result, req, uploadContext);
890
905
  if (replacement instanceof Response) return replacement;
891
906
  } catch (err) {
892
907
  reportError("onUpload threw, so the request got a 500.", err);
@@ -910,7 +925,7 @@ function createSeclaiHandlers(options) {
910
925
  const result = await callHook(
911
926
  "authorizeRun",
912
927
  req,
913
- resolveCtx,
928
+ resolve,
914
929
  (ctx) => authorizeRun(req, parsed, ctx)
915
930
  );
916
931
  if ("response" in result) return refused("run", result.response);
@@ -927,6 +942,12 @@ function createSeclaiHandlers(options) {
927
942
  }
928
943
  body = rewritten;
929
944
  }
945
+ let runContext;
946
+ if (onEvent || onRunEnd) {
947
+ const ctx = await callHook("context", req, resolve, (c) => c);
948
+ if ("response" in ctx) return refused("run", ctx.response);
949
+ runContext = ctx.value;
950
+ }
930
951
  const upstream = new AbortController();
931
952
  const abort = () => upstream.abort();
932
953
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
@@ -951,7 +972,11 @@ function createSeclaiHandlers(options) {
951
972
  try {
952
973
  const first = await events.next();
953
974
  log?.opened(Boolean(first.done));
954
- const observer = onEvent || onRunEnd || log ? createRunObserver({ onEvent, onRunEnd, log }, { body, request: req }, { keepReading }) : void 0;
975
+ const observer = onEvent || onRunEnd || log ? createRunObserver(
976
+ { onEvent, onRunEnd, log },
977
+ { body, request: req, context: runContext },
978
+ { keepReading }
979
+ ) : void 0;
955
980
  return new Response(
956
981
  relayRunEvents(
957
982
  first.done ? void 0 : first.value,
@@ -986,7 +1011,7 @@ function createSeclaiHandlers(options) {
986
1011
  const result = await callHook(
987
1012
  "authorizeDownload",
988
1013
  req,
989
- resolveCtx,
1014
+ resolve,
990
1015
  (ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
991
1016
  );
992
1017
  const ids = { run_id: runId, attachment_id: attachmentId };
package/dist/index.d.cts CHANGED
@@ -31,11 +31,17 @@ interface RunEvent {
31
31
  data: unknown;
32
32
  }
33
33
  /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
34
- interface RunCallbackContext {
35
- /** The validated body of the `run` request. */
34
+ interface RunCallbackContext<Ctx = undefined> {
35
+ /** The validated body of the `run` request: after any `authorizeRun` rewrite. */
36
36
  body: RunRequestBody;
37
37
  /** The browser's request to the `run` handler. */
38
38
  request: Request;
39
+ /**
40
+ * The app's context for this request: what the `context` option returned, or
41
+ * what `withContext(ctx)` was given. The same value the access-control hooks
42
+ * get. `undefined` without either.
43
+ */
44
+ context: Ctx;
39
45
  }
40
46
  type RunOutcomeStatus = "completed" | "failed" | "cancelled";
41
47
  /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
@@ -60,8 +66,8 @@ interface RunOutcome {
60
66
  /** Why the run failed. `null` unless `status` is `failed`. */
61
67
  error: string | null;
62
68
  }
63
- type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
64
- type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
69
+ type RunEventCallback<Ctx = undefined> = (event: RunEvent, ctx: RunCallbackContext<Ctx>) => void | Promise<void>;
70
+ type RunEndCallback<Ctx = undefined> = (outcome: RunOutcome, ctx: RunCallbackContext<Ctx>) => void | Promise<void>;
65
71
 
66
72
  /**
67
73
  * From this version uploads are `ready` at once and a run's `output` is plain
@@ -89,7 +95,7 @@ interface UploadResult {
89
95
  file_size: number;
90
96
  }
91
97
  /** Checks and a hook for the `upload` handler. All are off by default. */
92
- interface SeclaiUploadOptions {
98
+ interface SeclaiUploadOptions<Ctx = undefined> {
93
99
  /**
94
100
  * Largest file accepted, in bytes. Anything bigger gets a 413 without reaching
95
101
  * the API. A request whose `content-length` is too big is refused before its
@@ -115,8 +121,12 @@ interface SeclaiUploadOptions {
115
121
  * Called after a successful upload, for example to keep a copy of the file or
116
122
  * record which session it belongs to. Return a `Response` to send it instead of
117
123
  * the default JSON. `req`'s body has already been read. A throw becomes a 500.
124
+ *
125
+ * `context` is the app's context for this request, the same value the
126
+ * access-control hooks get. It is resolved before the file is uploaded, so a
127
+ * `context` that refuses does so before the file reaches Seclai.
118
128
  */
119
- onUpload?(file: File, result: UploadResult, req: Request): void | Response | Promise<void | Response>;
129
+ onUpload?(file: File, result: UploadResult, req: Request, context: Ctx): void | Response | Promise<void | Response>;
120
130
  }
121
131
  interface SeclaiHandlersOptions<Ctx = undefined> {
122
132
  /** Seclai API key. Server-side only: never expose it to the browser. */
@@ -128,20 +138,20 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
128
138
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
129
139
  runTimeoutMs?: number;
130
140
  /** Size limit, content-type check and hook for the `upload` handler. */
131
- upload?: SeclaiUploadOptions;
141
+ upload?: SeclaiUploadOptions<Ctx>;
132
142
  /**
133
143
  * Called with each event of a run stream, in order, and awaited before the
134
144
  * event is relayed to the browser. If it throws, the stream ends with an
135
145
  * `error` event.
136
146
  */
137
- onEvent?: RunEventCallback;
147
+ onEvent?: RunEventCallback<Ctx>;
138
148
  /**
139
149
  * Called exactly once for each run that started streaming, with how it ended.
140
150
  * Awaited before the final `done`, `error` or `timeout` event is relayed, so
141
151
  * whatever it stores is in place when the browser sees the run end. If it
142
152
  * throws, the browser gets an `error` event instead.
143
153
  */
144
- onRunEnd?: RunEndCallback;
154
+ onRunEnd?: RunEndCallback<Ctx>;
145
155
  /**
146
156
  * What happens to a run when the browser disconnects: closes the tab, moves
147
157
  * to another page, or aborts the request. The run itself always carries on at
package/dist/index.d.ts CHANGED
@@ -31,11 +31,17 @@ interface RunEvent {
31
31
  data: unknown;
32
32
  }
33
33
  /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
34
- interface RunCallbackContext {
35
- /** The validated body of the `run` request. */
34
+ interface RunCallbackContext<Ctx = undefined> {
35
+ /** The validated body of the `run` request: after any `authorizeRun` rewrite. */
36
36
  body: RunRequestBody;
37
37
  /** The browser's request to the `run` handler. */
38
38
  request: Request;
39
+ /**
40
+ * The app's context for this request: what the `context` option returned, or
41
+ * what `withContext(ctx)` was given. The same value the access-control hooks
42
+ * get. `undefined` without either.
43
+ */
44
+ context: Ctx;
39
45
  }
40
46
  type RunOutcomeStatus = "completed" | "failed" | "cancelled";
41
47
  /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
@@ -60,8 +66,8 @@ interface RunOutcome {
60
66
  /** Why the run failed. `null` unless `status` is `failed`. */
61
67
  error: string | null;
62
68
  }
63
- type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
64
- type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
69
+ type RunEventCallback<Ctx = undefined> = (event: RunEvent, ctx: RunCallbackContext<Ctx>) => void | Promise<void>;
70
+ type RunEndCallback<Ctx = undefined> = (outcome: RunOutcome, ctx: RunCallbackContext<Ctx>) => void | Promise<void>;
65
71
 
66
72
  /**
67
73
  * From this version uploads are `ready` at once and a run's `output` is plain
@@ -89,7 +95,7 @@ interface UploadResult {
89
95
  file_size: number;
90
96
  }
91
97
  /** Checks and a hook for the `upload` handler. All are off by default. */
92
- interface SeclaiUploadOptions {
98
+ interface SeclaiUploadOptions<Ctx = undefined> {
93
99
  /**
94
100
  * Largest file accepted, in bytes. Anything bigger gets a 413 without reaching
95
101
  * the API. A request whose `content-length` is too big is refused before its
@@ -115,8 +121,12 @@ interface SeclaiUploadOptions {
115
121
  * Called after a successful upload, for example to keep a copy of the file or
116
122
  * record which session it belongs to. Return a `Response` to send it instead of
117
123
  * the default JSON. `req`'s body has already been read. A throw becomes a 500.
124
+ *
125
+ * `context` is the app's context for this request, the same value the
126
+ * access-control hooks get. It is resolved before the file is uploaded, so a
127
+ * `context` that refuses does so before the file reaches Seclai.
118
128
  */
119
- onUpload?(file: File, result: UploadResult, req: Request): void | Response | Promise<void | Response>;
129
+ onUpload?(file: File, result: UploadResult, req: Request, context: Ctx): void | Response | Promise<void | Response>;
120
130
  }
121
131
  interface SeclaiHandlersOptions<Ctx = undefined> {
122
132
  /** Seclai API key. Server-side only: never expose it to the browser. */
@@ -128,20 +138,20 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
128
138
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
129
139
  runTimeoutMs?: number;
130
140
  /** Size limit, content-type check and hook for the `upload` handler. */
131
- upload?: SeclaiUploadOptions;
141
+ upload?: SeclaiUploadOptions<Ctx>;
132
142
  /**
133
143
  * Called with each event of a run stream, in order, and awaited before the
134
144
  * event is relayed to the browser. If it throws, the stream ends with an
135
145
  * `error` event.
136
146
  */
137
- onEvent?: RunEventCallback;
147
+ onEvent?: RunEventCallback<Ctx>;
138
148
  /**
139
149
  * Called exactly once for each run that started streaming, with how it ended.
140
150
  * Awaited before the final `done`, `error` or `timeout` event is relayed, so
141
151
  * whatever it stores is in place when the browser sees the run end. If it
142
152
  * throws, the browser gets an `error` event instead.
143
153
  */
144
- onRunEnd?: RunEndCallback;
154
+ onRunEnd?: RunEndCallback<Ctx>;
145
155
  /**
146
156
  * What happens to a run when the browser disconnects: closes the tab, moves
147
157
  * to another page, or aborts the request. The run itself always carries on at
package/dist/index.js CHANGED
@@ -773,6 +773,15 @@ function createSeclaiHandlers(options) {
773
773
  }
774
774
  }
775
775
  const build = (resolveCtx) => {
776
+ const resolved = /* @__PURE__ */ new WeakMap();
777
+ const resolve = (req) => {
778
+ let ctx = resolved.get(req);
779
+ if (!ctx) {
780
+ ctx = resolveCtx(req);
781
+ resolved.set(req, ctx);
782
+ }
783
+ return ctx;
784
+ };
776
785
  const handlers = {
777
786
  async attachmentReferences(req) {
778
787
  if (req.method !== "GET") return wrongMethod("GET");
@@ -809,7 +818,7 @@ function createSeclaiHandlers(options) {
809
818
  const result2 = await callHook(
810
819
  "authorizeUpload",
811
820
  req,
812
- resolveCtx,
821
+ resolve,
813
822
  (ctx) => authorizeUpload(req, file, ctx)
814
823
  );
815
824
  if ("response" in result2) return refused("upload", result2.response, fileFields);
@@ -824,6 +833,7 @@ function createSeclaiHandlers(options) {
824
833
  }
825
834
  }
826
835
  let result;
836
+ let uploadContext;
827
837
  try {
828
838
  const type = essence(file.type);
829
839
  if (checkContentType && !UNKNOWN_TYPES.has(type)) {
@@ -832,6 +842,11 @@ function createSeclaiHandlers(options) {
832
842
  return refused("upload", jsonError(415, `This agent does not accept files of type ${type}.`), fileFields);
833
843
  }
834
844
  }
845
+ if (onUpload) {
846
+ const ctx = await callHook("context", req, resolve, (c) => c);
847
+ if ("response" in ctx) return refused("upload", ctx.response, fileFields);
848
+ uploadContext = ctx.value;
849
+ }
835
850
  const upload = await client.uploadAgentInput(agentId, {
836
851
  file,
837
852
  fileName: file.name,
@@ -862,7 +877,7 @@ function createSeclaiHandlers(options) {
862
877
  }
863
878
  if (onUpload) {
864
879
  try {
865
- const replacement = await onUpload(file, result, req);
880
+ const replacement = await onUpload(file, result, req, uploadContext);
866
881
  if (replacement instanceof Response) return replacement;
867
882
  } catch (err) {
868
883
  reportError("onUpload threw, so the request got a 500.", err);
@@ -886,7 +901,7 @@ function createSeclaiHandlers(options) {
886
901
  const result = await callHook(
887
902
  "authorizeRun",
888
903
  req,
889
- resolveCtx,
904
+ resolve,
890
905
  (ctx) => authorizeRun(req, parsed, ctx)
891
906
  );
892
907
  if ("response" in result) return refused("run", result.response);
@@ -903,6 +918,12 @@ function createSeclaiHandlers(options) {
903
918
  }
904
919
  body = rewritten;
905
920
  }
921
+ let runContext;
922
+ if (onEvent || onRunEnd) {
923
+ const ctx = await callHook("context", req, resolve, (c) => c);
924
+ if ("response" in ctx) return refused("run", ctx.response);
925
+ runContext = ctx.value;
926
+ }
906
927
  const upstream = new AbortController();
907
928
  const abort = () => upstream.abort();
908
929
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
@@ -927,7 +948,11 @@ function createSeclaiHandlers(options) {
927
948
  try {
928
949
  const first = await events.next();
929
950
  log?.opened(Boolean(first.done));
930
- const observer = onEvent || onRunEnd || log ? createRunObserver({ onEvent, onRunEnd, log }, { body, request: req }, { keepReading }) : void 0;
951
+ const observer = onEvent || onRunEnd || log ? createRunObserver(
952
+ { onEvent, onRunEnd, log },
953
+ { body, request: req, context: runContext },
954
+ { keepReading }
955
+ ) : void 0;
931
956
  return new Response(
932
957
  relayRunEvents(
933
958
  first.done ? void 0 : first.value,
@@ -962,7 +987,7 @@ function createSeclaiHandlers(options) {
962
987
  const result = await callHook(
963
988
  "authorizeDownload",
964
989
  req,
965
- resolveCtx,
990
+ resolve,
966
991
  (ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
967
992
  );
968
993
  const ids = { run_id: runId, attachment_id: attachmentId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
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",