cloud / scripts / cloud-rehearsal / serve.tsmain at aacbc74
// serve.ts — one rehearsal's fake Cloudflare as a process of its own: `node serve.ts <run folder>`.
// start.ts runs it. It reads the folder's run.json, answers until it is stopped, and writes its
// port and pid to server.json once it listens.
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
import { missPrompt, runAgent } from "./ask-agent.ts";
import { loadCloudflareRoutes, routesOfARealInstall } from "./cloudflare-routes.ts";
import { startFakeCloudflare } from "./fake-cloudflare.ts";
import { World } from "./rules.ts";
/** What start.ts decides for a run, in the run's folder as run.json. */
const RunConfig = z.object({
id: z.string(),
/** The tunnel's address: https://fake-cf-123.example.com */
publicUrl: z.string(),
/** The first path segment every call must have (fake-cloudflare.ts). */
secret: z.string(),
/** The agent's command; the prompt goes to its stdin (ask-agent.ts). */
agentCommand: z.array(z.string()),
specCacheDir: z.string(),
/** A list of the routes a real install called, or null (cloudflare-routes.ts). */
realRoutesFile: z.string().nullable(),
});
export type RunConfig = z.infer<typeof RunConfig>;
const runDir = process.argv[2];
if (!runDir || !existsSync(join(runDir, "run.json")))
throw new Error("usage: node serve.ts <run folder>, with run.json in it");
const config = RunConfig.parse(JSON.parse(readFileSync(join(runDir, "run.json"), "utf8")));
const routes = await loadCloudflareRoutes({
cacheDir: config.specCacheDir,
extraRoutes: config.realRoutesFile
? routesOfARealInstall(readFileSync(config.realRoutesFile, "utf8"))
: [],
});
let agentRuns = 0;
const server = await startFakeCloudflare({
runDir,
port: 0,
secret: config.secret,
publicUrl: () => config.publicUrl,
now: () => Date.now(),
isCloudflareRoute: routes.has,
describeCloudflareRoute: routes.about,
// under the chat's own 50-second polling rounds, so that a round outlasts one miss
missWaitMs: 40_000,
maxAgentRuns: 25,
askAgent: (miss) => {
agentRuns += 1;
const world = World.parse(JSON.parse(readFileSync(join(runDir, "world.json"), "utf8")));
return runAgent({
command: config.agentCommand,
runDir,
prompt: missPrompt({ miss, scenario: world.scenario, now: new Date().toISOString() }),
logFile: join(runDir, `agent-${agentRuns}.log`),
timeoutMs: 300_000,
});
},
});
writeFileSync(
join(runDir, "server.json"),
JSON.stringify({ port: server.port, pid: process.pid, routes: routes.count }),
);
console.log(
`The fake Cloudflare ${config.id} listens on ${server.url} for ${config.publicUrl}, with ${routes.count} routes of Cloudflare's.`,
);