Multiplayer agent harness for work.
Stage Managed Agents scratch files inside the workspace (#2335)
Joshua France69c6cef1193b
diff --git a/src/sandbox/managed-agents-sandbox.ts b/src/sandbox/managed-agents-sandbox.tsindex f3e535f52..84a5302ba 100644--- a/src/sandbox/managed-agents-sandbox.ts+++ b/src/sandbox/managed-agents-sandbox.ts@@ -25,7 +25,7 @@ import {type CredentialPathSpec,} from "../credentials/resident-paths.ts";import { killableScript, killScript } from "./exec-kill.ts";-import { visibleNotInstalled, visibleTools } from "./sandbox.ts";+import { hasParentPathSegment, visibleNotInstalled, visibleTools } from "./sandbox.ts";import { sandboxScopeName } from "./exec-sandbox-base.ts";import {ManagedAgentsCommandLostError,@@ -52,7 +52,9 @@ import type {TeardownOptions,} from "./sandbox.ts";-const HOME_DIR = "/workspace/home";+const WORKSPACE_ROOT = "/workspace";+const HOME_DIR = `${WORKSPACE_ROOT}/home`;+const TRANSFER_RELAY_BASENAME = ".qm-transfer.";const WORKSPACE_BASENAME = "workspace";const RO_LAYERS_TAR = ".ro-layers.tar";const RO_LAYERS_MANIFEST = ".ro-layers.manifest";@@ -64,6 +66,10 @@ const CHECKPOINT_LABEL = "qm teardown";export const QM_TEMPLATE_TOOLS = ["jq", "rg", "unzip", "wget"];+function transfersDirectly(absPath: string): boolean {+ return (absPath === WORKSPACE_ROOT || absPath.startsWith(`${WORKSPACE_ROOT}/`)) && !hasParentPathSegment(absPath);+}+export interface StoredManagedAgentsSandbox {sessionId: string;sandboxId: string;@@ -324,27 +330,33 @@ export function createManagedAgentsSandbox(workspace: WorkspaceStore, opts: Mana};const procSessions = createExecProcessSessions(procIo);+ const relayFailure = (what: string, r: ExecResult): Error =>+ new Error(`do-managed-agents ${what} failed: ${r.stderr.trim() || `exit ${r.code}`}`);const writeAbsBytes = async (name: string, absPath: string, data: Uint8Array): Promise<void> => {- if (absPath.startsWith(`/${WORKSPACE_BASENAME}/`)) {- await withSession(name, (session) => session.writeFileBytes(absPath, data));- return;- }- const staged = `${HOME_DIR}/.qm-upload-${randomUUID()}`;- await withSession(name, (session) => session.writeFileBytes(staged, data));+ if (transfersDirectly(absPath)) return withSession(name, (session) => session.writeFileBytes(absPath, data));+ const relay = `${WORKSPACE_ROOT}/${TRANSFER_RELAY_BASENAME}${randomUUID()}`;+ await withSession(name, (session) => session.writeFileBytes(relay, data));const moved = await execRaw(name,- `mkdir -p ${shq(absPath.slice(0, absPath.lastIndexOf("/")) || "/")} && mv -f ${shq(staged)} ${shq(absPath)}`,+ `find ${WORKSPACE_ROOT} -maxdepth 1 -name ${shq(`${TRANSFER_RELAY_BASENAME}*`)} -mmin +120 -delete 2>/dev/null; mkdir -p "$(dirname ${shq(absPath)})" && mv -f ${shq(relay)} ${shq(absPath)} || { rm -f ${shq(relay)}; exit 1; }`,60,);- if (moved.code !== 0) {- await execRaw(name, `rm -f ${shq(staged)}`, 30).catch(- swallowAs("managed-agents-sandbox: clean staged upload", undefined),+ if (moved.code !== 0) throw relayFailure(`write ${absPath}`, moved);+ };+ const readAbsBytes = async (name: string, absPath: string): Promise<Uint8Array | null> => {+ if (transfersDirectly(absPath)) return withSession(name, (session) => session.readFileBytes(absPath));+ const relay = `${WORKSPACE_ROOT}/${TRANSFER_RELAY_BASENAME}${randomUUID()}`;+ const copied = await execRaw(name, `test -f ${shq(absPath)} || exit 3; cp ${shq(absPath)} ${shq(relay)}`, 60);+ if (copied.code === 3) return null;+ if (copied.code !== 0) throw relayFailure(`read ${absPath}`, copied);+ try {+ return await withSession(name, (session) => session.readFileBytes(relay));+ } finally {+ await execRaw(name, `rm -f ${shq(relay)}`, 60).catch(+ swallowAs("managed-agents-sandbox: transfer relay cleanup", undefined),);- throw new Error(`do-managed-agents write ${absPath} failed: ${(moved.stderr || moved.stdout).slice(0, 200)}`);}};- const readAbsBytes = (name: string, absPath: string): Promise<Uint8Array | null> =>- withSession(name, (session) => session.readFileBytes(absPath));const installLayerTools = opts.layerToolFiles ? createLayerToolInstaller(opts.layerToolFiles) : null;const execFileOps = createExecFileOps({diff --git a/test/managed-agents-sandbox.test.ts b/test/managed-agents-sandbox.test.tsindex cdef79e65..832548b3d 100644--- a/test/managed-agents-sandbox.test.ts+++ b/test/managed-agents-sandbox.test.ts@@ -20,6 +20,7 @@ import type { HomeSnapshotStore } from "../src/sandbox/home-snapshot.ts";import { supportsProcessSessions } from "../src/sandbox/sandbox.ts";import { createMemoryMap, type DurableMap } from "../src/persistence/durable-map.ts";import { scopeId } from "../src/types.ts";+import { prepareExecutionFiles } from "../src/credentials/execute-files.ts";import { installFakeManagedAgents, type FakeManagedAgents } from "./support/fake-managed-agents.ts";import type { Sandbox } from "../src/sandbox/sandbox.ts";@@ -385,6 +386,51 @@ test("session status wire values map onto backend states", () => {assert.equal(managedAgentsSessionState(undefined), "unspecified");});+const awsCredential = (value: string) => ({+ files: [{ path: ".aws/credentials", contentBase64: Buffer.from(value).toString("base64") }],+ save: async (): Promise<void> => {},+});++test("the guest refuses a transfer outside the workspace, the way the platform does", async () => {+ await sandbox.provision(layers);+ const current = fake.current(scopeName());+ assert.ok(current);+ const session = await fake.client.connect(current!.sessionId);+ await assert.rejects(() => session.writeFileBytes("/tmp/nope.txt", new Uint8Array([1])), /path outside workspace/);+ await assert.rejects(() => session.readFileBytes("/tmp/nope.txt"), /path outside workspace/);+});++const relayLeftovers = async (h: Awaited<ReturnType<Sandbox["provision"]>>): Promise<string> =>+ (await sandbox.run(h, "ls -a /workspace | grep -c '^.qm-transfer' || true")).stdout.trim();++test("per-command credential files outside the workspace stage through the transfer relay", async () => {+ const h = await sandbox.provision(layers);+ const prepared = await prepareExecutionFiles(sandbox, h, [awsCredential("key=abc")]);+ const read = await sandbox.run(h, `cat ${prepared.env.HOME}/.aws/credentials`);+ assert.equal(read.code, 0);+ assert.equal(read.stdout.trim(), "key=abc");+ await prepared.finish();+ assert.equal(await relayLeftovers(h), "0");+});++test("an upload through the relay clears relay files a crash left behind", async () => {+ const h = await sandbox.provision(layers);+ await sandbox.run(h, "touch -d '3 hours ago' /workspace/.qm-transfer.stale");+ const prepared = await prepareExecutionFiles(sandbox, h, [awsCredential("key=sweep")]);+ await prepared.finish();+ assert.equal(await relayLeftovers(h), "0");+});++test("exporting the computer reads its archive through the transfer relay", async () => {+ const h = await sandbox.provision(layers);+ await sandbox.writeFile(h, "notes/export-me.txt", "exported");+ const entries = await sandbox.exportFiles!(h, { include: ["workspace"] });+ const found = entries.find((e) => e.path.endsWith("export-me.txt"));+ assert.ok(found, "expected the written file to appear in the export");+ assert.equal(Buffer.from(found!.data).toString("utf8"), "exported");+ assert.equal(await relayLeftovers(h), "0");+});+test("process sessions stream output through the data plane exec path", async () => {assert.ok(supportsProcessSessions(sandbox));if (!supportsProcessSessions(sandbox)) return;diff --git a/test/support/fake-managed-agents.ts b/test/support/fake-managed-agents.tsindex aa57c8f57..807d8a031 100644--- a/test/support/fake-managed-agents.ts+++ b/test/support/fake-managed-agents.ts@@ -16,13 +16,22 @@ import {} from "../../src/sandbox/managed-agents-client.ts";import { mkdtempSync } from "node:fs";-const GUEST_HOME_DIR = "/workspace/home";+const GUEST_ROOT = "/workspace";+const GUEST_ROOT_PREFIX = new RegExp(`(?<![A-Za-z0-9._-])${GUEST_ROOT}(?![A-Za-z0-9._-])`, "g");++export class FakeOutsideWorkspaceError extends Error {+ constructor(absPath: string) {+ super(`path outside workspace: ${JSON.stringify(absPath)} (workspace ${JSON.stringify(GUEST_ROOT)})`);+ this.name = "FakeOutsideWorkspaceError";+ }+}interface FakeRecord {sessionId: string;sandboxId: string;name: string;state: ManagedAgentsSessionState;+ guestRoot: string;home: string;createdAt: number;loseNextCommand: boolean;@@ -84,17 +93,27 @@ export function installFakeManagedAgents(): FakeManagedAgents {};const remap = (r: FakeRecord, script: string): string => {- const homeRe = r.home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- const remapPath = new RegExp(`${homeRe}/tmp/|${homeRe}(?![A-Za-z0-9._-])|/tmp/`, "g");+ const rootRe = r.guestRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const remapPath = new RegExp(`${rootRe}/tmp/|${rootRe}(?![A-Za-z0-9._-])|/tmp/`, "g");return (`export HOME=${JSON.stringify(r.home)}; ` +script.replace(/\btimeout \d+ /g, "")- .replaceAll(GUEST_HOME_DIR, r.home)- .replace(remapPath, (mm) => (mm.startsWith(r.home) ? mm : `${r.home}/tmp/`))+ .replace(GUEST_ROOT_PREFIX, r.guestRoot)+ .replace(remapPath, (mm) => (mm.startsWith(r.guestRoot) ? mm : `${r.guestRoot}/tmp/`)));};+ const unmap = (r: FakeRecord, out: string): string =>+ out.replaceAll(`${r.guestRoot}/tmp/`, "/tmp/").replaceAll(r.guestRoot, GUEST_ROOT);++ const hostPathFor = (r: FakeRecord, absPath: string): string => {+ const clean = absPath.replace(/\/+$/, "");+ if (clean !== GUEST_ROOT && !clean.startsWith(`${GUEST_ROOT}/`)) throw new FakeOutsideWorkspaceError(absPath);+ if (clean.split("/").includes("..")) throw new FakeOutsideWorkspaceError(absPath);+ return r.guestRoot + clean.slice(GUEST_ROOT.length);+ };+const alive = (r: FakeRecord): void => {if (gone(r.state)) throw new ManagedAgentsSandboxGoneError(r.sessionId, `status ${r.state}`);if (r.state === "paused") r.state = "ready";@@ -123,29 +142,27 @@ export function installFakeManagedAgents(): FakeManagedAgents {throw new ManagedAgentsHitlRejectedError(r.sessionId);}execScripts.push(command);- mkdirSync(join(r.home, "tmp"), { recursive: true });+ mkdirSync(join(r.guestRoot, "tmp"), { recursive: true });const spawned = spawnSync("sh", ["-c", remap(r, command)], {encoding: "buffer",maxBuffer: 128 * 1024 * 1024,env: { ...process.env, COPYFILE_DISABLE: "1" },});return {- stdout: (spawned.stdout ?? Buffer.alloc(0)).toString("utf8"),- stderr: (spawned.stderr ?? Buffer.alloc(0)).toString("utf8"),+ stdout: unmap(r, (spawned.stdout ?? Buffer.alloc(0)).toString("utf8")),+ stderr: unmap(r, (spawned.stderr ?? Buffer.alloc(0)).toString("utf8")),exitCode: spawned.status ?? (spawned.signal ? 137 : -1),};},async readFileBytes(absPath): Promise<Uint8Array | null> {alive(r);- const hostPath = absPath.startsWith(GUEST_HOME_DIR) ? r.home + absPath.slice(GUEST_HOME_DIR.length) : absPath;+ const hostPath = hostPathFor(r, absPath);if (!existsSync(hostPath)) return null;return new Uint8Array(readFileSync(hostPath));},async writeFileBytes(absPath, data): Promise<void> {alive(r);- if (!absPath.startsWith("/workspace/"))- throw new Error('7 PERMISSION_DENIED: path outside workspace (workspace "/workspace")');- const hostPath = absPath.startsWith(GUEST_HOME_DIR) ? r.home + absPath.slice(GUEST_HOME_DIR.length) : absPath;+ const hostPath = hostPathFor(r, absPath);mkdirSync(dirname(hostPath), { recursive: true });writeFileSync(hostPath, Buffer.from(data));},@@ -184,7 +201,7 @@ export function installFakeManagedAgents(): FakeManagedAgents {async kill(): Promise<void> {guestDisconnects.push(r.sessionId);r.state = "destroyed";- rmSync(r.home, { recursive: true, force: true });+ rmSync(r.guestRoot, { recursive: true, force: true });},});@@ -202,7 +219,8 @@ export function installFakeManagedAgents(): FakeManagedAgents {sandboxId: `sbx-${id}`,name: opts.name,state: "ready",- home: join(root, id),+ guestRoot: join(root, id),+ home: join(root, id, "home"),createdAt: ++clock,loseNextCommand: false,rejectNextCommand: false,@@ -244,7 +262,7 @@ export function installFakeManagedAgents(): FakeManagedAgents {const r = records.get(sessionId);if (!r) return;r.state = "destroyed";- rmSync(r.home, { recursive: true, force: true });+ rmSync(r.guestRoot, { recursive: true, force: true });},};@@ -262,7 +280,7 @@ export function installFakeManagedAgents(): FakeManagedAgents {destroy: (name) => {const r = need(name);r.state = "destroyed";- rmSync(r.home, { recursive: true, force: true });+ rmSync(r.guestRoot, { recursive: true, force: true });},loseNextCommand: (name) => {need(name).loseNextCommand = true;