@seclai/handlers 0.0.15 → 0.0.17
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 +9 -1
- package/package.json +5 -12
- package/dist/index.cjs +0 -1132
- package/dist/index.d.cts +0 -344
package/dist/index.cjs
DELETED
|
@@ -1,1132 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var index_exports = {};
|
|
22
|
-
__export(index_exports, {
|
|
23
|
-
ATTACHMENT_SLOTS_TTL_MS: () => ATTACHMENT_SLOTS_TTL_MS,
|
|
24
|
-
DEFAULT_API_VERSION: () => DEFAULT_API_VERSION,
|
|
25
|
-
MIN_API_VERSION: () => MIN_API_VERSION,
|
|
26
|
-
consoleLogger: () => consoleLogger,
|
|
27
|
-
createSeclaiHandlers: () => createSeclaiHandlers,
|
|
28
|
-
deny: () => deny
|
|
29
|
-
});
|
|
30
|
-
module.exports = __toCommonJS(index_exports);
|
|
31
|
-
|
|
32
|
-
// src/handlers.ts
|
|
33
|
-
var import_sdk2 = require("@seclai/sdk");
|
|
34
|
-
|
|
35
|
-
// src/errors.ts
|
|
36
|
-
var import_sdk = require("@seclai/sdk");
|
|
37
|
-
function json(body, status = 200, headers) {
|
|
38
|
-
const merged = new Headers(headers);
|
|
39
|
-
merged.set("content-type", "application/json");
|
|
40
|
-
return new Response(JSON.stringify(body), { status, headers: merged });
|
|
41
|
-
}
|
|
42
|
-
function jsonError(status, message, headers) {
|
|
43
|
-
return json({ error: message, status }, status, headers);
|
|
44
|
-
}
|
|
45
|
-
function upstreamMessage(responseText) {
|
|
46
|
-
if (!responseText) return void 0;
|
|
47
|
-
try {
|
|
48
|
-
const body = JSON.parse(responseText);
|
|
49
|
-
for (const candidate of [
|
|
50
|
-
body.detail,
|
|
51
|
-
body.message,
|
|
52
|
-
body.error?.message,
|
|
53
|
-
body.error
|
|
54
|
-
]) {
|
|
55
|
-
if (typeof candidate === "string" && candidate) return candidate;
|
|
56
|
-
}
|
|
57
|
-
} catch {
|
|
58
|
-
}
|
|
59
|
-
return void 0;
|
|
60
|
-
}
|
|
61
|
-
function toErrorBody(err) {
|
|
62
|
-
if (err instanceof import_sdk.SeclaiAPIValidationError) {
|
|
63
|
-
return {
|
|
64
|
-
error: "The Seclai API rejected this request as invalid.",
|
|
65
|
-
status: 422,
|
|
66
|
-
details: err.validationError
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
if (err instanceof import_sdk.SeclaiAPIStatusError) {
|
|
70
|
-
const { statusCode } = err;
|
|
71
|
-
if (statusCode === 401 || statusCode === 403) {
|
|
72
|
-
return {
|
|
73
|
-
error: "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY.",
|
|
74
|
-
status: 502
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
if (statusCode >= 400 && statusCode < 500) {
|
|
78
|
-
return {
|
|
79
|
-
error: upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`,
|
|
80
|
-
status: statusCode
|
|
81
|
-
};
|
|
82
|
-
}
|
|
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
|
-
}
|
|
88
|
-
return { error: "Could not reach the Seclai API.", status: 502 };
|
|
89
|
-
}
|
|
90
|
-
function runErrorBody(err) {
|
|
91
|
-
const body = toErrorBody(err);
|
|
92
|
-
if (err instanceof import_sdk.SeclaiStreamingError) {
|
|
93
|
-
body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
|
|
94
|
-
}
|
|
95
|
-
return body;
|
|
96
|
-
}
|
|
97
|
-
function toErrorResponse(err) {
|
|
98
|
-
const body = toErrorBody(err);
|
|
99
|
-
return json(body, body.status);
|
|
100
|
-
}
|
|
101
|
-
function streamErrorMessage(err) {
|
|
102
|
-
if (err instanceof import_sdk.SeclaiStreamingError) {
|
|
103
|
-
return "Timed out waiting for the agent run to finish.";
|
|
104
|
-
}
|
|
105
|
-
return "The connection to the Seclai API was lost.";
|
|
106
|
-
}
|
|
107
|
-
function errorLogFields(err) {
|
|
108
|
-
if (err instanceof import_sdk.SeclaiAPIStatusError) {
|
|
109
|
-
return {
|
|
110
|
-
upstream_status: err.statusCode,
|
|
111
|
-
error: upstreamMessage(err.responseText) ?? err.message
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
if (err instanceof Error) return { error: err.message };
|
|
115
|
-
return { error: String(err) };
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// src/logger.ts
|
|
119
|
-
var ORDER = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
|
120
|
-
function consoleLogger(level = "info", target = console) {
|
|
121
|
-
const threshold = ORDER[level] ?? ORDER.info;
|
|
122
|
-
const method = (name) => (message, fields) => {
|
|
123
|
-
if (ORDER[name] < threshold) return;
|
|
124
|
-
const line = `[seclai] ${message}`;
|
|
125
|
-
if (fields === void 0) target[name](line);
|
|
126
|
-
else target[name](line, fields);
|
|
127
|
-
};
|
|
128
|
-
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
129
|
-
}
|
|
130
|
-
var MIN_SECRET_LENGTH = 8;
|
|
131
|
-
function safeLogger(logger, secret) {
|
|
132
|
-
const scrub = secret && secret.length >= MIN_SECRET_LENGTH ? (value) => value.split(secret).join("[redacted]") : (value) => value;
|
|
133
|
-
const method = (name) => (message, fields) => {
|
|
134
|
-
try {
|
|
135
|
-
if (fields === void 0) {
|
|
136
|
-
logger[name](scrub(message));
|
|
137
|
-
return;
|
|
138
|
-
}
|
|
139
|
-
const clean = {};
|
|
140
|
-
for (const [key, value] of Object.entries(fields)) {
|
|
141
|
-
if (value === void 0) continue;
|
|
142
|
-
clean[key] = typeof value === "string" ? scrub(value) : value;
|
|
143
|
-
}
|
|
144
|
-
logger[name](scrub(message), clean);
|
|
145
|
-
} catch {
|
|
146
|
-
}
|
|
147
|
-
};
|
|
148
|
-
return { debug: method("debug"), info: method("info"), warn: method("warn"), error: method("error") };
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// src/sse.ts
|
|
152
|
-
var KEEPALIVE_INTERVAL_MS = 15e3;
|
|
153
|
-
var SSE_HEADERS = {
|
|
154
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
155
|
-
"cache-control": "no-cache, no-transform",
|
|
156
|
-
// Stops nginx-style proxies from buffering the whole stream.
|
|
157
|
-
"x-accel-buffering": "no"
|
|
158
|
-
};
|
|
159
|
-
var encoder = new TextEncoder();
|
|
160
|
-
function frame(event, data) {
|
|
161
|
-
return encoder.encode(`event: ${event}
|
|
162
|
-
data: ${JSON.stringify(data)}
|
|
163
|
-
|
|
164
|
-
`);
|
|
165
|
-
}
|
|
166
|
-
var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
|
|
167
|
-
function relayRunEvents(first, events, abort, observer, options = {}) {
|
|
168
|
-
const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
|
|
169
|
-
let pending = first;
|
|
170
|
-
let closed = false;
|
|
171
|
-
let cancelled = false;
|
|
172
|
-
let closeReport;
|
|
173
|
-
let inflight;
|
|
174
|
-
let keepalive;
|
|
175
|
-
let ctrl;
|
|
176
|
-
let draining = false;
|
|
177
|
-
let pulling;
|
|
178
|
-
const finish = () => {
|
|
179
|
-
closed = true;
|
|
180
|
-
clearInterval(keepalive);
|
|
181
|
-
};
|
|
182
|
-
const stopUpstream = () => {
|
|
183
|
-
abort();
|
|
184
|
-
void events.return().catch(() => {
|
|
185
|
-
});
|
|
186
|
-
};
|
|
187
|
-
const call = async (hook) => {
|
|
188
|
-
try {
|
|
189
|
-
await hook();
|
|
190
|
-
return true;
|
|
191
|
-
} catch (err) {
|
|
192
|
-
try {
|
|
193
|
-
observer?.onError(err);
|
|
194
|
-
} catch {
|
|
195
|
-
}
|
|
196
|
-
return false;
|
|
197
|
-
}
|
|
198
|
-
};
|
|
199
|
-
const reportClose = (reason) => {
|
|
200
|
-
if (!observer) return Promise.resolve(true);
|
|
201
|
-
return closeReport ??= call(() => observer.onClose(reason));
|
|
202
|
-
};
|
|
203
|
-
const end = (controller, last) => {
|
|
204
|
-
if (cancelled) return;
|
|
205
|
-
if (last) controller.enqueue(last);
|
|
206
|
-
controller.close();
|
|
207
|
-
};
|
|
208
|
-
const fail = async (controller) => {
|
|
209
|
-
finish();
|
|
210
|
-
stopUpstream();
|
|
211
|
-
await reportClose("error");
|
|
212
|
-
end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
|
|
213
|
-
};
|
|
214
|
-
const relay = (controller, event, source = "upstream") => {
|
|
215
|
-
const work = (async () => {
|
|
216
|
-
if (observer && !await call(() => observer.onEvent(event, source))) {
|
|
217
|
-
if (!closed) await fail(controller);
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
if (closed || cancelled) return;
|
|
221
|
-
controller.enqueue(frame(event.event, event.data));
|
|
222
|
-
})();
|
|
223
|
-
inflight = work;
|
|
224
|
-
return work;
|
|
225
|
-
};
|
|
226
|
-
const pullOnce = async (controller) => {
|
|
227
|
-
if (pending) {
|
|
228
|
-
const event = pending;
|
|
229
|
-
pending = void 0;
|
|
230
|
-
await relay(controller, event);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
let next;
|
|
234
|
-
try {
|
|
235
|
-
next = await events.next();
|
|
236
|
-
} catch (err) {
|
|
237
|
-
if (closed) return;
|
|
238
|
-
try {
|
|
239
|
-
observer?.onConnectionError?.(err);
|
|
240
|
-
} catch {
|
|
241
|
-
}
|
|
242
|
-
await relay(
|
|
243
|
-
controller,
|
|
244
|
-
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
245
|
-
"connection-lost"
|
|
246
|
-
);
|
|
247
|
-
if (closed) return;
|
|
248
|
-
finish();
|
|
249
|
-
await reportClose("end");
|
|
250
|
-
end(controller);
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
if (closed) return;
|
|
254
|
-
if (next.done) {
|
|
255
|
-
finish();
|
|
256
|
-
const ok = await reportClose("end");
|
|
257
|
-
end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
await relay(controller, next.value);
|
|
261
|
-
};
|
|
262
|
-
const drain = async (controller) => {
|
|
263
|
-
await pulling;
|
|
264
|
-
await inflight;
|
|
265
|
-
if (closed) return;
|
|
266
|
-
if (pending) {
|
|
267
|
-
const event = pending;
|
|
268
|
-
pending = void 0;
|
|
269
|
-
await relay(controller, event);
|
|
270
|
-
}
|
|
271
|
-
while (!closed) {
|
|
272
|
-
let next;
|
|
273
|
-
try {
|
|
274
|
-
next = await events.next();
|
|
275
|
-
} catch (err) {
|
|
276
|
-
if (closed) return;
|
|
277
|
-
try {
|
|
278
|
-
observer?.onConnectionError?.(err);
|
|
279
|
-
} catch {
|
|
280
|
-
}
|
|
281
|
-
await relay(
|
|
282
|
-
controller,
|
|
283
|
-
{ event: "error", data: { error: streamErrorMessage(err) } },
|
|
284
|
-
"connection-lost"
|
|
285
|
-
);
|
|
286
|
-
if (closed) return;
|
|
287
|
-
finish();
|
|
288
|
-
await reportClose("end");
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
if (closed) return;
|
|
292
|
-
if (next.done) {
|
|
293
|
-
finish();
|
|
294
|
-
await reportClose("end");
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
await relay(controller, next.value);
|
|
298
|
-
}
|
|
299
|
-
};
|
|
300
|
-
const startDrain = (fromCancel) => {
|
|
301
|
-
if (draining || closed || !ctrl) return;
|
|
302
|
-
draining = true;
|
|
303
|
-
cancelled = true;
|
|
304
|
-
clearInterval(keepalive);
|
|
305
|
-
const controller = ctrl;
|
|
306
|
-
if (!fromCancel) {
|
|
307
|
-
try {
|
|
308
|
-
controller.close();
|
|
309
|
-
} catch {
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
try {
|
|
313
|
-
observer?.onDisconnect?.();
|
|
314
|
-
} catch {
|
|
315
|
-
}
|
|
316
|
-
void drain(controller).catch((err) => {
|
|
317
|
-
try {
|
|
318
|
-
observer?.onError(err);
|
|
319
|
-
} catch {
|
|
320
|
-
}
|
|
321
|
-
});
|
|
322
|
-
};
|
|
323
|
-
return new ReadableStream({
|
|
324
|
-
start(controller) {
|
|
325
|
-
ctrl = controller;
|
|
326
|
-
keepalive = setInterval(() => {
|
|
327
|
-
if (closed || cancelled) return;
|
|
328
|
-
controller.enqueue(encoder.encode(": keepalive\n\n"));
|
|
329
|
-
try {
|
|
330
|
-
observer?.onKeepalive?.();
|
|
331
|
-
} catch {
|
|
332
|
-
}
|
|
333
|
-
}, KEEPALIVE_INTERVAL_MS);
|
|
334
|
-
if (keepReading && options.signal) {
|
|
335
|
-
const { signal } = options;
|
|
336
|
-
const onAbort = () => startDrain(false);
|
|
337
|
-
if (signal.aborted) queueMicrotask(onAbort);
|
|
338
|
-
else signal.addEventListener("abort", onAbort, { once: true });
|
|
339
|
-
}
|
|
340
|
-
},
|
|
341
|
-
pull(controller) {
|
|
342
|
-
if (closed || draining) return;
|
|
343
|
-
const work = pullOnce(controller);
|
|
344
|
-
pulling = work;
|
|
345
|
-
return work;
|
|
346
|
-
},
|
|
347
|
-
async cancel() {
|
|
348
|
-
if (keepReading) {
|
|
349
|
-
startDrain(true);
|
|
350
|
-
return;
|
|
351
|
-
}
|
|
352
|
-
cancelled = true;
|
|
353
|
-
finish();
|
|
354
|
-
stopUpstream();
|
|
355
|
-
const unrelayed = pending;
|
|
356
|
-
pending = void 0;
|
|
357
|
-
if (unrelayed && observer?.onUnrelayed) {
|
|
358
|
-
await call(() => observer.onUnrelayed(unrelayed));
|
|
359
|
-
}
|
|
360
|
-
await inflight;
|
|
361
|
-
await reportClose("cancel");
|
|
362
|
-
}
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// src/run-callbacks.ts
|
|
367
|
-
var NO_RESULT_MESSAGE = "The stream ended without a result.";
|
|
368
|
-
var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
|
|
369
|
-
var FAILED_MESSAGE = "The run failed.";
|
|
370
|
-
function lastAttemptError(run) {
|
|
371
|
-
if (!Array.isArray(run.attempts)) return null;
|
|
372
|
-
for (let i = run.attempts.length - 1; i >= 0; i--) {
|
|
373
|
-
const error = run.attempts[i]?.error;
|
|
374
|
-
if (typeof error === "string" && error) return error;
|
|
375
|
-
}
|
|
376
|
-
return null;
|
|
377
|
-
}
|
|
378
|
-
function toAttachments(raw) {
|
|
379
|
-
if (!Array.isArray(raw)) return [];
|
|
380
|
-
return raw.flatMap(
|
|
381
|
-
(item) => typeof item?.id === "string" ? [
|
|
382
|
-
{
|
|
383
|
-
id: item.id,
|
|
384
|
-
name: typeof item.name === "string" ? item.name : null,
|
|
385
|
-
mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
|
|
386
|
-
}
|
|
387
|
-
] : []
|
|
388
|
-
);
|
|
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
|
-
}
|
|
404
|
-
function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
405
|
-
const { onEvent, onRunEnd, log } = callbacks;
|
|
406
|
-
const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
|
|
407
|
-
let runId = null;
|
|
408
|
-
let text = "";
|
|
409
|
-
let terminal;
|
|
410
|
-
let terminalEvent;
|
|
411
|
-
let ended = false;
|
|
412
|
-
const outcome = (o) => ({
|
|
413
|
-
runId,
|
|
414
|
-
attachments: [],
|
|
415
|
-
...o
|
|
416
|
-
});
|
|
417
|
-
const end = async (o) => {
|
|
418
|
-
if (ended) return;
|
|
419
|
-
ended = true;
|
|
420
|
-
await onRunEnd?.(o, ctx);
|
|
421
|
-
};
|
|
422
|
-
const failed = (error) => outcome({ status: "failed", output: text, error });
|
|
423
|
-
const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
|
|
424
|
-
const record = (event, source) => {
|
|
425
|
-
note(event, source);
|
|
426
|
-
if (terminal && !terminalEvent) terminalEvent = { event, source };
|
|
427
|
-
};
|
|
428
|
-
const note = (event, source) => {
|
|
429
|
-
const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
|
|
430
|
-
if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
|
|
431
|
-
if (terminal) return;
|
|
432
|
-
switch (event.event) {
|
|
433
|
-
case "stream_token":
|
|
434
|
-
if (typeof payload.token === "string") text += payload.token;
|
|
435
|
-
return;
|
|
436
|
-
case "done": {
|
|
437
|
-
const run = payload;
|
|
438
|
-
if (typeof run.run_id === "string") runId = run.run_id;
|
|
439
|
-
const attachments = toAttachments(run.attachments);
|
|
440
|
-
terminal = run.status === "failed" ? outcome({
|
|
441
|
-
status: "failed",
|
|
442
|
-
output: text,
|
|
443
|
-
attachments,
|
|
444
|
-
error: lastAttemptError(run) ?? FAILED_MESSAGE
|
|
445
|
-
}) : outcome({
|
|
446
|
-
status: "completed",
|
|
447
|
-
// Agents with no streaming step send no tokens, so `output`
|
|
448
|
-
// may be the only text.
|
|
449
|
-
output: typeof run.output === "string" && run.output || text,
|
|
450
|
-
attachments,
|
|
451
|
-
error: null
|
|
452
|
-
});
|
|
453
|
-
return;
|
|
454
|
-
}
|
|
455
|
-
case "error":
|
|
456
|
-
terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
|
|
457
|
-
return;
|
|
458
|
-
case "timeout":
|
|
459
|
-
terminal = failed(TIMEOUT_MESSAGE);
|
|
460
|
-
return;
|
|
461
|
-
}
|
|
462
|
-
};
|
|
463
|
-
return {
|
|
464
|
-
async onEvent(event, source) {
|
|
465
|
-
log?.event(event);
|
|
466
|
-
record(event, source);
|
|
467
|
-
await onEvent?.(event, ctx);
|
|
468
|
-
if (terminal) await end(terminal);
|
|
469
|
-
if (terminalEvent?.event === event) log?.result(event, source);
|
|
470
|
-
},
|
|
471
|
-
onUnrelayed(event) {
|
|
472
|
-
log?.event(event);
|
|
473
|
-
record(event, "upstream");
|
|
474
|
-
},
|
|
475
|
-
async onClose(reason) {
|
|
476
|
-
try {
|
|
477
|
-
switch (reason) {
|
|
478
|
-
case "end":
|
|
479
|
-
return await end(
|
|
480
|
-
terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE))
|
|
481
|
-
);
|
|
482
|
-
case "error":
|
|
483
|
-
return await end(failed(OBSERVER_ERROR_MESSAGE));
|
|
484
|
-
case "cancel":
|
|
485
|
-
return await end(terminal ?? cancelled());
|
|
486
|
-
}
|
|
487
|
-
} finally {
|
|
488
|
-
if (reason === "cancel" && terminalEvent) {
|
|
489
|
-
log?.result(terminalEvent.event, terminalEvent.source);
|
|
490
|
-
}
|
|
491
|
-
log?.close(reason);
|
|
492
|
-
}
|
|
493
|
-
},
|
|
494
|
-
onError(err) {
|
|
495
|
-
reportCallbackError(log, err);
|
|
496
|
-
},
|
|
497
|
-
onKeepalive: log && (() => log.keepalive()),
|
|
498
|
-
onDisconnect: log && (() => log.readingOn()),
|
|
499
|
-
onConnectionError: log && ((err) => log.connectionError(err))
|
|
500
|
-
};
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
// src/run-log.ts
|
|
504
|
-
var PROGRESS_INTERVAL_MS = 5e3;
|
|
505
|
-
var ZERO_TOKENS_MESSAGE = "no tokens streamed: the agent's result step may be `display_result` rather than `streaming_result`";
|
|
506
|
-
function startRunLog(log, start) {
|
|
507
|
-
const startedAt = Date.now();
|
|
508
|
-
let runId = null;
|
|
509
|
-
let tokens = 0;
|
|
510
|
-
let chars = 0;
|
|
511
|
-
let firstTokenAt = null;
|
|
512
|
-
let lastProgressAt = 0;
|
|
513
|
-
let lastStep = null;
|
|
514
|
-
let ended = false;
|
|
515
|
-
let cause;
|
|
516
|
-
const ms = () => Date.now() - startedAt;
|
|
517
|
-
const ctx = (fields) => ({
|
|
518
|
-
run_id: runId ?? void 0,
|
|
519
|
-
session_id: start.sessionId,
|
|
520
|
-
...fields
|
|
521
|
-
});
|
|
522
|
-
const disconnected = () => {
|
|
523
|
-
if (ended) return;
|
|
524
|
-
ended = true;
|
|
525
|
-
log.info("browser disconnected; the run continues on Seclai", ctx({ tokens, ms: ms() }));
|
|
526
|
-
};
|
|
527
|
-
log.info("run starting", {
|
|
528
|
-
session_id: start.sessionId,
|
|
529
|
-
uploads: start.uploads,
|
|
530
|
-
input_chars: start.inputChars
|
|
531
|
-
});
|
|
532
|
-
return {
|
|
533
|
-
opened(empty) {
|
|
534
|
-
if (empty) log.info("stream open", ctx({ ms: ms(), empty: true }));
|
|
535
|
-
else log.info("stream open", ctx({ ms: ms() }));
|
|
536
|
-
},
|
|
537
|
-
disconnected,
|
|
538
|
-
readingOn() {
|
|
539
|
-
if (ended) return;
|
|
540
|
-
log.info("browser left; reading the rest of the run in the background", ctx({ tokens, ms: ms() }));
|
|
541
|
-
},
|
|
542
|
-
rejected(err, status) {
|
|
543
|
-
log.error("run rejected", ctx({ status, ...errorLogFields(err), ms: ms() }));
|
|
544
|
-
},
|
|
545
|
-
event({ event, data }) {
|
|
546
|
-
const payload = typeof data === "object" && data !== null ? data : {};
|
|
547
|
-
if (runId === null && typeof payload.run_id === "string") runId = payload.run_id;
|
|
548
|
-
switch (event) {
|
|
549
|
-
case "init":
|
|
550
|
-
log.debug("event", ctx({ event }));
|
|
551
|
-
log.info("run started", ctx());
|
|
552
|
-
return;
|
|
553
|
-
case "step_progress": {
|
|
554
|
-
log.debug("event", ctx({ event }));
|
|
555
|
-
const step = typeof payload.step_name === "string" && payload.step_name ? payload.step_name : String(payload.step_id ?? "?");
|
|
556
|
-
const message = typeof payload.message === "string" ? payload.message : "";
|
|
557
|
-
const key = `${step}
|
|
558
|
-
${message}`;
|
|
559
|
-
if (key === lastStep) return;
|
|
560
|
-
lastStep = key;
|
|
561
|
-
log.info("step", ctx({ step, message: message || void 0 }));
|
|
562
|
-
return;
|
|
563
|
-
}
|
|
564
|
-
case "stream_token": {
|
|
565
|
-
const length = typeof payload.token === "string" ? payload.token.length : 0;
|
|
566
|
-
tokens += 1;
|
|
567
|
-
chars += length;
|
|
568
|
-
log.debug("token", ctx({ n: tokens, chars: length }));
|
|
569
|
-
const now = Date.now();
|
|
570
|
-
if (firstTokenAt === null) {
|
|
571
|
-
firstTokenAt = now;
|
|
572
|
-
lastProgressAt = now;
|
|
573
|
-
log.info("first token", ctx({ ms: now - startedAt }));
|
|
574
|
-
} else if (now - lastProgressAt >= PROGRESS_INTERVAL_MS) {
|
|
575
|
-
lastProgressAt = now;
|
|
576
|
-
log.info("streaming", ctx({ tokens, chars, ms: now - startedAt }));
|
|
577
|
-
}
|
|
578
|
-
return;
|
|
579
|
-
}
|
|
580
|
-
case "done":
|
|
581
|
-
if (typeof payload.run_id === "string") runId = payload.run_id;
|
|
582
|
-
log.debug("event", ctx({ event }));
|
|
583
|
-
return;
|
|
584
|
-
default:
|
|
585
|
-
log.debug("event", ctx({ event }));
|
|
586
|
-
}
|
|
587
|
-
},
|
|
588
|
-
result({ event, data }, source) {
|
|
589
|
-
if (ended) return;
|
|
590
|
-
const payload = typeof data === "object" && data !== null ? data : {};
|
|
591
|
-
switch (event) {
|
|
592
|
-
case "done": {
|
|
593
|
-
ended = true;
|
|
594
|
-
const output = typeof payload.output === "string" ? payload.output : "";
|
|
595
|
-
const fields = ctx({
|
|
596
|
-
status: payload.status,
|
|
597
|
-
attachments: Array.isArray(payload.attachments) ? payload.attachments.length : 0,
|
|
598
|
-
tokens,
|
|
599
|
-
output_chars: output.length || chars,
|
|
600
|
-
ms: ms()
|
|
601
|
-
});
|
|
602
|
-
if (payload.status === "failed") {
|
|
603
|
-
log.warn("run failed", { ...fields, error: lastAttemptError(payload) ?? void 0 });
|
|
604
|
-
return;
|
|
605
|
-
}
|
|
606
|
-
log.info("run done", fields);
|
|
607
|
-
if (tokens === 0) log.warn(ZERO_TOKENS_MESSAGE, ctx());
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
610
|
-
case "error":
|
|
611
|
-
if (source === "connection-lost" && start.disconnected()) {
|
|
612
|
-
disconnected();
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
ended = true;
|
|
616
|
-
log.error(
|
|
617
|
-
"stream error",
|
|
618
|
-
ctx({
|
|
619
|
-
error: payload.error,
|
|
620
|
-
...source === "connection-lost" ? cause : void 0,
|
|
621
|
-
tokens,
|
|
622
|
-
ms: ms()
|
|
623
|
-
})
|
|
624
|
-
);
|
|
625
|
-
return;
|
|
626
|
-
case "timeout":
|
|
627
|
-
ended = true;
|
|
628
|
-
log.error("run timed out", ctx({ tokens, ms: ms() }));
|
|
629
|
-
return;
|
|
630
|
-
}
|
|
631
|
-
},
|
|
632
|
-
connectionError(err) {
|
|
633
|
-
const { error, upstream_status } = errorLogFields(err);
|
|
634
|
-
cause = { cause: error, upstream_status };
|
|
635
|
-
},
|
|
636
|
-
keepalive() {
|
|
637
|
-
log.debug("keepalive", ctx({ ms: ms() }));
|
|
638
|
-
},
|
|
639
|
-
close(reason) {
|
|
640
|
-
if (ended) {
|
|
641
|
-
log.debug("stream closed", ctx({ reason, ms: ms() }));
|
|
642
|
-
return;
|
|
643
|
-
}
|
|
644
|
-
switch (reason) {
|
|
645
|
-
case "cancel":
|
|
646
|
-
disconnected();
|
|
647
|
-
return;
|
|
648
|
-
case "end":
|
|
649
|
-
if (start.disconnected()) disconnected();
|
|
650
|
-
else {
|
|
651
|
-
ended = true;
|
|
652
|
-
log.warn("stream ended without a result", ctx({ tokens, ms: ms() }));
|
|
653
|
-
}
|
|
654
|
-
return;
|
|
655
|
-
case "error":
|
|
656
|
-
ended = true;
|
|
657
|
-
log.error("run failed: a callback threw", ctx({ status: "failed", tokens, ms: ms() }));
|
|
658
|
-
return;
|
|
659
|
-
}
|
|
660
|
-
},
|
|
661
|
-
callbackError(err) {
|
|
662
|
-
log.error("an onEvent or onRunEnd callback threw", ctx({ error: err }));
|
|
663
|
-
}
|
|
664
|
-
};
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
// src/handlers.ts
|
|
668
|
-
var MIN_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_16;
|
|
669
|
-
var DEFAULT_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_28;
|
|
670
|
-
var DEFAULT_RUN_TIMEOUT_MS = 11 * 60 * 1e3;
|
|
671
|
-
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
672
|
-
var ATTACHMENT_ID = /^[A-Za-z0-9_-]+={0,2}$/;
|
|
673
|
-
var MAX_DOWNLOAD_NAME_LENGTH = 255;
|
|
674
|
-
var ATTACHMENT_SLOTS_TTL_MS = 60 * 1e3;
|
|
675
|
-
var MULTIPART_OVERHEAD_BYTES = 64 * 1024;
|
|
676
|
-
async function readLimitedForm(req, limit) {
|
|
677
|
-
if (!req.body) return req.formData();
|
|
678
|
-
let received = 0;
|
|
679
|
-
let exceeded = false;
|
|
680
|
-
const counted = req.body.pipeThrough(
|
|
681
|
-
new TransformStream({
|
|
682
|
-
transform(chunk, controller) {
|
|
683
|
-
received += chunk.byteLength;
|
|
684
|
-
if (received > limit) {
|
|
685
|
-
exceeded = true;
|
|
686
|
-
controller.error(new Error("The request body is over the size limit."));
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
controller.enqueue(chunk);
|
|
690
|
-
}
|
|
691
|
-
})
|
|
692
|
-
);
|
|
693
|
-
const headers = new Headers();
|
|
694
|
-
const contentType = req.headers.get("content-type");
|
|
695
|
-
if (contentType) headers.set("content-type", contentType);
|
|
696
|
-
try {
|
|
697
|
-
return await new Response(counted, { headers }).formData();
|
|
698
|
-
} catch (err) {
|
|
699
|
-
if (exceeded) return "too-large";
|
|
700
|
-
throw err;
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
function uploadParams(req) {
|
|
704
|
-
const params = /* @__PURE__ */ Object.create(null);
|
|
705
|
-
for (const [key, value] of new URL(req.url).searchParams) params[key] = value;
|
|
706
|
-
return params;
|
|
707
|
-
}
|
|
708
|
-
var ROUTES = {
|
|
709
|
-
"attachment-references": "attachmentReferences",
|
|
710
|
-
upload: "upload",
|
|
711
|
-
run: "run",
|
|
712
|
-
download: "download"
|
|
713
|
-
};
|
|
714
|
-
function wrongMethod(allow) {
|
|
715
|
-
return jsonError(405, "Method not allowed.", { allow });
|
|
716
|
-
}
|
|
717
|
-
var NOT_AUTHORIZED = "Could not authorize this request.";
|
|
718
|
-
function deny(status, message, headers) {
|
|
719
|
-
return jsonError(status, message, headers);
|
|
720
|
-
}
|
|
721
|
-
function parseRunBody(body) {
|
|
722
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
723
|
-
return "The request body must be a JSON object.";
|
|
724
|
-
}
|
|
725
|
-
const { input, uploadIds, sessionId } = body;
|
|
726
|
-
if (input !== void 0 && typeof input !== "string") {
|
|
727
|
-
return "`input` must be a string.";
|
|
728
|
-
}
|
|
729
|
-
if (uploadIds !== void 0 && !(Array.isArray(uploadIds) && uploadIds.every((id) => typeof id === "string"))) {
|
|
730
|
-
return "`uploadIds` must be an array of strings.";
|
|
731
|
-
}
|
|
732
|
-
if (sessionId !== void 0 && (typeof sessionId !== "string" || !sessionId)) {
|
|
733
|
-
return "`sessionId` must be a non-empty string.";
|
|
734
|
-
}
|
|
735
|
-
if (!input && !uploadIds?.length) {
|
|
736
|
-
return "Provide `input`, `uploadIds`, or both.";
|
|
737
|
-
}
|
|
738
|
-
return { input, uploadIds, sessionId };
|
|
739
|
-
}
|
|
740
|
-
var UNKNOWN_TYPES = /* @__PURE__ */ new Set(["", "application/octet-stream"]);
|
|
741
|
-
function essence(type) {
|
|
742
|
-
return type.split(";")[0].trim().toLowerCase();
|
|
743
|
-
}
|
|
744
|
-
function slotAllows(slot, type) {
|
|
745
|
-
const patterns = slot.content_types ?? [];
|
|
746
|
-
if (patterns.length === 0) return true;
|
|
747
|
-
return patterns.some((raw) => {
|
|
748
|
-
const pattern = essence(raw);
|
|
749
|
-
if (pattern === "*" || pattern === "*/*") return true;
|
|
750
|
-
if (pattern.endsWith("/*")) return type.startsWith(pattern.slice(0, -1));
|
|
751
|
-
return pattern === type;
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
function createSeclaiHandlers(options) {
|
|
755
|
-
const {
|
|
756
|
-
apiKey,
|
|
757
|
-
agentId,
|
|
758
|
-
apiVersion = DEFAULT_API_VERSION,
|
|
759
|
-
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
|
|
760
|
-
upload: uploadOptions = {},
|
|
761
|
-
keepReadingAfterDisconnect = false,
|
|
762
|
-
onEvent,
|
|
763
|
-
onRunEnd,
|
|
764
|
-
context,
|
|
765
|
-
authorizeRun,
|
|
766
|
-
authorizeUpload,
|
|
767
|
-
authorizeDownload
|
|
768
|
-
} = options;
|
|
769
|
-
const { maxBytes, checkContentType = false, onUpload } = uploadOptions;
|
|
770
|
-
const logger = options.logger && safeLogger(options.logger, apiKey);
|
|
771
|
-
function reportError(message, err) {
|
|
772
|
-
if (logger) logger.error(message, err === void 0 ? void 0 : errorLogFields(err));
|
|
773
|
-
else if (err === void 0) console.error(`[seclai] ${message}`);
|
|
774
|
-
else console.error(`[seclai] ${message}`, err);
|
|
775
|
-
}
|
|
776
|
-
function refused(what, res, fields = {}) {
|
|
777
|
-
logger?.info(`${what} refused`, { ...fields, status: res.status });
|
|
778
|
-
return res;
|
|
779
|
-
}
|
|
780
|
-
if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
|
|
781
|
-
if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
|
|
782
|
-
if (apiVersion < MIN_API_VERSION) {
|
|
783
|
-
throw new Error(
|
|
784
|
-
`createSeclaiHandlers: \`apiVersion\` must be ${MIN_API_VERSION} or later, got ${apiVersion}.`
|
|
785
|
-
);
|
|
786
|
-
}
|
|
787
|
-
if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes > 0)) {
|
|
788
|
-
throw new Error("createSeclaiHandlers: `upload.maxBytes` must be a positive number.");
|
|
789
|
-
}
|
|
790
|
-
const client = new import_sdk2.Seclai({
|
|
791
|
-
apiKey,
|
|
792
|
-
apiVersion,
|
|
793
|
-
// The SDK calls this as a method. Workers' fetch throws "Illegal invocation"
|
|
794
|
-
// when called with any `this` but the global, so it can't be passed bare.
|
|
795
|
-
fetch: (input, init) => globalThis.fetch(input, init)
|
|
796
|
-
});
|
|
797
|
-
let refsCache;
|
|
798
|
-
function remember(promise) {
|
|
799
|
-
const entry = { promise, expires: Date.now() + ATTACHMENT_SLOTS_TTL_MS };
|
|
800
|
-
entry.promise.catch(() => {
|
|
801
|
-
if (refsCache === entry) refsCache = void 0;
|
|
802
|
-
});
|
|
803
|
-
refsCache = entry;
|
|
804
|
-
}
|
|
805
|
-
function cachedReferences() {
|
|
806
|
-
if (!refsCache || Date.now() >= refsCache.expires) {
|
|
807
|
-
remember(client.getAgentAttachmentReferences(agentId));
|
|
808
|
-
}
|
|
809
|
-
return refsCache.promise;
|
|
810
|
-
}
|
|
811
|
-
const attachmentSlots = async () => (await cachedReferences()).accepted_attachments ?? [];
|
|
812
|
-
const getAttachmentReferences = async () => structuredClone(await cachedReferences());
|
|
813
|
-
const tooLarge = () => jsonError(413, `The file is larger than the ${maxBytes}-byte limit.`);
|
|
814
|
-
let warnedDownloadResult = false;
|
|
815
|
-
async function callHook(name, req, resolveCtx, hook) {
|
|
816
|
-
let ctx;
|
|
817
|
-
try {
|
|
818
|
-
ctx = await resolveCtx(req);
|
|
819
|
-
return { value: await hook(ctx) };
|
|
820
|
-
} catch (err) {
|
|
821
|
-
if (err instanceof Response) return { response: err };
|
|
822
|
-
const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
|
|
823
|
-
reportError(`${name} threw, so the request got a 500.${hint}`, err);
|
|
824
|
-
return { response: jsonError(500, NOT_AUTHORIZED) };
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
const build = (resolveCtx) => {
|
|
828
|
-
const resolved = /* @__PURE__ */ new WeakMap();
|
|
829
|
-
const resolve = (req) => {
|
|
830
|
-
let ctx = resolved.get(req);
|
|
831
|
-
if (!ctx) {
|
|
832
|
-
ctx = resolveCtx(req);
|
|
833
|
-
resolved.set(req, ctx);
|
|
834
|
-
}
|
|
835
|
-
return ctx;
|
|
836
|
-
};
|
|
837
|
-
const handlers = {
|
|
838
|
-
async attachmentReferences(req) {
|
|
839
|
-
if (req.method !== "GET") return wrongMethod("GET");
|
|
840
|
-
try {
|
|
841
|
-
const refs = await client.getAgentAttachmentReferences(agentId);
|
|
842
|
-
remember(Promise.resolve(refs));
|
|
843
|
-
return json(refs);
|
|
844
|
-
} catch (err) {
|
|
845
|
-
return toErrorResponse(err);
|
|
846
|
-
}
|
|
847
|
-
},
|
|
848
|
-
async upload(req) {
|
|
849
|
-
if (req.method !== "POST") return wrongMethod("POST");
|
|
850
|
-
const bodyLimit = maxBytes === void 0 ? void 0 : maxBytes + MULTIPART_OVERHEAD_BYTES;
|
|
851
|
-
if (bodyLimit !== void 0) {
|
|
852
|
-
const length = Number(req.headers.get("content-length"));
|
|
853
|
-
if (length > bodyLimit) return refused("upload", tooLarge(), { content_length: length });
|
|
854
|
-
}
|
|
855
|
-
let form;
|
|
856
|
-
try {
|
|
857
|
-
const read = bodyLimit === void 0 ? await req.formData() : await readLimitedForm(req, bodyLimit);
|
|
858
|
-
if (read === "too-large") return refused("upload", tooLarge(), { reason: "body over limit" });
|
|
859
|
-
form = read;
|
|
860
|
-
} catch {
|
|
861
|
-
return jsonError(400, "The request body must be multipart form data.");
|
|
862
|
-
}
|
|
863
|
-
const file = form.get("file");
|
|
864
|
-
if (file === null || typeof file === "string") {
|
|
865
|
-
return jsonError(400, "The form must include a `file` field holding a file.");
|
|
866
|
-
}
|
|
867
|
-
const started = Date.now();
|
|
868
|
-
const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
|
|
869
|
-
logger?.info("upload received", fileFields);
|
|
870
|
-
if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
|
|
871
|
-
const params = authorizeUpload || onUpload ? uploadParams(req) : {};
|
|
872
|
-
if (authorizeUpload) {
|
|
873
|
-
const result2 = await callHook(
|
|
874
|
-
"authorizeUpload",
|
|
875
|
-
req,
|
|
876
|
-
resolve,
|
|
877
|
-
(ctx) => authorizeUpload(req, file, ctx, params)
|
|
878
|
-
);
|
|
879
|
-
if ("response" in result2) return refused("upload", result2.response, fileFields);
|
|
880
|
-
const allowed = result2.value;
|
|
881
|
-
if (allowed instanceof Response) return refused("upload", allowed, fileFields);
|
|
882
|
-
if (allowed === false) return refused("upload", jsonError(403, "This upload isn't allowed."), fileFields);
|
|
883
|
-
if (allowed !== void 0 && allowed !== true) {
|
|
884
|
-
reportError(
|
|
885
|
-
`authorizeUpload returned ${String(allowed)}, not true, false, nothing or a Response, so the request got a 500.`
|
|
886
|
-
);
|
|
887
|
-
return jsonError(500, NOT_AUTHORIZED);
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
let result;
|
|
891
|
-
let uploadContext;
|
|
892
|
-
try {
|
|
893
|
-
const type = essence(file.type);
|
|
894
|
-
if (checkContentType && !UNKNOWN_TYPES.has(type)) {
|
|
895
|
-
const accepted = await attachmentSlots();
|
|
896
|
-
if (!accepted.some((slot) => slotAllows(slot, type))) {
|
|
897
|
-
return refused("upload", jsonError(415, `This agent does not accept files of type ${type}.`), fileFields);
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
if (onUpload) {
|
|
901
|
-
const ctx = await callHook("context", req, resolve, (c) => c);
|
|
902
|
-
if ("response" in ctx) return refused("upload", ctx.response, fileFields);
|
|
903
|
-
uploadContext = ctx.value;
|
|
904
|
-
}
|
|
905
|
-
const upload = await client.uploadAgentInput(agentId, {
|
|
906
|
-
file,
|
|
907
|
-
fileName: file.name,
|
|
908
|
-
mimeType: file.type || void 0
|
|
909
|
-
});
|
|
910
|
-
result = {
|
|
911
|
-
id: upload.id,
|
|
912
|
-
status: upload.status,
|
|
913
|
-
filename: upload.filename,
|
|
914
|
-
content_type: upload.content_type,
|
|
915
|
-
file_size: upload.file_size
|
|
916
|
-
};
|
|
917
|
-
logger?.info("uploaded", {
|
|
918
|
-
...fileFields,
|
|
919
|
-
upload_id: upload.id,
|
|
920
|
-
status: upload.status,
|
|
921
|
-
ms: Date.now() - started
|
|
922
|
-
});
|
|
923
|
-
} catch (err) {
|
|
924
|
-
const res = toErrorResponse(err);
|
|
925
|
-
logger?.error("upload failed", {
|
|
926
|
-
...fileFields,
|
|
927
|
-
status: res.status,
|
|
928
|
-
...errorLogFields(err),
|
|
929
|
-
ms: Date.now() - started
|
|
930
|
-
});
|
|
931
|
-
return res;
|
|
932
|
-
}
|
|
933
|
-
if (onUpload) {
|
|
934
|
-
try {
|
|
935
|
-
const replacement = await onUpload(file, result, req, uploadContext, params);
|
|
936
|
-
if (replacement instanceof Response) return replacement;
|
|
937
|
-
} catch (err) {
|
|
938
|
-
reportError("onUpload threw, so the request got a 500.", err);
|
|
939
|
-
return jsonError(500, "The server failed to finish handling the upload.");
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
return json(result);
|
|
943
|
-
},
|
|
944
|
-
async run(req) {
|
|
945
|
-
if (req.method !== "POST") return wrongMethod("POST");
|
|
946
|
-
let raw;
|
|
947
|
-
try {
|
|
948
|
-
raw = await req.json();
|
|
949
|
-
} catch {
|
|
950
|
-
return jsonError(400, "The request body must be JSON.");
|
|
951
|
-
}
|
|
952
|
-
const parsed = parseRunBody(raw);
|
|
953
|
-
if (typeof parsed === "string") return jsonError(400, parsed);
|
|
954
|
-
let body = parsed;
|
|
955
|
-
if (authorizeRun) {
|
|
956
|
-
const result = await callHook(
|
|
957
|
-
"authorizeRun",
|
|
958
|
-
req,
|
|
959
|
-
resolve,
|
|
960
|
-
(ctx) => authorizeRun(req, parsed, ctx)
|
|
961
|
-
);
|
|
962
|
-
if ("response" in result) return refused("run", result.response);
|
|
963
|
-
const verdict = result.value;
|
|
964
|
-
if (verdict instanceof Response) return refused("run", verdict);
|
|
965
|
-
if (verdict === false) return refused("run", jsonError(403, "This request isn't allowed."));
|
|
966
|
-
const kept = verdict === void 0 || verdict === true;
|
|
967
|
-
const rewritten = parseRunBody(kept ? parsed : verdict);
|
|
968
|
-
if (typeof rewritten === "string") {
|
|
969
|
-
reportError(
|
|
970
|
-
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}`
|
|
971
|
-
);
|
|
972
|
-
return jsonError(500, NOT_AUTHORIZED);
|
|
973
|
-
}
|
|
974
|
-
body = rewritten;
|
|
975
|
-
}
|
|
976
|
-
let runContext;
|
|
977
|
-
if (onEvent || onRunEnd) {
|
|
978
|
-
const ctx = await callHook("context", req, resolve, (c) => c);
|
|
979
|
-
if ("response" in ctx) return refused("run", ctx.response);
|
|
980
|
-
runContext = ctx.value;
|
|
981
|
-
}
|
|
982
|
-
const upstream = new AbortController();
|
|
983
|
-
const abort = () => upstream.abort();
|
|
984
|
-
const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
|
|
985
|
-
if (!keepReading) {
|
|
986
|
-
if (req.signal?.aborted) abort();
|
|
987
|
-
else req.signal?.addEventListener("abort", abort, { once: true });
|
|
988
|
-
}
|
|
989
|
-
const log = logger && startRunLog(logger, {
|
|
990
|
-
sessionId: body.sessionId,
|
|
991
|
-
uploads: body.uploadIds?.length ?? 0,
|
|
992
|
-
inputChars: body.input?.length ?? 0,
|
|
993
|
-
// Kept reading, the browser leaving doesn't stop the upstream, so a
|
|
994
|
-
// failure after it is a real one.
|
|
995
|
-
disconnected: () => !keepReading && (req.signal?.aborted ?? false)
|
|
996
|
-
});
|
|
997
|
-
const events = client.runStreamingAgent(
|
|
998
|
-
agentId,
|
|
999
|
-
{
|
|
1000
|
-
...body.input ? { input: body.input } : {},
|
|
1001
|
-
...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
|
|
1002
|
-
...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
|
|
1003
|
-
},
|
|
1004
|
-
{ timeoutMs: runTimeoutMs, signal: upstream.signal }
|
|
1005
|
-
);
|
|
1006
|
-
try {
|
|
1007
|
-
const first = await events.next();
|
|
1008
|
-
log?.opened(Boolean(first.done));
|
|
1009
|
-
const observer = onEvent || onRunEnd || log ? createRunObserver(
|
|
1010
|
-
{ onEvent, onRunEnd, log },
|
|
1011
|
-
{ body, request: req, context: runContext },
|
|
1012
|
-
{ keepReading }
|
|
1013
|
-
) : void 0;
|
|
1014
|
-
return new Response(
|
|
1015
|
-
relayRunEvents(
|
|
1016
|
-
first.done ? void 0 : first.value,
|
|
1017
|
-
events,
|
|
1018
|
-
abort,
|
|
1019
|
-
observer,
|
|
1020
|
-
keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
|
|
1021
|
-
),
|
|
1022
|
-
{ headers: SSE_HEADERS }
|
|
1023
|
-
);
|
|
1024
|
-
} catch (err) {
|
|
1025
|
-
const error = runErrorBody(err);
|
|
1026
|
-
const browserLeft = upstream.signal.aborted;
|
|
1027
|
-
await reportRefusedRun(
|
|
1028
|
-
{ onRunEnd, log },
|
|
1029
|
-
{ body, request: req, context: runContext },
|
|
1030
|
-
browserLeft ? { cancelled: true } : { error: error.error }
|
|
1031
|
-
);
|
|
1032
|
-
if (browserLeft) log?.disconnected();
|
|
1033
|
-
else log?.rejected(err, error.status);
|
|
1034
|
-
return json(error, error.status);
|
|
1035
|
-
}
|
|
1036
|
-
},
|
|
1037
|
-
async download(req) {
|
|
1038
|
-
if (req.method !== "GET") return wrongMethod("GET");
|
|
1039
|
-
const params = new URL(req.url).searchParams;
|
|
1040
|
-
const runId = params.get("runId") ?? "";
|
|
1041
|
-
const attachmentId = params.get("attachmentId") ?? "";
|
|
1042
|
-
const name = params.get("name") ?? void 0;
|
|
1043
|
-
if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
|
|
1044
|
-
if (!ATTACHMENT_ID.test(attachmentId)) {
|
|
1045
|
-
return jsonError(400, "`attachmentId` is not valid.");
|
|
1046
|
-
}
|
|
1047
|
-
if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
|
|
1048
|
-
return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
|
|
1049
|
-
}
|
|
1050
|
-
if (authorizeDownload) {
|
|
1051
|
-
const result = await callHook(
|
|
1052
|
-
"authorizeDownload",
|
|
1053
|
-
req,
|
|
1054
|
-
resolve,
|
|
1055
|
-
(ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
|
|
1056
|
-
);
|
|
1057
|
-
const ids = { run_id: runId, attachment_id: attachmentId };
|
|
1058
|
-
if ("response" in result) return refused("download", result.response, ids);
|
|
1059
|
-
const allowed = result.value;
|
|
1060
|
-
if (allowed instanceof Response) return refused("download", allowed, ids);
|
|
1061
|
-
if (allowed !== true && allowed !== false && !warnedDownloadResult) {
|
|
1062
|
-
warnedDownloadResult = true;
|
|
1063
|
-
const warning = `authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`;
|
|
1064
|
-
if (logger) logger.warn(warning);
|
|
1065
|
-
else console.warn(`[seclai] ${warning}`);
|
|
1066
|
-
}
|
|
1067
|
-
if (allowed !== true) return refused("download", jsonError(404, "Not found."), ids);
|
|
1068
|
-
}
|
|
1069
|
-
try {
|
|
1070
|
-
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
1071
|
-
...name ? { downloadName: name } : {},
|
|
1072
|
-
signal: req.signal
|
|
1073
|
-
});
|
|
1074
|
-
const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
|
|
1075
|
-
const headers = new Headers({
|
|
1076
|
-
"content-type": contentType,
|
|
1077
|
-
"cache-control": "private, no-store",
|
|
1078
|
-
"x-content-type-options": "nosniff"
|
|
1079
|
-
});
|
|
1080
|
-
const disposition = upstream.headers.get("content-disposition");
|
|
1081
|
-
if (disposition) headers.set("content-disposition", disposition);
|
|
1082
|
-
const length = upstream.headers.get("content-length");
|
|
1083
|
-
if (length && !upstream.headers.has("content-encoding")) {
|
|
1084
|
-
headers.set("content-length", length);
|
|
1085
|
-
}
|
|
1086
|
-
if (!contentType.toLowerCase().startsWith("application/pdf")) {
|
|
1087
|
-
headers.set("content-security-policy", "sandbox; default-src 'none'");
|
|
1088
|
-
}
|
|
1089
|
-
logger?.info("download served", {
|
|
1090
|
-
run_id: runId,
|
|
1091
|
-
attachment_id: attachmentId,
|
|
1092
|
-
status: upstream.status,
|
|
1093
|
-
content_type: contentType
|
|
1094
|
-
});
|
|
1095
|
-
return new Response(upstream.body, { status: upstream.status, headers });
|
|
1096
|
-
} catch (err) {
|
|
1097
|
-
const res = toErrorResponse(err);
|
|
1098
|
-
logger?.error("download failed", {
|
|
1099
|
-
run_id: runId,
|
|
1100
|
-
attachment_id: attachmentId,
|
|
1101
|
-
status: res.status,
|
|
1102
|
-
...errorLogFields(err)
|
|
1103
|
-
});
|
|
1104
|
-
return res;
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
};
|
|
1108
|
-
return {
|
|
1109
|
-
...handlers,
|
|
1110
|
-
getAttachmentReferences,
|
|
1111
|
-
async handle(req) {
|
|
1112
|
-
const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
|
|
1113
|
-
const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
|
|
1114
|
-
if (!name) return jsonError(404, "Not found.");
|
|
1115
|
-
return handlers[name](req);
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
};
|
|
1119
|
-
const unbound = build(
|
|
1120
|
-
context ? async (req) => context(req) : async () => void 0
|
|
1121
|
-
);
|
|
1122
|
-
return { ...unbound, withContext: (ctx) => build(async () => ctx) };
|
|
1123
|
-
}
|
|
1124
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1125
|
-
0 && (module.exports = {
|
|
1126
|
-
ATTACHMENT_SLOTS_TTL_MS,
|
|
1127
|
-
DEFAULT_API_VERSION,
|
|
1128
|
-
MIN_API_VERSION,
|
|
1129
|
-
consoleLogger,
|
|
1130
|
-
createSeclaiHandlers,
|
|
1131
|
-
deny
|
|
1132
|
-
});
|