One install's production archive was 2 GB: 2457 MB of computer workspaces (983 MB of npm, pip and bun caches, plus 697 MB of node_modules and 446 MB of pip installs), 993 MB of Chrome profile caches, 148 MB of database snapshots and 15 MB of bun-sqlite scratch space, against 178 MB of bot files. Runs had HOME on the mounted workspace and no cache variables, so every side cache was persisted forever, and the archiver tarred the whole volume with one exclusion. - Runs keep their caches inside the container: computerCacheEnv points XDG_CACHE_HOME, npm_config_cache, PIP_CACHE_DIR, BUN_INSTALL_CACHE_DIR and PYTHONPYCACHEPREFIX at the account's own home, never the run's folder. - prune-computer-caches (daily) clears what earlier runs left in bot folders, user folders, workspaces and Chrome profiles, skipping a computer with a task queued or running. The agent clears a profile's regenerable cache at each start and caps its HTTP cache. - listArchiveExclusions is the one definition of what a data archive leaves out, as exact member paths (--no-wildcards --exclude-from): computers, Chrome profile caches, db/.backups and .bun-sqlite. A restore keeps the running install's db/.backups, since no archive carries them, and still leaves computer folders live. - A computer's workspace has a quota (computer_workspace_quota_mb, Settings > General, default AppData.ComputerWorkspaceQuotaMb): the agent measures it, the app refuses a write past it and warns after computer_bash and browser calls. - An upload's bytes go with the messages that carried them, and prune-orphan-media takes what is left after AppData.MediaOrphanKeepDays; moved-aside old computer homes are pruned after AppData.ComputerOldHomeKeepDays. - install.sh removes the image the previous container ran and dangling layers, so updates stop accumulating gigabytes on the host.
148 lines
5.9 KiB
TypeScript
148 lines
5.9 KiB
TypeScript
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
import { AgentState } from "./agent-state";
|
|
import { AgentConfig } from "./config";
|
|
import handleExec from "./handle-exec";
|
|
import handleFileDownload from "./handle-file-download";
|
|
import handleFileStat from "./handle-file-stat";
|
|
import handleFileWrite from "./handle-file-write";
|
|
import handleUsage from "./handle-usage";
|
|
import isAuthorized from "./is-authorized";
|
|
import isPortAnswering from "./is-port-answering";
|
|
import log from "./log";
|
|
import bridgeLoopbackSocket from "./bridge-loopback-socket";
|
|
import bridgeVncSocket from "./bridge-vnc-socket";
|
|
import type { BrowserParking } from "./create-browser-parking";
|
|
import proxyLoopback from "./proxy-loopback";
|
|
import sendJson from "./send-json";
|
|
import serveStaticFile from "./serve-static-file";
|
|
|
|
/**
|
|
* The agent's one port:
|
|
*
|
|
* - `GET /health` (open): 200 once the browser and its tools answer.
|
|
* - `GET /api/info`, `POST /api/exec`, `GET /api/files/stat|download`,
|
|
* `POST /api/files/write`: the app's shell and file access, as gem or
|
|
* as a worker bot's own account (`run_as`).
|
|
* - `GET /api/usage`: how much the workspace holds.
|
|
* - `/mcp`: Playwright MCP, driving the computer's browser.
|
|
* - `/desktop/` and its `/desktop/websockify` websocket: the screen
|
|
* (noVNC over Xvnc), Chrome's whole window.
|
|
* - `/terminal/` and its websocket: a shell in the browser (ttyd).
|
|
*
|
|
* Everything but the health check needs the computer's token. Browser
|
|
* tool calls and screen views wake a parked browser first (`parking`).
|
|
*/
|
|
export default function createAgentServer({ parking }: { parking: BrowserParking }) {
|
|
const server = createServer((req, res) => {
|
|
route({ req, res, parking }).catch((error) => {
|
|
log({ name: "agent", message: `${req.method} ${req.url} failed: ${error?.message || error}` });
|
|
|
|
if (!res.headersSent) sendJson({ res, status: 500, body: { error: String(error?.message || error) } });
|
|
else res.destroy();
|
|
});
|
|
});
|
|
|
|
server.on("upgrade", (req, socket, head) => {
|
|
const pathname = new URL(req.url || "/", "http://agent").pathname;
|
|
|
|
const authorized = isAuthorized({ headers: req.headers, token: AgentConfig.Token });
|
|
|
|
if (authorized && pathname == "/desktop/websockify") {
|
|
const watching = parking.watch();
|
|
|
|
socket.once("close", watching.done);
|
|
bridgeVncSocket({ req, socket, head, port: AgentConfig.VncPort });
|
|
return;
|
|
}
|
|
|
|
if (authorized && pathname.startsWith("/terminal/")) {
|
|
bridgeLoopbackSocket({ req, socket, head, port: AgentConfig.TerminalPort });
|
|
return;
|
|
}
|
|
|
|
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
|
|
});
|
|
|
|
/**
|
|
* Commands and event streams can run long; the app keeps its own
|
|
* timeouts.
|
|
*/
|
|
server.requestTimeout = 0;
|
|
server.headersTimeout = 60_000;
|
|
|
|
return server;
|
|
}
|
|
|
|
async function route({ req, res, parking }: { req: IncomingMessage; res: ServerResponse; parking: BrowserParking }) {
|
|
const { pathname } = new URL(req.url || "/", "http://agent");
|
|
|
|
if (pathname == "/health") {
|
|
const [browser, mcp] = await Promise.all([
|
|
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.CdpPort}/json/version` }),
|
|
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.McpPort}/mcp` }),
|
|
]);
|
|
|
|
return sendJson({ res, status: browser && mcp ? 200 : 503, body: { ok: browser && mcp, browser, mcp } });
|
|
}
|
|
|
|
if (!isAuthorized({ headers: req.headers, token: AgentConfig.Token })) {
|
|
return sendJson({ res, status: 401, body: { error: "Unauthorized" } });
|
|
}
|
|
|
|
if (pathname == "/mcp" || pathname.startsWith("/mcp/")) {
|
|
// A GET is the session's event stream, open for as long as the
|
|
// session: only calls hold parking off while they run.
|
|
const holding = req.method == "GET" ? undefined : parking.hold();
|
|
|
|
if (holding) res.once("close", holding.done);
|
|
|
|
await parking.wake();
|
|
|
|
return proxyLoopback({ req, res, port: AgentConfig.McpPort, unavailable: "The browser tools aren't answering yet." });
|
|
}
|
|
|
|
if (pathname == "/terminal") {
|
|
res.writeHead(302, { location: "terminal/" }).end();
|
|
return;
|
|
}
|
|
|
|
if (pathname.startsWith("/terminal/")) {
|
|
return proxyLoopback({ req, res, port: AgentConfig.TerminalPort, unavailable: "The shell isn't answering yet." });
|
|
}
|
|
|
|
if (pathname == "/" || pathname == "/desktop") {
|
|
res.writeHead(302, { location: "desktop/" }).end();
|
|
return;
|
|
}
|
|
|
|
if (pathname == "/desktop/") return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: "vnc.html" });
|
|
if (pathname.startsWith("/desktop/")) {
|
|
return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: pathname.slice("/desktop/".length) });
|
|
}
|
|
|
|
if (pathname == "/api/info" && req.method == "GET") {
|
|
return sendJson({
|
|
res,
|
|
body: {
|
|
home_dir: AgentConfig.Home,
|
|
workspace_dir: AgentConfig.WorkspaceDir,
|
|
user: AgentConfig.User,
|
|
workers_guarded: AgentState.workers_guarded,
|
|
browser: {
|
|
binary: AgentState.browser_binary,
|
|
version: AgentState.browser_version,
|
|
sandbox: AgentState.browser_sandbox,
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
if (pathname == "/api/exec" && req.method == "POST") return handleExec({ req, res });
|
|
if (pathname == "/api/files/stat" && req.method == "GET") return handleFileStat({ req, res });
|
|
if (pathname == "/api/files/download" && req.method == "GET") return handleFileDownload({ req, res });
|
|
if (pathname == "/api/files/write" && req.method == "POST") return handleFileWrite({ req, res });
|
|
if (pathname == "/api/usage" && req.method == "GET") return handleUsage({ req, res });
|
|
|
|
sendJson({ res, status: 404, body: { error: "Not Found" } });
|
|
}
|