Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ strict output schemas.
- App permission, event, or label: update
`scripts/lib/requirements.ts`, setup behavior, and doctor tests.
- Agent harness: declare the env var of its key as the adapter's
`credential` and the hosts it calls as its `egress`; setup and `doctor`
derive the key list, and Sandbox allow-lists include every harness's
hosts. It must give the model only the factory's tools; add it to `HARNESSES` in
`credential`, its exact non-overlapping `credentialBroker` route, and the
hosts it calls as its `egress`; setup and `doctor` derive the key list, and
Sandbox allow-lists include every harness's hosts. It must give the model
only the factory's tools; add it to `HARNESSES` in
`tests/helpers/runner.ts` if it can run the conformance suite.
- Database migration: keep `app/db/migrations/` additive, because one service
can run old code while the other migrates. Derive projections in
Expand Down
24 changes: 14 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,10 @@ can start a run.

Credentials stay out of reach of the agents:

- GitHub write credentials never enter a Sandbox. Clone and fetch credentials
are read-only and removed before repository code or agents run.
- GitHub write credentials never enter a Sandbox. Render brokers read-only
clone and fetch credentials only to the configured repository path.
- Render brokers the model key only to the selected provider endpoint; the
key never enters Sandbox files, environment variables, stdin, or memory.
- Sandboxes reach only an HTTPS allow-list: GitHub and the agents' model APIs.
Add anything your repository's install and verify commands need.
- Nothing in a Sandbox holds a database credential. The Workflows host records
Expand All @@ -99,10 +101,12 @@ Credentials stay out of reach of the agents:
submodules, oversized changes, and branches with human commits, and GitHub
must reproduce the candidate tree SHA before the factory publishes it.

