@seclai/handlers 0.0.7 → 0.0.9
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 +60 -2
- package/dist/index.cjs +331 -33
- package/dist/index.d.cts +33 -1
- package/dist/index.d.ts +33 -1
- package/dist/index.js +330 -33
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,6 +60,7 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
|
|
|
60
60
|
| `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
|
|
61
61
|
| `authorizeDownload` | None | `(req, { runId, attachmentId }, ctx)`: return `true` to serve the file |
|
|
62
62
|
| `upload` | None | Size limit, content-type check and hook for `upload`, below |
|
|
63
|
+
| `logger` | None | `{ debug, info, warn, error }`, such as `console`: gets a line for each step of a run, upload and download. See [Logging](#logging) |
|
|
63
64
|
|
|
64
65
|
### Upload options
|
|
65
66
|
|
|
@@ -134,7 +135,7 @@ const seclai = createSeclaiHandlers({
|
|
|
134
135
|
- **`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.
|
|
135
136
|
- **`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.
|
|
136
137
|
- **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.
|
|
137
|
-
- **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
|
|
138
|
+
- **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 `logger.error` if you set a [`logger`](#logging) and `console.error` otherwise. A rewrite that fails validation is also a logged 500, with the reason.
|
|
138
139
|
|
|
139
140
|
**Context your framework already has**
|
|
140
141
|
|
|
@@ -206,7 +207,7 @@ const seclai = createSeclaiHandlers({
|
|
|
206
207
|
|
|
207
208
|
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`.
|
|
208
209
|
|
|
209
|
-
If `onEvent` or `onRunEnd` throws or rejects, the handler logs the error with `console.error
|
|
210
|
+
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.
|
|
210
211
|
|
|
211
212
|
### Saving replies after a disconnect
|
|
212
213
|
|
|
@@ -231,6 +232,63 @@ const seclai = createSeclaiHandlers({
|
|
|
231
232
|
|
|
232
233
|
The option only takes effect with `onEvent` or `onRunEnd` set.
|
|
233
234
|
|
|
235
|
+
## Logging
|
|
236
|
+
|
|
237
|
+
Pass a `logger` to see what the handlers saw: when the stream opened, which steps ran, when the first token arrived and how the run ended. Each method is called as `(message, fields)`, with short, stable messages and the ids, timings and counts in `fields`, so `console` works, and so do winston and consola. Without a `logger`, the handlers log nothing.
|
|
238
|
+
|
|
239
|
+
pino takes its arguments the other way round, `(fields, message)`, and would drop the fields, so wrap it:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
const log = pino();
|
|
243
|
+
const logger = {
|
|
244
|
+
debug: (m, f) => log.debug(f, m),
|
|
245
|
+
info: (m, f) => log.info(f, m),
|
|
246
|
+
warn: (m, f) => log.warn(f, m),
|
|
247
|
+
error: (m, f) => log.error(f, m),
|
|
248
|
+
};
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
import { consoleLogger, createSeclaiHandlers } from "@seclai/handlers";
|
|
253
|
+
|
|
254
|
+
const seclai = createSeclaiHandlers({
|
|
255
|
+
apiKey: process.env.SECLAI_API_KEY!,
|
|
256
|
+
agentId: process.env.SECLAI_AGENT_ID!,
|
|
257
|
+
logger: console,
|
|
258
|
+
// Or drop the debug lines, and prefix each message with `[seclai]`:
|
|
259
|
+
// logger: consoleLogger("info"),
|
|
260
|
+
});
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
A run with `logger: console` logs lines like these (debug lines left out, run ids shortened):
|
|
264
|
+
|
|
265
|
+
```
|
|
266
|
+
run starting { session_id: 'chat-42', uploads: 1, input_chars: 38 }
|
|
267
|
+
stream open { session_id: 'chat-42', ms: 412 }
|
|
268
|
+
run started { run_id: '3f2b8c1e-7a4d-4e9b-9c11-0d5e6f7a8b9c', session_id: 'chat-42' }
|
|
269
|
+
step { run_id: '3f2b8c1e-…', session_id: 'chat-42', step: 'Describe photo', message: 'started' }
|
|
270
|
+
first token { run_id: '3f2b8c1e-…', session_id: 'chat-42', ms: 2310 }
|
|
271
|
+
streaming { run_id: '3f2b8c1e-…', session_id: 'chat-42', tokens: 214, chars: 905, ms: 7318 }
|
|
272
|
+
run done { run_id: '3f2b8c1e-…', session_id: 'chat-42', status: 'completed', attachments: 2, tokens: 388, output_chars: 1622, ms: 11904 }
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
| Level | Lines |
|
|
276
|
+
|---|---|
|
|
277
|
+
| `info` | `run starting`, `stream open` (`ms` to the first event), `run started` (the `run_id` from `init`), `step` for each `step_progress` (once while the same step and message repeat), `first token`, `streaming` (every 5 seconds while tokens arrive), `run done`, `browser disconnected; the run continues on Seclai` (or, with `keepReadingAfterDisconnect`, `browser left; reading the rest of the run in the background`, and the run's end when it comes), `upload received`, `uploaded`, `download served`, and `run refused`, `upload refused` or `download refused` (with the `status`) when an [access-control hook](#access-control), `maxBytes` or `checkContentType` turns a request away |
|
|
278
|
+
| `warn` | `run failed` (a `done` with status `failed`), `stream ended without a result`, and a warning when a completed run streamed no tokens |
|
|
279
|
+
| `error` | `run rejected` (the API refused the run up front, with `status`, `upstream_status` and the API's `error`), `stream error` (with the real `cause` when the connection failed), `run timed out`, `run failed: a callback threw`, `upload failed`, `download failed`, callback errors from `onEvent` and `onRunEnd`, and errors from the access-control hooks, `context` and `onUpload` |
|
|
280
|
+
| `debug` | Every event, each token (its length, not its text) and each keepalive |
|
|
281
|
+
|
|
282
|
+
The line for how a run ended (`run done`, `run failed`, `stream error`, `run timed out`) is logged after `onEvent` and `onRunEnd` have handled it, so it matches the outcome they reported. If one of them throws while the browser is still connected, `run failed: a callback threw` is logged in its place. After a disconnect, the line reflects the outcome `onRunEnd` received (usually `browser disconnected`).
|
|
283
|
+
|
|
284
|
+
A completed run with no tokens usually means the agent's result step is `display_result` rather than `streaming_result`: the reply then arrives all at once in `done`, which looks like broken streaming.
|
|
285
|
+
|
|
286
|
+
`run rejected` and the other error lines carry the upstream status and message, which matters when the browser only sees a 502 (for a bad API key, say).
|
|
287
|
+
|
|
288
|
+
The lines never include the API key, the input text, or file contents. A logger that throws is ignored, so it can't break a run or an upload, and logging doesn't change what the browser receives.
|
|
289
|
+
|
|
290
|
+
`consoleLogger(level?, target?)` returns a logger that writes from `level` up (`debug`, `info`, `warn`, `error` or `silent`; default `info`) to `target` (default `console`), prefixing each message with `[seclai]`. Pass your own logger as `target` to add a level threshold to it.
|
|
291
|
+
|
|
234
292
|
## Limits to know before deploying
|
|
235
293
|
|
|
236
294
|
- **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.
|
package/dist/index.cjs
CHANGED
|
@@ -23,6 +23,7 @@ __export(index_exports, {
|
|
|
23
23
|
ATTACHMENT_SLOTS_TTL_MS: () => ATTACHMENT_SLOTS_TTL_MS,
|
|
24
24
|
DEFAULT_API_VERSION: () => DEFAULT_API_VERSION,
|
|
25
25
|
MIN_API_VERSION: () => MIN_API_VERSION,
|
|
26
|
+
consoleLogger: () => consoleLogger,
|
|
26
27
|
createSeclaiHandlers: () => createSeclaiHandlers,
|
|
27
28
|
deny: () => deny
|
|
28
29
|
});
|
|
@@ -95,6 +96,49 @@ function streamErrorMessage(err) {
|
|
|
95
96
|
}
|
|
96
97
|
return "The connection to the Seclai API was lost.";
|
|
97
98
|
}
|
|
99
|
+
function errorLogFields(err) {
|
|
100
|
+
if (err instanceof import_sdk.SeclaiAPIStatusError) {
|
|
101
|
+
return {
|
|
102
|
+
upstream_status: err.statusCode,
|
|
103
|
+
error: upstreamMessage(err.responseText) ?? err.message
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
if (err instanceof Error) return { error: err.message };
|
|
107
|
+
return { error: String(err) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/logger.ts
|
|
111
|
+
var ORDER = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
|
112
|
+
function consoleLogger(level = "info", target = console) {
|
|
113
|
+
const threshold = ORDER[level] ?? ORDER.info;
|
|
114
|
+
const method = (name) => (message, fields) => {
|
|
115
|
+
if (ORDER[name] < threshold) return;
|
|
116
|
+
const line = `[seclai] ${message}`;
|
|
117
|
+
if (fields === void 0) target[name](line);
|
|
118
|
+
else target[name](line, fields);
|
|
119
|
+
};
|
|
120
|
+
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
121
|
+
}
|
|
122
|
+
var MIN_SECRET_LENGTH = 8;
|
|
123
|
+
function safeLogger(logger, secret) {
|
|
124
|
+
const scrub = secret && secret.length >= MIN_SECRET_LENGTH ? (value) => value.split(secret).join("[redacted]") : (value) => value;
|
|
125
|
+
const method = (name) => (message, fields) => {
|
|
126
|
+
try {
|
|
127
|
+
if (fields === void 0) {
|
|
128
|
+
logger[name](scrub(message));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const clean = {};
|
|
132
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
133
|
+
if (value === void 0) continue;
|
|
134
|
+
clean[key] = typeof value === "string" ? scrub(value) : value;
|
|
135
|
+
}
|
|
136
|
+
logger[name](scrub(message), clean);
|
|
137
|
+
} catch {
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
141
|
+
}
|
|
98
142
|
|
|
99
143
|
// src/sse.ts
|
|
100
144
|
var KEEPALIVE_INTERVAL_MS = 15e3;
|
|
@@ -183,6 +227,10 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
183
227
|
next = await events.next();
|
|
184
228
|
} catch (err) {
|
|
185
229
|
if (closed) return;
|
|
230
|
+
try {
|
|
231
|
+
observer?.onConnectionError?.(err);
|
|
232
|
+
} catch {
|
|
233
|
+
}
|
|
186
234
|
await relay(
|
|
187
235
|
controller,
|
|
188
236
|
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
@@ -218,6 +266,10 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
218
266
|
next = await events.next();
|
|
219
267
|
} catch (err) {
|
|
220
268
|
if (closed) return;
|
|
269
|
+
try {
|
|
270
|
+
observer?.onConnectionError?.(err);
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
221
273
|
await relay(
|
|
222
274
|
controller,
|
|
223
275
|
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
@@ -264,7 +316,12 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
264
316
|
start(controller) {
|
|
265
317
|
ctrl = controller;
|
|
266
318
|
keepalive = setInterval(() => {
|
|
267
|
-
if (
|
|
319
|
+
if (closed || cancelled) return;
|
|
320
|
+
controller.enqueue(encoder.encode(": keepalive\n\n"));
|
|
321
|
+
try {
|
|
322
|
+
observer?.onKeepalive?.();
|
|
323
|
+
} catch {
|
|
324
|
+
}
|
|
268
325
|
}, KEEPALIVE_INTERVAL_MS);
|
|
269
326
|
if (keepReading && options.signal) {
|
|
270
327
|
const { signal } = options;
|
|
@@ -323,11 +380,12 @@ function toAttachments(raw) {
|
|
|
323
380
|
);
|
|
324
381
|
}
|
|
325
382
|
function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
326
|
-
const { onEvent, onRunEnd } = callbacks;
|
|
383
|
+
const { onEvent, onRunEnd, log } = callbacks;
|
|
327
384
|
const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
|
|
328
385
|
let runId = null;
|
|
329
386
|
let text = "";
|
|
330
387
|
let terminal;
|
|
388
|
+
let terminalEvent;
|
|
331
389
|
let ended = false;
|
|
332
390
|
const outcome = (o) => ({
|
|
333
391
|
runId,
|
|
@@ -342,6 +400,10 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
342
400
|
const failed = (error) => outcome({ status: "failed", output: text, error });
|
|
343
401
|
const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
|
|
344
402
|
const record = (event, source) => {
|
|
403
|
+
note(event, source);
|
|
404
|
+
if (terminal && !terminalEvent) terminalEvent = { event, source };
|
|
405
|
+
};
|
|
406
|
+
const note = (event, source) => {
|
|
345
407
|
const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
|
|
346
408
|
if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
|
|
347
409
|
if (terminal) return;
|
|
@@ -378,25 +440,205 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
378
440
|
};
|
|
379
441
|
return {
|
|
380
442
|
async onEvent(event, source) {
|
|
443
|
+
log?.event(event);
|
|
381
444
|
record(event, source);
|
|
382
445
|
await onEvent?.(event, ctx);
|
|
383
446
|
if (terminal) await end(terminal);
|
|
447
|
+
if (terminalEvent?.event === event) log?.result(event, source);
|
|
384
448
|
},
|
|
385
449
|
onUnrelayed(event) {
|
|
450
|
+
log?.event(event);
|
|
386
451
|
record(event, "upstream");
|
|
387
452
|
},
|
|
388
453
|
async onClose(reason) {
|
|
454
|
+
try {
|
|
455
|
+
switch (reason) {
|
|
456
|
+
case "end":
|
|
457
|
+
return await end(
|
|
458
|
+
terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE))
|
|
459
|
+
);
|
|
460
|
+
case "error":
|
|
461
|
+
return await end(failed(OBSERVER_ERROR_MESSAGE));
|
|
462
|
+
case "cancel":
|
|
463
|
+
return await end(terminal ?? cancelled());
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
if (reason === "cancel" && terminalEvent) {
|
|
467
|
+
log?.result(terminalEvent.event, terminalEvent.source);
|
|
468
|
+
}
|
|
469
|
+
log?.close(reason);
|
|
470
|
+
}
|
|
471
|
+
},
|
|
472
|
+
onError(err) {
|
|
473
|
+
if (log) log.callbackError(err);
|
|
474
|
+
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
475
|
+
},
|
|
476
|
+
onKeepalive: log && (() => log.keepalive()),
|
|
477
|
+
onDisconnect: log && (() => log.readingOn()),
|
|
478
|
+
onConnectionError: log && ((err) => log.connectionError(err))
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/run-log.ts
|
|
483
|
+
var PROGRESS_INTERVAL_MS = 5e3;
|
|
484
|
+
var ZERO_TOKENS_MESSAGE = "no tokens streamed: the agent's result step may be `display_result` rather than `streaming_result`";
|
|
485
|
+
function startRunLog(log, start) {
|
|
486
|
+
const startedAt = Date.now();
|
|
487
|
+
let runId = null;
|
|
488
|
+
let tokens = 0;
|
|
489
|
+
let chars = 0;
|
|
490
|
+
let firstTokenAt = null;
|
|
491
|
+
let lastProgressAt = 0;
|
|
492
|
+
let lastStep = null;
|
|
493
|
+
let ended = false;
|
|
494
|
+
let cause;
|
|
495
|
+
const ms = () => Date.now() - startedAt;
|
|
496
|
+
const ctx = (fields) => ({
|
|
497
|
+
run_id: runId ?? void 0,
|
|
498
|
+
session_id: start.sessionId,
|
|
499
|
+
...fields
|
|
500
|
+
});
|
|
501
|
+
const disconnected = () => {
|
|
502
|
+
if (ended) return;
|
|
503
|
+
ended = true;
|
|
504
|
+
log.info("browser disconnected; the run continues on Seclai", ctx({ tokens, ms: ms() }));
|
|
505
|
+
};
|
|
506
|
+
log.info("run starting", {
|
|
507
|
+
session_id: start.sessionId,
|
|
508
|
+
uploads: start.uploads,
|
|
509
|
+
input_chars: start.inputChars
|
|
510
|
+
});
|
|
511
|
+
return {
|
|
512
|
+
opened(empty) {
|
|
513
|
+
if (empty) log.info("stream open", ctx({ ms: ms(), empty: true }));
|
|
514
|
+
else log.info("stream open", ctx({ ms: ms() }));
|
|
515
|
+
},
|
|
516
|
+
disconnected,
|
|
517
|
+
readingOn() {
|
|
518
|
+
if (ended) return;
|
|
519
|
+
log.info("browser left; reading the rest of the run in the background", ctx({ tokens, ms: ms() }));
|
|
520
|
+
},
|
|
521
|
+
rejected(err, status) {
|
|
522
|
+
log.error("run rejected", ctx({ status, ...errorLogFields(err), ms: ms() }));
|
|
523
|
+
},
|
|
524
|
+
event({ event, data }) {
|
|
525
|
+
const payload = typeof data === "object" && data !== null ? data : {};
|
|
526
|
+
if (runId === null && typeof payload.run_id === "string") runId = payload.run_id;
|
|
527
|
+
switch (event) {
|
|
528
|
+
case "init":
|
|
529
|
+
log.debug("event", ctx({ event }));
|
|
530
|
+
log.info("run started", ctx());
|
|
531
|
+
return;
|
|
532
|
+
case "step_progress": {
|
|
533
|
+
log.debug("event", ctx({ event }));
|
|
534
|
+
const step = typeof payload.step_name === "string" && payload.step_name ? payload.step_name : String(payload.step_id ?? "?");
|
|
535
|
+
const message = typeof payload.message === "string" ? payload.message : "";
|
|
536
|
+
const key = `${step}
|
|
537
|
+
${message}`;
|
|
538
|
+
if (key === lastStep) return;
|
|
539
|
+
lastStep = key;
|
|
540
|
+
log.info("step", ctx({ step, message: message || void 0 }));
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
case "stream_token": {
|
|
544
|
+
const length = typeof payload.token === "string" ? payload.token.length : 0;
|
|
545
|
+
tokens += 1;
|
|
546
|
+
chars += length;
|
|
547
|
+
log.debug("token", ctx({ n: tokens, chars: length }));
|
|
548
|
+
const now = Date.now();
|
|
549
|
+
if (firstTokenAt === null) {
|
|
550
|
+
firstTokenAt = now;
|
|
551
|
+
lastProgressAt = now;
|
|
552
|
+
log.info("first token", ctx({ ms: now - startedAt }));
|
|
553
|
+
} else if (now - lastProgressAt >= PROGRESS_INTERVAL_MS) {
|
|
554
|
+
lastProgressAt = now;
|
|
555
|
+
log.info("streaming", ctx({ tokens, chars, ms: now - startedAt }));
|
|
556
|
+
}
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
case "done":
|
|
560
|
+
if (typeof payload.run_id === "string") runId = payload.run_id;
|
|
561
|
+
log.debug("event", ctx({ event }));
|
|
562
|
+
return;
|
|
563
|
+
default:
|
|
564
|
+
log.debug("event", ctx({ event }));
|
|
565
|
+
}
|
|
566
|
+
},
|
|
567
|
+
result({ event, data }, source) {
|
|
568
|
+
if (ended) return;
|
|
569
|
+
const payload = typeof data === "object" && data !== null ? data : {};
|
|
570
|
+
switch (event) {
|
|
571
|
+
case "done": {
|
|
572
|
+
ended = true;
|
|
573
|
+
const output = typeof payload.output === "string" ? payload.output : "";
|
|
574
|
+
const fields = ctx({
|
|
575
|
+
status: payload.status,
|
|
576
|
+
attachments: Array.isArray(payload.attachments) ? payload.attachments.length : 0,
|
|
577
|
+
tokens,
|
|
578
|
+
output_chars: output.length || chars,
|
|
579
|
+
ms: ms()
|
|
580
|
+
});
|
|
581
|
+
if (payload.status === "failed") {
|
|
582
|
+
log.warn("run failed", { ...fields, error: lastAttemptError(payload) ?? void 0 });
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
log.info("run done", fields);
|
|
586
|
+
if (tokens === 0) log.warn(ZERO_TOKENS_MESSAGE, ctx());
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
case "error":
|
|
590
|
+
if (source === "connection-lost" && start.disconnected()) {
|
|
591
|
+
disconnected();
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
ended = true;
|
|
595
|
+
log.error(
|
|
596
|
+
"stream error",
|
|
597
|
+
ctx({
|
|
598
|
+
error: payload.error,
|
|
599
|
+
...source === "connection-lost" ? cause : void 0,
|
|
600
|
+
tokens,
|
|
601
|
+
ms: ms()
|
|
602
|
+
})
|
|
603
|
+
);
|
|
604
|
+
return;
|
|
605
|
+
case "timeout":
|
|
606
|
+
ended = true;
|
|
607
|
+
log.error("run timed out", ctx({ tokens, ms: ms() }));
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
},
|
|
611
|
+
connectionError(err) {
|
|
612
|
+
const { error, upstream_status } = errorLogFields(err);
|
|
613
|
+
cause = { cause: error, upstream_status };
|
|
614
|
+
},
|
|
615
|
+
keepalive() {
|
|
616
|
+
log.debug("keepalive", ctx({ ms: ms() }));
|
|
617
|
+
},
|
|
618
|
+
close(reason) {
|
|
619
|
+
if (ended) {
|
|
620
|
+
log.debug("stream closed", ctx({ reason, ms: ms() }));
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
389
623
|
switch (reason) {
|
|
624
|
+
case "cancel":
|
|
625
|
+
disconnected();
|
|
626
|
+
return;
|
|
390
627
|
case "end":
|
|
391
|
-
|
|
628
|
+
if (start.disconnected()) disconnected();
|
|
629
|
+
else {
|
|
630
|
+
ended = true;
|
|
631
|
+
log.warn("stream ended without a result", ctx({ tokens, ms: ms() }));
|
|
632
|
+
}
|
|
633
|
+
return;
|
|
392
634
|
case "error":
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
return
|
|
635
|
+
ended = true;
|
|
636
|
+
log.error("run failed: a callback threw", ctx({ status: "failed", tokens, ms: ms() }));
|
|
637
|
+
return;
|
|
396
638
|
}
|
|
397
639
|
},
|
|
398
|
-
|
|
399
|
-
|
|
640
|
+
callbackError(err) {
|
|
641
|
+
log.error("an onEvent or onRunEnd callback threw", ctx({ error: err }));
|
|
400
642
|
}
|
|
401
643
|
};
|
|
402
644
|
}
|
|
@@ -499,6 +741,16 @@ function createSeclaiHandlers(options) {
|
|
|
499
741
|
authorizeDownload
|
|
500
742
|
} = options;
|
|
501
743
|
const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
|
|
744
|
+
const logger = options.logger && safeLogger(options.logger, apiKey);
|
|
745
|
+
function reportError(message, err) {
|
|
746
|
+
if (logger) logger.error(message, err === void 0 ? void 0 : errorLogFields(err));
|
|
747
|
+
else if (err === void 0) console.error(`[seclai] ${message}`);
|
|
748
|
+
else console.error(`[seclai] ${message}`, err);
|
|
749
|
+
}
|
|
750
|
+
function refused(what, res, fields = {}) {
|
|
751
|
+
logger?.info(`${what} refused`, { ...fields, status: res.status });
|
|
752
|
+
return res;
|
|
753
|
+
}
|
|
502
754
|
if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
|
|
503
755
|
if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
|
|
504
756
|
if (apiVersion < MIN_API_VERSION) {
|
|
@@ -540,7 +792,7 @@ function createSeclaiHandlers(options) {
|
|
|
540
792
|
} catch (err) {
|
|
541
793
|
if (err instanceof Response) return { response: err };
|
|
542
794
|
const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
|
|
543
|
-
|
|
795
|
+
reportError(`${name} threw, so the request got a 500.${hint}`, err);
|
|
544
796
|
return { response: jsonError(500, NOT_AUTHORIZED) };
|
|
545
797
|
}
|
|
546
798
|
}
|
|
@@ -559,12 +811,12 @@ function createSeclaiHandlers(options) {
|
|
|
559
811
|
const bodyLimit = maxBytes === void 0 ? void 0 : maxBytes + MULTIPART_OVERHEAD_BYTES;
|
|
560
812
|
if (bodyLimit !== void 0) {
|
|
561
813
|
const length = Number(req.headers.get("content-length"));
|
|
562
|
-
if (length > bodyLimit) return tooLarge();
|
|
814
|
+
if (length > bodyLimit) return refused("upload", tooLarge(), { content_length: length });
|
|
563
815
|
}
|
|
564
816
|
let form;
|
|
565
817
|
try {
|
|
566
818
|
const read = bodyLimit === void 0 ? await req.formData() : await readLimitedForm(req, bodyLimit);
|
|
567
|
-
if (read === "too-large") return tooLarge();
|
|
819
|
+
if (read === "too-large") return refused("upload", tooLarge(), { reason: "body over limit" });
|
|
568
820
|
form = read;
|
|
569
821
|
} catch {
|
|
570
822
|
return jsonError(400, "The request body must be multipart form data.");
|
|
@@ -573,7 +825,10 @@ function createSeclaiHandlers(options) {
|
|
|
573
825
|
if (file === null || typeof file === "string") {
|
|
574
826
|
return jsonError(400, "The form must include a `file` field holding a file.");
|
|
575
827
|
}
|
|
576
|
-
|
|
828
|
+
const started = Date.now();
|
|
829
|
+
const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
|
|
830
|
+
logger?.info("upload received", fileFields);
|
|
831
|
+
if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
|
|
577
832
|
if (authorizeUpload) {
|
|
578
833
|
const result2 = await callHook(
|
|
579
834
|
"authorizeUpload",
|
|
@@ -581,12 +836,14 @@ function createSeclaiHandlers(options) {
|
|
|
581
836
|
resolveCtx,
|
|
582
837
|
(ctx) => authorizeUpload(req, file, ctx)
|
|
583
838
|
);
|
|
584
|
-
if ("response" in result2) return result2.response;
|
|
839
|
+
if ("response" in result2) return refused("upload", result2.response, fileFields);
|
|
585
840
|
const allowed = result2.value;
|
|
586
|
-
if (allowed instanceof Response) return allowed;
|
|
587
|
-
if (allowed === false) return jsonError(403, "This upload isn't allowed.");
|
|
841
|
+
if (allowed instanceof Response) return refused("upload", allowed, fileFields);
|
|
842
|
+
if (allowed === false) return refused("upload", jsonError(403, "This upload isn't allowed."), fileFields);
|
|
588
843
|
if (allowed !== void 0 && allowed !== true) {
|
|
589
|
-
|
|
844
|
+
reportError(
|
|
845
|
+
`authorizeUpload returned ${String(allowed)}, not true, false, nothing or a Response, so the request got a 500.`
|
|
846
|
+
);
|
|
590
847
|
return jsonError(500, NOT_AUTHORIZED);
|
|
591
848
|
}
|
|
592
849
|
}
|
|
@@ -596,7 +853,7 @@ function createSeclaiHandlers(options) {
|
|
|
596
853
|
if (checkContentType && !UNKNOWN_TYPES.has(type)) {
|
|
597
854
|
const accepted = await attachmentSlots();
|
|
598
855
|
if (!accepted.some((slot) => slotAllows(slot, type))) {
|
|
599
|
-
return jsonError(415, `This agent does not accept files of type ${type}.`);
|
|
856
|
+
return refused("upload", jsonError(415, `This agent does not accept files of type ${type}.`), fileFields);
|
|
600
857
|
}
|
|
601
858
|
}
|
|
602
859
|
const upload = await client.uploadAgentInput(agentId, {
|
|
@@ -611,14 +868,28 @@ function createSeclaiHandlers(options) {
|
|
|
611
868
|
content_type: upload.content_type,
|
|
612
869
|
file_size: upload.file_size
|
|
613
870
|
};
|
|
871
|
+
logger?.info("uploaded", {
|
|
872
|
+
...fileFields,
|
|
873
|
+
upload_id: upload.id,
|
|
874
|
+
status: upload.status,
|
|
875
|
+
ms: Date.now() - started
|
|
876
|
+
});
|
|
614
877
|
} catch (err) {
|
|
615
|
-
|
|
878
|
+
const res = toErrorResponse(err);
|
|
879
|
+
logger?.error("upload failed", {
|
|
880
|
+
...fileFields,
|
|
881
|
+
status: res.status,
|
|
882
|
+
...errorLogFields(err),
|
|
883
|
+
ms: Date.now() - started
|
|
884
|
+
});
|
|
885
|
+
return res;
|
|
616
886
|
}
|
|
617
887
|
if (onUpload) {
|
|
618
888
|
try {
|
|
619
889
|
const replacement = await onUpload(file, result, req);
|
|
620
890
|
if (replacement instanceof Response) return replacement;
|
|
621
|
-
} catch {
|
|
891
|
+
} catch (err) {
|
|
892
|
+
reportError("onUpload threw, so the request got a 500.", err);
|
|
622
893
|
return jsonError(500, "The server failed to finish handling the upload.");
|
|
623
894
|
}
|
|
624
895
|
}
|
|
@@ -642,15 +913,15 @@ function createSeclaiHandlers(options) {
|
|
|
642
913
|
resolveCtx,
|
|
643
914
|
(ctx) => authorizeRun(req, parsed, ctx)
|
|
644
915
|
);
|
|
645
|
-
if ("response" in result) return result.response;
|
|
916
|
+
if ("response" in result) return refused("run", result.response);
|
|
646
917
|
const verdict = result.value;
|
|
647
|
-
if (verdict instanceof Response) return verdict;
|
|
648
|
-
if (verdict === false) return jsonError(403, "This request isn't allowed.");
|
|
918
|
+
if (verdict instanceof Response) return refused("run", verdict);
|
|
919
|
+
if (verdict === false) return refused("run", jsonError(403, "This request isn't allowed."));
|
|
649
920
|
const kept = verdict === void 0 || verdict === true;
|
|
650
921
|
const rewritten = parseRunBody(kept ? parsed : verdict);
|
|
651
922
|
if (typeof rewritten === "string") {
|
|
652
|
-
|
|
653
|
-
kept ? `
|
|
923
|
+
reportError(
|
|
924
|
+
kept ? `authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
|
|
654
925
|
);
|
|
655
926
|
return jsonError(500, NOT_AUTHORIZED);
|
|
656
927
|
}
|
|
@@ -660,6 +931,14 @@ function createSeclaiHandlers(options) {
|
|
|
660
931
|
const abort = () => upstream.abort();
|
|
661
932
|
const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
|
|
662
933
|
if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
|
|
934
|
+
const log = logger && startRunLog(logger, {
|
|
935
|
+
sessionId: body.sessionId,
|
|
936
|
+
uploads: body.uploadIds?.length ?? 0,
|
|
937
|
+
inputChars: body.input?.length ?? 0,
|
|
938
|
+
// Kept reading, the browser leaving doesn't stop the upstream, so a
|
|
939
|
+
// failure after it is a real one.
|
|
940
|
+
disconnected: () => !keepReading && (req.signal?.aborted ?? false)
|
|
941
|
+
});
|
|
663
942
|
const events = client.runStreamingAgent(
|
|
664
943
|
agentId,
|
|
665
944
|
{
|
|
@@ -671,7 +950,8 @@ function createSeclaiHandlers(options) {
|
|
|
671
950
|
);
|
|
672
951
|
try {
|
|
673
952
|
const first = await events.next();
|
|
674
|
-
|
|
953
|
+
log?.opened(Boolean(first.done));
|
|
954
|
+
const observer = onEvent || onRunEnd || log ? createRunObserver({ onEvent, onRunEnd, log }, { body, request: req }, { keepReading }) : void 0;
|
|
675
955
|
return new Response(
|
|
676
956
|
relayRunEvents(
|
|
677
957
|
first.done ? void 0 : first.value,
|
|
@@ -683,7 +963,10 @@ function createSeclaiHandlers(options) {
|
|
|
683
963
|
{ headers: SSE_HEADERS }
|
|
684
964
|
);
|
|
685
965
|
} catch (err) {
|
|
686
|
-
|
|
966
|
+
const res = toErrorResponse(err);
|
|
967
|
+
if (!keepReading && req.signal?.aborted) log?.disconnected();
|
|
968
|
+
else log?.rejected(err, res.status);
|
|
969
|
+
return res;
|
|
687
970
|
}
|
|
688
971
|
},
|
|
689
972
|
async download(req) {
|
|
@@ -706,16 +989,17 @@ function createSeclaiHandlers(options) {
|
|
|
706
989
|
resolveCtx,
|
|
707
990
|
(ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
|
|
708
991
|
);
|
|
709
|
-
|
|
992
|
+
const ids = { run_id: runId, attachment_id: attachmentId };
|
|
993
|
+
if ("response" in result) return refused("download", result.response, ids);
|
|
710
994
|
const allowed = result.value;
|
|
711
|
-
if (allowed instanceof Response) return allowed;
|
|
995
|
+
if (allowed instanceof Response) return refused("download", allowed, ids);
|
|
712
996
|
if (allowed !== true && allowed !== false && !warnedDownloadResult) {
|
|
713
997
|
warnedDownloadResult = true;
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
);
|
|
998
|
+
const warning = `authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`;
|
|
999
|
+
if (logger) logger.warn(warning);
|
|
1000
|
+
else console.warn(`[seclai] ${warning}`);
|
|
717
1001
|
}
|
|
718
|
-
if (allowed !== true) return jsonError(404, "Not found.");
|
|
1002
|
+
if (allowed !== true) return refused("download", jsonError(404, "Not found."), ids);
|
|
719
1003
|
}
|
|
720
1004
|
try {
|
|
721
1005
|
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
@@ -737,9 +1021,22 @@ function createSeclaiHandlers(options) {
|
|
|
737
1021
|
if (!contentType.toLowerCase().startsWith("application/pdf")) {
|
|
738
1022
|
headers.set("content-security-policy", "sandbox; default-src 'none'");
|
|
739
1023
|
}
|
|
1024
|
+
logger?.info("download served", {
|
|
1025
|
+
run_id: runId,
|
|
1026
|
+
attachment_id: attachmentId,
|
|
1027
|
+
status: upstream.status,
|
|
1028
|
+
content_type: contentType
|
|
1029
|
+
});
|
|
740
1030
|
return new Response(upstream.body, { status: upstream.status, headers });
|
|
741
1031
|
} catch (err) {
|
|
742
|
-
|
|
1032
|
+
const res = toErrorResponse(err);
|
|
1033
|
+
logger?.error("download failed", {
|
|
1034
|
+
run_id: runId,
|
|
1035
|
+
attachment_id: attachmentId,
|
|
1036
|
+
status: res.status,
|
|
1037
|
+
...errorLogFields(err)
|
|
1038
|
+
});
|
|
1039
|
+
return res;
|
|
743
1040
|
}
|
|
744
1041
|
}
|
|
745
1042
|
};
|
|
@@ -763,6 +1060,7 @@ function createSeclaiHandlers(options) {
|
|
|
763
1060
|
ATTACHMENT_SLOTS_TTL_MS,
|
|
764
1061
|
DEFAULT_API_VERSION,
|
|
765
1062
|
MIN_API_VERSION,
|
|
1063
|
+
consoleLogger,
|
|
766
1064
|
createSeclaiHandlers,
|
|
767
1065
|
deny
|
|
768
1066
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
import { ApiVersion } from '@seclai/sdk';
|
|
2
2
|
|
|
3
|
+
/** Structured details of a log line: ids, timings and counts. */
|
|
4
|
+
type SeclaiLogFields = Record<string, unknown>;
|
|
5
|
+
/**
|
|
6
|
+
* Where the handlers send their log lines, each called as `(message, fields)`.
|
|
7
|
+
* `console` fits, and so do winston and consola. pino takes `(fields, message)`
|
|
8
|
+
* and would drop the fields, so wrap it, one line per level:
|
|
9
|
+
* `info: (m, f) => log.info(f, m)`.
|
|
10
|
+
*/
|
|
11
|
+
interface SeclaiLogger {
|
|
12
|
+
debug(message: string, fields?: SeclaiLogFields): void;
|
|
13
|
+
info(message: string, fields?: SeclaiLogFields): void;
|
|
14
|
+
warn(message: string, fields?: SeclaiLogFields): void;
|
|
15
|
+
error(message: string, fields?: SeclaiLogFields): void;
|
|
16
|
+
}
|
|
17
|
+
type SeclaiLogLevel = "debug" | "info" | "warn" | "error" | "silent";
|
|
18
|
+
/**
|
|
19
|
+
* A {@link SeclaiLogger} that writes to `console` from `level` up, with each
|
|
20
|
+
* message prefixed `[seclai]`. Passing `console` itself also works, but logs
|
|
21
|
+
* `debug` lines too: every token and keepalive.
|
|
22
|
+
*
|
|
23
|
+
* @param level - The lowest level written. Defaults to `info`.
|
|
24
|
+
* @param target - Where to write. Defaults to `console`.
|
|
25
|
+
*/
|
|
26
|
+
declare function consoleLogger(level?: SeclaiLogLevel, target?: SeclaiLogger): SeclaiLogger;
|
|
27
|
+
|
|
3
28
|
/** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
|
|
4
29
|
interface RunEvent {
|
|
5
30
|
event: string;
|
|
@@ -133,6 +158,13 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
133
158
|
* nothing to read the rest of the run for.
|
|
134
159
|
*/
|
|
135
160
|
keepReadingAfterDisconnect?: boolean;
|
|
161
|
+
/**
|
|
162
|
+
* Receives log lines about runs, uploads and downloads, with ids, timings and
|
|
163
|
+
* counts in `fields`. `console` works. Never given the API key, the input
|
|
164
|
+
* text or file contents. Without one, nothing is logged, and the few errors
|
|
165
|
+
* the handlers report themselves go to `console`.
|
|
166
|
+
*/
|
|
167
|
+
logger?: SeclaiLogger;
|
|
136
168
|
/**
|
|
137
169
|
* Your app's per-request context (for example the signed-in user), passed to
|
|
138
170
|
* each hook as its last argument. Called only when a hook is about to run.
|
|
@@ -251,4 +283,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
|
|
|
251
283
|
context?: undefined;
|
|
252
284
|
}): UnboundSeclaiHandlers<Ctx>;
|
|
253
285
|
|
|
254
|
-
export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, createSeclaiHandlers, deny };
|
|
286
|
+
export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
import { ApiVersion } from '@seclai/sdk';
|
|
2
2
|
|
|
3
|
+
/** Structured details of a log line: ids, timings and counts. */
|
|
4
|
+
type SeclaiLogFields = Record<string, unknown>;
|
|
5
|
+
/**
|
|
6
|
+
* Where the handlers send their log lines, each called as `(message, fields)`.
|
|
7
|
+
* `console` fits, and so do winston and consola. pino takes `(fields, message)`
|
|
8
|
+
* and would drop the fields, so wrap it, one line per level:
|
|
9
|
+
* `info: (m, f) => log.info(f, m)`.
|
|
10
|
+
*/
|
|
11
|
+
interface SeclaiLogger {
|
|
12
|
+
debug(message: string, fields?: SeclaiLogFields): void;
|
|
13
|
+
info(message: string, fields?: SeclaiLogFields): void;
|
|
14
|
+
warn(message: string, fields?: SeclaiLogFields): void;
|
|
15
|
+
error(message: string, fields?: SeclaiLogFields): void;
|
|
16
|
+
}
|
|
17
|
+
type SeclaiLogLevel = "debug" | "info" | "warn" | "error" | "silent";
|
|
18
|
+
/**
|
|
19
|
+
* A {@link SeclaiLogger} that writes to `console` from `level` up, with each
|
|
20
|
+
* message prefixed `[seclai]`. Passing `console` itself also works, but logs
|
|
21
|
+
* `debug` lines too: every token and keepalive.
|
|
22
|
+
*
|
|
23
|
+
* @param level - The lowest level written. Defaults to `info`.
|
|
24
|
+
* @param target - Where to write. Defaults to `console`.
|
|
25
|
+
*/
|
|
26
|
+
declare function consoleLogger(level?: SeclaiLogLevel, target?: SeclaiLogger): SeclaiLogger;
|
|
27
|
+
|
|
3
28
|
/** One event of the run stream, as the API sent it. `data` is the parsed JSON. */
|
|
4
29
|
interface RunEvent {
|
|
5
30
|
event: string;
|
|
@@ -133,6 +158,13 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
133
158
|
* nothing to read the rest of the run for.
|
|
134
159
|
*/
|
|
135
160
|
keepReadingAfterDisconnect?: boolean;
|
|
161
|
+
/**
|
|
162
|
+
* Receives log lines about runs, uploads and downloads, with ids, timings and
|
|
163
|
+
* counts in `fields`. `console` works. Never given the API key, the input
|
|
164
|
+
* text or file contents. Without one, nothing is logged, and the few errors
|
|
165
|
+
* the handlers report themselves go to `console`.
|
|
166
|
+
*/
|
|
167
|
+
logger?: SeclaiLogger;
|
|
136
168
|
/**
|
|
137
169
|
* Your app's per-request context (for example the signed-in user), passed to
|
|
138
170
|
* each hook as its last argument. Called only when a hook is about to run.
|
|
@@ -251,4 +283,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
|
|
|
251
283
|
context?: undefined;
|
|
252
284
|
}): UnboundSeclaiHandlers<Ctx>;
|
|
253
285
|
|
|
254
|
-
export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, createSeclaiHandlers, deny };
|
|
286
|
+
export { ATTACHMENT_SLOTS_TTL_MS, 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 SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
|
package/dist/index.js
CHANGED
|
@@ -72,6 +72,49 @@ function streamErrorMessage(err) {
|
|
|
72
72
|
}
|
|
73
73
|
return "The connection to the Seclai API was lost.";
|
|
74
74
|
}
|
|
75
|
+
function errorLogFields(err) {
|
|
76
|
+
if (err instanceof SeclaiAPIStatusError) {
|
|
77
|
+
return {
|
|
78
|
+
upstream_status: err.statusCode,
|
|
79
|
+
error: upstreamMessage(err.responseText) ?? err.message
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (err instanceof Error) return { error: err.message };
|
|
83
|
+
return { error: String(err) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/logger.ts
|
|
87
|
+
var ORDER = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
|
88
|
+
function consoleLogger(level = "info", target = console) {
|
|
89
|
+
const threshold = ORDER[level] ?? ORDER.info;
|
|
90
|
+
const method = (name) => (message, fields) => {
|
|
91
|
+
if (ORDER[name] < threshold) return;
|
|
92
|
+
const line = `[seclai] ${message}`;
|
|
93
|
+
if (fields === void 0) target[name](line);
|
|
94
|
+
else target[name](line, fields);
|
|
95
|
+
};
|
|
96
|
+
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
97
|
+
}
|
|
98
|
+
var MIN_SECRET_LENGTH = 8;
|
|
99
|
+
function safeLogger(logger, secret) {
|
|
100
|
+
const scrub = secret && secret.length >= MIN_SECRET_LENGTH ? (value) => value.split(secret).join("[redacted]") : (value) => value;
|
|
101
|
+
const method = (name) => (message, fields) => {
|
|
102
|
+
try {
|
|
103
|
+
if (fields === void 0) {
|
|
104
|
+
logger[name](scrub(message));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const clean = {};
|
|
108
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
109
|
+
if (value === void 0) continue;
|
|
110
|
+
clean[key] = typeof value === "string" ? scrub(value) : value;
|
|
111
|
+
}
|
|
112
|
+
logger[name](scrub(message), clean);
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
117
|
+
}
|
|
75
118
|
|
|
76
119
|
// src/sse.ts
|
|
77
120
|
var KEEPALIVE_INTERVAL_MS = 15e3;
|
|
@@ -160,6 +203,10 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
160
203
|
next = await events.next();
|
|
161
204
|
} catch (err) {
|
|
162
205
|
if (closed) return;
|
|
206
|
+
try {
|
|
207
|
+
observer?.onConnectionError?.(err);
|
|
208
|
+
} catch {
|
|
209
|
+
}
|
|
163
210
|
await relay(
|
|
164
211
|
controller,
|
|
165
212
|
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
@@ -195,6 +242,10 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
195
242
|
next = await events.next();
|
|
196
243
|
} catch (err) {
|
|
197
244
|
if (closed) return;
|
|
245
|
+
try {
|
|
246
|
+
observer?.onConnectionError?.(err);
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
198
249
|
await relay(
|
|
199
250
|
controller,
|
|
200
251
|
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
@@ -241,7 +292,12 @@ function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
|
241
292
|
start(controller) {
|
|
242
293
|
ctrl = controller;
|
|
243
294
|
keepalive = setInterval(() => {
|
|
244
|
-
if (
|
|
295
|
+
if (closed || cancelled) return;
|
|
296
|
+
controller.enqueue(encoder.encode(": keepalive\n\n"));
|
|
297
|
+
try {
|
|
298
|
+
observer?.onKeepalive?.();
|
|
299
|
+
} catch {
|
|
300
|
+
}
|
|
245
301
|
}, KEEPALIVE_INTERVAL_MS);
|
|
246
302
|
if (keepReading && options.signal) {
|
|
247
303
|
const { signal } = options;
|
|
@@ -300,11 +356,12 @@ function toAttachments(raw) {
|
|
|
300
356
|
);
|
|
301
357
|
}
|
|
302
358
|
function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
303
|
-
const { onEvent, onRunEnd } = callbacks;
|
|
359
|
+
const { onEvent, onRunEnd, log } = callbacks;
|
|
304
360
|
const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
|
|
305
361
|
let runId = null;
|
|
306
362
|
let text = "";
|
|
307
363
|
let terminal;
|
|
364
|
+
let terminalEvent;
|
|
308
365
|
let ended = false;
|
|
309
366
|
const outcome = (o) => ({
|
|
310
367
|
runId,
|
|
@@ -319,6 +376,10 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
319
376
|
const failed = (error) => outcome({ status: "failed", output: text, error });
|
|
320
377
|
const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
|
|
321
378
|
const record = (event, source) => {
|
|
379
|
+
note(event, source);
|
|
380
|
+
if (terminal && !terminalEvent) terminalEvent = { event, source };
|
|
381
|
+
};
|
|
382
|
+
const note = (event, source) => {
|
|
322
383
|
const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
|
|
323
384
|
if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
|
|
324
385
|
if (terminal) return;
|
|
@@ -355,25 +416,205 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
355
416
|
};
|
|
356
417
|
return {
|
|
357
418
|
async onEvent(event, source) {
|
|
419
|
+
log?.event(event);
|
|
358
420
|
record(event, source);
|
|
359
421
|
await onEvent?.(event, ctx);
|
|
360
422
|
if (terminal) await end(terminal);
|
|
423
|
+
if (terminalEvent?.event === event) log?.result(event, source);
|
|
361
424
|
},
|
|
362
425
|
onUnrelayed(event) {
|
|
426
|
+
log?.event(event);
|
|
363
427
|
record(event, "upstream");
|
|
364
428
|
},
|
|
365
429
|
async onClose(reason) {
|
|
430
|
+
try {
|
|
431
|
+
switch (reason) {
|
|
432
|
+
case "end":
|
|
433
|
+
return await end(
|
|
434
|
+
terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE))
|
|
435
|
+
);
|
|
436
|
+
case "error":
|
|
437
|
+
return await end(failed(OBSERVER_ERROR_MESSAGE));
|
|
438
|
+
case "cancel":
|
|
439
|
+
return await end(terminal ?? cancelled());
|
|
440
|
+
}
|
|
441
|
+
} finally {
|
|
442
|
+
if (reason === "cancel" && terminalEvent) {
|
|
443
|
+
log?.result(terminalEvent.event, terminalEvent.source);
|
|
444
|
+
}
|
|
445
|
+
log?.close(reason);
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
onError(err) {
|
|
449
|
+
if (log) log.callbackError(err);
|
|
450
|
+
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
451
|
+
},
|
|
452
|
+
onKeepalive: log && (() => log.keepalive()),
|
|
453
|
+
onDisconnect: log && (() => log.readingOn()),
|
|
454
|
+
onConnectionError: log && ((err) => log.connectionError(err))
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// src/run-log.ts
|
|
459
|
+
var PROGRESS_INTERVAL_MS = 5e3;
|
|
460
|
+
var ZERO_TOKENS_MESSAGE = "no tokens streamed: the agent's result step may be `display_result` rather than `streaming_result`";
|
|
461
|
+
function startRunLog(log, start) {
|
|
462
|
+
const startedAt = Date.now();
|
|
463
|
+
let runId = null;
|
|
464
|
+
let tokens = 0;
|
|
465
|
+
let chars = 0;
|
|
466
|
+
let firstTokenAt = null;
|
|
467
|
+
let lastProgressAt = 0;
|
|
468
|
+
let lastStep = null;
|
|
469
|
+
let ended = false;
|
|
470
|
+
let cause;
|
|
471
|
+
const ms = () => Date.now() - startedAt;
|
|
472
|
+
const ctx = (fields) => ({
|
|
473
|
+
run_id: runId ?? void 0,
|
|
474
|
+
session_id: start.sessionId,
|
|
475
|
+
...fields
|
|
476
|
+
});
|
|
477
|
+
const disconnected = () => {
|
|
478
|
+
if (ended) return;
|
|
479
|
+
ended = true;
|
|
480
|
+
log.info("browser disconnected; the run continues on Seclai", ctx({ tokens, ms: ms() }));
|
|
481
|
+
};
|
|
482
|
+
log.info("run starting", {
|
|
483
|
+
session_id: start.sessionId,
|
|
484
|
+
uploads: start.uploads,
|
|
485
|
+
input_chars: start.inputChars
|
|
486
|
+
});
|
|
487
|
+
return {
|
|
488
|
+
opened(empty) {
|
|
489
|
+
if (empty) log.info("stream open", ctx({ ms: ms(), empty: true }));
|
|
490
|
+
else log.info("stream open", ctx({ ms: ms() }));
|
|
491
|
+
},
|
|
492
|
+
disconnected,
|
|
493
|
+
readingOn() {
|
|
494
|
+
if (ended) return;
|
|
495
|
+
log.info("browser left; reading the rest of the run in the background", ctx({ tokens, ms: ms() }));
|
|
496
|
+
},
|
|
497
|
+
rejected(err, status) {
|
|
498
|
+
log.error("run rejected", ctx({ status, ...errorLogFields(err), ms: ms() }));
|
|
499
|
+
},
|
|
500
|
+
event({ event, data }) {
|
|
501
|
+
const payload = typeof data === "object" && data !== null ? data : {};
|
|
502
|
+
if (runId === null && typeof payload.run_id === "string") runId = payload.run_id;
|
|
503
|
+
switch (event) {
|
|
504
|
+
case "init":
|
|
505
|
+
log.debug("event", ctx({ event }));
|
|
506
|
+
log.info("run started", ctx());
|
|
507
|
+
return;
|
|
508
|
+
case "step_progress": {
|
|
509
|
+
log.debug("event", ctx({ event }));
|
|
510
|
+
const step = typeof payload.step_name === "string" && payload.step_name ? payload.step_name : String(payload.step_id ?? "?");
|
|
511
|
+
const message = typeof payload.message === "string" ? payload.message : "";
|
|
512
|
+
const key = `${step}
|
|
513
|
+
${message}`;
|
|
514
|
+
if (key === lastStep) return;
|
|
515
|
+
lastStep = key;
|
|
516
|
+
log.info("step", ctx({ step, message: message || void 0 }));
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
case "stream_token": {
|
|
520
|
+
const length = typeof payload.token === "string" ? payload.token.length : 0;
|
|
521
|
+
tokens += 1;
|
|
522
|
+
chars += length;
|
|
523
|
+
log.debug("token", ctx({ n: tokens, chars: length }));
|
|
524
|
+
const now = Date.now();
|
|
525
|
+
if (firstTokenAt === null) {
|
|
526
|
+
firstTokenAt = now;
|
|
527
|
+
lastProgressAt = now;
|
|
528
|
+
log.info("first token", ctx({ ms: now - startedAt }));
|
|
529
|
+
} else if (now - lastProgressAt >= PROGRESS_INTERVAL_MS) {
|
|
530
|
+
lastProgressAt = now;
|
|
531
|
+
log.info("streaming", ctx({ tokens, chars, ms: now - startedAt }));
|
|
532
|
+
}
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
case "done":
|
|
536
|
+
if (typeof payload.run_id === "string") runId = payload.run_id;
|
|
537
|
+
log.debug("event", ctx({ event }));
|
|
538
|
+
return;
|
|
539
|
+
default:
|
|
540
|
+
log.debug("event", ctx({ event }));
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
result({ event, data }, source) {
|
|
544
|
+
if (ended) return;
|
|
545
|
+
const payload = typeof data === "object" && data !== null ? data : {};
|
|
546
|
+
switch (event) {
|
|
547
|
+
case "done": {
|
|
548
|
+
ended = true;
|
|
549
|
+
const output = typeof payload.output === "string" ? payload.output : "";
|
|
550
|
+
const fields = ctx({
|
|
551
|
+
status: payload.status,
|
|
552
|
+
attachments: Array.isArray(payload.attachments) ? payload.attachments.length : 0,
|
|
553
|
+
tokens,
|
|
554
|
+
output_chars: output.length || chars,
|
|
555
|
+
ms: ms()
|
|
556
|
+
});
|
|
557
|
+
if (payload.status === "failed") {
|
|
558
|
+
log.warn("run failed", { ...fields, error: lastAttemptError(payload) ?? void 0 });
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
log.info("run done", fields);
|
|
562
|
+
if (tokens === 0) log.warn(ZERO_TOKENS_MESSAGE, ctx());
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
case "error":
|
|
566
|
+
if (source === "connection-lost" && start.disconnected()) {
|
|
567
|
+
disconnected();
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
ended = true;
|
|
571
|
+
log.error(
|
|
572
|
+
"stream error",
|
|
573
|
+
ctx({
|
|
574
|
+
error: payload.error,
|
|
575
|
+
...source === "connection-lost" ? cause : void 0,
|
|
576
|
+
tokens,
|
|
577
|
+
ms: ms()
|
|
578
|
+
})
|
|
579
|
+
);
|
|
580
|
+
return;
|
|
581
|
+
case "timeout":
|
|
582
|
+
ended = true;
|
|
583
|
+
log.error("run timed out", ctx({ tokens, ms: ms() }));
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
},
|
|
587
|
+
connectionError(err) {
|
|
588
|
+
const { error, upstream_status } = errorLogFields(err);
|
|
589
|
+
cause = { cause: error, upstream_status };
|
|
590
|
+
},
|
|
591
|
+
keepalive() {
|
|
592
|
+
log.debug("keepalive", ctx({ ms: ms() }));
|
|
593
|
+
},
|
|
594
|
+
close(reason) {
|
|
595
|
+
if (ended) {
|
|
596
|
+
log.debug("stream closed", ctx({ reason, ms: ms() }));
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
366
599
|
switch (reason) {
|
|
600
|
+
case "cancel":
|
|
601
|
+
disconnected();
|
|
602
|
+
return;
|
|
367
603
|
case "end":
|
|
368
|
-
|
|
604
|
+
if (start.disconnected()) disconnected();
|
|
605
|
+
else {
|
|
606
|
+
ended = true;
|
|
607
|
+
log.warn("stream ended without a result", ctx({ tokens, ms: ms() }));
|
|
608
|
+
}
|
|
609
|
+
return;
|
|
369
610
|
case "error":
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
return
|
|
611
|
+
ended = true;
|
|
612
|
+
log.error("run failed: a callback threw", ctx({ status: "failed", tokens, ms: ms() }));
|
|
613
|
+
return;
|
|
373
614
|
}
|
|
374
615
|
},
|
|
375
|
-
|
|
376
|
-
|
|
616
|
+
callbackError(err) {
|
|
617
|
+
log.error("an onEvent or onRunEnd callback threw", ctx({ error: err }));
|
|
377
618
|
}
|
|
378
619
|
};
|
|
379
620
|
}
|
|
@@ -476,6 +717,16 @@ function createSeclaiHandlers(options) {
|
|
|
476
717
|
authorizeDownload
|
|
477
718
|
} = options;
|
|
478
719
|
const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
|
|
720
|
+
const logger = options.logger && safeLogger(options.logger, apiKey);
|
|
721
|
+
function reportError(message, err) {
|
|
722
|
+
if (logger) logger.error(message, err === void 0 ? void 0 : errorLogFields(err));
|
|
723
|
+
else if (err === void 0) console.error(`[seclai] ${message}`);
|
|
724
|
+
else console.error(`[seclai] ${message}`, err);
|
|
725
|
+
}
|
|
726
|
+
function refused(what, res, fields = {}) {
|
|
727
|
+
logger?.info(`${what} refused`, { ...fields, status: res.status });
|
|
728
|
+
return res;
|
|
729
|
+
}
|
|
479
730
|
if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
|
|
480
731
|
if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
|
|
481
732
|
if (apiVersion < MIN_API_VERSION) {
|
|
@@ -517,7 +768,7 @@ function createSeclaiHandlers(options) {
|
|
|
517
768
|
} catch (err) {
|
|
518
769
|
if (err instanceof Response) return { response: err };
|
|
519
770
|
const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
|
|
520
|
-
|
|
771
|
+
reportError(`${name} threw, so the request got a 500.${hint}`, err);
|
|
521
772
|
return { response: jsonError(500, NOT_AUTHORIZED) };
|
|
522
773
|
}
|
|
523
774
|
}
|
|
@@ -536,12 +787,12 @@ function createSeclaiHandlers(options) {
|
|
|
536
787
|
const bodyLimit = maxBytes === void 0 ? void 0 : maxBytes + MULTIPART_OVERHEAD_BYTES;
|
|
537
788
|
if (bodyLimit !== void 0) {
|
|
538
789
|
const length = Number(req.headers.get("content-length"));
|
|
539
|
-
if (length > bodyLimit) return tooLarge();
|
|
790
|
+
if (length > bodyLimit) return refused("upload", tooLarge(), { content_length: length });
|
|
540
791
|
}
|
|
541
792
|
let form;
|
|
542
793
|
try {
|
|
543
794
|
const read = bodyLimit === void 0 ? await req.formData() : await readLimitedForm(req, bodyLimit);
|
|
544
|
-
if (read === "too-large") return tooLarge();
|
|
795
|
+
if (read === "too-large") return refused("upload", tooLarge(), { reason: "body over limit" });
|
|
545
796
|
form = read;
|
|
546
797
|
} catch {
|
|
547
798
|
return jsonError(400, "The request body must be multipart form data.");
|
|
@@ -550,7 +801,10 @@ function createSeclaiHandlers(options) {
|
|
|
550
801
|
if (file === null || typeof file === "string") {
|
|
551
802
|
return jsonError(400, "The form must include a `file` field holding a file.");
|
|
552
803
|
}
|
|
553
|
-
|
|
804
|
+
const started = Date.now();
|
|
805
|
+
const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
|
|
806
|
+
logger?.info("upload received", fileFields);
|
|
807
|
+
if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
|
|
554
808
|
if (authorizeUpload) {
|
|
555
809
|
const result2 = await callHook(
|
|
556
810
|
"authorizeUpload",
|
|
@@ -558,12 +812,14 @@ function createSeclaiHandlers(options) {
|
|
|
558
812
|
resolveCtx,
|
|
559
813
|
(ctx) => authorizeUpload(req, file, ctx)
|
|
560
814
|
);
|
|
561
|
-
if ("response" in result2) return result2.response;
|
|
815
|
+
if ("response" in result2) return refused("upload", result2.response, fileFields);
|
|
562
816
|
const allowed = result2.value;
|
|
563
|
-
if (allowed instanceof Response) return allowed;
|
|
564
|
-
if (allowed === false) return jsonError(403, "This upload isn't allowed.");
|
|
817
|
+
if (allowed instanceof Response) return refused("upload", allowed, fileFields);
|
|
818
|
+
if (allowed === false) return refused("upload", jsonError(403, "This upload isn't allowed."), fileFields);
|
|
565
819
|
if (allowed !== void 0 && allowed !== true) {
|
|
566
|
-
|
|
820
|
+
reportError(
|
|
821
|
+
`authorizeUpload returned ${String(allowed)}, not true, false, nothing or a Response, so the request got a 500.`
|
|
822
|
+
);
|
|
567
823
|
return jsonError(500, NOT_AUTHORIZED);
|
|
568
824
|
}
|
|
569
825
|
}
|
|
@@ -573,7 +829,7 @@ function createSeclaiHandlers(options) {
|
|
|
573
829
|
if (checkContentType && !UNKNOWN_TYPES.has(type)) {
|
|
574
830
|
const accepted = await attachmentSlots();
|
|
575
831
|
if (!accepted.some((slot) => slotAllows(slot, type))) {
|
|
576
|
-
return jsonError(415, `This agent does not accept files of type ${type}.`);
|
|
832
|
+
return refused("upload", jsonError(415, `This agent does not accept files of type ${type}.`), fileFields);
|
|
577
833
|
}
|
|
578
834
|
}
|
|
579
835
|
const upload = await client.uploadAgentInput(agentId, {
|
|
@@ -588,14 +844,28 @@ function createSeclaiHandlers(options) {
|
|
|
588
844
|
content_type: upload.content_type,
|
|
589
845
|
file_size: upload.file_size
|
|
590
846
|
};
|
|
847
|
+
logger?.info("uploaded", {
|
|
848
|
+
...fileFields,
|
|
849
|
+
upload_id: upload.id,
|
|
850
|
+
status: upload.status,
|
|
851
|
+
ms: Date.now() - started
|
|
852
|
+
});
|
|
591
853
|
} catch (err) {
|
|
592
|
-
|
|
854
|
+
const res = toErrorResponse(err);
|
|
855
|
+
logger?.error("upload failed", {
|
|
856
|
+
...fileFields,
|
|
857
|
+
status: res.status,
|
|
858
|
+
...errorLogFields(err),
|
|
859
|
+
ms: Date.now() - started
|
|
860
|
+
});
|
|
861
|
+
return res;
|
|
593
862
|
}
|
|
594
863
|
if (onUpload) {
|
|
595
864
|
try {
|
|
596
865
|
const replacement = await onUpload(file, result, req);
|
|
597
866
|
if (replacement instanceof Response) return replacement;
|
|
598
|
-
} catch {
|
|
867
|
+
} catch (err) {
|
|
868
|
+
reportError("onUpload threw, so the request got a 500.", err);
|
|
599
869
|
return jsonError(500, "The server failed to finish handling the upload.");
|
|
600
870
|
}
|
|
601
871
|
}
|
|
@@ -619,15 +889,15 @@ function createSeclaiHandlers(options) {
|
|
|
619
889
|
resolveCtx,
|
|
620
890
|
(ctx) => authorizeRun(req, parsed, ctx)
|
|
621
891
|
);
|
|
622
|
-
if ("response" in result) return result.response;
|
|
892
|
+
if ("response" in result) return refused("run", result.response);
|
|
623
893
|
const verdict = result.value;
|
|
624
|
-
if (verdict instanceof Response) return verdict;
|
|
625
|
-
if (verdict === false) return jsonError(403, "This request isn't allowed.");
|
|
894
|
+
if (verdict instanceof Response) return refused("run", verdict);
|
|
895
|
+
if (verdict === false) return refused("run", jsonError(403, "This request isn't allowed."));
|
|
626
896
|
const kept = verdict === void 0 || verdict === true;
|
|
627
897
|
const rewritten = parseRunBody(kept ? parsed : verdict);
|
|
628
898
|
if (typeof rewritten === "string") {
|
|
629
|
-
|
|
630
|
-
kept ? `
|
|
899
|
+
reportError(
|
|
900
|
+
kept ? `authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
|
|
631
901
|
);
|
|
632
902
|
return jsonError(500, NOT_AUTHORIZED);
|
|
633
903
|
}
|
|
@@ -637,6 +907,14 @@ function createSeclaiHandlers(options) {
|
|
|
637
907
|
const abort = () => upstream.abort();
|
|
638
908
|
const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
|
|
639
909
|
if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
|
|
910
|
+
const log = logger && startRunLog(logger, {
|
|
911
|
+
sessionId: body.sessionId,
|
|
912
|
+
uploads: body.uploadIds?.length ?? 0,
|
|
913
|
+
inputChars: body.input?.length ?? 0,
|
|
914
|
+
// Kept reading, the browser leaving doesn't stop the upstream, so a
|
|
915
|
+
// failure after it is a real one.
|
|
916
|
+
disconnected: () => !keepReading && (req.signal?.aborted ?? false)
|
|
917
|
+
});
|
|
640
918
|
const events = client.runStreamingAgent(
|
|
641
919
|
agentId,
|
|
642
920
|
{
|
|
@@ -648,7 +926,8 @@ function createSeclaiHandlers(options) {
|
|
|
648
926
|
);
|
|
649
927
|
try {
|
|
650
928
|
const first = await events.next();
|
|
651
|
-
|
|
929
|
+
log?.opened(Boolean(first.done));
|
|
930
|
+
const observer = onEvent || onRunEnd || log ? createRunObserver({ onEvent, onRunEnd, log }, { body, request: req }, { keepReading }) : void 0;
|
|
652
931
|
return new Response(
|
|
653
932
|
relayRunEvents(
|
|
654
933
|
first.done ? void 0 : first.value,
|
|
@@ -660,7 +939,10 @@ function createSeclaiHandlers(options) {
|
|
|
660
939
|
{ headers: SSE_HEADERS }
|
|
661
940
|
);
|
|
662
941
|
} catch (err) {
|
|
663
|
-
|
|
942
|
+
const res = toErrorResponse(err);
|
|
943
|
+
if (!keepReading && req.signal?.aborted) log?.disconnected();
|
|
944
|
+
else log?.rejected(err, res.status);
|
|
945
|
+
return res;
|
|
664
946
|
}
|
|
665
947
|
},
|
|
666
948
|
async download(req) {
|
|
@@ -683,16 +965,17 @@ function createSeclaiHandlers(options) {
|
|
|
683
965
|
resolveCtx,
|
|
684
966
|
(ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
|
|
685
967
|
);
|
|
686
|
-
|
|
968
|
+
const ids = { run_id: runId, attachment_id: attachmentId };
|
|
969
|
+
if ("response" in result) return refused("download", result.response, ids);
|
|
687
970
|
const allowed = result.value;
|
|
688
|
-
if (allowed instanceof Response) return allowed;
|
|
971
|
+
if (allowed instanceof Response) return refused("download", allowed, ids);
|
|
689
972
|
if (allowed !== true && allowed !== false && !warnedDownloadResult) {
|
|
690
973
|
warnedDownloadResult = true;
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
);
|
|
974
|
+
const warning = `authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`;
|
|
975
|
+
if (logger) logger.warn(warning);
|
|
976
|
+
else console.warn(`[seclai] ${warning}`);
|
|
694
977
|
}
|
|
695
|
-
if (allowed !== true) return jsonError(404, "Not found.");
|
|
978
|
+
if (allowed !== true) return refused("download", jsonError(404, "Not found."), ids);
|
|
696
979
|
}
|
|
697
980
|
try {
|
|
698
981
|
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
@@ -714,9 +997,22 @@ function createSeclaiHandlers(options) {
|
|
|
714
997
|
if (!contentType.toLowerCase().startsWith("application/pdf")) {
|
|
715
998
|
headers.set("content-security-policy", "sandbox; default-src 'none'");
|
|
716
999
|
}
|
|
1000
|
+
logger?.info("download served", {
|
|
1001
|
+
run_id: runId,
|
|
1002
|
+
attachment_id: attachmentId,
|
|
1003
|
+
status: upstream.status,
|
|
1004
|
+
content_type: contentType
|
|
1005
|
+
});
|
|
717
1006
|
return new Response(upstream.body, { status: upstream.status, headers });
|
|
718
1007
|
} catch (err) {
|
|
719
|
-
|
|
1008
|
+
const res = toErrorResponse(err);
|
|
1009
|
+
logger?.error("download failed", {
|
|
1010
|
+
run_id: runId,
|
|
1011
|
+
attachment_id: attachmentId,
|
|
1012
|
+
status: res.status,
|
|
1013
|
+
...errorLogFields(err)
|
|
1014
|
+
});
|
|
1015
|
+
return res;
|
|
720
1016
|
}
|
|
721
1017
|
}
|
|
722
1018
|
};
|
|
@@ -739,6 +1035,7 @@ export {
|
|
|
739
1035
|
ATTACHMENT_SLOTS_TTL_MS,
|
|
740
1036
|
DEFAULT_API_VERSION,
|
|
741
1037
|
MIN_API_VERSION,
|
|
1038
|
+
consoleLogger,
|
|
742
1039
|
createSeclaiHandlers,
|
|
743
1040
|
deny
|
|
744
1041
|
};
|
package/package.json
CHANGED