@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.d.cts CHANGED
@@ -1,5 +1,43 @@
1
1
  import { ApiVersion } from '@seclai/sdk';
2
2
 
3
+ /** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
4
+ interface RunEvent {
5
+ event: string;
6
+ data: unknown;
7
+ }
8
+ /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
9
+ interface RunCallbackContext {
10
+ /** The validated body of the `run` request. */
11
+ body: RunRequestBody;
12
+ /** The browser's request to the `run` handler. */
13
+ request: Request;
14
+ }
15
+ type RunOutcomeStatus = "completed" | "failed" | "cancelled";
16
+ /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
17
+ interface RunOutcomeAttachment {
18
+ id: string;
19
+ name: string | null;
20
+ mime: string;
21
+ }
22
+ /** How a run ended, as reported to `onRunEnd`. */
23
+ interface RunOutcome {
24
+ /** From `init` or `done`. `null` if the stream ended before either. */
25
+ runId: string | null;
26
+ /**
27
+ * `cancelled` means the browser went away before the run ended. The run
28
+ * itself may still finish on Seclai.
29
+ */
30
+ status: RunOutcomeStatus;
31
+ /** The run's output when it completed, otherwise the text streamed so far. */
32
+ output: string;
33
+ /** Files from `done`. Empty unless the run sent `done`. */
34
+ attachments: RunOutcomeAttachment[];
35
+ /** Why the run failed. `null` unless `status` is `failed`. */
36
+ error: string | null;
37
+ }
38
+ type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
39
+ type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
40
+
3
41
  /**
4
42
  * From this version uploads are `ready` at once and a run's `output` is plain
5
43
  * text with files in `attachments`. The handlers rely on both.
@@ -10,7 +48,7 @@ declare const MIN_API_VERSION: "2026-10-16";
10
48
  * and could change response shapes underneath a deployed app.
11
49
  */
12
50
  declare const DEFAULT_API_VERSION: "2026-10-28";
