An open-source, faster Devin alternative
TypeScript
fix(flue): resolve optional sandboxes on first use
Igor Zalutski56904e129aeb
diff --git a/sdks/flue/README.md b/sdks/flue/README.mdindex b46e580c..5a1321dc 100644--- a/sdks/flue/README.md+++ b/sdks/flue/README.md@@ -9,8 +9,8 @@ tenant script); this package supplies the OC-specific wiring the app opts into.- **`useOcGateway(ctx)` + `DEFAULT_MODEL`** — point the managed `anthropic` provider at the OC modelgateway (org key injected + per-session metering). Call it **inside** your `defineAgent` initializer.- **`route`** — the HTTP-transport opt-in every OC-hosted agent must export (`export { route }`).-- **`ocSandbox(env)`** — a durable OpenComputer-fleet sandbox as the agent's `SandboxApi` (workspace- survives across turns; also serves the repo plane).+- **`ocSandbox(env)`** — optional, demand-driven Linux shell/files. Declaring it makes no network+ request; the first actual sandbox operation resolves the persistent session sandbox.- **`ocRepoTools(env)`** — `publish_pull_request` and friends (open PRs as the OpenComputer GitHub App).- **`@opencomputer/flue/app`** — a default hosting app (`flue()` routes + `/health` + telemetry). Or`import '@opencomputer/flue/wire'` from your own `app.ts` for telemetry only.@@ -18,17 +18,16 @@ tenant script); this package supplies the OC-specific wiring the app opts into.## Minimal agent```ts-import { defineAgent, defineAgentProfile } from '@flue/runtime';-import { useOcGateway, route, ocSandbox, DEFAULT_MODEL, type OcSandboxEnv } from '@opencomputer/flue';+import { defineAgent, defineAgentProfile } from "@flue/runtime";+import { useOcGateway, route, DEFAULT_MODEL } from "@opencomputer/flue";export { route };-export default defineAgent<OcSandboxEnv>((ctx) => {+export default defineAgent((ctx) => {useOcGateway(ctx);return {- profile: defineAgentProfile({ instructions: 'You help customers.' }),- model: DEFAULT_MODEL, // prompt-caching-safe- sandbox: ocSandbox(ctx.env),+ profile: defineAgentProfile({ instructions: "You help customers." }),+ model: DEFAULT_MODEL, // prompt-caching-safe};});```@@ -36,12 +35,13 @@ export default defineAgent<OcSandboxEnv>((ctx) => {`src/app.ts`:```ts-export { default } from '@opencomputer/flue/app';+export { default } from "@opencomputer/flue/app";```Then `flue build --target cloudflare` and `oc agent deploy`. See `oc-flue-starter` for a full example.## Environment (set on the tenant script by the OC deploy)-`OC_GATEWAY`, `OC_SESSION_TOKEN`, `OC_INGEST`, `OC_SANDBOX_API` (+ `OC_SANDBOX_ID` or a resolve seam),-`OC_REPO_API`. Reserved `OC_`/`FLUE_` prefixes are OC-managed.+`OC_GATEWAY` and `OC_SESSION_TOKEN` are always managed by OC. Agents that explicitly use+`ocSandbox` use the managed `OC_SANDBOX_API`; `OC_SANDBOX_ID` may be pre-resolved. Reserved+`OC_`/`FLUE_` prefixes are platform-managed.diff --git a/sdks/flue/src/index.ts b/sdks/flue/src/index.tsindex 12168f24..6e5b6f96 100644--- a/sdks/flue/src/index.ts+++ b/sdks/flue/src/index.ts@@ -1,6 +1,6 @@// @opencomputer/flue — make a stock Flue agent OpenComputer-native (design 013 §4/§5).// - useOcGateway + route + DEFAULT_MODEL: point managed anthropic at the OC gateway; HTTP-transport opt-in.-// - ocSandbox: a durable OC-fleet sandbox as the agent's SandboxApi.+// - ocSandbox: optional, demand-driven durable shell/files as the agent's SandboxApi.// - ocRepoTools: publish/repo tools (repo plane).// - installOcObserver: forward lifecycle/usage to OC_INGEST.// Default hosting app is at `@opencomputer/flue/app`; `@opencomputer/flue/wire` is the telemetry-onlydiff --git a/sdks/flue/src/sandbox.test.ts b/sdks/flue/src/sandbox.test.tsnew file mode 100644index 00000000..7c6e0ae8--- /dev/null+++ b/sdks/flue/src/sandbox.test.ts@@ -0,0 +1,97 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { ocSandbox } from "./sandbox.js";++afterEach(() => vi.unstubAllGlobals());++async function initialize(id = "ses_1") {+ const factory = ocSandbox({+ OC_SANDBOX_API: "https://api.opencomputer.test",+ OC_SESSION_TOKEN: "deploy-token",+ });+ const env = await factory.createSessionEnv({ id });+ // Flue beta.9's fixed harness bootstrap sequence.+ expect(await env.exists("/workspace/AGENTS.md")).toBe(false);+ expect(await env.exists("/workspace/CLAUDE.md")).toBe(false);+ expect(await env.exists("/workspace/.agents/skills")).toBe(false);+ expect(await env.readdir("/workspace")).toEqual([]);+ return { factory, env };+}++describe("ocSandbox lazy allocation", () => {+ it("makes zero requests for initialization and model/custom-tool-only work", async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ await initialize();+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("shares one resolution across concurrent first operations and reuses it", async () => {+ const calls: string[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ calls.push(url);+ if (url.includes("/flue/session-sandbox")) {+ return new Response(JSON.stringify({ sandbox_id: "sbx_1" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }+ if (url.includes("/exec/run")) {+ return new Response(+ JSON.stringify({ exitCode: 0, stdout: "ok", stderr: "" }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ );+ }+ return new Response("hello", { status: 200 });+ }),+ );+ const { factory, env } = await initialize();+ await Promise.all([env.exec("echo one"), env.readFile("note.txt")]);+ const laterTurn = await factory.createSessionEnv({ id: "ses_1" });+ expect(await laterTurn.exists("/workspace/AGENTS.md")).toBe(false);+ expect(await laterTurn.exists("/workspace/CLAUDE.md")).toBe(false);+ expect(await laterTurn.exists("/workspace/.agents/skills")).toBe(false);+ expect(await laterTurn.readdir("/workspace")).toEqual([]);+ await laterTurn.exec("echo later turn");++ expect(+ calls.filter((url) => url.includes("/flue/session-sandbox")),+ ).toHaveLength(1);+ expect(+ calls.filter((url) => url.includes("/sandboxes/sbx_1/")),+ ).toHaveLength(3);+ });++ it("surfaces resolution failure to the invoking operation and permits a later retry", async () => {+ let resolves = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/flue/session-sandbox")) {+ resolves++;+ if (resolves === 1)+ return new Response("unavailable", { status: 503 });+ return new Response(JSON.stringify({ sandbox_id: "sbx_retry" }), {+ status: 200,+ });+ }+ return new Response(+ JSON.stringify({ exitCode: 0, stdout: "ok", stderr: "" }),+ { status: 200 },+ );+ }),+ );+ const { env } = await initialize();+ await expect(env.exec("first")).rejects.toThrow(+ "oc sandbox resolve failed",+ );+ await expect(env.exec("second")).resolves.toMatchObject({ exitCode: 0 });+ expect(resolves).toBe(2);+ });+});diff --git a/sdks/flue/src/sandbox.ts b/sdks/flue/src/sandbox.tsindex c66f835d..ea1476cb 100644--- a/sdks/flue/src/sandbox.ts+++ b/sdks/flue/src/sandbox.ts@@ -1,10 +1,10 @@-// ocSandbox — a Flue `SandboxApi`/`SandboxFactory` (design 013 §5) driving an OpenComputer fleet sandbox-// over its public HTTP API, so the workspace is DURABLE across turns (git checkout + build cache survive)-// and also serves the repo plane (§5.2). Public-seam impl, no trick.+// ocSandbox — an optional Flue `SandboxApi`/`SandboxFactory` driving an OpenComputer fleet sandbox+// over its public HTTP API. Merely declaring the adapter does not allocate a machine: the first real+// shell/file operation resolves the session sandbox and all concurrent callers share that promise.//-// The session's sandbox is provisioned by the control plane at Flue-session create (§5.2); this client-// resolves it per instance and proxies exec/fs. Endpoints (from @opencomputer/sdk, all fetch-based so-// they run in a CF DO):+// The first real shell/file operation resolves (and, when needed, provisions) the persistent session+// sandbox through the control plane; this client then proxies exec/fs. Endpoints (from+// @opencomputer/sdk, all fetch-based so they run in a CF DO):// exec POST {base}/sandboxes/{id}/exec/run {args:["-c",cmd],cwd,envs,timeout} -> {exitCode,stdout,stderr}// read GET {base}/sandboxes/{id}/files?path=// write PUT {base}/sandboxes/{id}/files?path= (body = content)@@ -12,7 +12,13 @@// stat/exists/mkdir/rm compose over exec (shell), mirroring cloudflareSandbox.import { createSandboxSessionEnv } from "@flue/runtime";-import type { SandboxApi, SandboxFactory, FileStat, ShellResult, SessionEnv } from "@flue/runtime";+import type {+ SandboxApi,+ SandboxFactory,+ FileStat,+ ShellResult,+ SessionEnv,+} from "@flue/runtime";import type { OcEnv } from "./gateway.js";import { ocResolveEnv } from "./cf-env.js";@@ -20,14 +26,18 @@ import { ocResolveEnv } from "./cf-env.js";export const WORKSPACE_CWD = "/workspace";export interface OcSandboxEnv extends OcEnv {- /** OC sandbox API base, e.g. `https://app.opencomputer.dev/api`. */+ /** OC sandbox API base, e.g. `https://api.opencomputer.dev`. */OC_SANDBOX_API?: string;/** Pre-resolved sandbox id, when the control plane injects it; else resolved lazily (see below). */OC_SANDBOX_ID?: string;}class OcSandboxApi implements SandboxApi {- constructor(private readonly base: string, private readonly token: string, private sandboxId: string) {}+ constructor(+ private readonly base: string,+ private readonly token: string,+ private sandboxId: string,+ ) {}private headers(extra?: Record<string, string>): Record<string, string> {return { authorization: `Bearer ${this.token}`, ...extra };@@ -36,55 +46,186 @@ class OcSandboxApi implements SandboxApi {return `${this.base.replace(/\/+$/, "")}/sandboxes/${this.sandboxId}${suffix}`;}- async exec(command: string, options?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number; signal?: AbortSignal }): Promise<ShellResult> {- const body: Record<string, unknown> = { args: ["-c", command], timeout: Math.ceil((options?.timeoutMs ?? 60_000) / 1000) };+ async exec(+ command: string,+ options?: {+ cwd?: string;+ env?: Record<string, string>;+ timeoutMs?: number;+ signal?: AbortSignal;+ },+ ): Promise<ShellResult> {+ const body: Record<string, unknown> = {+ args: ["-c", command],+ timeout: Math.ceil((options?.timeoutMs ?? 60_000) / 1000),+ };if (options?.cwd) body.cwd = options.cwd;if (options?.env) body.envs = options.env;- const resp = await fetch(this.url("/exec/run"), { method: "POST", headers: this.headers({ "content-type": "application/json" }), body: JSON.stringify(body), signal: options?.signal });- if (!resp.ok) throw new Error(`oc sandbox exec failed: ${resp.status} ${(await resp.text()).slice(0, 200)}`);- const r = (await resp.json()) as { exitCode?: number; stdout?: string; stderr?: string };- return { stdout: r.stdout ?? "", stderr: r.stderr ?? "", exitCode: r.exitCode ?? 0 };+ const resp = await fetch(this.url("/exec/run"), {+ method: "POST",+ headers: this.headers({ "content-type": "application/json" }),+ body: JSON.stringify(body),+ signal: options?.signal,+ });+ if (!resp.ok)+ throw new Error(+ `oc sandbox exec failed: ${resp.status} ${(await resp.text()).slice(0, 200)}`,+ );+ const r = (await resp.json()) as {+ exitCode?: number;+ stdout?: string;+ stderr?: string;+ };+ return {+ stdout: r.stdout ?? "",+ stderr: r.stderr ?? "",+ exitCode: r.exitCode ?? 0,+ };}async readFile(path: string): Promise<string> {- const resp = await fetch(this.url(`/files?path=${encodeURIComponent(path)}`), { headers: this.headers() });+ const resp = await fetch(+ this.url(`/files?path=${encodeURIComponent(path)}`),+ { headers: this.headers() },+ );if (!resp.ok) throw new Error(`oc sandbox read ${path}: ${resp.status}`);return resp.text();}async readFileBuffer(path: string): Promise<Uint8Array> {- const resp = await fetch(this.url(`/files?path=${encodeURIComponent(path)}`), { headers: this.headers() });+ const resp = await fetch(+ this.url(`/files?path=${encodeURIComponent(path)}`),+ { headers: this.headers() },+ );if (!resp.ok) throw new Error(`oc sandbox read ${path}: ${resp.status}`);return new Uint8Array(await resp.arrayBuffer());}async writeFile(path: string, content: string | Uint8Array): Promise<void> {- const resp = await fetch(this.url(`/files?path=${encodeURIComponent(path)}`), { method: "PUT", headers: this.headers({ "content-type": "application/octet-stream" }), body: content });+ const resp = await fetch(+ this.url(`/files?path=${encodeURIComponent(path)}`),+ {+ method: "PUT",+ headers: this.headers({ "content-type": "application/octet-stream" }),+ body: content,+ },+ );if (!resp.ok) throw new Error(`oc sandbox write ${path}: ${resp.status}`);}async readdir(path: string): Promise<string[]> {- const resp = await fetch(this.url(`/files/list?path=${encodeURIComponent(path)}`), { headers: this.headers() });+ const resp = await fetch(+ this.url(`/files/list?path=${encodeURIComponent(path)}`),+ { headers: this.headers() },+ );if (!resp.ok) throw new Error(`oc sandbox list ${path}: ${resp.status}`);- const entries = (await resp.json()) as Array<{ name?: string; path?: string }>;- return entries.map((e) => e.name ?? (e.path ?? "").split("/").pop() ?? "").filter(Boolean);+ const entries = (await resp.json()) as Array<{+ name?: string;+ path?: string;+ }>;+ return entries+ .map((e) => e.name ?? (e.path ?? "").split("/").pop() ?? "")+ .filter(Boolean);}// stat/exists/mkdir/rm over the shell (mirrors cloudflareSandbox — the files API has no stat/mkdir/rm).async stat(path: string): Promise<FileStat> {const r = await this.exec(`stat -L -c '%s/%F' ${shq(path)}`);- if (r.exitCode !== 0) throw new Error(`oc sandbox stat ${path}: ${r.stderr.slice(0, 120)}`);+ if (r.exitCode !== 0)+ throw new Error(`oc sandbox stat ${path}: ${r.stderr.slice(0, 120)}`);const [sizeStr, kind = ""] = r.stdout.trim().split("/");- return { isFile: /regular file/.test(kind), isDirectory: /directory/.test(kind), size: Number(sizeStr) || undefined };+ return {+ isFile: /regular file/.test(kind),+ isDirectory: /directory/.test(kind),+ size: Number(sizeStr) || undefined,+ };}async exists(path: string): Promise<boolean> {return (await this.exec(`test -e ${shq(path)}`)).exitCode === 0;}async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {- const r = await this.exec(`mkdir ${options?.recursive ? "-p " : ""}${shq(path)}`);- if (r.exitCode !== 0) throw new Error(`oc sandbox mkdir ${path}: ${r.stderr.slice(0, 120)}`);+ const r = await this.exec(+ `mkdir ${options?.recursive ? "-p " : ""}${shq(path)}`,+ );+ if (r.exitCode !== 0)+ throw new Error(`oc sandbox mkdir ${path}: ${r.stderr.slice(0, 120)}`);}- async rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {+ async rm(+ path: string,+ options?: { recursive?: boolean; force?: boolean },+ ): Promise<void> {const flags = `${options?.recursive ? "r" : ""}${options?.force ? "f" : ""}`;const r = await this.exec(`rm ${flags ? `-${flags} ` : ""}${shq(path)}`);- if (r.exitCode !== 0 && !options?.force) throw new Error(`oc sandbox rm ${path}: ${r.stderr.slice(0, 120)}`);+ if (r.exitCode !== 0 && !options?.force)+ throw new Error(`oc sandbox rm ${path}: ${r.stderr.slice(0, 120)}`);+ }+}++/**+ * Flue discovers workspace context while initializing every harness. OC does not materialize repo+ * sources for Flue sessions yet, and a newly allocated sandbox is empty, so those fixed bootstrap+ * probes must not turn a model-only turn into a machine allocation. Any operation outside the exact+ * discovery sequence falls through to the real remote environment.+ */+class LazyOcSandboxApi implements SandboxApi {+ private bootstrapping = true;+ private readonly bootstrapAbsent: Set<string>;++ constructor(+ private readonly cwd: string,+ private readonly load: () => Promise<SandboxApi>,+ ) {+ this.bootstrapAbsent = new Set([+ `${cwd}/AGENTS.md`,+ `${cwd}/CLAUDE.md`,+ `${cwd}/.agents/skills`,+ ]);+ }++ private remote(): Promise<SandboxApi> {+ this.bootstrapping = false;+ return this.load();+ }++ async exec(+ command: string,+ options?: {+ cwd?: string;+ env?: Record<string, string>;+ timeoutMs?: number;+ signal?: AbortSignal;+ },+ ): Promise<ShellResult> {+ return (await this.remote()).exec(command, options);+ }+ async readFile(path: string): Promise<string> {+ return (await this.remote()).readFile(path);+ }+ async readFileBuffer(path: string): Promise<Uint8Array> {+ return (await this.remote()).readFileBuffer(path);+ }+ async writeFile(path: string, content: string | Uint8Array): Promise<void> {+ return (await this.remote()).writeFile(path, content);+ }+ async stat(path: string): Promise<FileStat> {+ return (await this.remote()).stat(path);+ }+ async readdir(path: string): Promise<string[]> {+ if (this.bootstrapping && path === this.cwd) {+ this.bootstrapping = false;+ return [];+ }+ return (await this.remote()).readdir(path);+ }+ async exists(path: string): Promise<boolean> {+ if (this.bootstrapping && this.bootstrapAbsent.has(path)) return false;+ return (await this.remote()).exists(path);+ }+ async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {+ return (await this.remote()).mkdir(path, options);+ }+ async rm(+ path: string,+ options?: { recursive?: boolean; force?: boolean },+ ): Promise<void> {+ return (await this.remote()).rm(path, options);}}@@ -94,38 +235,74 @@ function shq(s: string): string {/** Resolve the session's OC sandbox id (control-plane seam). Uses the injected id when present, else a* documented resolve endpoint keyed by the session id. Kept a single point so W1/W5 can pin the contract. */-async function resolveSandboxId(env: OcSandboxEnv, sessionId: string): Promise<string> {+async function resolveSandboxId(+ env: OcSandboxEnv,+ sessionId: string,+): Promise<string> {if (env.OC_SANDBOX_ID) return env.OC_SANDBOX_ID;const base = (env.OC_SANDBOX_API ?? "").replace(/\/+$/, "");- const resp = await fetch(`${base}/flue/session-sandbox?session=${encodeURIComponent(sessionId)}`, {- method: "POST",- headers: { authorization: `Bearer ${env.OC_SESSION_TOKEN ?? ""}` },- });- if (!resp.ok) throw new Error(`oc sandbox resolve failed for ${sessionId}: ${resp.status}`);- return ((await resp.json()) as { sandbox_id: string }).sandbox_id;+ const resp = await fetch(+ `${base}/flue/session-sandbox?session=${encodeURIComponent(sessionId)}`,+ {+ method: "POST",+ headers: { authorization: `Bearer ${env.OC_SESSION_TOKEN ?? ""}` },+ },+ );+ if (!resp.ok)+ throw new Error(+ `oc sandbox resolve failed for ${sessionId}: ${resp.status}`,+ );+ const sandboxId = ((await resp.json()) as { sandbox_id?: unknown })+ .sandbox_id;+ if (typeof sandboxId !== "string" || !sandboxId) {+ throw new Error(+ `oc sandbox resolve failed for ${sessionId}: response has no sandbox_id`,+ );+ }+ return sandboxId;}/**- * The OC-fleet sandbox factory. Set `sandbox: ocSandbox(env)` in your `defineAgent` initializer; the OC- * template scaffolds exactly this. Lazily resolves the session's sandbox (keyed by the DO instance id =- * `ses_`) on first tool use, so no sandbox is provisioned for tool-free turns (§5).+ * The optional OC-fleet sandbox factory. Add `sandbox: ocSandbox(env)` only when an agent needs a+ * Linux shell or durable files. The default starter intentionally omits it.** Reads the CF ambient env (`cloudflare:workers`), not the passed `ctx.env`: on the `--target* cloudflare` build the real `OC_SANDBOX_*`/`OC_SESSION_TOKEN` bindings live on the ambient env and- * `ctx.env` is empty for them (same reason as `useOcGateway`). The resolution happens lazily inside- * `createSessionEnv`, so a tool-free turn never touches the sandbox config.+ * `ctx.env` is empty for them (same reason as `useOcGateway`). `createSessionEnv` validates local+ * configuration and returns a lazy environment without fetching or provisioning anything.*/-export function ocSandbox(env: OcSandboxEnv, opts?: { cwd?: string }): SandboxFactory {+export function ocSandbox(+ env: OcSandboxEnv,+ opts?: { cwd?: string },+): SandboxFactory {const cwd = opts?.cwd ?? WORKSPACE_CWD;+ const remoteBySession = new Map<string, Promise<SandboxApi>>();return {async createSessionEnv({ id }: { id: string }): Promise<SessionEnv> {const resolved = ocResolveEnv<OcSandboxEnv>(env);- if (!resolved.OC_SANDBOX_API && !resolved.OC_SANDBOX_ID) {- throw new Error("[oc-flue] ocSandbox: set OC_SANDBOX_API (+ OC_SESSION_TOKEN) or OC_SANDBOX_ID — the OC sandbox binding is not configured.");+ if (!resolved.OC_SANDBOX_API) {+ throw new Error(+ "[oc-flue] ocSandbox: OC_SANDBOX_API is required for sandbox operations.",+ );}- const sandboxId = await resolveSandboxId(resolved, id);- const api = new OcSandboxApi((resolved.OC_SANDBOX_API ?? "").replace(/\/+$/, ""), resolved.OC_SESSION_TOKEN ?? "", sandboxId);- return createSandboxSessionEnv(api, cwd);+ const load = (): Promise<SandboxApi> => {+ const existing = remoteBySession.get(id);+ if (existing) return existing;+ const pending = (async () => {+ const sandboxId = await resolveSandboxId(resolved, id);+ return new OcSandboxApi(+ (resolved.OC_SANDBOX_API ?? "").replace(/\/+$/, ""),+ resolved.OC_SESSION_TOKEN ?? "",+ sandboxId,+ );+ })();+ remoteBySession.set(id, pending);+ void pending.catch(() => {+ if (remoteBySession.get(id) === pending) remoteBySession.delete(id);+ });+ return pending;+ };+ return createSandboxSessionEnv(new LazyOcSandboxApi(cwd, load), cwd);},};}