Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
457 lines (451 loc) · 15.3 KB
/
Copy pathserver.mjs
File metadata and controls
457 lines (451 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import { maxUploadBytes, readMediaBytes } from "./shared/media.mjs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { buildDirectory } from "./paths.mjs";
import { isIPv4 } from "node:net";
import { openStore, dataPath, AppError } from "./server/store.mjs";
import { productAPI } from "./server/product.mjs";
import { boundAgents } from "./server/capability-kinds.mjs";
import { createFeishuTransport, feishuWorkers } from "./server/feishu.mjs";
const root = fileURLToPath(new URL(".", import.meta.url));
const routes = [
[/^\/v1\/agents\/sessions$/, ["GET"]],
[/^\/v1\/vaults$/, ["GET", "POST"]],
[/^\/v1\/vaults\/[a-f0-9-]{36}$/, ["GET", "DELETE"]],
[/^\/v1\/vaults\/[a-f0-9-]{36}\/credentials$/, ["GET", "POST"]],
[
/^\/v1\/vaults\/[a-f0-9-]{36}\/credentials\/[a-f0-9-]{36}$/,
["GET", "POST", "DELETE"],
],
[/^\/v1\/agents\/environments\/[a-f0-9-]{36}$/, ["GET"]],
[/^\/v1\/agents\/environments\/[a-f0-9-]{36}\/files$/, ["GET", "POST"]],
[/^\/v1\/files$/, ["POST"]],
[/^\/v1\/agents\/sessions\/[a-f0-9-]{36}\/artifacts$/, ["GET"]],
[
/^\/v1\/agents\/sessions\/[a-f0-9-]{36}\/artifacts\/[a-f0-9-]{36}\/content$/,
["GET"],
],
[/^\/v1\/agents\/sessions\/[a-f0-9-]{36}$/, ["GET"]],
[/^\/v1\/agents\/sessions\/[a-f0-9-]{36}\/(items|turns)$/, ["GET"]],
[/^\/v1\/agents\/sessions\/[a-f0-9-]{36}\/events$/, ["GET", "POST"]],
];
routes.push(
[
/^\/v1\/skills\/skill_[A-Za-z0-9][A-Za-z0-9_-]{0,127}\/versions\/[1-9][0-9]*\/content$/,
["GET"],
],
[/^\/v1\/skills$/, ["GET", "POST"]],
[
/^\/v1\/skills\/skill_[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/,
["GET", "POST", "DELETE"],
],
[
/^\/v1\/skills\/skill_[A-Za-z0-9][A-Za-z0-9_-]{0,127}\/versions$/,
["GET", "POST"],
],
);
const mime = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
".png": "image/png",
".svg": "image/svg+xml",
};
export function configuration(env = process.env) {
const target = new URL(env.OPENAI_BASE_URL || "http://127.0.0.1:8091/v1");
if (
target.username ||
target.password ||
target.search ||
target.hash ||
!["/v1", "/v1/"].includes(target.pathname) ||
!(
target.protocol === "https:" ||
(target.protocol === "http:" &&
["127.0.0.1", "localhost", "[::1]"].includes(target.hostname))
)
) {
throw new Error(
"OPENAI_BASE_URL must be an HTTPS URL, or a loopback HTTP URL, ending in /v1.",
);
}
const key = env.OPENAI_API_KEY?.trim();
if (!key || /[\r\n]/.test(key))
throw new Error("Set OPENAI_API_KEY to a Project API key.");
const port = Number(env.OAC_EXAMPLE_PORT || 18180);
if (!Number.isInteger(port) || port < 1 || port > 65535)
throw new Error("Invalid OAC_EXAMPLE_PORT.");
// The listen address is also the only accepted Host, so it must be concrete.
const host = env.OAC_EXAMPLE_HOST || "127.0.0.1";
if (!isIPv4(host) || host === "0.0.0.0")
throw new Error("OAC_EXAMPLE_HOST must be one IPv4 address of this machine.");
return { target: target.origin, key, port, host };
}
function fail(res, status, message) {
res.writeHead(status, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(JSON.stringify({ error: { message } }));
}
export function coreClient(config, fetchImpl = fetch) {
return async (path, method, body, key) => {
// A FormData body is a multipart upload, which sets its own Content-Type.
const form = body instanceof FormData;
const response = await fetchImpl(`${config.target}${path}`, {
method,
...(body === undefined ? {} : { body: form ? body : JSON.stringify(body) }),
redirect: "manual",
signal: AbortSignal.timeout(form ? 300_000 : 30_000),
headers: {
...(key ? { "Idempotency-Key": key } : {}),
Authorization: `Bearer ${config.key}`,
"OpenAI-Beta": "agents=v1",
...(form ? {} : { "Content-Type": "application/json" }),
},
});
if (response.status >= 300 && response.status < 400)
throw new AppError(502, "Core returned a redirect.");
if (response.ok && path.endsWith("/content")) {
try { return Buffer.from(await readMediaBytes(response)); }
catch (error) { if (error instanceof RangeError) throw new AppError(413, error.message); throw error; }
}
const value =
response.status === 202 || response.status === 204
? undefined
: await response.json();
if (!response.ok)
throw new AppError(
response.status,
value.error?.message || "Core request failed.",
value.error?.code,
);
return value;
};
}
export function createHandler(
config,
{ fetchImpl = fetch, frontend, store, productHandler } = {},
) {
const product =
productHandler ||
(store &&
productAPI(
store,
coreClient(config, fetchImpl),
fetchImpl,
`http://${config.host || "127.0.0.1"}:${config.port}`,
));
const hosts =
(config.host || "127.0.0.1") === "127.0.0.1"
? ["127.0.0.1", "localhost"]
: [config.host];
return async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
const path = req.url.split("?")[0];
const homeNavigation =
req.method === "GET" &&
["/", "/index.html"].includes(path) &&
req.headers["sec-fetch-mode"] === "navigate" &&
req.headers["sec-fetch-dest"] === "document";
const host = /^([^:]+)(?::([1-9]\d{0,4}))?$/.exec(req.headers.host || "");
if (
!host ||
!hosts.includes(host[1]) ||
(host[2] && Number(host[2]) > 65535) ||
(req.headers.origin &&
req.headers.origin !== `http://${req.headers.host}`) ||
(req.headers["sec-fetch-site"] === "cross-site" &&
!homeNavigation &&
!(req.method === "GET" && path === "/oauth/callback"))
) {
return fail(
res,
403,
"This local example accepts same-origin requests only.",
);
}
const url = new URL(req.url, `http://${req.headers.host}`);
if (url.pathname.startsWith("/app/")) {
if (
req.method !== "GET" &&
req.headers.origin !== `http://${req.headers.host}`
)
return fail(
res,
403,
"A same-origin Origin header is required for writes.",
);
try {
if (!product) return fail(res, 404, "Product storage unavailable.");
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (
size >
(url.pathname.startsWith("/app/capabilities/")
? 45 * 1024 * 1024
: 1024 * 1024)
)
return fail(res, 413, "Request too large.");
chunks.push(chunk);
}
let body = {};
try {
if (size) body = JSON.parse(Buffer.concat(chunks));
} catch {
throw new AppError(400, "Invalid JSON.");
}
if (!body || typeof body !== "object" || Array.isArray(body))
throw new AppError(400, "Invalid request.");
const value = await product(req.method, url.pathname, body);
if (Buffer.isBuffer(value)) {
res.writeHead(200, { "Content-Type": "image/png", "Cache-Control": "no-store" });
res.end(value);
return;
}
res.writeHead(200, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(JSON.stringify(value));
} catch (error) {
fail(
res,
error instanceof AppError ? error.status : 502,
error instanceof AppError ? error.message : "无法完成请求,请重试。",
);
}
return;
}
if (
url.pathname.startsWith("/v1/") ||
url.pathname.startsWith("/core/") ||
url.pathname.startsWith("/api/")
) {
if (
!routes.some(
([pattern, methods]) =>
pattern.test(url.pathname) && methods.includes(req.method),
)
) {
return fail(res, 404, "This example does not expose that route.");
}
if (
req.method !== "GET" &&
req.headers.origin !== `http://${req.headers.host}`
) {
return fail(
res,
403,
"A same-origin Origin header is required for writes.",
);
}
// Skills live in Core; one an Agent still binds is not deleted.
const skill = req.method === "DELETE" && url.pathname.match(/^\/v1\/skills\/(skill_[A-Za-z0-9_-]+)$/)?.[1];
if (skill && store && boundAgents(store, "skills", skill).length)
return fail(res, 409, "Skill 仍被 Agent 使用,请先在 Agent 中解除绑定。");
const streaming =
req.method === "GET" && url.pathname.endsWith("/events");
const controller = new AbortController();
const fileWrite =
req.method === "POST" && url.pathname.endsWith("/files");
const timer = setTimeout(
() => controller.abort(),
fileWrite ? 240_000 : 30_000,
);
res.on("close", () => controller.abort());
try {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (
size >
(url.pathname === "/v1/files"
? maxUploadBytes + 64 * 1024
: url.pathname.startsWith("/v1/skills") ||
url.pathname.endsWith("/files")
? 8 * 1024 * 1024
: 1024 * 1024)
)
return fail(res, 413, "Request too large.");
chunks.push(chunk);
}
const headers = {
Authorization: `Bearer ${config.key}`,
"OpenAI-Beta": "agents=v1",
"Content-Type": req.headers["content-type"] || "application/json",
...(streaming ? { Accept: "text/event-stream" } : {}),
};
if (url.pathname.startsWith("/v1/skills") || url.pathname === "/v1/files")
delete headers["OpenAI-Beta"];
if (req.headers["idempotency-key"])
headers["Idempotency-Key"] = req.headers["idempotency-key"];
const upstream = await fetchImpl(
`${config.target}${url.pathname}${url.search}`,
{
method: req.method,
headers,
redirect: "manual",
signal: controller.signal,
...(req.method === "POST" ? { body: Buffer.concat(chunks) } : {}),
},
);
if (upstream.status >= 300 && upstream.status < 400)
return fail(
res,
502,
"Core returned a redirect; check its configured origin.",
);
if (streaming && upstream.ok) {
if (
!upstream.headers
.get("content-type")
?.startsWith("text/event-stream") ||
!upstream.body
)
return fail(res, 502, "Core did not return an event stream.");
clearTimeout(timer);
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-store",
"X-Accel-Buffering": "no",
});
res.flushHeaders();
await pipeline(Readable.fromWeb(upstream.body), res);
return;
}
if (url.pathname.endsWith("/content") && upstream.ok && upstream.body) {
// Downloads stay binary and are never rendered as active browser content.
clearTimeout(timer);
res.writeHead(upstream.status, {
"Content-Type": "application/octet-stream",
...(upstream.headers.has("content-length") &&
!upstream.headers.has("content-encoding")
? { "Content-Length": upstream.headers.get("content-length") }
: {}),
"Content-Disposition":
upstream.headers.get("content-disposition") || "attachment",
"Cache-Control": "no-store",
});
await pipeline(Readable.fromWeb(upstream.body), res);
return;
}
const body = await upstream.text();
res.writeHead(upstream.status, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(body);
} catch {
if (res.headersSent) {
res.destroy();
return;
}
if (!res.destroyed)
fail(
res,
502,
"Cannot reach Core. Check the example server configuration and retry the same request.",
);
} finally {
clearTimeout(timer);
}
return;
}
if (!["GET", "HEAD"].includes(req.method))
return fail(res, 405, "Method not allowed.");
if (frontend) return frontend(req, res);
try {
const path = resolve(
buildDirectory,
`.${decodeURIComponent(url.pathname)}`,
);
if (
!path.startsWith(`${buildDirectory}${sep}`) &&
path !== buildDirectory
)
return fail(res, 404, "Not found.");
const asset = extname(path)
? path
: resolve(buildDirectory, "index.html");
const content = await readFile(asset);
res.writeHead(200, {
"Content-Type": mime[extname(asset)] || "application/octet-stream",
"Cache-Control": "no-cache",
});
res.end(req.method === "HEAD" ? undefined : content);
} catch {
fail(res, 404, "Page not found. Run the example build first.");
}
};
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
const config = configuration();
const server = createServer();
const vite = process.argv.includes("--dev")
? await (
await import("vite")
).createServer({
root,
server: { middlewareMode: true, hmr: { server } },
appType: "spa",
})
: undefined;
const store = openStore(dataPath(config));
const core = coreClient(config);
const productHandler = productAPI(
store,
core,
fetch,
`http://${config.host}:${config.port}`,
);
const feishu = feishuWorkers(
store,
core,
productHandler,
createFeishuTransport,
);
feishu.start();
// Prepared Sessions follow configuration changes within one interval.
const refreshPrepared = () =>
void productHandler.sessions
.refreshWarm()
.catch((error) => console.error("Prepared sessions:", error.message));
// Saved Core Agents and Templates that no longer resolve, as after moving to
// a new Project, are created again on next use.
await productHandler.resources
.verify()
.catch((error) => console.error("Core resources:", error.message));
refreshPrepared();
setInterval(refreshPrepared, 15000).unref();
// Running Turns are watched for stalls and failed Environments.
setInterval(() => void productHandler.sessions.turns.monitor(), 1500).unref();
server.on(
"request",
createHandler(config, {
frontend: vite?.middlewares,
store,
productHandler,
}),
);
server.listen(config.port, config.host, () => {
process.stdout.write(`Parsar: http://${config.host}:${config.port}\n`);
});
for (const signal of ["SIGINT", "SIGTERM"])
process.on(signal, async () => {
await feishu.stop();
server.close(() => store.close());
void vite?.close();
});
}