Allowed hosts can still carry data out, and the model key exists in runner
memory during a call. Read the [trust boundaries](docs/architecture.md#trust-boundaries)
and [residual risks](docs/architecture.md#residual-risks) before using private
code or untrusted pull requests.
Allowed hosts can still carry data out, and any Sandbox process can exercise
a credential by making a request that matches its broker route even though it
cannot read the value. Read the
[trust boundaries](docs/architecture.md#trust-boundaries) and
[residual risks](docs/architecture.md#residual-risks) before using private code
or untrusted pull requests.

## Deploy

Expand All @@ -121,9 +125,9 @@ service), and `factory-db` (a Basic-256mb Postgres database). Sandbox and model
usage are billed separately.

Setup is agent-guided. Prepare a fork of this repository, a Render workspace
with Sandboxes access, a Render API key, an Anthropic API key with a spend
limit, and admin access to each target repository. Then open your fork in a
coding agent:
with Sandboxes and Sandbox credential brokering access, a Render API key owned
by a workspace admin, an Anthropic API key with a spend limit, and admin
access to each target repository. Then open your fork in a coding agent:

```text
Set up software-factory by following docs/runbooks/setup.md.
Expand Down Expand Up @@ -152,7 +156,7 @@ Configure each repository in [`factory.config.ts`](factory.config.ts):
| --- | --- | --- |
| `baseBranch` | Yes | Branch used for Triage, implementation, and snapshots |
| `verify` | Yes | Commands that must pass before publishing, and that PR Reviewer runs |
| `install` | No | Dependency command, run after clone credentials are removed |
| `install` | No | Dependency command, run after the repository is cloned |
| `egress` | No | Extra HTTPS hosts the repository's Sandboxes may reach, or `"allow-all"` |

Labels, `minimumPermission`, and limits are set in the same file, with their
Expand Down
7 changes: 3 additions & 4 deletions app/agent-runs/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { z } from "zod";
import type { Agent, OutputSchema } from "../agents/index.js";
import { type Db, workflowsDb } from "../db/index.js";
import { PROTOCOL_VERSION, type RunnerErrorCode, RunnerEvent, type RunnerInput, type ToolName, type Usage } from "../runner/index.js";
import { APP_DIR, type ExecStreamOptions, REPO_DIR, type Sandbox, SCRATCH_DIR } from "../sandbox/index.js";
import { APP_DIR, type ExecStreamOptions, modelCredential, REPO_DIR, type Sandbox, SCRATCH_DIR } from "../sandbox/index.js";
import type { ThreadKey } from "../threads/index.js";
import { errorMessage } from "../util/index.js";
import { AgentRunRecorder } from "./recorder.js";
Expand Down Expand Up @@ -86,12 +86,13 @@ export async function runAgent<Tools extends readonly ToolName[], Output extends
};
const apiKey = process.env[harness.credential]?.trim();
if (!apiKey) throw failure("agent_error", `${harness.credential} is not set: the ${harness.name} harness needs it`);
await sandbox.brokerCredential(modelCredential(harness.credential, harness.credentialBroker, apiKey));

const relay = new LineRelay((line) => {
const event = parseLine(line);
if (event) recorder.onRunnerEvent(event);
});
const stdout = await runInSandbox(sandbox, runnerInput, apiKey, timeoutMs, relay, base.signal);
const stdout = await runInSandbox(sandbox, runnerInput, timeoutMs, relay, base.signal);
const { events, invalidLines } = parseEvents(stdout.text);
summary = summarize(events, invalidLines);
const end = summary.terminal;
Expand Down Expand Up @@ -121,7 +122,6 @@ interface RunnerOutput {
async function runInSandbox(
sandbox: Sandbox,
input: RunnerInput,
apiKey: string,
timeoutMs: number,
relay: LineRelay,
signal?: AbortSignal,
Expand All @@ -131,7 +131,6 @@ async function runInSandbox(
if (mkdir.exitCode !== 0) return { text: "", detail: `mkdir ${runDir} exited ${mkdir.exitCode}: ${tail(mkdir.stderr)}` };
try {
await sandbox.upload(`${runDir}/input.json`, JSON.stringify(input));
await sandbox.upload(`${runDir}/key`, apiKey);
const details: string[] = [];
const deadline = Date.now() + timeoutMs + EXEC_GRACE_MS;
let stderr = "";
Expand Down
2 changes: 1 addition & 1 deletion app/harness/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type { Driver, DriverContext, DriverSession, HarnessRun, HarnessRuntime, Report, SubmitTool } from "../runner/index.js";
export { InvalidInput } from "../runner/index.js";
export { type PiOptions, pi, type ThinkingLevel } from "./pi.js";
export type { Harness } from "./types.js";
export type { CredentialBrokerRoute, Harness } from "./types.js";
30 changes: 28 additions & 2 deletions app/harness/pi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Api, Model, MutableModels } from "@earendil-works/pi-ai";
import { piDriver, type ThinkingLevel } from "../runner/index.js";
import type { Harness } from "./types.js";
import type { CredentialBrokerRoute, Harness } from "./types.js";

export type { ThinkingLevel };

Expand All @@ -15,6 +15,7 @@ export interface PiOptions {
thinkingLevel?: ThinkingLevel;
models?: () => MutableModels;
credential?: string;
credentialBroker?: CredentialBrokerRoute;
egress?: string[];
}

Expand All @@ -24,12 +25,37 @@ export function pi(opts: PiOptions): Harness {
if (!credential) {
throw new Error(`pi: no default key for provider "${provider}"; pass credential, or use one of ${Object.keys(PI_PROVIDER_KEY_ENV).join(", ")}`);
}
const credentialBroker = opts.credentialBroker ?? defaultCredentialBroker(opts.model);
if (!credentialBroker) throw new Error(`pi: no default credential broker route for API "${opts.model.api}"; pass credentialBroker`);
const modelHost = new URL(opts.model.baseUrl).hostname;
if (credentialBroker.domain !== modelHost) {
throw new Error(`pi: credential broker domain "${credentialBroker.domain}" does not match model host "${modelHost}"`);
}
if (!credentialBroker.methods?.length || !credentialBroker.paths?.length) {
throw new Error("pi: credentialBroker must restrict both methods and paths");
}
const thinkingLevel = opts.thinkingLevel ?? "medium";
return {
name: "pi",
label: `${provider}/${id}`,
credential,
egress: opts.egress ?? [new URL(opts.model.baseUrl).hostname],
credentialBroker,
egress: opts.egress ?? [modelHost],
driver: piDriver({ model: opts.model, thinkingLevel, models: opts.models }),
};
}

function defaultCredentialBroker(model: Model<Api>): CredentialBrokerRoute | undefined {
const url = new URL(model.baseUrl);
const route = (path: string, injection: CredentialBrokerRoute["injection"]): CredentialBrokerRoute => ({
domain: url.hostname,
injection,
methods: ["POST"],
paths: [`${url.pathname.replace(/\/+$/, "")}${path}`],
});
if (model.api === "anthropic-messages") return route("/v1/messages", { type: "header", name: "x-api-key" });
if (model.api === "openai-responses") return route("/responses", { type: "header", name: "Authorization", template: `Bearer \${SECRET}` });
if (model.api === "openai-completions")
return route("/chat/completions", { type: "header", name: "Authorization", template: `Bearer \${SECRET}` });
if (model.api === "google-generative-ai") return route("/models/*", { type: "header", name: "x-goog-api-key" });
}
12 changes: 12 additions & 0 deletions app/harness/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import type { HarnessRuntime } from "../runner/index.js";

export interface CredentialBrokerRoute {
readonly domain: string;
readonly injection: {
readonly type: "header" | "basic" | "cookie" | "query";
readonly name?: string;
readonly template?: string;
};
readonly methods?: readonly string[];
readonly paths?: readonly string[];
}

export interface Harness extends HarnessRuntime {
readonly label: string;
readonly credential: string;
readonly credentialBroker: CredentialBrokerRoute;
readonly egress: readonly string[];
}
23 changes: 7 additions & 16 deletions app/runner/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { executeHarness } from "./core/kernel.js";
import { scrubKeys } from "./core/keys.js";
import { PROTOCOL_VERSION, RUNNER_EXIT } from "./core/protocol.js";

const BROKERED_MODEL_KEY = "render-credential-broker";

interface MainIO {
stdin: AsyncIterable<string | Uint8Array>;
write(chunk: string): Promise<void>;
Expand All @@ -35,12 +37,12 @@ export async function main(argv: string[], io: MainIO = processIO()): Promise<nu
return code === "invalid_input" ? RUNNER_EXIT.invalid_input : RUNNER_EXIT.error;
};

let args: { "key-stdin"?: boolean; "self-test"?: boolean };
let args: { "brokered-key"?: boolean; "self-test"?: boolean };
try {
args = parseArgs({
args: argv,
options: {
"key-stdin": { type: "boolean" },
"brokered-key": { type: "boolean" },
"self-test": { type: "boolean" },
},
}).values;
Expand All @@ -55,34 +57,23 @@ export async function main(argv: string[], io: MainIO = processIO()): Promise<nu
emit.redact(secret);
console.log = console.info = console.debug = console.error;

let stdin: string | undefined;
let apiKey: string | undefined;
if (args["key-stdin"]) {
const text = await readAll(io.stdin);
const newline = text.indexOf("\n");
apiKey = (newline === -1 ? text : text.slice(0, newline)).trim();
emit.redact(apiKey);
if (!apiKey) return fail("invalid_input", "--key-stdin: the first line of stdin is empty");
stdin = newline === -1 ? "" : text.slice(newline + 1);
}

if (args["self-test"]) return selfTest(io, agents);

let json: unknown;
try {
json = JSON.parse(stdin ?? (await readAll(io.stdin)));
json = JSON.parse(await readAll(io.stdin));
} catch (err) {
return fail("invalid_input", `stdin is not valid JSON: ${errorMessage(err)}`);
}
const input = parseInput(json);
if (typeof input === "string") return fail("invalid_input", input);
const agent = agents.find((a) => a.id === input.agent_id);
if (!agent) return fail("invalid_input", `unknown agent "${input.agent_id}": the runner bundle doesn't define it`);
if (!apiKey) return fail("invalid_input", "no model key: pass it as the first line of stdin with --key-stdin");
if (!args["brokered-key"]) return fail("invalid_input", "no brokered model key: pass --brokered-key");

try {
if (input.scratch_dir) useScratch(input.scratch_dir);
return await executeHarness({ input, emit, apiKey, startedAt }, agent.harness);
return await executeHarness({ input, emit, apiKey: BROKERED_MODEL_KEY, startedAt }, agent.harness);
} catch (err) {
console.error(err);
if (!emit.terminated) return await fail("agent_error", errorMessage(err));
Expand Down
34 changes: 29 additions & 5 deletions app/sandbox/client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { setTimeout as sleep } from "node:timers/promises";
import { ClientError, Render, ServerError } from "@renderinc/sdk";
import type { SandboxesClient, SandboxUploadContentType } from "@renderinc/sdk/experimental";
import {
ClientError,
Render,
SandboxCredentialNotFoundError,
type SandboxesClient,
type SandboxUploadContentType,
ServerError,
} from "@renderinc/sdk";
import { requireEnv } from "../config/index.js";
import { errorMessage } from "../util/index.js";
import { log } from "./shell.js";
import type { ExecResult, ExecStreamOptions } from "./types.js";
import type { BrokerCredential, ExecResult, ExecStreamOptions } from "./types.js";

export type SandboxApi = Pick<SandboxesClient, "create" | "get" | "exec" | "upload" | "download" | "terminate"> & {
export type SandboxApi = Pick<SandboxesClient, "create" | "get" | "exec" | "upload" | "download" | "terminate" | "listGroups" | "createGroup"> & {
credentials: Pick<SandboxesClient["credentials"], "create" | "update">;
snapshots: Pick<SandboxesClient["snapshots"], "create" | "get" | "list" | "delete">;
};

Expand Down Expand Up @@ -116,6 +123,23 @@ export class SandboxClient {
return file.data;
}

async brokerCredential(sandboxGroupId: string, credential: BrokerCredential): Promise<void> {
const { id: credentialId, ...fields } = credential;
const input = { sandboxGroupId, credentialId, ...fields };
const update = () => this.call(() => this.api.credentials.update(input), { retryOn: TRANSIENT });
try {
await update();
} catch (err) {
if (!(err instanceof SandboxCredentialNotFoundError)) throw err;
try {
await this.call(() => this.api.credentials.create(input), { retryOn: TRANSIENT });
} catch (createErr) {
if (!(createErr instanceof ClientError) || createErr.statusCode !== 409) throw createErr;
await update();
}
}
}

async waitRunning(id: string): Promise<void> {
const until = Date.now() + this.t.bootTimeoutMs;
for (;;) {
Expand Down Expand Up @@ -148,7 +172,7 @@ export function sandboxClient(): SandboxClient {
const workspaceId = requireEnv("RENDER_WORKSPACE_ID");
if (!workspaceId.startsWith("tea-")) throw new Error("RENDER_WORKSPACE_ID must be a tea-… workspace id");
const render = new Render({ useLocalDev: false, token: requireEnv("RENDER_API_KEY"), ownerId: workspaceId });
shared = new SandboxClient(render.experimental.sandboxes);
shared = new SandboxClient(render.sandboxes);
}
return shared;
}
30 changes: 30 additions & 0 deletions app/sandbox/credentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { createHash } from "node:crypto";
import type { RepoContext } from "../config/index.js";
import type { CredentialBrokerRoute } from "../harness/index.js";
import type { BrokerCredential } from "./types.js";

export function githubCredential(repo: RepoContext, value: string): BrokerCredential {
return {
id: credentialId("github", repo.fullName),
domain: "github.com",
value,
injection: { type: "basic", template: `x-access-token:\${SECRET}` },
methods: ["GET", "POST"],
paths: [`/${repo.owner}/${repo.name}.git/**`],
};
}

export function modelCredential(credential: string, route: CredentialBrokerRoute, value: string): BrokerCredential {
return {
id: credentialId("model", credential),
domain: route.domain,
value,
injection: { ...route.injection },
...(route.methods ? { methods: [...route.methods] } : {}),
...(route.paths ? { paths: [...route.paths] } : {}),
};
}

function credentialId(kind: string, source: string): string {
return `factory-${kind}-${createHash("sha256").update(source).digest("hex").slice(0, 24)}`;
}
2 changes: 1 addition & 1 deletion app/sandbox/egress.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { SandboxNetworkPolicy } from "@renderinc/sdk/experimental";
import type { SandboxNetworkPolicy } from "@renderinc/sdk";
import { AGENTS } from "../agents/index.js";
import { assertEgressHosts, type RepoContext } from "../config/index.js";

Expand Down
33 changes: 33 additions & 0 deletions app/sandbox/groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { createHash } from "node:crypto";
import { ClientError } from "@renderinc/sdk";
import type { RepoContext } from "../config/index.js";
import { type SandboxClient, TRANSIENT } from "./client.js";

function sandboxGroupName(repo: Pick<RepoContext, "owner" | "name" | "fullName">): string {
const suffix = createHash("sha256").update(repo.fullName).digest("hex").slice(0, 24);
return `factory-${repo.owner}-${repo.name}-${suffix}`.replace(/[^A-Za-z0-9_.-]/g, "-");
}

export async function ensureSandboxGroup(client: SandboxClient, repo: RepoContext): Promise<string> {
const name = sandboxGroupName(repo);
const existing = await findSandboxGroup(client, name);
if (existing) return existing;
try {
return (await client.call(() => client.api.createGroup({ name }), { retryOn: TRANSIENT })).id;
} catch (err) {
if (!(err instanceof ClientError) || err.statusCode !== 409) throw err;
const raced = await findSandboxGroup(client, name);
if (raced) return raced;
throw err;
}
}

async function findSandboxGroup(client: SandboxClient, name: string): Promise<string | undefined> {
for (let cursor: string | undefined; ; ) {
const page = await client.call(() => client.api.listGroups({ cursor, limit: 100 }), { retryOn: TRANSIENT });
const match = page.find(({ sandboxGroup }) => sandboxGroup.name === name);
if (match) return match.sandboxGroup.id;
cursor = page.at(-1)?.cursor;
if (page.length < 100 || !cursor) return undefined;
}
}
1 change: 1 addition & 0 deletions app/sandbox/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { type SandboxApi, SandboxClient, type SandboxTimings, sandboxClient } from "./client.js";
export { modelCredential } from "./credentials.js";
export { type OpenSandboxDeps, openSandbox, withSandbox } from "./sandbox.js";
export { SAFE_REF, shq } from "./shell.js";
export { type BuiltSnapshot, buildSnapshot, type SnapshotDeps } from "./snapshot.js";
Expand Down
Loading
Loading