@openlegion/platform 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/README.md +1189 -2
- package/dist/body.d.ts +9 -0
- package/dist/body.js +28 -0
- package/dist/chat-history.d.ts +53 -0
- package/dist/chat-history.js +11 -0
- package/dist/client.d.ts +217 -0
- package/dist/client.js +367 -0
- package/dist/core.d.ts +47 -0
- package/dist/core.js +1 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +81 -0
- package/dist/errors.d.ts +111 -0
- package/dist/errors.js +134 -0
- package/dist/events.d.ts +131 -0
- package/dist/events.js +5 -0
- package/dist/generated/api.d.ts +5505 -0
- package/dist/generated/api.js +446 -0
- package/dist/handler.d.ts +201 -0
- package/dist/handler.js +682 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +12 -0
- package/dist/kit-agents.d.ts +95 -0
- package/dist/kit-agents.js +280 -0
- package/dist/kit-codes.d.ts +279 -0
- package/dist/kit-codes.js +44 -0
- package/dist/kit-connections.d.ts +21 -0
- package/dist/kit-connections.js +189 -0
- package/dist/kit-files.d.ts +8 -0
- package/dist/kit-files.js +117 -0
- package/dist/kit-model-keys.d.ts +8 -0
- package/dist/kit-model-keys.js +86 -0
- package/dist/kit-threads.d.ts +3 -0
- package/dist/kit-threads.js +92 -0
- package/dist/kit-tools.d.ts +21 -0
- package/dist/kit-tools.js +47 -0
- package/dist/kit.d.ts +130 -0
- package/dist/kit.js +155 -0
- package/dist/mcp-server.d.ts +27 -0
- package/dist/mcp-server.js +166 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +6 -0
- package/dist/ol-signed.d.ts +82 -0
- package/dist/ol-signed.js +115 -0
- package/dist/react/add-server.d.ts +90 -0
- package/dist/react/add-server.js +183 -0
- package/dist/react/agent-chat.d.ts +925 -0
- package/dist/react/agent-chat.js +1917 -0
- package/dist/react/agent-editor.d.ts +133 -0
- package/dist/react/agent-editor.js +222 -0
- package/dist/react/agent-kit.d.ts +160 -0
- package/dist/react/agent-kit.js +279 -0
- package/dist/react/agent-list.d.ts +247 -0
- package/dist/react/agent-list.js +248 -0
- package/dist/react/approval-card.d.ts +272 -0
- package/dist/react/approval-card.js +372 -0
- package/dist/react/artifact-card.d.ts +38 -0
- package/dist/react/artifact-card.js +39 -0
- package/dist/react/avatar.d.ts +21 -0
- package/dist/react/avatar.js +33 -0
- package/dist/react/card-ledger.d.ts +30 -0
- package/dist/react/card-ledger.js +49 -0
- package/dist/react/chat-timing.d.ts +121 -0
- package/dist/react/chat-timing.js +229 -0
- package/dist/react/computer-view.d.ts +309 -0
- package/dist/react/computer-view.js +543 -0
- package/dist/react/computer-viewer.d.ts +175 -0
- package/dist/react/computer-viewer.js +555 -0
- package/dist/react/computer-wire.d.ts +178 -0
- package/dist/react/computer-wire.js +244 -0
- package/dist/react/connect-button.d.ts +145 -0
- package/dist/react/connect-button.js +212 -0
- package/dist/react/connection-request.d.ts +16 -0
- package/dist/react/connection-request.js +18 -0
- package/dist/react/connections-list.d.ts +90 -0
- package/dist/react/connections-list.js +76 -0
- package/dist/react/errors.d.ts +250 -0
- package/dist/react/errors.js +146 -0
- package/dist/react/files.d.ts +41 -0
- package/dist/react/files.js +78 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.js +26 -0
- package/dist/react/limit-words.d.ts +80 -0
- package/dist/react/limit-words.js +53 -0
- package/dist/react/markdown.d.ts +42 -0
- package/dist/react/markdown.js +56 -0
- package/dist/react/md-parse.d.ts +106 -0
- package/dist/react/md-parse.js +638 -0
- package/dist/react/model-keys-card.d.ts +94 -0
- package/dist/react/model-keys-card.js +123 -0
- package/dist/react/reload.d.ts +211 -0
- package/dist/react/reload.js +339 -0
- package/dist/react/reveal.d.ts +17 -0
- package/dist/react/reveal.js +22 -0
- package/dist/react/schedule-editor.d.ts +107 -0
- package/dist/react/schedule-editor.js +172 -0
- package/dist/react/schedule-time.d.ts +66 -0
- package/dist/react/schedule-time.js +90 -0
- package/dist/react/styles.css +1274 -0
- package/dist/react/transport.d.ts +49 -0
- package/dist/react/transport.js +380 -0
- package/dist/react/use-connections.d.ts +155 -0
- package/dist/react/use-connections.js +231 -0
- package/dist/react/use-model-keys.d.ts +47 -0
- package/dist/react/use-model-keys.js +57 -0
- package/dist/react/use-threads.d.ts +63 -0
- package/dist/react/use-threads.js +73 -0
- package/dist/react/vault-form.d.ts +92 -0
- package/dist/react/vault-form.js +151 -0
- package/dist/schema.d.ts +47 -0
- package/dist/schema.js +16 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +18 -0
- package/dist/stream.d.ts +129 -0
- package/dist/stream.js +192 -0
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +40 -0
- package/dist/webhooks.d.ts +31 -0
- package/dist/webhooks.js +72 -0
- package/package.json +85 -3
package/dist/handler.js
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
import { readCapped } from "./body.js";
|
|
2
|
+
import { toAgentChatMessages } from "./chat-history.js";
|
|
3
|
+
import { envVar, OpenLegion, subjectNameProblem } from "./client.js";
|
|
4
|
+
import { bytesToHex, fromUtf8, utf8 } from "./crypto.js";
|
|
5
|
+
import { errorLimitOf, OpenLegionError, SignatureVerificationError } from "./errors.js";
|
|
6
|
+
import { checkToolSet } from "./kit.js";
|
|
7
|
+
import { createKitAgentRoutes } from "./kit-agents.js";
|
|
8
|
+
import { createKitThreadRoutes } from "./kit-threads.js";
|
|
9
|
+
import { createKitConnectionRoutes } from "./kit-connections.js";
|
|
10
|
+
import { createKitModelKeyRoutes } from "./kit-model-keys.js";
|
|
11
|
+
import { createKitFileRoutes } from "./kit-files.js";
|
|
12
|
+
import { createMcpServer } from "./mcp-server.js";
|
|
13
|
+
import { OL_CONTEXT_HEADER, OL_SIGNATURE_HEADER, verifyOpenLegionSignature } from "./ol-signed.js";
|
|
14
|
+
import { webhooks as verifier } from "./webhooks.js";
|
|
15
|
+
const DEFAULT_BASE_PATH = "/api/openlegion";
|
|
16
|
+
const MAX_WEBHOOK_BYTES = 1024 * 1024;
|
|
17
|
+
const MAX_CHAT_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
const THREAD_RE = /^thr_[0-9A-Za-z]{1,64}$/;
|
|
19
|
+
const RUN_RE = /^run_[0-9A-Za-z]{1,64}$/;
|
|
20
|
+
const APPROVAL_RE = /^apr_[0-9A-Za-z]{1,64}$/;
|
|
21
|
+
const MAX_DECIDE_BYTES = 1024;
|
|
22
|
+
const MESSAGE_RE = /^msg_[0-9A-Za-z]{1,64}$/;
|
|
23
|
+
const FILE_RE = /^file_[0-9A-Za-z]{1,64}$/;
|
|
24
|
+
const FILES_PER_MESSAGE = 5;
|
|
25
|
+
const UI_MESSAGE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
26
|
+
const RESOLVE_FIX = { string: "Have resolve return a string", shorter: "Have resolve return a shorter name", remove: "Have resolve remove it" };
|
|
27
|
+
const MAX_VAULT_BYTES = 16 * 1024;
|
|
28
|
+
const VAULT_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
|
|
29
|
+
const VAULT_KINDS = ["login", "api_key", "secret"];
|
|
30
|
+
const VAULT_SECRET_FIELDS = ["username", "password", "totp", "value"];
|
|
31
|
+
const MAX_TEMPLATE_BODY_BYTES = 64 * 1024;
|
|
32
|
+
export function canonicalJson(value) {
|
|
33
|
+
if (Array.isArray(value))
|
|
34
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
35
|
+
if (value !== null && typeof value === "object") {
|
|
36
|
+
const o = value;
|
|
37
|
+
return `{${Object.keys(o)
|
|
38
|
+
.filter((k) => o[k] !== undefined)
|
|
39
|
+
.sort()
|
|
40
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)
|
|
41
|
+
.join(",")}}`;
|
|
42
|
+
}
|
|
43
|
+
return JSON.stringify(value);
|
|
44
|
+
}
|
|
45
|
+
async function sha256Hex(text) {
|
|
46
|
+
return bytesToHex(await crypto.subtle.digest("SHA-256", utf8(text)));
|
|
47
|
+
}
|
|
48
|
+
export async function templateDefinition(template, connector) {
|
|
49
|
+
const version = connector ? template.toTemplateSpec(connector) : structuredClone(template.spec);
|
|
50
|
+
const tools = await Promise.all(Object.keys(template.tools)
|
|
51
|
+
.sort()
|
|
52
|
+
.map(async (name) => {
|
|
53
|
+
const t = template.tools[name];
|
|
54
|
+
return { name, description_sha256: await sha256Hex(canonicalJson({ title: t.title ?? null, description: t.description })), input_schema_sha256: await sha256Hex(canonicalJson(t.inputSchema)) };
|
|
55
|
+
}));
|
|
56
|
+
return { object: "template_definition", slug: template.slug, name: template.name, version, tools, hash: await sha256Hex(canonicalJson(version)) };
|
|
57
|
+
}
|
|
58
|
+
function error(status, code, message, extra = {}) {
|
|
59
|
+
return new Response(JSON.stringify({ error: { code, message, ...extra } }), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
60
|
+
}
|
|
61
|
+
function crossOriginRefused(req, allowed) {
|
|
62
|
+
const site = req.headers.get("sec-fetch-site");
|
|
63
|
+
const origin = req.headers.get("origin");
|
|
64
|
+
if (site !== null) {
|
|
65
|
+
if (site === "same-origin" || site === "none")
|
|
66
|
+
return false;
|
|
67
|
+
return origin === null || !allowed.has(origin);
|
|
68
|
+
}
|
|
69
|
+
if (origin === null)
|
|
70
|
+
return false;
|
|
71
|
+
if (allowed.has(origin))
|
|
72
|
+
return false;
|
|
73
|
+
const host = req.headers.get("host");
|
|
74
|
+
let originHost;
|
|
75
|
+
try {
|
|
76
|
+
originHost = new URL(origin).host;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
return host === null || originHost !== host.toLowerCase();
|
|
82
|
+
}
|
|
83
|
+
function allowedOriginSet(list) {
|
|
84
|
+
const out = new Set();
|
|
85
|
+
for (const entry of list ?? []) {
|
|
86
|
+
let parsed;
|
|
87
|
+
try {
|
|
88
|
+
parsed = typeof entry === "string" ? new URL(entry) : null;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
parsed = null;
|
|
92
|
+
}
|
|
93
|
+
const exact = parsed !== null && (parsed.protocol === "https:" || parsed.protocol === "http:") && !entry.includes("*") && parsed.origin === entry;
|
|
94
|
+
if (!exact) {
|
|
95
|
+
throw new TypeError(`createHandler: allowedOrigins takes exact origins, scheme://host[:port] as a browser sends them (lower case, no default port, no path, no trailing slash, no *): ${JSON.stringify(entry)}`);
|
|
96
|
+
}
|
|
97
|
+
out.add(entry);
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
function lastUserMessage(body) {
|
|
102
|
+
const messages = body["messages"];
|
|
103
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
104
|
+
return { problem: "messages must be a non-empty array." };
|
|
105
|
+
const last = messages[messages.length - 1];
|
|
106
|
+
if (!last || typeof last !== "object" || last["role"] !== "user")
|
|
107
|
+
return { problem: "The last message must be the user's." };
|
|
108
|
+
const parts = Array.isArray(last["parts"]) ? last["parts"] : [];
|
|
109
|
+
if (parts.some((p) => p && p["type"] === "file"))
|
|
110
|
+
return { problem: "Upload a file to the files route first, and send its id in a data-attachments part." };
|
|
111
|
+
const attachments = [];
|
|
112
|
+
for (const p of parts) {
|
|
113
|
+
if (!p || p["type"] !== "data-attachments")
|
|
114
|
+
continue;
|
|
115
|
+
const files = p["data"]?.files;
|
|
116
|
+
if (!Array.isArray(files))
|
|
117
|
+
return { problem: "A data-attachments part names its files: {files: [{id: \"file_…\"}]}." };
|
|
118
|
+
for (const f of files) {
|
|
119
|
+
const id = f?.id;
|
|
120
|
+
if (typeof id !== "string" || !FILE_RE.test(id))
|
|
121
|
+
return { problem: "An attachment must be a file id (file_…)." };
|
|
122
|
+
if (!attachments.includes(id))
|
|
123
|
+
attachments.push(id);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (attachments.length > FILES_PER_MESSAGE)
|
|
127
|
+
return { problem: `A message can carry at most ${FILES_PER_MESSAGE} files.` };
|
|
128
|
+
const text = parts
|
|
129
|
+
.filter((p) => p && p["type"] === "text" && typeof p["text"] === "string")
|
|
130
|
+
.map((p) => p["text"])
|
|
131
|
+
.join("\n")
|
|
132
|
+
.trim();
|
|
133
|
+
if (text === "")
|
|
134
|
+
return { problem: "The message has no text." };
|
|
135
|
+
const id = typeof last["id"] === "string" && UI_MESSAGE_ID_RE.test(last["id"]) ? last["id"] : null;
|
|
136
|
+
return { text, id, attachments };
|
|
137
|
+
}
|
|
138
|
+
const CHAT_MESSAGE_RE = /^[0-9A-Za-z_-]{1,100}$/;
|
|
139
|
+
function sites(v) {
|
|
140
|
+
if (v === undefined)
|
|
141
|
+
return undefined;
|
|
142
|
+
return Array.isArray(v) && v.length <= 8 && v.every((x) => typeof x === "string" && x.length > 0 && x.length <= 300) ? v : null;
|
|
143
|
+
}
|
|
144
|
+
function vaultSave(body) {
|
|
145
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
146
|
+
return { problem: "The body must be an object." };
|
|
147
|
+
const b = body;
|
|
148
|
+
for (const k of Object.keys(b))
|
|
149
|
+
if (!["name", "kind", "label", "origins", "hosts", "secret", "ask"].includes(k))
|
|
150
|
+
return { problem: `Unknown field: ${k.slice(0, 40)}.` };
|
|
151
|
+
if (typeof b["name"] !== "string" || !VAULT_NAME_RE.test(b["name"]))
|
|
152
|
+
return { problem: "name is 1 to 48 characters: a-z, 0-9, - and _." };
|
|
153
|
+
if (!VAULT_KINDS.includes(b["kind"]))
|
|
154
|
+
return { problem: "kind is login, api_key or secret." };
|
|
155
|
+
if (b["label"] !== undefined && (typeof b["label"] !== "string" || b["label"].length < 1 || b["label"].length > 200))
|
|
156
|
+
return { problem: "label is 1 to 200 characters." };
|
|
157
|
+
const origins = sites(b["origins"]);
|
|
158
|
+
const hosts = sites(b["hosts"]);
|
|
159
|
+
if (origins === null || hosts === null)
|
|
160
|
+
return { problem: "origins and hosts are lists of at most 8 sites." };
|
|
161
|
+
const a = b["ask"];
|
|
162
|
+
const askKeys = a && typeof a === "object" && !Array.isArray(a) ? Object.keys(a) : null;
|
|
163
|
+
const ask = a;
|
|
164
|
+
if (!askKeys || askKeys.some((k) => k !== "thread" && k !== "message") || typeof ask["thread"] !== "string" || !THREAD_RE.test(ask["thread"]) || typeof ask["message"] !== "string" || !CHAT_MESSAGE_RE.test(ask["message"])) {
|
|
165
|
+
return { problem: "ask is required: {thread, message}, the conversation and the agent's message that asked." };
|
|
166
|
+
}
|
|
167
|
+
const raw = b["secret"];
|
|
168
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
169
|
+
return { problem: "secret is required." };
|
|
170
|
+
const secret = {};
|
|
171
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
172
|
+
if (!VAULT_SECRET_FIELDS.includes(k))
|
|
173
|
+
return { problem: `Unknown secret field: ${k.slice(0, 40)}.` };
|
|
174
|
+
if (v === undefined || v === null || v === "")
|
|
175
|
+
continue;
|
|
176
|
+
if (typeof v !== "string" || v.length > 8192)
|
|
177
|
+
return { problem: `secret.${k} must be text.` };
|
|
178
|
+
secret[k] = v;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
name: b["name"],
|
|
182
|
+
kind: b["kind"],
|
|
183
|
+
...(typeof b["label"] === "string" ? { label: b["label"] } : {}),
|
|
184
|
+
...(origins ? { origins } : {}),
|
|
185
|
+
...(hosts ? { hosts } : {}),
|
|
186
|
+
secret,
|
|
187
|
+
ask: { thread: ask["thread"], message: ask["message"] },
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function askOf(data) {
|
|
191
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
192
|
+
return null;
|
|
193
|
+
const d = data;
|
|
194
|
+
const list = (v) => (Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null);
|
|
195
|
+
const origins = list(d["origins"]);
|
|
196
|
+
const hosts = list(d["hosts"]);
|
|
197
|
+
if (d["object"] !== "vault_request" || typeof d["name"] !== "string" || typeof d["kind"] !== "string" || !origins || !hosts)
|
|
198
|
+
return null;
|
|
199
|
+
return { name: d["name"], kind: d["kind"], origins, hosts };
|
|
200
|
+
}
|
|
201
|
+
export function createHandler(opts = {}) {
|
|
202
|
+
const tools = opts.tools ?? opts.template?.tools ?? {};
|
|
203
|
+
if (opts.tools)
|
|
204
|
+
checkToolSet(opts.tools);
|
|
205
|
+
const resolve = opts.resolve;
|
|
206
|
+
if (resolve !== undefined && typeof resolve !== "function")
|
|
207
|
+
throw new TypeError("createHandler: resolve must be a function; it reads your session and answers the workspace.");
|
|
208
|
+
if (resolve === undefined && opts.allowedOrigins !== undefined)
|
|
209
|
+
throw new TypeError("createHandler: allowedOrigins opens nothing without resolve; the browser routes stay closed until you pass resolve.");
|
|
210
|
+
const allowedOrigins = allowedOriginSet(opts.allowedOrigins);
|
|
211
|
+
const basePath = (opts.basePath ?? DEFAULT_BASE_PATH).replace(/\/+$/, "");
|
|
212
|
+
const rawOnError = opts.onError ?? ((err, where) => console.error(`[openlegion] ${where}:`, err));
|
|
213
|
+
const onError = (err, where) => {
|
|
214
|
+
try {
|
|
215
|
+
rawOnError(err, where);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const mcp = createMcpServer({ tools, secret: () => opts.connectorSecret ?? envVar("OPENLEGION_CONNECTOR_SECRET"), onError });
|
|
221
|
+
let client = opts.client ?? null;
|
|
222
|
+
const ol = () => (client ??= new OpenLegion());
|
|
223
|
+
async function webhook(req) {
|
|
224
|
+
if (req.method !== "POST")
|
|
225
|
+
return error(405, "method_not_allowed", "POST only.");
|
|
226
|
+
const secret = opts.webhookSecret ?? envVar("OPENLEGION_WEBHOOK_SECRET");
|
|
227
|
+
const raw = await readCapped(req, MAX_WEBHOOK_BYTES);
|
|
228
|
+
if (raw === null)
|
|
229
|
+
return error(413, "body_too_large", `At most ${MAX_WEBHOOK_BYTES} bytes.`);
|
|
230
|
+
let event;
|
|
231
|
+
try {
|
|
232
|
+
event = await verifier.constructEvent(raw, req.headers, secret ?? []);
|
|
233
|
+
}
|
|
234
|
+
catch (err) {
|
|
235
|
+
if (err instanceof SignatureVerificationError && err.reason === "no_secret") {
|
|
236
|
+
onError(new Error("No live webhook secret (set OPENLEGION_WEBHOOK_SECRET, or pass webhookSecret): every delivery is refused."), "webhooks");
|
|
237
|
+
return error(500, "not_configured", "This endpoint has no webhook secret.");
|
|
238
|
+
}
|
|
239
|
+
if (err instanceof SignatureVerificationError)
|
|
240
|
+
return error(400, "signature_invalid", "The signature did not verify.", { reason: err.reason });
|
|
241
|
+
return error(400, "invalid_body", "The body is not JSON.");
|
|
242
|
+
}
|
|
243
|
+
const handlers = (opts.webhooks ?? {});
|
|
244
|
+
const fn = Object.prototype.hasOwnProperty.call(handlers, event.type) ? handlers[event.type] : handlers["*"];
|
|
245
|
+
if (fn) {
|
|
246
|
+
try {
|
|
247
|
+
await fn(event, { delivery: req.headers.get("openlegion-delivery"), request: req });
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
onError(err, `webhooks ${event.type}`);
|
|
251
|
+
return error(500, "handler_failed", "The handler failed; OpenLegion will retry the delivery.");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return new Response(JSON.stringify(fn ? { received: true } : { received: true, handled: false }), { status: 200, headers: { "content-type": "application/json" } });
|
|
255
|
+
}
|
|
256
|
+
async function templateRoute(req) {
|
|
257
|
+
if (req.method !== "POST")
|
|
258
|
+
return error(405, "method_not_allowed", "POST only.");
|
|
259
|
+
const contextHeader = req.headers.get(OL_CONTEXT_HEADER);
|
|
260
|
+
const signatureHeader = req.headers.get(OL_SIGNATURE_HEADER);
|
|
261
|
+
if (!contextHeader || !signatureHeader)
|
|
262
|
+
return error(401, "signature_invalid", "Not signed by OpenLegion.", { reason: "missing_headers" });
|
|
263
|
+
const raw = await readCapped(req, MAX_TEMPLATE_BODY_BYTES);
|
|
264
|
+
if (raw === null)
|
|
265
|
+
return error(401, "signature_invalid", `Not verified: the body is over ${MAX_TEMPLATE_BODY_BYTES} bytes.`, { reason: "body_too_large" });
|
|
266
|
+
const verified = await verifyOpenLegionSignature({ contextHeader, signatureHeader, body: raw, secrets: (opts.connectorSecret ?? envVar("OPENLEGION_CONNECTOR_SECRET")) ?? [] });
|
|
267
|
+
if (!verified.ok) {
|
|
268
|
+
if (verified.reason === "no_secret") {
|
|
269
|
+
onError(new Error("No live connector secret (set OPENLEGION_CONNECTOR_SECRET, or pass connectorSecret): every signed call is refused."), "template");
|
|
270
|
+
return error(500, "not_configured", "This route has no connector secret.");
|
|
271
|
+
}
|
|
272
|
+
return error(401, "signature_invalid", "Not signed by OpenLegion.", { reason: verified.reason });
|
|
273
|
+
}
|
|
274
|
+
const template = opts.template;
|
|
275
|
+
if (!template)
|
|
276
|
+
return error(404, "no_template", "This handler has no template: pass `template` to createHandler.");
|
|
277
|
+
let body;
|
|
278
|
+
try {
|
|
279
|
+
body = raw.byteLength === 0 ? {} : JSON.parse(fromUtf8(raw));
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return error(400, "invalid_body", "The body is not JSON.");
|
|
283
|
+
}
|
|
284
|
+
const c = body && typeof body === "object" && !Array.isArray(body) ? body["connector"] : undefined;
|
|
285
|
+
let connector = null;
|
|
286
|
+
if (c !== undefined && c !== null) {
|
|
287
|
+
const ref = c;
|
|
288
|
+
if (typeof c !== "object" || typeof ref["id"] !== "string" || typeof ref["slug"] !== "string")
|
|
289
|
+
return error(400, "invalid_connector", "connector must be {id, slug}.");
|
|
290
|
+
connector = { id: ref["id"], slug: ref["slug"] };
|
|
291
|
+
}
|
|
292
|
+
if (!connector && Object.keys(template.tools).length > 0)
|
|
293
|
+
return error(400, "connector_required", "This template has tools: name the connector that serves them ({connector: {id, slug}}).");
|
|
294
|
+
try {
|
|
295
|
+
return new Response(JSON.stringify(await templateDefinition(template, connector)), { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
if (err instanceof TypeError)
|
|
299
|
+
return error(400, "invalid_connector", err.message);
|
|
300
|
+
onError(err, "template");
|
|
301
|
+
return error(500, "template_failed", "Could not build the template's definition.");
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
async function scope(req, resolve) {
|
|
305
|
+
if (crossOriginRefused(req, allowedOrigins))
|
|
306
|
+
return error(403, "cross_origin", "This origin may not call these routes.");
|
|
307
|
+
let resolved;
|
|
308
|
+
try {
|
|
309
|
+
resolved = await resolve(req);
|
|
310
|
+
}
|
|
311
|
+
catch (err) {
|
|
312
|
+
onError(err, "resolve");
|
|
313
|
+
if (err instanceof OpenLegionError)
|
|
314
|
+
return error(502, "agent_unavailable", "The agent is not available right now.");
|
|
315
|
+
return error(500, "resolve_failed", "Could not read the session.");
|
|
316
|
+
}
|
|
317
|
+
if (!resolved)
|
|
318
|
+
return error(401, "unauthorized", "Sign in first.");
|
|
319
|
+
if (typeof resolved.workspace !== "string" || !resolved.workspace.startsWith("ws_")) {
|
|
320
|
+
onError(new TypeError(`resolve must answer { workspace: "ws_…" }, not ${JSON.stringify(resolved).slice(0, 80)}`), "resolve");
|
|
321
|
+
return error(500, "resolve_failed", "Could not read the session.");
|
|
322
|
+
}
|
|
323
|
+
if (resolved.displayName !== undefined && resolved.displayName !== null) {
|
|
324
|
+
const problem = subjectNameProblem(resolved.displayName);
|
|
325
|
+
if (problem !== null) {
|
|
326
|
+
onError(new TypeError(`resolve's displayName was left out of this request, which went on without it: ${problem.why}. ${RESOLVE_FIX[problem.fix]}, or leave displayName out.`), "resolve");
|
|
327
|
+
const { displayName: _left, ...rest } = resolved;
|
|
328
|
+
return rest;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return resolved;
|
|
332
|
+
}
|
|
333
|
+
const scoped = (s) => ol().workspace(s.workspace, s.subject ? { subject: s.subject, ...(s.displayName !== undefined ? { subjectName: s.displayName } : {}) } : {});
|
|
334
|
+
function upstream(err, where) {
|
|
335
|
+
const status = err instanceof OpenLegionError ? err.status : null;
|
|
336
|
+
if (err instanceof OpenLegionError && status !== null && status >= 400 && status < 500 && status !== 401 && status !== 403) {
|
|
337
|
+
return error(status, err.code ?? err.type, err.message, { type: err.type, ...(err.limit ? { limit: err.limit } : {}) });
|
|
338
|
+
}
|
|
339
|
+
onError(err, where);
|
|
340
|
+
return error(502, "agent_unavailable", "The agent is not available right now.");
|
|
341
|
+
}
|
|
342
|
+
const streamed = (s) => s.toResponse();
|
|
343
|
+
async function chatPost(req, resolve) {
|
|
344
|
+
const s = await scope(req, resolve);
|
|
345
|
+
if (s instanceof Response)
|
|
346
|
+
return s;
|
|
347
|
+
const raw = await readCapped(req, MAX_CHAT_BYTES);
|
|
348
|
+
if (raw === null)
|
|
349
|
+
return error(413, "body_too_large", `At most ${MAX_CHAT_BYTES} bytes.`);
|
|
350
|
+
let body;
|
|
351
|
+
try {
|
|
352
|
+
body = JSON.parse(new TextDecoder().decode(raw));
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return error(400, "invalid_body", "The body is not JSON.");
|
|
356
|
+
}
|
|
357
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
358
|
+
return error(400, "invalid_body", "The body must be an object.");
|
|
359
|
+
const thread = body["id"];
|
|
360
|
+
if (typeof thread !== "string" || !THREAD_RE.test(thread))
|
|
361
|
+
return error(400, "invalid_thread", "id must be the thread's id (thr_…): pass it to useChat({ id }).");
|
|
362
|
+
const trigger = body["trigger"] ?? "submit-message";
|
|
363
|
+
if (trigger === "regenerate-message")
|
|
364
|
+
return error(400, "not_supported", "Regenerating an answer is not supported yet.");
|
|
365
|
+
if (trigger !== "submit-message")
|
|
366
|
+
return error(400, "invalid_trigger", "trigger must be submit-message.");
|
|
367
|
+
if (body["messageId"] !== undefined && body["messageId"] !== null)
|
|
368
|
+
return error(400, "not_supported", "Editing a sent message is not supported: send a new one.");
|
|
369
|
+
const message = lastUserMessage(body);
|
|
370
|
+
if ("problem" in message)
|
|
371
|
+
return error(400, "invalid_message", message.problem);
|
|
372
|
+
try {
|
|
373
|
+
const content = message.attachments.length > 0 ? { content: message.text, attachments: message.attachments } : { content: message.text };
|
|
374
|
+
const stream = await scoped(s).messages.stream(thread, content, message.id ? { idempotencyKey: `chat_${thread}_${message.id}` } : {});
|
|
375
|
+
return streamed(stream);
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
return upstream(err, "chat");
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
async function chatResume(req, resolve, thread) {
|
|
382
|
+
const s = await scope(req, resolve);
|
|
383
|
+
if (s instanceof Response)
|
|
384
|
+
return s;
|
|
385
|
+
try {
|
|
386
|
+
const ws = scoped(s);
|
|
387
|
+
const t = await ws.threads.retrieve(thread);
|
|
388
|
+
if (t.active_run)
|
|
389
|
+
return streamed(await ws.runs.stream(t.active_run));
|
|
390
|
+
return new Response(null, { status: 204, headers: { "openlegion-last-message-at": typeof t.last_message_at === "string" ? t.last_message_at : "" } });
|
|
391
|
+
}
|
|
392
|
+
catch (err) {
|
|
393
|
+
return upstream(err, "chat resume");
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async function chatHistory(req, resolve, thread) {
|
|
397
|
+
const before = new URL(req.url).searchParams.get("before");
|
|
398
|
+
if (before !== null && !MESSAGE_RE.test(before))
|
|
399
|
+
return error(400, "invalid_before", "before must be a message id (msg_…).");
|
|
400
|
+
const s = await scope(req, resolve);
|
|
401
|
+
if (s instanceof Response)
|
|
402
|
+
return s;
|
|
403
|
+
try {
|
|
404
|
+
const page = await scoped(s).messages.list(thread, before === null ? { limit: 20 } : { limit: 20, starting_after: before });
|
|
405
|
+
const oldest = page.data.at(-1)?.id ?? null;
|
|
406
|
+
return Response.json({ object: "list", data: toAgentChatMessages(page.data), has_more: page.has_more, next_before: page.has_more ? oldest : null }, { status: 200, headers: { "cache-control": "no-store" } });
|
|
407
|
+
}
|
|
408
|
+
catch (err) {
|
|
409
|
+
return upstream(err, "chat history");
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
async function runStream(req, resolve, run) {
|
|
413
|
+
const s = await scope(req, resolve);
|
|
414
|
+
if (s instanceof Response)
|
|
415
|
+
return s;
|
|
416
|
+
const last = req.headers.get("last-event-id");
|
|
417
|
+
const after = last !== null && /^\d{1,15}$/.test(last) ? Number(last) : undefined;
|
|
418
|
+
try {
|
|
419
|
+
return streamed(await scoped(s).runs.stream(run, after === undefined ? {} : { after }));
|
|
420
|
+
}
|
|
421
|
+
catch (err) {
|
|
422
|
+
return upstream(err, "run stream");
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async function runOutcome(req, resolve, run) {
|
|
426
|
+
const s = await scope(req, resolve);
|
|
427
|
+
if (s instanceof Response)
|
|
428
|
+
return s;
|
|
429
|
+
const ws = scoped(s);
|
|
430
|
+
let r;
|
|
431
|
+
try {
|
|
432
|
+
r = await ws.runs.retrieve(run);
|
|
433
|
+
}
|
|
434
|
+
catch (err) {
|
|
435
|
+
return upstream(err, "run outcome");
|
|
436
|
+
}
|
|
437
|
+
const failed = r.status === "failed";
|
|
438
|
+
let actions = [];
|
|
439
|
+
if (r.status === "completed" || failed) {
|
|
440
|
+
try {
|
|
441
|
+
const listed = (await ws.actions.list({ run, limit: 100 })).data;
|
|
442
|
+
actions = listed.map((a) => ({ id: a.id, tool: a.tool.replace(/\./g, "_"), status: a.status, outcome: a.outcome, message: a.error ? a.error.message : null, approval: a.approval }));
|
|
443
|
+
}
|
|
444
|
+
catch (err) {
|
|
445
|
+
onError(err, "run outcome actions");
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const body = { object: "run_outcome", id: r.id, status: r.status, code: failed && r.error ? r.error.code : null, message: failed && r.error ? r.error.message : null, limit: failed && r.error ? errorLimitOf(r.error.limit) : null, started_at: r.started_at, ended_at: r.ended_at, actions };
|
|
449
|
+
return Response.json(body, { status: 200 });
|
|
450
|
+
}
|
|
451
|
+
async function runCancel(req, resolve, run) {
|
|
452
|
+
const s = await scope(req, resolve);
|
|
453
|
+
if (s instanceof Response)
|
|
454
|
+
return s;
|
|
455
|
+
try {
|
|
456
|
+
const r = await scoped(s).runs.cancel(run);
|
|
457
|
+
return Response.json({ object: "run", id: r.id, status: r.status }, { status: r.lastResponse.status === 202 ? 202 : 200, headers: { "cache-control": "no-store" } });
|
|
458
|
+
}
|
|
459
|
+
catch (err) {
|
|
460
|
+
return upstream(err, "run cancel");
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function approvalCard(a, canDecide, runRefused) {
|
|
464
|
+
return { object: "approval", id: a.id, status: a.status, title: a.title, fields: a.fields.map((f) => ({ label: f.label, value: f.value, ...(f.detail === true ? { detail: true } : {}), ...(f.truncated === true ? { truncated: true } : {}), ...(f.from_page === true ? { from_page: true } : {}) })), expires_at: a.expires_at, action_hash: a.action ? a.action.action_hash : null, can_decide: canDecide, ...(typeof a.action?.computer_session === "string" ? { computer_session: a.action.computer_session } : {}), ...(runRefused ? { run_refused: runRefused } : {}), ...(a.status === "approved" && a.action ? { action: { status: a.action.status, outcome: a.action.outcome, message: a.action.outcome !== null && a.action.outcome !== "succeeded" && a.action.error ? a.action.error.message : null } } : {}) };
|
|
465
|
+
}
|
|
466
|
+
function runRefusedOf(raw) {
|
|
467
|
+
if (!raw || typeof raw !== "object")
|
|
468
|
+
return undefined;
|
|
469
|
+
const r = raw;
|
|
470
|
+
if (typeof r.code !== "string" || r.code === "" || typeof r.message !== "string")
|
|
471
|
+
return undefined;
|
|
472
|
+
const limit = errorLimitOf(r.limit);
|
|
473
|
+
return { type: "refusal", code: r.code, message: r.message, ...(limit ? { limit } : {}) };
|
|
474
|
+
}
|
|
475
|
+
async function approvalGet(req, resolve, id) {
|
|
476
|
+
const s = await scope(req, resolve);
|
|
477
|
+
if (s instanceof Response)
|
|
478
|
+
return s;
|
|
479
|
+
try {
|
|
480
|
+
const a = await scoped(s).approvals.retrieve(id);
|
|
481
|
+
return Response.json(approvalCard(a, typeof a.can_decide === "boolean" ? a.can_decide : null), { status: 200, headers: { "cache-control": "no-store" } });
|
|
482
|
+
}
|
|
483
|
+
catch (err) {
|
|
484
|
+
return upstream(err, "approval");
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
async function approvalDecide(req, resolve, id) {
|
|
488
|
+
const s = await scope(req, resolve);
|
|
489
|
+
if (s instanceof Response)
|
|
490
|
+
return s;
|
|
491
|
+
const notAllowed = () => error(403, "insufficient_role", "Only an admin can decide this.");
|
|
492
|
+
if (!s.subject)
|
|
493
|
+
return notAllowed();
|
|
494
|
+
const raw = await readCapped(req, MAX_DECIDE_BYTES);
|
|
495
|
+
if (raw === null)
|
|
496
|
+
return error(413, "body_too_large", `At most ${MAX_DECIDE_BYTES} bytes.`);
|
|
497
|
+
let body;
|
|
498
|
+
try {
|
|
499
|
+
body = JSON.parse(new TextDecoder().decode(raw));
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
return error(400, "invalid_body", "The body is not JSON.");
|
|
503
|
+
}
|
|
504
|
+
const b = (body && typeof body === "object" ? body : {});
|
|
505
|
+
if (b.decision !== "approve" && b.decision !== "reject")
|
|
506
|
+
return error(400, "invalid_decision", "decision is approve or reject.");
|
|
507
|
+
if (b.action_hash !== null && typeof b.action_hash !== "string")
|
|
508
|
+
return error(400, "invalid_decision", "action_hash is the card's, or null.");
|
|
509
|
+
try {
|
|
510
|
+
const a = await scoped(s).approvals.decide(id, { decision: b.decision, action_hash: b.action_hash });
|
|
511
|
+
return Response.json(approvalCard(a, null, runRefusedOf(a.run_refused)), { status: 200, headers: { "cache-control": "no-store" } });
|
|
512
|
+
}
|
|
513
|
+
catch (err) {
|
|
514
|
+
if (err instanceof OpenLegionError && err.status === 403)
|
|
515
|
+
return notAllowed();
|
|
516
|
+
return upstream(err, "approval decide");
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
async function vaultState(req, resolve) {
|
|
520
|
+
const s = await scope(req, resolve);
|
|
521
|
+
if (s instanceof Response)
|
|
522
|
+
return s;
|
|
523
|
+
const q = new URL(req.url).searchParams;
|
|
524
|
+
const thread = q.get("thread") ?? "";
|
|
525
|
+
const message = q.get("message") ?? "";
|
|
526
|
+
const name = q.get("name") ?? "";
|
|
527
|
+
if (!THREAD_RE.test(thread) || !MESSAGE_RE.test(message) || !VAULT_NAME_RE.test(name))
|
|
528
|
+
return error(400, "invalid_vault_query", "thread (thr_…), message (msg_…) and name (a vault name) are required.");
|
|
529
|
+
const answer = (saved) => Response.json({ object: "vault_item_state", saved }, { status: 200 });
|
|
530
|
+
try {
|
|
531
|
+
const ws = scoped(s);
|
|
532
|
+
let page;
|
|
533
|
+
try {
|
|
534
|
+
page = await ws.messages.list(thread, { limit: 100 });
|
|
535
|
+
}
|
|
536
|
+
catch (err) {
|
|
537
|
+
if (err instanceof OpenLegionError && err.status === 404)
|
|
538
|
+
return answer(false);
|
|
539
|
+
throw err;
|
|
540
|
+
}
|
|
541
|
+
const m = page.data.find((x) => x.id === message && x.role === "assistant");
|
|
542
|
+
const asks = (m?.parts ?? []).filter((p) => p.type === "data-vault-request").map((p) => askOf(p["data"])).filter((a) => a !== null && a.name === name);
|
|
543
|
+
const ask = asks[asks.length - 1];
|
|
544
|
+
if (!ask)
|
|
545
|
+
return answer(false);
|
|
546
|
+
const item = (await ws.vaultItems.list({ "ask[thread]": thread, "ask[message]": message })).data.find((i) => i.name === name);
|
|
547
|
+
if (!item || item.kind !== ask.kind)
|
|
548
|
+
return answer(false);
|
|
549
|
+
return answer(ask.origins.every((o) => item.origins.includes(o)) && ask.hosts.every((h) => item.hosts.includes(h)));
|
|
550
|
+
}
|
|
551
|
+
catch (err) {
|
|
552
|
+
return upstream(err, "vault state");
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async function vaultPost(req, resolve) {
|
|
556
|
+
const s = await scope(req, resolve);
|
|
557
|
+
if (s instanceof Response)
|
|
558
|
+
return s;
|
|
559
|
+
const raw = await readCapped(req, MAX_VAULT_BYTES);
|
|
560
|
+
if (raw === null)
|
|
561
|
+
return error(413, "body_too_large", `At most ${MAX_VAULT_BYTES} bytes.`);
|
|
562
|
+
let parsed;
|
|
563
|
+
try {
|
|
564
|
+
parsed = JSON.parse(new TextDecoder().decode(raw));
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
return error(400, "invalid_body", "The body is not JSON.");
|
|
568
|
+
}
|
|
569
|
+
const save = vaultSave(parsed);
|
|
570
|
+
if ("problem" in save)
|
|
571
|
+
return error(400, "invalid_vault_item", save.problem);
|
|
572
|
+
try {
|
|
573
|
+
const ws = scoped(s);
|
|
574
|
+
let message = save.ask.message;
|
|
575
|
+
if (!MESSAGE_RE.test(message)) {
|
|
576
|
+
const page = await ws.messages.list(save.ask.thread, { limit: 100 });
|
|
577
|
+
const asked = page.data.find((m) => m.role === "assistant" && (m.parts ?? []).some((p) => p.type === "data-vault-request" && askOf(p["data"])?.name === save.name && askOf(p["data"])?.kind === save.kind));
|
|
578
|
+
if (!asked)
|
|
579
|
+
return error(409, "vault_ask_missing", `This conversation has no ask for vault://${save.name} yet. Try again in a moment.`);
|
|
580
|
+
message = asked.id;
|
|
581
|
+
}
|
|
582
|
+
const item = await ws.vaultItems.create({
|
|
583
|
+
name: save.name,
|
|
584
|
+
kind: save.kind,
|
|
585
|
+
...(save.label ? { label: save.label } : {}),
|
|
586
|
+
...(save.origins ? { origins: save.origins } : {}),
|
|
587
|
+
...(save.hosts ? { hosts: save.hosts } : {}),
|
|
588
|
+
secret: save.secret,
|
|
589
|
+
ask: { thread: save.ask.thread, message },
|
|
590
|
+
});
|
|
591
|
+
return Response.json({ object: "vault_item", id: item.id, handle: item.handle, kind: item.kind, origins: item.origins, hosts: item.hosts }, { status: 200 });
|
|
592
|
+
}
|
|
593
|
+
catch (err) {
|
|
594
|
+
if (err instanceof OpenLegionError && err.status === 409 && err.code === "vault_item_exists")
|
|
595
|
+
return error(409, "vault_kind_mismatch", `vault://${save.name} is saved as another kind. Ask the agent to use another name.`);
|
|
596
|
+
if (err instanceof OpenLegionError && err.status === 403 && err.code === "insufficient_role")
|
|
597
|
+
return error(403, "insufficient_role", err.message);
|
|
598
|
+
return upstream(err, "vault");
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const kitContext = {
|
|
602
|
+
scope: (req) => (resolve ? scope(req, resolve) : Promise.resolve(error(404, "resource_missing", "Not configured."))),
|
|
603
|
+
client: scoped,
|
|
604
|
+
subjectOf: (s) => s.subject,
|
|
605
|
+
upstream,
|
|
606
|
+
error,
|
|
607
|
+
readJson: async (req, max) => {
|
|
608
|
+
const raw = await readCapped(req, max);
|
|
609
|
+
if (raw === null)
|
|
610
|
+
return { ok: false, response: error(413, "body_too_large", `At most ${max} bytes.`) };
|
|
611
|
+
try {
|
|
612
|
+
return { ok: true, value: JSON.parse(new TextDecoder().decode(raw)) };
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
return { ok: false, response: error(400, "invalid_body", "The body is not JSON.") };
|
|
616
|
+
}
|
|
617
|
+
},
|
|
618
|
+
};
|
|
619
|
+
const kitAgents = createKitAgentRoutes(kitContext, opts.allowModelTier ? { allowModelTier: opts.allowModelTier, onError } : {});
|
|
620
|
+
const kitThreads = createKitThreadRoutes(kitContext);
|
|
621
|
+
const kitConnections = createKitConnectionRoutes(kitContext, { basePath, connectReturnUrl: opts.connectReturnUrl });
|
|
622
|
+
const kitModelKeys = createKitModelKeyRoutes(kitContext, opts.allowModelKeys ? { allow: opts.allowModelKeys, onError } : {});
|
|
623
|
+
const kitFiles = createKitFileRoutes(kitContext);
|
|
624
|
+
const notFound = (path) => error(404, "resource_missing", `No OpenLegion route at ${path.slice(0, 200)}. This handler serves ${basePath}/{mcp,template,webhooks,chat,threads,vault,approvals,files,artifacts,agents,template_agents,model_presets,schedules,catalog,connections,connect_sessions,model_keys}; set basePath if you mounted it elsewhere.`);
|
|
625
|
+
return async function handler(req) {
|
|
626
|
+
const path = new URL(req.url).pathname;
|
|
627
|
+
if (path !== basePath && !path.startsWith(`${basePath}/`))
|
|
628
|
+
return notFound(path);
|
|
629
|
+
const route = path.slice(basePath.length).replace(/\/+$/, "") || "/";
|
|
630
|
+
if (route === "/mcp")
|
|
631
|
+
return mcp(req);
|
|
632
|
+
if (route === "/template")
|
|
633
|
+
return templateRoute(req);
|
|
634
|
+
if (route === "/webhooks")
|
|
635
|
+
return webhook(req);
|
|
636
|
+
if (!resolve)
|
|
637
|
+
return notFound(path);
|
|
638
|
+
if (route === "/chat")
|
|
639
|
+
return req.method === "POST" ? chatPost(req, resolve) : error(405, "method_not_allowed", "POST only.");
|
|
640
|
+
if (route === "/vault")
|
|
641
|
+
return req.method === "POST" ? vaultPost(req, resolve) : req.method === "GET" ? vaultState(req, resolve) : error(405, "method_not_allowed", "GET or POST only.");
|
|
642
|
+
const resume = /^\/chat\/([^/]+)\/stream$/.exec(route);
|
|
643
|
+
if (resume) {
|
|
644
|
+
if (req.method !== "GET")
|
|
645
|
+
return error(405, "method_not_allowed", "GET only.");
|
|
646
|
+
return THREAD_RE.test(resume[1]) ? chatResume(req, resolve, resume[1]) : error(400, "invalid_thread", "Not a thread id (thr_…).");
|
|
647
|
+
}
|
|
648
|
+
const history = /^\/chat\/([^/]+)\/messages$/.exec(route);
|
|
649
|
+
if (history) {
|
|
650
|
+
if (req.method !== "GET")
|
|
651
|
+
return error(405, "method_not_allowed", "GET only.");
|
|
652
|
+
return THREAD_RE.test(history[1]) ? chatHistory(req, resolve, history[1]) : error(400, "invalid_thread", "Not a thread id (thr_…).");
|
|
653
|
+
}
|
|
654
|
+
const run = /^\/runs\/([^/]+)\/stream$/.exec(route);
|
|
655
|
+
if (run) {
|
|
656
|
+
if (req.method !== "GET")
|
|
657
|
+
return error(405, "method_not_allowed", "GET only.");
|
|
658
|
+
return RUN_RE.test(run[1]) ? runStream(req, resolve, run[1]) : error(400, "invalid_run", "Not a run id (run_…).");
|
|
659
|
+
}
|
|
660
|
+
const cancel = /^\/runs\/([^/]+)\/cancel$/.exec(route);
|
|
661
|
+
if (cancel) {
|
|
662
|
+
if (req.method !== "POST")
|
|
663
|
+
return error(405, "method_not_allowed", "POST only.");
|
|
664
|
+
return RUN_RE.test(cancel[1]) ? runCancel(req, resolve, cancel[1]) : error(400, "invalid_run", "Not a run id (run_…).");
|
|
665
|
+
}
|
|
666
|
+
const ran = /^\/runs\/([^/]+)$/.exec(route);
|
|
667
|
+
if (ran) {
|
|
668
|
+
if (req.method !== "GET")
|
|
669
|
+
return error(405, "method_not_allowed", "GET only.");
|
|
670
|
+
return RUN_RE.test(ran[1]) ? runOutcome(req, resolve, ran[1]) : error(400, "invalid_run", "Not a run id (run_…).");
|
|
671
|
+
}
|
|
672
|
+
const approval = /^\/approvals\/([^/]+)(\/decide)?$/.exec(route);
|
|
673
|
+
if (approval) {
|
|
674
|
+
if (!APPROVAL_RE.test(approval[1]))
|
|
675
|
+
return error(400, "invalid_approval", "Not an approval id (apr_…).");
|
|
676
|
+
if (approval[2])
|
|
677
|
+
return req.method === "POST" ? approvalDecide(req, resolve, approval[1]) : error(405, "method_not_allowed", "POST only.");
|
|
678
|
+
return req.method === "GET" ? approvalGet(req, resolve, approval[1]) : error(405, "method_not_allowed", "GET only.");
|
|
679
|
+
}
|
|
680
|
+
return (await kitFiles(route, req)) ?? (await kitThreads(route, req)) ?? (await kitAgents(route, req)) ?? (await kitConnections(route, req)) ?? (await kitModelKeys(route, req)) ?? notFound(path);
|
|
681
|
+
};
|
|
682
|
+
}
|