@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/README.md CHANGED
@@ -52,6 +52,75 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
52
52
  | `agentId` | Required | The agent to run |
53
53
  | `apiVersion` | `2026-10-28` | Dated API version. Must be `2026-10-16` or later |
54
54
  | `runTimeoutMs` | 11 minutes | How long a streaming run may take |
55
+ | `onEvent` | None | `(event, ctx)`: called with each run event before it is relayed. See [Run callbacks](#run-callbacks) |
56
+ | `onRunEnd` | None | `(outcome, ctx)`: called once per run with how it ended. See [Run callbacks](#run-callbacks) |
57
+ | `keepReadingAfterDisconnect` | `false` | Keep reading a run after the browser leaves, so `onRunEnd` gets its real outcome. See [Saving replies after a disconnect](#saving-replies-after-a-disconnect) |
58
+ | `context` | None | `(req)`: your per-request context, such as the signed-in user, passed to every hook. See [Access control](#access-control) |
59
+ | `authorizeRun` | None | `(req, body, ctx)`: refuse or rewrite a run. See [Access control](#access-control) |
60
+ | `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
61
+ | `authorizeDownload` | None | `(req, { runId, attachmentId }, ctx)`: return `true` to serve the file |
62
+
63
+ ### Access control
64
+
65
+ Three hooks check requests against your own data before they reach the API. They apply to the individual handlers and to `handle`, and may be sync or async.
66
+
67
+ ```ts
68
+ import { createSeclaiHandlers, deny } from "@seclai/handlers";
69
+
70
+ const seclai = createSeclaiHandlers({
71
+ apiKey: process.env.SECLAI_API_KEY!,
72
+ agentId: process.env.SECLAI_AGENT_ID!,
73
+
74
+ // Runs once per hooked request, only when a hook needs it.
75
+ async context(req) {
76
+ const user = await getUser(req);
77
+ if (!user) throw deny(401, "Sign in first.");
78
+ return { user };
79
+ },
80
+
81
+ async authorizeRun(req, body, { user }) {
82
+ if (body.sessionId && !(await db.sessionBelongsTo(body.sessionId, user.id))) {
83
+ return deny(403, "That isn't your conversation.");
84
+ }
85
+ // Returning nothing runs the body as it is.
86
+ },
87
+
88
+ authorizeUpload: (req, file, { user }) => user.canUpload,
89
+
90
+ async authorizeDownload(req, { runId }, { user }) {
91
+ return db.runBelongsTo(runId, user.id);
92
+ },
93
+ });
94
+ ```
95
+
96
+ **Allowing and refusing**
97
+
98
+ | Hook | Allow | Refuse |
99
+ |---|---|---|
100
+ | `authorizeRun` | Return nothing or `true`, or a rewritten body to run instead | `false` (403), or a `Response` |
101
+ | `authorizeUpload` | Return nothing or `true` | `false` (403), or a `Response` |
102
+ | `authorizeDownload` | Return `true` | `false` (404), or a `Response`. Returning nothing also refuses, and logs a warning |
103
+
104
+ - **Any hook can refuse by throwing a `Response`**, or by returning one, so a check deep in your data layer can `throw deny(...)`. The `context` function can too, which refuses every hooked request at once.
105
+ - **`deny(status, message)`** builds the same `{ error, status }` JSON the handlers use for their own errors. `@seclai/react` shows the `error` text to the user.
106
+ - **`authorizeDownload` fails closed** because it guards stored files: anything but `true` or a `Response` is a 404, the same as a missing file, so a refusal doesn't confirm the file exists.
107
+ - **Rewrites.** `authorizeRun` gets the body after `run` has validated it. It may return a rewritten body, for example to add context to `input` or swap in server-side `uploadIds`. The rewrite is validated again.
108
+ - **Errors.** If a hook or `context` throws anything other than a `Response`, the browser gets a 500 with a generic message, and the error is logged with `console.error`. A rewrite that fails validation is also a logged 500, with the reason.
109
+
110
+ **Context your framework already has**
111
+
112
+ When your framework has already resolved the user, pass it with `withContext` instead of the `context` option. It returns the same handlers with that context bound, so they keep the `(req) => Response` shape:
113
+
114
+ ```ts
115
+ // React Router: app/routes/api.seclai.$action.ts
116
+ const seclai = createSeclaiHandlers<{ userId: string }>({ apiKey, agentId, authorizeRun, authorizeDownload });
117
+
118
+ export const loader = ({ request, context }: Route.LoaderArgs) =>
119
+ seclai.withContext({ userId: context.get(userContext).id }).handle(request);
120
+ export const action = loader;
121
+ ```
122
+
123
+ The context's type is inferred from the `context` option, or set as the type parameter. Without a `context` option, a typed context is only reachable through `withContext`: TypeScript doesn't offer `seclai.handle` on its own, so a route can't call the hooks without the context. A context type that includes `undefined` keeps the plain handlers.
55
124
 
56
125
  ## The run stream
57
126
 
@@ -61,10 +130,82 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
61
130
  - If the stream fails after it has started, it ends with an `error` event carrying `{ error }`.
62
131
  - When the browser disconnects, the upstream connection closes. **The run itself keeps going on Seclai** and may keep using credits.
63
132
 
133
+ ## Run callbacks
134
+
135
+ `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.
136
+
137
+ ```ts
138
+ const seclai = createSeclaiHandlers({
139
+ apiKey: process.env.SECLAI_API_KEY!,
140
+ agentId: process.env.SECLAI_AGENT_ID!,
141
+ async onRunEnd(outcome, { body }) {
142
+ if (!body.sessionId) return;
143
+ await db.messages.insert({
144
+ sessionId: body.sessionId,
145
+ role: "assistant",
146
+ runId: outcome.runId,
147
+ status: outcome.status,
148
+ content: outcome.output,
149
+ attachments: outcome.attachments,
150
+ error: outcome.error,
151
+ });
152
+ },
153
+ });
154
+ ```
155
+
156
+ **`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.
157
+
158
+ **`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.
159
+
160
+ | `outcome` field | |
161
+ |---|---|
162
+ | `runId` | From `init` or `done`. `null` if the stream ended before either |
163
+ | `status` | `completed`, `failed` or `cancelled` |
164
+ | `output` | The run's output when it completed. Otherwise the text streamed in `stream_token` events so far |
165
+ | `attachments` | Files from `done`, as `{ id, name, mime }`. Fetch them with `download` |
166
+ | `error` | Why the run failed, or `null` |
167
+
168
+ | The run stream... | `status` | `error` |
169
+ |---|---|---|
170
+ | Sends `done` | `completed`, or `failed` if the run failed | The last attempt's error |
171
+ | Sends `error`, or the upstream connection fails | `failed` | The event's `error` |
172
+ | Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
173
+ | Ends with none of these | `failed` | `The stream ended without a result.` |
174
+ | Is cancelled by the browser | `cancelled`, unless `keepReadingAfterDisconnect` is on | `null` |
175
+
176
+ `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.
177
+
178
+ 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`.
179
+
180
+ If `onEvent` or `onRunEnd` throws or rejects, the handler logs the error with `console.error`, 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.
181
+
182
+ ### Saving replies after a disconnect
183
+
184
+ By default, when the browser leaves (it closes the tab, navigates to another chat, or aborts the request), the handler stops reading the run and `onRunEnd` reports `cancelled` with the text streamed so far. The run itself still finishes on Seclai and is billed, and a chat agent's memory keeps its reply, so an app that saves replies ends up with a turn the agent remembers but the app never showed.
185
+
186
+ Set `keepReadingAfterDisconnect: true` to keep reading the run in the background instead:
187
+
188
+ ```ts
189
+ const seclai = createSeclaiHandlers({
190
+ apiKey, agentId,
191
+ keepReadingAfterDisconnect: true,
192
+ onRunEnd: (outcome, { body }) => db.saveReply(body.sessionId, outcome),
193
+ });
194
+ ```
195
+
196
+ - **Callbacks.** The browser stops getting events, but `onEvent` still gets each one, and `onRunEnd` gets the run's real outcome with its output and files.
197
+ - **Outcomes.** A lost connection or a quiet end is reported as `failed`, since the browser leaving no longer stops the upstream, and `cancelled` doesn't occur. A callback that throws during the background reading is `failed` too.
198
+ - **Unread responses.** The handler also watches the request's signal, so it reads on even when the framework drops the response unread after the browser aborts. React Router does this when the browser leaves before the response starts.
199
+ - **Limits.** Reading the upstream stops at `runTimeoutMs` at the latest, and stops at once if a callback throws. A callback that never settles isn't bounded by it, so put a timeout on slow writes.
200
+ - **Show the reply when the user comes back.** For example, reload the conversation when it ends with a message that has no reply yet.
201
+ - **Serverless platforms** may freeze or end the function when the response closes, which cuts the background reading short. Use it on long-running servers, or check your platform's background-work support, such as `waitUntil`.
202
+
203
+ The option only takes effect with `onEvent` or `onRunEnd` set.
204
+
64
205
  ## Limits to know before deploying
65
206
 
66
- - **The endpoints have no auth.** Anyone who can reach them can run your agent on your credits. Put your own access control or rate limiting in front of a public deployment.
67
- - **The API key is account-wide.** `download` checks that ids are well formed, but the API only checks that a run belongs to the account, not to this agent. Anyone holding a run's id and a file's id from the same account could fetch that file. Run ids are random UUIDs, so they can't be guessed.
207
+ - **The endpoints have no auth by default.** Anyone who can reach them can run your agent on your credits. Use the [access-control hooks](#access-control) to check the caller, and put rate limiting in front of a public deployment. `attachment-references` has no hook, so guard that route yourself if the agent's accepted files are sensitive.
208
+ - **The API key is account-wide.** `download` checks that ids are well formed, but the API only checks that a run belongs to the account, not to this agent. Without [`authorizeDownload`](#access-control), anyone holding a run's id and a file's id from the same account could fetch that file. Run ids are random UUIDs, so they can't be guessed, but only your app knows which runs a caller may read.
68
209
  - **Uploads pass through your function**, so your platform's body limit applies, not the API's 200 MB: about 4.5 MB on Vercel and 6 MB on Netlify. The API has no CORS, so the browser can't upload to it directly.
69
210
  - **Your platform's function duration limit** may end a long run before `runTimeoutMs` does.
70
211