@seclai/handlers 0.0.13 → 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
@@ -204,7 +204,7 @@ const seclai = createSeclaiHandlers({
204
204
 
205
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.
206
206
 
207
- **`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.
208
208
 
209
209
  | `outcome` field | |
210
210
  |---|---|
@@ -221,9 +221,12 @@ const seclai = createSeclaiHandlers({
221
221
  | Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
222
222
  | Ends with none of these | `failed` | `The stream ended without a result.` |
223
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 |
224
225
 
225
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.
226
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
+
227
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`.
228
231
 
229
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 };
84
+ }
85
+ if (err instanceof import_sdk.SeclaiStreamingError) {
86
+ return { error: "Timed out waiting for the Seclai API.", status: 504 };
87
87
  }
88
+ return { error: "Could not reach the Seclai API.", status: 502 };
89
+ }
90
+ function runErrorBody(err) {
91
+ const body = toErrorBody(err);
88
92
  if (err instanceof import_sdk.SeclaiStreamingError) {
89
- return jsonError(504, "Timed out waiting for the Seclai API.");
93
+ body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
90
94
  }
91
- return jsonError(502, "Could not reach the Seclai API.");
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()),
@@ -955,7 +976,10 @@ function createSeclaiHandlers(options) {
955
976
  const upstream = new AbortController();
956
977
  const abort = () => upstream.abort();
957
978
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
958
- 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
+ }
959
983
  const log = logger && startRunLog(logger, {
960
984
  sessionId: body.sessionId,
961
985
  uploads: body.uploadIds?.length ?? 0,
@@ -992,10 +1016,16 @@ function createSeclaiHandlers(options) {
992
1016
  { headers: SSE_HEADERS }
993
1017
  );
994
1018
  } catch (err) {
995
- const res = toErrorResponse(err);
996
- if (!keepReading && req.signal?.aborted) log?.disconnected();
997
- else log?.rejected(err, res.status);
998
- 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);
999
1029
  }
1000
1030
  },
1001
1031
  async download(req) {
package/dist/index.d.cts CHANGED
@@ -148,10 +148,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
148
148
  */
149
149
  onEvent?: RunEventCallback<Ctx>;
150
150
  /**
151
- * Called exactly once for each run that started streaming, with how it ended.
152
- * Awaited before the final `done`, `error` or `timeout` event is relayed, so
153
- * whatever it stores is in place when the browser sees the run end. If it
154
- * 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.
155
162
  */
156
163
  onRunEnd?: RunEndCallback<Ctx>;
157
164
  /**
package/dist/index.d.ts CHANGED
@@ -148,10 +148,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
148
148
  */
149
149
  onEvent?: RunEventCallback<Ctx>;
150
150
  /**
151
- * Called exactly once for each run that started streaming, with how it ended.
152
- * Awaited before the final `done`, `error` or `timeout` event is relayed, so
153
- * whatever it stores is in place when the browser sees the run end. If it
154
- * 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.
155
162
  */
156
163
  onRunEnd?: RunEndCallback<Ctx>;
157
164
  /**
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 };
60
+ }
61
+ if (err instanceof SeclaiStreamingError) {
62
+ return { error: "Timed out waiting for the Seclai API.", status: 504 };
63
63
  }
64
+ return { error: "Could not reach the Seclai API.", status: 502 };
65
+ }
66
+ function runErrorBody(err) {
67
+ const body = toErrorBody(err);
64
68
  if (err instanceof SeclaiStreamingError) {
65
- return jsonError(504, "Timed out waiting for the Seclai API.");
69
+ body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
66
70
  }
67
- return jsonError(502, "Could not reach the Seclai API.");
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()),
@@ -931,7 +952,10 @@ function createSeclaiHandlers(options) {
931
952
  const upstream = new AbortController();
932
953
  const abort = () => upstream.abort();
933
954
  const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
934
- 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
+ }
935
959
  const log = logger && startRunLog(logger, {
936
960
  sessionId: body.sessionId,
937
961
  uploads: body.uploadIds?.length ?? 0,
@@ -968,10 +992,16 @@ function createSeclaiHandlers(options) {
968
992
  { headers: SSE_HEADERS }
969
993
  );
970
994
  } catch (err) {
971
- const res = toErrorResponse(err);
972
- if (!keepReading && req.signal?.aborted) log?.disconnected();
973
- else log?.rejected(err, res.status);
974
- 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);
975
1005
  }
976
1006
  },
977
1007
  async download(req) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.13",
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",