103 lines
4.8 KiB
JavaScript
103 lines
4.8 KiB
JavaScript
// #1873 triage-host: the two owner routes of the Triage session. serve.mjs sends a request here only
|
|
// for the instance owner's own session (rootOwner, signed in on the public name, no organization
|
|
// selected); everyone else falls through to the answer an unknown route gives. The read carries the
|
|
// transcript, the last health snapshot and the cards; the write carries one owner message and also
|
|
// needs --send and the same-origin checks the org admin routes use. No body, path, token or
|
|
// exception text reaches a response or a log line.
|
|
|
|
export const TRIAGE_PATHS = Object.freeze(["/api/triage", "/api/triage/message"]);
|
|
export const BODY_MAX = 16384;
|
|
// A read refreshes the snapshot when the one it holds is older than this.
|
|
export const SNAPSHOT_MAX_AGE_MS = 30000;
|
|
export const NO_ROUTE_MESSAGE = "No model route is set for Triage, so Triage will not start. The instance owner sets the route first.";
|
|
|
|
const STATUS = Object.freeze({
|
|
"invalid-request": 400,
|
|
"triage-message-empty": 400,
|
|
"triage-message-too-long": 400,
|
|
"triage-no-route": 409,
|
|
"triage-route-refused": 409,
|
|
"triage-route-invalid": 409,
|
|
"triage-over-cap": 429,
|
|
"triage-busy": 429,
|
|
});
|
|
// Fixed words for each code; the host's own messages are fixed too, but the route never forwards text.
|
|
const MESSAGES = Object.freeze({
|
|
"invalid-request": "the request is not a Triage message",
|
|
"triage-message-empty": "the message is empty",
|
|
"triage-message-too-long": "the message is too long",
|
|
"triage-no-route": NO_ROUTE_MESSAGE,
|
|
"triage-route-refused": "the model route refused to start Triage",
|
|
"triage-route-invalid": "the model route's answer is not usable",
|
|
"triage-route-unreadable": "the model route could not be read",
|
|
"triage-over-cap": "Triage is over its daily token cap and starts again after the time shown",
|
|
"triage-busy": "Triage has too many messages waiting",
|
|
"triage-dir-unsafe": "a Triage directory is not safe to use",
|
|
"triage-start-failed": "the Triage session did not start",
|
|
"outcome-unknown": "Triage did not answer",
|
|
});
|
|
|
|
const json = (res, status, value) => {
|
|
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
res.end(JSON.stringify(value));
|
|
};
|
|
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
|
|
|
|
async function readBody(req) {
|
|
if ((req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "application/json") throw Error();
|
|
const chunks = [];
|
|
let size = 0;
|
|
for await (const chunk of req) {
|
|
size += chunk.length;
|
|
if (size > BODY_MAX) throw Error();
|
|
chunks.push(chunk);
|
|
}
|
|
const value = JSON.parse(Buffer.concat(chunks));
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error();
|
|
if (Object.keys(value).some((k) => k !== "text") || typeof value.text !== "string") throw Error();
|
|
return value.text;
|
|
}
|
|
|
|
// The read's answer. `send` tells the drawer whether it may offer the message box.
|
|
export async function triageView(triage, { send, now = Date.now } = {}) {
|
|
const held = triage.snapshotAt?.() ?? null;
|
|
if (held === null || now() - held > SNAPSHOT_MAX_AGE_MS) await triage.refresh();
|
|
const s = await triage.state();
|
|
return {
|
|
route: s.route,
|
|
...(s.route === "set" ? {} : { routeMessage: NO_ROUTE_MESSAGE }),
|
|
running: s.running,
|
|
lastExit: s.lastExit,
|
|
snapshot: s.snapshot,
|
|
transcript: s.transcript,
|
|
send: send === true,
|
|
};
|
|
}
|
|
|
|
export async function triageHTTP(req, res, { path, triage, send, origin, log = () => {} }) {
|
|
const done = (status, value) => {
|
|
// Method, path and status only.
|
|
log(`${new Date().toISOString()} ${req.method} ${path} ${status}`);
|
|
return json(res, status, value);
|
|
};
|
|
// `code` is always a key of MESSAGES.
|
|
const refuse = (code, extra = {}) => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code], ...extra });
|
|
if (path === "/api/triage") {
|
|
if (req.method !== "GET") return done(405, { error: "method not allowed" });
|
|
try { return done(200, await triageView(triage, { send })); }
|
|
catch { return refuse("outcome-unknown"); }
|
|
}
|
|
if (req.method !== "POST") return done(405, { error: "method not allowed" });
|
|
if (!send) return done(403, { error: "read-only" });
|
|
if (one(req, "origin") !== origin) return done(403, { error: "cross-origin request refused" });
|
|
if (one(req, "sec-fetch-site") !== "same-origin") return done(403, { error: "cross-site request refused" });
|
|
let text;
|
|
try { text = await readBody(req); } catch { return refuse("invalid-request"); }
|
|
try {
|
|
return done(202, await triage.message(text));
|
|
} catch (error) {
|
|
const code = typeof error?.code === "string" && Object.hasOwn(MESSAGES, error.code) ? error.code : "outcome-unknown";
|
|
return refuse(code, code === "triage-over-cap" && typeof error.until === "string" ? { until: error.until } : {});
|
|
}
|
|
}
|