13
- interface SeclaiHandlersOptions {
51
+ interface SeclaiHandlersOptions<Ctx = undefined> {
14
52
  /** Seclai API key. Server-side only: never expose it to the browser. */
15
53
  apiKey: string;
16
54
  /** The agent these handlers run. */
@@ -19,7 +57,80 @@ interface SeclaiHandlersOptions {
19
57
  apiVersion?: ApiVersion;
20
58
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
21
59
  runTimeoutMs?: number;
60
+ /**
61
+ * Called with each event of a run stream, in order, and awaited before the
62
+ * event is relayed to the browser. If it throws, the stream ends with an
63
+ * `error` event.
64
+ */
65
+ onEvent?: RunEventCallback;
66
+ /**
67
+ * Called exactly once for each run that started streaming, with how it ended.
68
+ * Awaited before the final `done`, `error` or `timeout` event is relayed, so
69
+ * whatever it stores is in place when the browser sees the run end. If it
70
+ * throws, the browser gets an `error` event instead.
71
+ */
72
+ onRunEnd?: RunEndCallback;
73
+ /**
74
+ * What happens to a run when the browser disconnects: closes the tab, moves
75
+ * to another page, or aborts the request. The run itself always carries on at
76
+ * Seclai and uses credits.
77
+ *
78
+ * - `false` (default): the handler stops reading it. `onRunEnd` reports
79
+ * `cancelled` with what had streamed so far.
80
+ * - `true`: the handler keeps reading it in the background until it ends,
81
+ * still calling `onEvent` for each event, so `onRunEnd` gets the real
82
+ * outcome, with its output and files. Use it when `onRunEnd` saves replies.
83
+ * Reading stops at `runTimeoutMs` at the latest.
84
+ *
85
+ * Only takes effect with `onEvent` or `onRunEnd` set: without them there is
86
+ * nothing to read the rest of the run for.
87
+ */
88
+ keepReadingAfterDisconnect?: boolean;
89
+ /**
90
+ * Your app's per-request context (for example the signed-in user), passed to
91
+ * each hook as its last argument. Called only when a hook is about to run.
92
+ * Throw `deny(401, …)` here to refuse every hooked request at once. To pass
93
+ * context your framework already has instead, use
94
+ * {@link WithContext.withContext}.
95
+ */
96
+ context?: (req: Request) => Ctx | Promise<Ctx>;
97
+ /**
98
+ * Called after the `run` body has been validated, before the agent runs. Check
99
+ * `sessionId` and `uploadIds` against your own data here.
100
+ *
101
+ * Return nothing (or `true`) to run the body as it is, a rewritten body to run
102
+ * that instead (it is validated again), or `false` or a `Response` to refuse.
103
+ * `false` sends a 403. A rewritten body that fails validation gets a 500, and
104
+ * the reason is logged.
105
+ */
106
+ authorizeRun?: AuthorizeRun<Ctx>;
107
+ /**
108
+ * Called after `upload` has read the form, before the file is sent to Seclai.
109
+ * Return nothing (or `true`) to upload it, or `false` or a `Response` to
110
+ * refuse. `false` sends a 403.
111
+ */
112
+ authorizeUpload?: AuthorizeUpload<Ctx>;
113
+ /**
114
+ * Called after `download` has checked the ids' format, before the API call.
115
+ * Return `true` to serve the file, or `false` or a `Response` to refuse.
116
+ * `false` sends a 404, so a refusal doesn't confirm the file exists.
117
+ *
118
+ * Unlike the other hooks this one fails closed: returning nothing also
119
+ * refuses with a 404, and logs a warning, because it guards stored files.
120
+ */
121
+ authorizeDownload?: AuthorizeDownload<Ctx>;
122
+ }
123
+ /** See {@link SeclaiHandlersOptions.authorizeRun}. */
124
+ type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
125
+ /** See {@link SeclaiHandlersOptions.authorizeUpload}. */
126
+ type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
127
+ /** The ids a `download` request asks for. */
128
+ interface DownloadIds {
129
+ runId: string;
130
+ attachmentId: string;
22
131
  }
132
+ /** See {@link SeclaiHandlersOptions.authorizeDownload}. */
133
+ type AuthorizeDownload<Ctx = undefined> = (req: Request, ids: DownloadIds, ctx: Ctx) => boolean | Response | Promise<boolean | Response>;
23
134
  /** JSON body accepted by the `run` handler. */
24
135
  interface RunRequestBody {
25
136
  /** The prompt text. */
@@ -46,13 +157,51 @@ interface SeclaiHandlers {
46
157
  */
47
158
  handle: SeclaiHandler;
48
159
  }
160
+ /** What {@link createSeclaiHandlers} adds to the handlers. */
161
+ interface WithContext<Ctx> {
162
+ /**
163
+ * The same handlers, with `ctx` passed to the hooks instead of calling the
164
+ * `context` option. Use it when your framework already knows the user:
165
+ *
166
+ * ```ts
167
+ * export const action = ({ request, context }) =>
168
+ * seclai.withContext({ userId: context.get(user).id }).handle(request);
169
+ * ```
170
+ */
171
+ withContext(ctx: Ctx): SeclaiHandlers;
172
+ }
173
+ /**
174
+ * A refusal for a hook to return or throw: the `{ error, status }` JSON the
175
+ * handlers use for their own errors, which `@seclai/react` shows to the user.
176
+ *
177
+ * ```ts
178
+ * authorizeRun(req, body, { userId }) {
179
+ * if (!ownsSession(userId, body.sessionId)) return deny(403, "That isn't your conversation.");
180
+ * }
181
+ * ```
182
+ */
183
+ declare function deny(status: number, message: string, headers?: HeadersInit): Response;
184
+ /**
185
+ * The handlers {@link createSeclaiHandlers} returns without a `context` option.
186
+ * When the hooks need a context (`Ctx` doesn't include `undefined`), only
187
+ * `withContext` is offered, so a route can't call the hooks without one.
188
+ */
189
+ type UnboundSeclaiHandlers<Ctx> = undefined extends Ctx ? SeclaiHandlers & WithContext<Ctx> : WithContext<Ctx>;
49
190
  /**
50
191
  * Create the server handlers for one agent. Each takes a Web `Request` and
51
192
  * returns a Web `Response`, so they mount on any runtime with those APIs. Routing
52
193
  * is left to the host framework.
53
194
  *
195
+ * With a `context` option, the handlers resolve the hooks' context from each
196
+ * request. Without one, a typed context is passed with `withContext(ctx)`.
197
+ *
54
198
  * @throws If `apiKey` or `agentId` is missing, or `apiVersion` is too old.
55
199
  */
56
- declare function createSeclaiHandlers(options: SeclaiHandlersOptions): SeclaiHandlers;
200
+ declare function createSeclaiHandlers<Ctx>(options: SeclaiHandlersOptions<Ctx> & {
201
+ context: (req: Request) => Ctx | Promise<Ctx>;
202
+ }): SeclaiHandlers & WithContext<Ctx>;
203
+ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOptions<Ctx> & {
204
+ context?: undefined;
205
+ }): UnboundSeclaiHandlers<Ctx>;
57
206
 
58
- export { DEFAULT_API_VERSION, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, createSeclaiHandlers };
207
+ export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,43 @@
1
1
  import { ApiVersion } from '@seclai/sdk';
2
2
 
3
+ /** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
4
+ interface RunEvent {
5
+ event: string;
6
+ data: unknown;
7
+ }
8
+ /** What the run callbacks get besides the event or outcome. The same object for the whole run. */
9
+ interface RunCallbackContext {
10
+ /** The validated body of the `run` request. */
11
+ body: RunRequestBody;
12
+ /** The browser's request to the `run` handler. */
13
+ request: Request;
14
+ }
15
+ type RunOutcomeStatus = "completed" | "failed" | "cancelled";
16
+ /** A file the run produced, as stored with the outcome. Fetch it with the `download` handler. */
17
+ interface RunOutcomeAttachment {
18
+ id: string;
19
+ name: string | null;
20
+ mime: string;
21
+ }
22
+ /** How a run ended, as reported to `onRunEnd`. */
23
+ interface RunOutcome {
24
+ /** From `init` or `done`. `null` if the stream ended before either. */
25
+ runId: string | null;
26
+ /**
27
+ * `cancelled` means the browser went away before the run ended. The run
28
+ * itself may still finish on Seclai.
29
+ */
30
+ status: RunOutcomeStatus;
31
+ /** The run's output when it completed, otherwise the text streamed so far. */
32
+ output: string;
33
+ /** Files from `done`. Empty unless the run sent `done`. */
34
+ attachments: RunOutcomeAttachment[];
35
+ /** Why the run failed. `null` unless `status` is `failed`. */
36
+ error: string | null;
37
+ }
38
+ type RunEventCallback = (event: RunEvent, ctx: RunCallbackContext) => void | Promise<void>;
39
+ type RunEndCallback = (outcome: RunOutcome, ctx: RunCallbackContext) => void | Promise<void>;
40
+
3
41
  /**
4
42
  * From this version uploads are `ready` at once and a run's `output` is plain
5
43
  * text with files in `attachments`. The handlers rely on both.
@@ -10,7 +48,7 @@ declare const MIN_API_VERSION: "2026-10-16";
10
48
  * and could change response shapes underneath a deployed app.
11
49
  */
12
50
  declare const DEFAULT_API_VERSION: "2026-10-28";
13
- interface SeclaiHandlersOptions {
51
+ interface SeclaiHandlersOptions<Ctx = undefined> {
14
52
  /** Seclai API key. Server-side only: never expose it to the browser. */
15
53
  apiKey: string;
16
54
  /** The agent these handlers run. */
@@ -19,7 +57,80 @@ interface SeclaiHandlersOptions {
19
57
  apiVersion?: ApiVersion;
20
58
  /** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
21
59
  runTimeoutMs?: number;
60
+ /**
61
+ * Called with each event of a run stream, in order, and awaited before the
62
+ * event is relayed to the browser. If it throws, the stream ends with an
63
+ * `error` event.
64
+ */
65
+ onEvent?: RunEventCallback;
66
+ /**
67
+ * Called exactly once for each run that started streaming, with how it ended.
68
+ * Awaited before the final `done`, `error` or `timeout` event is relayed, so
69
+ * whatever it stores is in place when the browser sees the run end. If it
70
+ * throws, the browser gets an `error` event instead.
71
+ */
72
+ onRunEnd?: RunEndCallback;
73
+ /**
74
+ * What happens to a run when the browser disconnects: closes the tab, moves
75
+ * to another page, or aborts the request. The run itself always carries on at
76
+ * Seclai and uses credits.
77
+ *
78
+ * - `false` (default): the handler stops reading it. `onRunEnd` reports
79
+ * `cancelled` with what had streamed so far.
80
+ * - `true`: the handler keeps reading it in the background until it ends,
81
+ * still calling `onEvent` for each event, so `onRunEnd` gets the real
82
+ * outcome, with its output and files. Use it when `onRunEnd` saves replies.
83
+ * Reading stops at `runTimeoutMs` at the latest.
84
+ *
85
+ * Only takes effect with `onEvent` or `onRunEnd` set: without them there is
86
+ * nothing to read the rest of the run for.
87
+ */
88
+ keepReadingAfterDisconnect?: boolean;
89
+ /**
90
+ * Your app's per-request context (for example the signed-in user), passed to
91
+ * each hook as its last argument. Called only when a hook is about to run.
92
+ * Throw `deny(401, …)` here to refuse every hooked request at once. To pass
93
+ * context your framework already has instead, use
94
+ * {@link WithContext.withContext}.
95
+ */
96
+ context?: (req: Request) => Ctx | Promise<Ctx>;
97
+ /**
98
+ * Called after the `run` body has been validated, before the agent runs. Check
99
+ * `sessionId` and `uploadIds` against your own data here.
100
+ *
101
+ * Return nothing (or `true`) to run the body as it is, a rewritten body to run
102
+ * that instead (it is validated again), or `false` or a `Response` to refuse.
103
+ * `false` sends a 403. A rewritten body that fails validation gets a 500, and
104
+ * the reason is logged.
105
+ */
106
+ authorizeRun?: AuthorizeRun<Ctx>;
107
+ /**
108
+ * Called after `upload` has read the form, before the file is sent to Seclai.
109
+ * Return nothing (or `true`) to upload it, or `false` or a `Response` to
110
+ * refuse. `false` sends a 403.
111
+ */
112
+ authorizeUpload?: AuthorizeUpload<Ctx>;
113
+ /**
114
+ * Called after `download` has checked the ids' format, before the API call.
115
+ * Return `true` to serve the file, or `false` or a `Response` to refuse.
116
+ * `false` sends a 404, so a refusal doesn't confirm the file exists.
117
+ *
118
+ * Unlike the other hooks this one fails closed: returning nothing also
119
+ * refuses with a 404, and logs a warning, because it guards stored files.
120
+ */
121
+ authorizeDownload?: AuthorizeDownload<Ctx>;
122
+ }
123
+ /** See {@link SeclaiHandlersOptions.authorizeRun}. */
124
+ type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
125
+ /** See {@link SeclaiHandlersOptions.authorizeUpload}. */
126
+ type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
127
+ /** The ids a `download` request asks for. */
128
+ interface DownloadIds {
129
+ runId: string;
130
+ attachmentId: string;
22
131
  }
132
+ /** See {@link SeclaiHandlersOptions.authorizeDownload}. */
133
+ type AuthorizeDownload<Ctx = undefined> = (req: Request, ids: DownloadIds, ctx: Ctx) => boolean | Response | Promise<boolean | Response>;
23
134
  /** JSON body accepted by the `run` handler. */
24
135
  interface RunRequestBody {
25
136
  /** The prompt text. */
@@ -46,13 +157,51 @@ interface SeclaiHandlers {
46
157
  */
47
158
  handle: SeclaiHandler;
48
159
  }
160
+ /** What {@link createSeclaiHandlers} adds to the handlers. */
161
+ interface WithContext<Ctx> {
162
+ /**
163
+ * The same handlers, with `ctx` passed to the hooks instead of calling the
164
+ * `context` option. Use it when your framework already knows the user:
165
+ *
166
+ * ```ts
167
+ * export const action = ({ request, context }) =>
168
+ * seclai.withContext({ userId: context.get(user).id }).handle(request);
169
+ * ```
170
+ */
171
+ withContext(ctx: Ctx): SeclaiHandlers;
172
+ }
173
+ /**
174
+ * A refusal for a hook to return or throw: the `{ error, status }` JSON the
175
+ * handlers use for their own errors, which `@seclai/react` shows to the user.
176
+ *
177
+ * ```ts
178
+ * authorizeRun(req, body, { userId }) {
179
+ * if (!ownsSession(userId, body.sessionId)) return deny(403, "That isn't your conversation.");
180
+ * }
181
+ * ```
182
+ */
183
+ declare function deny(status: number, message: string, headers?: HeadersInit): Response;
184
+ /**
185
+ * The handlers {@link createSeclaiHandlers} returns without a `context` option.
186
+ * When the hooks need a context (`Ctx` doesn't include `undefined`), only
187
+ * `withContext` is offered, so a route can't call the hooks without one.
188
+ */
189
+ type UnboundSeclaiHandlers<Ctx> = undefined extends Ctx ? SeclaiHandlers & WithContext<Ctx> : WithContext<Ctx>;
49
190
  /**
50
191
  * Create the server handlers for one agent. Each takes a Web `Request` and
51
192
  * returns a Web `Response`, so they mount on any runtime with those APIs. Routing
52
193
  * is left to the host framework.
53
194
  *
195
+ * With a `context` option, the handlers resolve the hooks' context from each
196
+ * request. Without one, a typed context is passed with `withContext(ctx)`.
197
+ *
54
198
  * @throws If `apiKey` or `agentId` is missing, or `apiVersion` is too old.
55
199
  */
56
- declare function createSeclaiHandlers(options: SeclaiHandlersOptions): SeclaiHandlers;
200
+ declare function createSeclaiHandlers<Ctx>(options: SeclaiHandlersOptions<Ctx> & {
201
+ context: (req: Request) => Ctx | Promise<Ctx>;
202
+ }): SeclaiHandlers & WithContext<Ctx>;
203
+ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOptions<Ctx> & {
204
+ context?: undefined;
205
+ }): UnboundSeclaiHandlers<Ctx>;
57
206
 
58
- export { DEFAULT_API_VERSION, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, createSeclaiHandlers };
207
+ export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };