import { spawn } from "node:child_process"; import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import * as Effect from "effect/Effect"; export interface ExecResult { readonly exitCode: number; readonly stdout: string; readonly stderr: string; readonly timedOut: boolean; } export interface WorkspaceHandle { readonly workspaceId: string; readonly exec: ( command: string, options?: { readonly cwd?: string }, ) => Effect.Effect; readonly read: (path: string) => Effect.Effect; readonly write: (path: string, content: string) => Effect.Effect; readonly dispose: () => Effect.Effect; } export interface WorkspaceProvider { readonly provision: (input: { readonly sessionId: string; }) => Effect.Effect; readonly dispose: (workspaceId: string) => Effect.Effect; } export class WorkspaceError extends Error {} const STDOUT_CAP = 8 * 1024; const STDERR_CAP = 2 * 1024; const READ_CAP = 64 * 1024; const WRITE_CAP = 256 * 1024; const EXEC_TIMEOUT_MS = 120_000; const CAP_MARKER = "\n…[output truncated]"; function cap(value: string, limit: number): string { return value.length > limit ? `${value.slice(0, limit)}${CAP_MARKER}` : value; } function run(command: string, args: Array, timeoutMs: number): Promise { return new Promise((resolvePromise) => { const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; let timedOut = false; let settled = false; const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, timeoutMs); const finish = (exitCode: number) => { if (settled) return; settled = true; clearTimeout(timer); resolvePromise({ exitCode, stdout: cap(stdout, STDOUT_CAP), stderr: cap(stderr, STDERR_CAP), timedOut, }); }; child.stdout.on("data", (chunk: Buffer) => { stdout += chunk.toString(); }); child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); }); child.on("error", (error) => { stderr += `\n${error.message}`; finish(127); }); child.on("close", (code) => finish(code ?? (timedOut ? 124 : 1))); }); } function checkedPath(root: string, relative: string): string { const target = resolve(root, relative); if (target !== root && !target.startsWith(`${root}/`)) { throw new WorkspaceError(`path escapes the workspace: ${relative}`); } return target; } export interface DockerWorkspaceOptions { readonly rootDir: string; readonly image?: string | undefined; readonly execTimeoutMs?: number | undefined; } interface DockerWorkspace { readonly workspaceId: string; readonly container: string; readonly workdir: string; readonly root: string; } const WORKDIR = "/home/node/workspace"; export function dockerWorkspaceProvider(options: DockerWorkspaceOptions): WorkspaceProvider { const root = resolve(options.rootDir); const image = options.image ?? "node:22-bookworm"; const timeoutMs = options.execTimeoutMs ?? EXEC_TIMEOUT_MS; const execIn = (workspace: DockerWorkspace, command: string, cwd?: string) => Effect.tryPromise({ try: () => run( "docker", ["exec", "-u", "node", "-w", cwd ?? WORKDIR, workspace.container, "sh", "-lc", command], timeoutMs, ), catch: (error) => new WorkspaceError(`workspace exec failed: ${String(error)}`), }); return { provision: ({ sessionId }) => Effect.gen(function* () { const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "-"); const container = `agent-loop-ws-${safe}`; const hostDir = join(root, safe); yield* Effect.try({ try: () => mkdirSync(hostDir, { recursive: true }), catch: (error) => new WorkspaceError(`workspace directory failed: ${String(error)}`), }); const up = yield* Effect.tryPromise({ try: () => run( "docker", [ "run", "-d", "--name", container, "--user", "node", "-w", WORKDIR, "-v", `${hostDir}:${WORKDIR}`, "--memory", "1g", "--cpus", "1", "--pids-limit", "128", image, "sleep", "infinity", ], 300_000, ), catch: (error) => new WorkspaceError(`workspace container failed to start: ${String(error)}`), }); if (up.exitCode !== 0) { return yield* Effect.fail( new WorkspaceError(`workspace container failed to start: ${up.stderr.slice(0, 300)}`), ); } const workspace: DockerWorkspace = { workspaceId: safe, container, workdir: WORKDIR, root: hostDir, }; yield* execIn(workspace, `mkdir -p ${WORKDIR} && chown node:node ${WORKDIR}`); const handle: WorkspaceHandle = { workspaceId: safe, exec: (command, execOptions) => Effect.gen(function* () { const cwd = execOptions?.cwd ? checkedPath(workspace.root, execOptions.cwd) : undefined; const relativeCwd = cwd === undefined ? undefined : cwd.replace(workspace.root, WORKDIR); return yield* execIn(workspace, command, relativeCwd); }), read: (path) => Effect.try({ try: () => { const target = checkedPath(workspace.root, path); const content = readFileSync(target, "utf8"); return cap(content, READ_CAP); }, catch: (error) => new WorkspaceError(`workspace read failed: ${String(error)}`), }), write: (path, content) => Effect.try({ try: () => { if (content.length > WRITE_CAP) { throw new WorkspaceError(`write content exceeds the ${WRITE_CAP} byte cap`); } const target = checkedPath(workspace.root, path); writeFileSync(target, content); }, catch: (error) => new WorkspaceError(`workspace write failed: ${String(error)}`), }), dispose: () => Effect.try({ try: () => { rmSync(hostDir, { recursive: true, force: true }); }, catch: (error) => new WorkspaceError(`workspace cleanup failed: ${String(error)}`), }), }; return handle; }), dispose: (workspaceId) => Effect.gen(function* () { yield* Effect.tryPromise({ try: () => run("docker", ["rm", "-f", `agent-loop-ws-${workspaceId}`], 30_000), catch: (error) => new WorkspaceError(`workspace teardown failed: ${String(error)}`), }); yield* Effect.try({ try: () => rmSync(join(root, workspaceId), { recursive: true, force: true }), catch: (error) => new WorkspaceError(`workspace cleanup failed: ${String(error)}`), }); }), }; }