An open-source, faster Devin alternative
TypeScript
Download workspace files directly from CloudFront (#810)
Mohamed Habibbd574a6dc4cc
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex a5c3e604..cbe5c81c 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.7.11",+ "version": "0.7.12","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.7.11",+ "version": "0.7.12","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex eb5a8dbf..f75570e5 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.7.11",+ "version": "0.7.12","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex 210a946d..5448316f 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -84,6 +84,50 @@ test("workspace exports derive one idempotency key per workspace path", async (cassert.notEqual(keys[0], keys[2], "each path is its own export operation");});+test("workspace artifact downloads use a signed URL without forwarding credentials", async (context) => {+ const requests: Request[] = [];+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ requests.push(request);+ if (request.url.includes("/workspace/exports/wsart_1/download")) {+ return Response.json({+ url: "https://objects.example.test/artifact?signature=test",+ expiresAt: "2026-09-25T20:00:00.000Z",+ });+ }+ return new Response(new Uint8Array([1, 2, 3]));+ },+ );+ const client = new OpenComputerClient({+ apiUrl: "https://app.opencomputer.dev",+ apiKey: "test",+ });+ const response = await client.workspaceArtifactContent({+ sessionId: "ses",+ id: "wsart_1",+ });+ assert.deepEqual(+ new Uint8Array(await response.arrayBuffer()),+ new Uint8Array([1, 2, 3]),+ );+ assert.equal(requests.length, 2);+ assert.equal(+ requests[0]?.url,+ "https://app.opencomputer.dev/api/managed-agents/sessions/ses/workspace/exports/wsart_1/download",+ );+ assert.equal(requests[0]?.redirect, "manual");+ assert.equal(requests[0]?.headers.get("x-api-key"), "test");+ assert.equal(+ requests[1]?.url,+ "https://objects.example.test/artifact?signature=test",+ );+ assert.equal(requests[1]?.redirect, "error");+ assert.equal(requests[1]?.headers.get("x-api-key"), null);+});+test("memory documents travel with their ETag and send it back as a precondition", async (context) => {const requests: Request[] = [];const document = {diff --git a/cli/src/api.ts b/cli/src/api.tsindex 29a1d7ad..557bc99a 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -330,7 +330,8 @@ export interface ManagedSessionPage {export type MemoryEnvironment = "development" | "production";export type MemoryWriter =- { kind: "owner" } | { kind: "agent"; sessionId: string };+ | { kind: "owner" }+ | { kind: "agent"; sessionId: string };/** One document's metadata, as the list route returns it (no text). */export interface MemoryDocumentMeta {@@ -1467,6 +1468,48 @@ export class OpenComputerClient {return result.artifacts;}+ async workspaceDownload(+ sessionId: string,+ path: string,+ ): Promise<WorkspaceDownload> {+ return this.request<WorkspaceDownload>(+ this.workspacePath(sessionId, "/download"),+ { method: "POST", body: JSON.stringify({ path }) },+ );+ }++ async workspaceFileContent(+ download: WorkspaceDownload,+ signal?: AbortSignal,+ ): Promise<Response> {+ const downloadSignal = workspaceContentSignal(signal);+ const location = new URL(download.url);+ if (+ location.protocol !== "https:" ||+ location.username ||+ location.password+ ) {+ throw new APIError(+ "Workspace download did not provide a secure signed location.",+ 502,+ "workspace_export_failed",+ );+ }+ const response = await fetch(location, {+ method: "GET",+ redirect: "error",+ signal: downloadSignal,+ });+ if (!response.ok) {+ throw new APIError(+ `Workspace object download failed (${response.status}).`,+ response.status,+ "workspace_export_failed",+ );+ }+ return response;+ }+/** Provider-side export: retains and hashes the file, returns its manifest. */async exportWorkspaceFile(sessionId: string,@@ -1504,17 +1547,54 @@ export class OpenComputerClient {* Raw bytes of a retained artifact; callers verify size and SHA-256. The* request always carries the one-hour deadline, combined with `signal`.*/- workspaceArtifactContent(+ async workspaceArtifactContent(artifact: Pick<WorkspaceArtifact, "sessionId" | "id">,signal?: AbortSignal,): Promise<Response> {- return this.response(+ const downloadSignal = workspaceContentSignal(signal);+ const handoff = await this.request<{ url: string; expiresAt: string }>(this.workspacePath(artifact.sessionId,- `/exports/${encodeURIComponent(artifact.id)}/content`,+ `/exports/${encodeURIComponent(artifact.id)}/download`,),- { signal: workspaceContentSignal(signal) },+ { signal: downloadSignal },);+ let location: URL;+ try {+ location = new URL(handoff.url);+ } catch {+ throw new APIError(+ "Workspace download did not provide a valid signed location.",+ 502,+ "workspace_export_failed",+ );+ }+ if (+ location.protocol !== "https:" ||+ location.username ||+ location.password+ ) {+ throw new APIError(+ "Workspace download did not provide a secure signed location.",+ 502,+ "workspace_export_failed",+ );+ }+ // Never forward the OpenComputer API key to object storage. The signed+ // query authorizes this exact immutable object for a few minutes.+ const response = await fetch(location, {+ method: "GET",+ redirect: "error",+ signal: downloadSignal,+ });+ if (!response.ok) {+ throw new APIError(+ `Workspace object download failed (${response.status}).`,+ response.status,+ "workspace_export_failed",+ );+ }+ return response;}}@@ -1534,6 +1614,13 @@ export type WorkspaceFile = {etag: string | null;};+export type WorkspaceDownload = WorkspaceFile & {+ versionId: string | null;+ mediaType: string;+ url: string;+ expiresAt: string;+};+type WorkspaceFilePage = {files: WorkspaceFile[];nextCursor: string | null;diff --git a/cli/src/index.ts b/cli/src/index.tsindex 89c47a75..ba2d1c75 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -75,7 +75,7 @@ Usage:lists the files under the session's /workspaceopencomputer session files download <session-id> <workspace-path> [dest]opencomputer session files download <session-id> --all [dest-dir]- exports the file(s) provider-side, streams the retained copy to disk and+ streams the versioned workspace file(s) directly to disk andverifies size and SHA-256 against the manifest before saving; "cp" is an aliasopencomputer secrets set <name> --value-stdin [--environment development|production] [--agent <agent>|current]opencomputer secrets list [--environment development|production] [--agent <agent>|current]diff --git a/cli/src/session-files.test.ts b/cli/src/session-files.test.tsindex 75bcce50..9ad831f0 100644--- a/cli/src/session-files.test.ts+++ b/cli/src/session-files.test.ts@@ -12,7 +12,12 @@ import { tmpdir } from "node:os";import path from "node:path";import test from "node:test";-import { APIError, type WorkspaceArtifact, type WorkspaceFile } from "./api.js";+import {+ APIError,+ type WorkspaceArtifact,+ type WorkspaceDownload,+ type WorkspaceFile,+} from "./api.js";import {VerificationError,downloadWorkspace,@@ -60,6 +65,22 @@ function fakeClient(fixtures: Fixture[]): WorkspaceClient & {async workspaceArtifacts() {return fixtures.map(artifactFor);},+ async workspaceDownload(_session, filePath) {+ const fixture = byPath.get(filePath);+ if (!fixture) throw new Error(`no such file ${filePath}`);+ return {+ ...files.find((file) => file.path === filePath)!,+ versionId: `version-${filePath}`,+ mediaType: "application/octet-stream",+ url: `https://downloads.example/${encodeURIComponent(filePath)}`,+ expiresAt: "2026-01-01T00:05:00.000Z",+ };+ },+ async workspaceFileContent(download: WorkspaceDownload) {+ const fixture = byPath.get(download.path);+ if (!fixture) throw new Error("unknown workspace file");+ return new Response(new Uint8Array(fixture.served ?? fixture.bytes));+ },async exportWorkspaceFile(_session, filePath) {const fixture = byPath.get(filePath);if (!fixture) throw new Error(`no such file ${filePath}`);@@ -114,7 +135,7 @@ test("localPathFor never escapes the destination root", () => {assert.throws(() => localPathFor(root, "a/../../x"), /outside/);});-test("download exports first, then saves the verified bytes", async () => {+test("download streams direct and computes a local hash", async () => {const bytes = new TextEncoder().encode("hello evidence");const client = fakeClient([{ path: "out/a.txt", bytes }]);await withDirectory(async (dir) => {@@ -125,7 +146,7 @@ test("download exports first, then saves the verified bytes", async () => {"out/a.txt",destination,);- assert.deepEqual(client.exports, ["out/a.txt"]);+ assert.deepEqual(client.exports, []);assert.equal(result.size, bytes.length);assert.equal(result.sha256, sha256(bytes));assert.equal(await readFile(destination, "utf8"), "hello evidence");@@ -134,7 +155,6 @@ test("download exports first, then saves the verified bytes", async () => {});for (const [name, served] of [- ["corrupted", new TextEncoder().encode("hello EVIDENCE")],["truncated", new TextEncoder().encode("hello")],["oversized", new TextEncoder().encode("hello evidence and more")],] as const) {@@ -181,7 +201,7 @@ test("an ended session falls back to its retained artifacts", async () => {const client: WorkspaceClient = {...base,workspaceFiles: gone,- exportWorkspaceFile: gone,+ workspaceDownload: gone,};await withDirectory(async (dir) => {const single = await downloadWorkspaceFile(diff --git a/cli/src/session-files.ts b/cli/src/session-files.tsindex 411219f6..61f65050 100644--- a/cli/src/session-files.ts+++ b/cli/src/session-files.ts@@ -8,6 +8,7 @@ import {APIError,workspaceContentSignal,type WorkspaceArtifact,+ type WorkspaceDownload,type WorkspaceFile,} from "./api.js";@@ -15,6 +16,14 @@ import {export type WorkspaceClient = {workspaceFiles(sessionId: string): Promise<WorkspaceFile[]>;workspaceArtifacts(sessionId: string): Promise<WorkspaceArtifact[]>;+ workspaceDownload(+ sessionId: string,+ path: string,+ ): Promise<WorkspaceDownload>;+ workspaceFileContent(+ download: WorkspaceDownload,+ signal?: AbortSignal,+ ): Promise<Response>;exportWorkspaceFile(sessionId: string,path: string,@@ -55,7 +64,7 @@ async function withInterruptAbort<T>(export type DownloadResult = {path: string;destination: string;- artifactId: string;+ artifactId?: string;size: number;sha256: string;};@@ -114,9 +123,8 @@ export async function listWorkspaceFiles(}/**- * Exports (retains) the workspace file provider-side, then streams the retained- * artifact to `destination`, verifying byte count and SHA-256 against the- * manifest before the file becomes visible at its final path.+ * Authorizes a short-lived direct file URL, streams it to `destination`, and+ * computes SHA-256 locally before the file becomes visible at its final path.*/export async function downloadWorkspaceFile(client: WorkspaceClient,@@ -125,17 +133,75 @@ export async function downloadWorkspaceFile(destination: string,root?: string,): Promise<DownloadResult> {- let artifact: WorkspaceArtifact;+ let download: WorkspaceDownload;try {- artifact = await client.exportWorkspaceFile(sessionId, workspacePath);+ download = await client.workspaceDownload(sessionId, workspacePath);} catch (error) {if (!isWorkspaceGone(error)) throw error;const retained = await latestRetainedArtifacts(client, sessionId);const fallback = retained.get(workspacePath);if (!fallback) throw error;- artifact = fallback;+ return downloadArtifact(client, fallback, destination, root);+ }+ await mkdir(path.dirname(destination), { recursive: true });+ if (root !== undefined) await assertResolvedWithin(root, destination);+ const temporary = `${destination}.${randomBytes(6).toString("hex")}.part`;+ let sha256 = "";+ await withInterruptAbort(async (signal) => {+ try {+ sha256 = await streamDirect(client, download, temporary, signal);+ signal.throwIfAborted();+ await rename(temporary, destination);+ } catch (error) {+ await rm(temporary, { force: true }).catch(() => undefined);+ throw error;+ }+ });+ return {+ path: download.path,+ destination,+ size: download.size,+ sha256,+ };+}++async function streamDirect(+ client: WorkspaceClient,+ download: WorkspaceDownload,+ temporary: string,+ interrupt: AbortSignal,+): Promise<string> {+ const signal = workspaceContentSignal(interrupt);+ const response = await client.workspaceFileContent(download, signal);+ if (!response.body)+ throw new VerificationError("Empty workspace file response.");+ const hash = createHash("sha256");+ let received = 0;+ const verify = new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ received += chunk.length;+ if (received > download.size) {+ callback(+ new VerificationError(`Received more than ${download.size} bytes.`),+ );+ return;+ }+ hash.update(chunk);+ callback(null, chunk);+ },+ });+ await pipeline(+ Readable.fromWeb(response.body as import("node:stream/web").ReadableStream),+ verify,+ createWriteStream(temporary, { flags: "wx", mode: 0o600 }),+ { signal },+ );+ if (received !== download.size) {+ throw new VerificationError(+ `Received ${received} bytes but expected ${download.size}.`,+ );}- return downloadArtifact(client, artifact, destination, root);+ return hash.digest("hex");}/**diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 8191e432..c837c282 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -109,6 +109,37 @@ describe("managed agents proxy", () => {expect(fetchMock).not.toHaveBeenCalled();});+ it("redirects browser workspace downloads to the signed file URL", async () => {+ const signed =+ "https://downloads.mo-oc-dev.com/r/us-west-2/file.txt?Policy=signed";+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ new Response(null, { status: 302, headers: { location: signed } }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const response = await proxyManagedAgents(+ new Request(+ "https://mo-oc-dev.com/api/dashboard/managed-agents/sessions/sess_1/workspace/download?path=reports%2Fresult.txt",+ ),+ {+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ },+ { orgID: "org_test", userID: "user_test", role: "admin" },+ "/api/dashboard/managed-agents",+ );++ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(signed);+ expect(response.headers.get("cache-control")).toBe("private, no-store");+ expect(response.headers.get("referrer-policy")).toBe("no-referrer");+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(+ "https://managedagents.test/v1/sessions/sess_1/workspace/download?path=reports%2Fresult.txt",+ );+ });+it("forwards managed GitHub project connection requests", async () => {const fetchMock = vi.fn().mockResolvedValue(Response.json({@@ -430,6 +461,15 @@ describe("managed agents proxy", () => {},});}+ if (url.endsWith("/workspace/exports/wsart_1/download")) {+ return Response.json(+ {+ url: "https://objects.example.test/private/capture.har?signature=secret",+ expiresAt: "2026-09-25T20:00:00.000Z",+ },+ { headers: { "cache-control": "private, no-store" } },+ );+ }throw new Error(`unexpected upstream ${url}`);}),);@@ -498,6 +538,21 @@ describe("managed agents proxy", () => {expect(content.headers.get("cache-control")).toBe("private, no-store");expect(content.headers.get("x-storage-provider")).toBeNull();+ const download = await proxyManagedAgents(+ new Request(+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/download",+ ),+ env,+ caller,+ "/api/managed-agents",+ );+ expect(download.status).toBe(200);+ expect(await download.json()).toEqual({+ url: "https://objects.example.test/private/capture.har?signature=secret",+ expiresAt: "2026-09-25T20:00:00.000Z",+ });+ expect(download.headers.get("cache-control")).toBe("private, no-store");+const blocked = await proxyManagedAgents(new Request("https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/content",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex ac8d4a6a..da449ea6 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -1992,6 +1992,37 @@ function publicSuccessBody(nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null,};}+ if (+ (method === "GET" || method === "POST") &&+ /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix)+ ) {+ const url = typeof body.url === "string" ? new URL(body.url) : null;+ if (+ !url ||+ url.protocol !== "https:" ||+ url.username ||+ url.password ||+ typeof body.path !== "string" ||+ typeof body.size !== "number" ||+ typeof body.expiresAt !== "string"+ ) {+ throw new Error("Invalid workspace download authorization");+ }+ return {+ path: body.path,+ size: body.size,+ etag: typeof body.etag === "string" ? body.etag : null,+ versionId: typeof body.versionId === "string" ? body.versionId : null,+ lastModified:+ typeof body.lastModified === "string" ? body.lastModified : null,+ mediaType:+ typeof body.mediaType === "string"+ ? body.mediaType+ : "application/octet-stream",+ url: url.toString(),+ expiresAt: body.expiresAt,+ };+ }if (method === "GET" &&/^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)@@ -2018,6 +2049,22 @@ function publicSuccessBody(artifact: body.artifact ? publicWorkspaceArtifact(body.artifact) : null,};}+ if (+ method === "GET" &&+ /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+\/download$/.test(suffix)+ ) {+ const url = typeof body.url === "string" ? new URL(body.url) : null;+ if (+ !url ||+ url.protocol !== "https:" ||+ url.username ||+ url.password ||+ typeof body.expiresAt !== "string"+ ) {+ throw new Error("Invalid workspace download authorization");+ }+ return { url: url.toString(), expiresAt: body.expiresAt };+ }throw new Error("Unsupported managed agents response");}@@ -2490,6 +2537,12 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {) {return true;}+ if (+ (method === "GET" || method === "POST") &&+ /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix)+ ) {+ return true;+ }if ((method === "GET" || method === "POST") &&/^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)@@ -2498,7 +2551,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {}if (method === "GET" &&- /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+(?:\/content)?$/.test(suffix)+ /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+(?:\/(?:content|download))?$/.test(+ suffix,+ )) {return true;}@@ -3116,6 +3171,34 @@ export async function proxyManagedAgents(try {const upstream = await fetch(target, init);if (memoryRoute) return memoryResponse(upstream, method, suffix);+ if (+ method === "GET" &&+ /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix) &&+ upstream.status === 302+ ) {+ const value = upstream.headers.get("location");+ let location: URL;+ try {+ location = new URL(value ?? "");+ } catch {+ throw new Error("Invalid workspace download redirect");+ }+ if (+ location.protocol !== "https:" ||+ location.username ||+ location.password+ ) {+ throw new Error("Invalid workspace download redirect");+ }+ return new Response(null, {+ status: 302,+ headers: {+ location: location.toString(),+ "cache-control": "private, no-store",+ "referrer-policy": "no-referrer",+ },+ });+ }if (!upstream.ok) return publicErrorResponse(upstream);if (upstream.status === 204) return new Response(null, { status: 204 });if (diff --git a/create-start/package.json b/create-start/package.jsonindex 3c803118..b1b7415d 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.7.11",+ "version": "0.7.12","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "0.7.11"+ "@opencomputer/cli": "0.7.12"},"publishConfig": {"access": "public"diff --git a/docs/agents/playground.mdx b/docs/agents/playground.mdxindex 6de7a08d..c3eca59d 100644--- a/docs/agents/playground.mdx+++ b/docs/agents/playground.mdx@@ -29,6 +29,9 @@ The inspector shows the information needed to explain a turn:a single file or the whole workspace as a zip (see[Workspace files](/agents/sessions#workspace-files))+Newly written workspace files appear gradually and may take a few moments to+finish syncing. Use the refresh action when a file has just been created.+OpenComputer's private platform instructions and credentials are intentionallynot shown. The inspector describes your deployed agent configuration, not theinternal execution implementation.diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex 81cca2b3..caac4f4e 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -42,11 +42,11 @@ the label bounds are on the [API reference](/agents/api#get-and-list).These describe different parts of a session:-| Field | What it answers |-| --- | --- |-| `status` and `activity` | Is work queued, running, stopping or finished? |-| `labels` | How does your application organize the session? A ticket ID or `archived` label is your convention; changing it does not stop work. |-| `result` | What did the agent last report? Its `data` is validated against the [result tool's](/agents/tools#the-session-result) output schema; `turnId` and `callId` identify the report. |+| Field | What it answers |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `status` and `activity` | Is work queued, running, stopping or finished? |+| `labels` | How does your application organize the session? A ticket ID or `archived` label is your convention; changing it does not stop work. |+| `result` | What did the agent last report? Its `data` is validated against the [result tool's](/agents/tools#the-session-result) output schema; `turnId` and `callId` identify the report. |A report does not finish a turn, and each report replaces the whole result.Later work can run, fail or be cancelled while an earlier result remains.@@ -138,10 +138,14 @@ the command exits.### Workspace filesFiles an agent writes under `/workspace` (reports, captures, screenshots, tool-output) can be listed and downloaded with `session files`. Downloads never pass-through the model or the session transcript: OpenComputer exports the file into-provider-owned storage, records its byte count and SHA-256, and the CLI streams-that retained copy to disk, verifying both before the file is saved.+output) can be listed and downloaded with `session files`. Newly written files+appear gradually and may take a few moments to finish syncing. Refresh or list+the workspace again if a file has just been created.++Downloads never pass through the model or the session transcript: OpenComputer+authorizes the exact versioned workspace object for a short-lived direct+download through its file-delivery edge. The CLI streams that object to disk,+checks its byte count, and computes SHA-256 locally before the file is saved.```bash# List the files in the session's /workspace@@ -155,17 +159,18 @@ opencomputer session files download <session-id> /workspace/captures/run.har ./e# Download the whole workspace, mirroring its layoutopencomputer session files download <session-id> --all ./workspace-copy-# Machine-readable output with artifactId, size and sha256 per file+# Machine-readable output with size and locally computed sha256 per fileopencomputer session files download <session-id> --all ./workspace-copy --json````cp` is an alias for `download`. Workspace paths may be written relative to`/workspace` or with the `/workspace/` prefix; paths that leave the workspaceare refused before any request is made. Each download is written to a-temporary file and renamed into place only after the size and SHA-256 match-the export manifest, so an interrupted or corrupted transfer never leaves a-partial file behind. Retained copies remain downloadable after the session-ends, from the CLI, the session page's **Files** tab, or the+temporary file and renamed into place only after the expected byte count is+received; SHA-256 is reported from the completed local file. An interrupted+transfer never leaves a partial file behind. The versioned S3-backed workspace+remains the source of the file in the+CLI, the session page's **Files** tab, and the[playground debug inspector](/agents/playground).## From an applicationdiff --git a/web/src/managed-agents/SessionFiles.tsx b/web/src/managed-agents/SessionFiles.tsxindex f6099625..7ebd75d2 100644--- a/web/src/managed-agents/SessionFiles.tsx+++ b/web/src/managed-agents/SessionFiles.tsx@@ -1,9 +1,8 @@-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useMutation, useQuery } from '@tanstack/react-query'import { useState } from 'react'import {ChevronRight,Download,- FileCheck2,FolderDown,Loader2,RefreshCw,@@ -17,12 +16,10 @@ import {import { Button } from '@/components/ui/button'import { notifyError, notifySuccess } from '@/lib/errors'import {+ authorizeManagedAgentWorkspaceDownload,downloadManagedAgentWorkspaceArchive,- downloadManagedAgentWorkspaceArtifact,- exportManagedAgentWorkspaceFile,- getManagedAgentWorkspaceArtifacts,getManagedAgentWorkspaceFiles,- type ManagedWorkspaceArtifact,+ managedAgentWorkspaceBrowserDownloadPath,type ManagedWorkspaceFile,} from './api'import { DownloadCancelled } from './workspace-download'@@ -39,137 +36,48 @@ function formatBytes(bytes: number): string {return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unit]}`}-function fileName(path: string) {- return path.split('/').pop() ?? path-}-function reportDownloadError(error: unknown) {if (error instanceof DownloadCancelled) returnnotifyError("Couldn't download that file.", error)}/**- * Workspace listing, retained manifests and the verified download actions- * shared by the session Files tab and the playground debug inspector.+ * Workspace listing and direct download actions shared by the session Files+ * tab and the playground debug inspector.*/function useWorkspaceFiles(sessionId: string, live: boolean) {- const queryClient = useQueryClient()- const artifactsKey = ['managed-agent-session-artifacts', sessionId]const filesKey = ['managed-agent-session-workspace-files', sessionId]const files = useQuery({queryKey: filesKey,queryFn: () => getManagedAgentWorkspaceFiles(sessionId),refetchInterval: live ? 5_000 : false,})- const artifacts = useQuery({- queryKey: artifactsKey,- queryFn: () => getManagedAgentWorkspaceArtifacts(sessionId),- })-- const exportFile = useMutation({- mutationFn: (path: string) =>- exportManagedAgentWorkspaceFile(sessionId, path),- onSuccess: (artifact) => {- void queryClient.invalidateQueries({ queryKey: artifactsKey })- notifySuccess(- `Retained ${artifact.path} (${formatBytes(artifact.size)}).`,- )- },- onError: (error) => notifyError("Couldn't export that file.", error),- })-- const download = useMutation({- mutationFn: (artifact: ManagedWorkspaceArtifact) =>- downloadManagedAgentWorkspaceArtifact(- fileName(artifact.path),- artifact.size,- () => Promise.resolve(artifact),- ),- onError: reportDownloadError,- })-- const exportThenDownload = useMutation({- mutationFn: (file: ManagedWorkspaceFile) =>- downloadManagedAgentWorkspaceArtifact(- fileName(file.path),- file.size,- async () => {- const artifact = await exportManagedAgentWorkspaceFile(- sessionId,- file.path,- )- void queryClient.invalidateQueries({ queryKey: artifactsKey })- return artifact- },- ),- onError: reportDownloadError,- })-- // An artifact only stands in for the current file when it was exported- // from the very same S3 revision; a rewritten file needs a fresh export.- const retainedFor = (file: ManagedWorkspaceFile) =>- file.etag- ? (artifacts.data ?? []).find(- (artifact) =>- artifact.path === file.path &&- artifact.receipt.sourceEtag === file.etag,- )- : undefined-const [archiveProgress, setArchiveProgress] = useState<string | null>(null)const downloadAll = useMutation({mutationFn: (workspace: ManagedWorkspaceFile[]) =>downloadManagedAgentWorkspaceArchive(`${sessionId}-workspace.zip`,workspace,- async () => {- const retained: ManagedWorkspaceArtifact[] = []- for (const [index, file] of workspace.entries()) {- setArchiveProgress(`Retaining ${index + 1}/${workspace.length}`)- retained.push(- retainedFor(file) ??- (await exportManagedAgentWorkspaceFile(sessionId, file.path)),- )- }- void queryClient.invalidateQueries({ queryKey: artifactsKey })- return retained- },- (done, total) => setArchiveProgress(`Verifying ${done}/${total}`),+ (file) => authorizeManagedAgentWorkspaceDownload(sessionId, file.path),+ (done, total) => setArchiveProgress(`Downloading ${done}/${total}`),),- onSuccess: (retained) =>- notifySuccess(`Downloaded ${retained.length} verified files.`),+ onSuccess: (downloads) =>+ notifySuccess(`Downloaded ${downloads.length} files.`),onError: reportDownloadError,onSettled: () => setArchiveProgress(null),})- const busy =- exportFile.isPending ||- download.isPending ||- exportThenDownload.isPending ||- downloadAll.isPending- const busyPath =- exportFile.variables ??- exportThenDownload.variables?.path ??- download.variables?.path-return {files,- artifacts,- retainedFor,- exportFile,- download,- exportThenDownload,downloadAll,archiveProgress,- busy,- busyPath,+ busy: downloadAll.isPending,}}/**- * Files the agent wrote under /workspace and the ones the provider has- * retained. "Export" asks the provider to copy and hash a file; "Download"- * fetches the retained bytes and verifies them against the manifest.+ * Files the agent wrote under /workspace. Downloads use a short-lived URL to+ * stream directly from the file edge.*/export function SessionFiles({sessionId,@@ -179,18 +87,10 @@ export function SessionFiles({/** The agent may still be writing; keep the listing fresh. */live: boolean}) {- const {- files,- artifacts,- retainedFor,- exportFile,- download,- exportThenDownload,- downloadAll,- archiveProgress,- busy,- busyPath,- } = useWorkspaceFiles(sessionId, live)+ const { files, downloadAll, archiveProgress, busy } = useWorkspaceFiles(+ sessionId,+ live,+ )return (<div className="space-y-5">@@ -200,7 +100,9 @@ export function SessionFiles({<PanelTitle>Workspace</PanelTitle><PanelDescription className="mt-1">Files under <code>/workspace</code> as last synced from the- sandbox. Downloading retains a verified copy first.+ sandbox. Newly written files appear gradually and may take a few+ moments to finish syncing. Downloads stream directly from our file+ delivery edge.</PanelDescription></div><div className="flex items-center gap-2">@@ -242,13 +144,12 @@ export function SessionFiles({</p>) : (files.data ?? []).length === 0 ? (<p className="text-muted-foreground px-5 py-4 text-sm">- The agent has not written any files yet.+ No files are visible yet. Newly written files may take a few moments+ to finish syncing.</p>) : (<div className="divide-y text-sm">{(files.data ?? []).map((file: ManagedWorkspaceFile) => {- const retained = retainedFor(file)- const working = busy && busyPath === file.pathreturn (<divkey={file.path}@@ -260,137 +161,30 @@ export function SessionFiles({<span className="text-muted-foreground text-xs tabular-nums">{formatBytes(file.size)}</span>- {retained ? (- <span- className="text-muted-foreground flex items-center gap-1 text-xs"- title={`sha256 ${retained.sha256}`}+ <Button asChild variant="outline" size="sm">+ <a+ href={managedAgentWorkspaceBrowserDownloadPath(+ sessionId,+ file.path,+ )}>- <FileCheck2 className="size-3.5" /> retained- </span>- ) : null}- <Button- variant="outline"- size="sm"- disabled={busy}- onClick={() =>- retained- ? download.mutate(retained)- : exportThenDownload.mutate(file)- }- >- {working ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (<Download className="size-3.5" />- )}- Download+ Download+ </a></Button>- {!retained ? (- <Button- variant="ghost"- size="sm"- disabled={busy}- onClick={() => exportFile.mutate(file.path)}- >- Retain- </Button>- ) : null}</div>)})}</div>)}</Panel>-- <Panel>- <PanelHeader>- <div>- <PanelTitle>Retained artifacts</PanelTitle>- <PanelDescription className="mt-1">- Manifests kept after the session ends. Each download is checked- against its byte count and SHA-256.- </PanelDescription>- </div>- </PanelHeader>- {artifacts.isLoading ? (- <div className="flex min-h-24 items-center justify-center">- <Loader2 className="text-muted-foreground size-4 animate-spin" />- </div>- ) : artifacts.isError ? (- <div className="flex items-center gap-3 px-5 py-4 text-sm">- <p className="text-status-error">- Retained artifacts could not be loaded.- </p>- <Button- variant="outline"- size="sm"- onClick={() => void artifacts.refetch()}- >- Retry- </Button>- </div>- ) : (artifacts.data ?? []).length === 0 ? (- <p className="text-muted-foreground px-5 py-4 text-sm">- No files have been retained from this session.- </p>- ) : (- <div className="divide-y text-sm">- {(artifacts.data ?? []).map((artifact) => (- <div- key={artifact.id}- className="grid gap-x-4 gap-y-1 px-5 py-3 md:grid-cols-[1fr_auto_auto]"- >- <div className="min-w-0">- <p className="truncate font-mono text-xs">{artifact.path}</p>- <p className="text-muted-foreground mt-0.5 truncate font-mono text-[11px]">- sha256 {artifact.sha256}- </p>- <p className="text-muted-foreground mt-0.5 text-xs">- {artifact.id} · {formatBytes(artifact.size)} · exported{' '}- {new Date(artifact.exportedAt).toLocaleString()}- </p>- </div>- <div className="flex items-start md:col-start-3">- <Button- variant="outline"- size="sm"- disabled={busy}- onClick={() => download.mutate(artifact)}- >- {download.isPending &&- download.variables?.id === artifact.id ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <Download className="size-3.5" />- )}- Download- </Button>- </div>- </div>- ))}- </div>- )}- </Panel></div>)}-function latestRetainedByPath(- artifacts: ManagedWorkspaceArtifact[],-): ManagedWorkspaceArtifact[] {- const latest = new Map<string, ManagedWorkspaceArtifact>()- for (const artifact of artifacts) {- const current = latest.get(artifact.path)- if (!current || current.exportedAt < artifact.exportedAt) {- latest.set(artifact.path, artifact)- }- }- return [...latest.values()].sort((a, b) => a.path.localeCompare(b.path))-}-/*** Compact workspace listing for the playground debug inspector: the same- * verified export-then-download path as the Files tab, one row per file.+ * direct-download path as the Files tab, one row per file.*/export function WorkspaceFilesInspector({sessionId,@@ -399,23 +193,11 @@ export function WorkspaceFilesInspector({sessionId: stringlive: boolean}) {- const {- files,- artifacts,- retainedFor,- download,- exportThenDownload,- downloadAll,- archiveProgress,- busy,- busyPath,- } = useWorkspaceFiles(sessionId, live)+ const { files, downloadAll, archiveProgress, busy } = useWorkspaceFiles(+ sessionId,+ live,+ )const list = files.data ?? []- // Once the workspace is gone (session ended), the retained copies are all- // that is left to offer; newest export per path.- const retainedOnly = files.isError- ? latestRetainedByPath(artifacts.data ?? [])- : []return (<details open className="group bg-background rounded-md border">@@ -455,60 +237,26 @@ export function WorkspaceFilesInspector({/></Button></div>+ <p className="text-muted-foreground border-t px-3 py-1.5 text-[10px]">+ Newly written files appear gradually and may take a few moments to+ finish syncing.+ </p><div className="max-h-72 overflow-y-auto border-t">{files.isLoading ? (<div className="flex min-h-16 items-center justify-center"><Loader2 className="text-muted-foreground size-4 animate-spin" /></div>- ) : files.isError && retainedOnly.length > 0 ? (- <div className="divide-y">- <p className="text-muted-foreground px-3 py-1.5 text-[10px]">- Workspace listing is unavailable; showing retained copies.- </p>- {retainedOnly.map((artifact) => (- <div- key={artifact.id}- className="flex items-center gap-2 px-3 py-1.5"- >- <span- className="min-w-0 flex-1 truncate font-mono text-[10px]"- title={`sha256 ${artifact.sha256}`}- >- {artifact.path}- </span>- <FileCheck2 className="text-muted-foreground size-3" />- <span className="text-muted-foreground text-[10px] tabular-nums">- {formatBytes(artifact.size)}- </span>- <Button- variant="ghost"- size="sm"- disabled={busy}- aria-label={`Download ${artifact.path}`}- onClick={() => download.mutate(artifact)}- >- {busy && busyPath === artifact.path ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <Download className="size-3.5" />- )}- </Button>- </div>- ))}- </div>) : files.isError ? (<p className="text-status-error px-3 py-2 text-xs">Workspace listing is unavailable.</p>) : list.length === 0 ? (<p className="text-muted-foreground px-3 py-2 text-xs">- The agent has not written any files yet.+ No files are visible yet. Try refreshing in a few moments.</p>) : (<div className="divide-y">{list.map((file: ManagedWorkspaceFile) => {- const retained = retainedFor(file)- const working = busy && busyPath === file.pathreturn (<divkey={file.path}@@ -516,32 +264,23 @@ export function WorkspaceFilesInspector({><spanclassName="min-w-0 flex-1 truncate font-mono text-[10px]"- title={retained ? `sha256 ${retained.sha256}` : file.path}+ title={file.path}>{file.path}</span>- {retained ? (- <FileCheck2 className="text-muted-foreground size-3" />- ) : null}<span className="text-muted-foreground text-[10px] tabular-nums">{formatBytes(file.size)}</span>- <Button- variant="ghost"- size="sm"- disabled={busy}- aria-label={`Download ${file.path}`}- onClick={() =>- retained- ? download.mutate(retained)- : exportThenDownload.mutate(file)- }- >- {working ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (+ <Button asChild variant="ghost" size="sm">+ <a+ href={managedAgentWorkspaceBrowserDownloadPath(+ sessionId,+ file.path,+ )}+ aria-label={`Download ${file.path}`}+ ><Download className="size-3.5" />- )}+ </a></Button></div>)diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.tsindex c8882466..8f5eb210 100644--- a/web/src/managed-agents/api.test.ts+++ b/web/src/managed-agents/api.test.ts@@ -1,11 +1,34 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {collectManagedAgentEventPages,displayManagedAgentName,+ fetchManagedAgentWorkspaceObject,managedAgentModelRoute,managedAgentRenderDebug,} from './api'+afterEach(() => vi.restoreAllMocks())++describe('fetchManagedAgentWorkspaceObject', () => {+ it('fetches the signed object without platform credentials or redirects', async () => {+ const fetch = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(new Uint8Array([1, 2, 3])))++ const response = await fetchManagedAgentWorkspaceObject(+ 'https://objects.example.test/artifact?signature=test',+ )++ expect(new Uint8Array(await response.arrayBuffer())).toEqual(+ new Uint8Array([1, 2, 3]),+ )+ expect(fetch).toHaveBeenCalledWith(+ 'https://objects.example.test/artifact?signature=test',+ expect.objectContaining({ credentials: 'omit', redirect: 'error' }),+ )+ })+})+describe('collectManagedAgentEventPages', () => {it('follows event cursors until the API returns an empty page', async () => {const cursors: number[] = []diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 9e42505b..47a1cb1d 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -1665,9 +1665,31 @@ const workspaceExportResponseSchema = z.object({export: z.object({ id: z.string(), state: z.string() }).optional(),artifact: workspaceArtifactSchema.nullable(),})+const workspaceDownloadResponseSchema = z.object({+ url: z+ .string()+ .url()+ .refine((value) => {+ const url = new URL(value)+ return url.protocol === 'https:' && !url.username && !url.password+ }),+ expiresAt: z.string(),+})+const workspaceFileDownloadResponseSchema =+ workspaceDownloadResponseSchema.extend({+ path: z.string(),+ size: z.number(),+ etag: z.string().nullable(),+ versionId: z.string().nullable(),+ lastModified: z.string().nullable(),+ mediaType: z.string(),+ })export type ManagedWorkspaceFile = z.infer<typeof workspaceFileSchema>export type ManagedWorkspaceArtifact = z.infer<typeof workspaceArtifactSchema>+export type ManagedWorkspaceDownload = z.infer<+ typeof workspaceFileDownloadResponseSchema+>/** Every file the agent wrote under /workspace, across all list pages. */export async function getManagedAgentWorkspaceFiles(sessionId: string) {@@ -1696,6 +1718,25 @@ export async function getManagedAgentWorkspaceArtifacts(sessionId: string) {).artifacts}+export function authorizeManagedAgentWorkspaceDownload(+ sessionId: string,+ path: string,+) {+ return apiFetch(+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/download`,+ { method: 'POST', body: JSON.stringify({ path }) },+ workspaceFileDownloadResponseSchema,+ )+}++/** A normal browser download: same-origin auth redirects to signed CloudFront. */+export function managedAgentWorkspaceBrowserDownloadPath(+ sessionId: string,+ path: string,+) {+ return `/api/dashboard/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/download?path=${encodeURIComponent(path)}`+}+/** Provider-side export: retains and hashes the file, returns its manifest. */export async function exportManagedAgentWorkspaceFile(sessionId: string,@@ -1712,10 +1753,55 @@ export async function exportManagedAgentWorkspaceFile(return result.artifact}-export function managedAgentWorkspaceArtifactContentPath(+export function managedAgentWorkspaceArtifactDownloadPath(artifact: Pick<ManagedWorkspaceArtifact, 'sessionId' | 'id'>,) {- return `/managed-agents/sessions/${encodeURIComponent(artifact.sessionId)}/workspace/exports/${encodeURIComponent(artifact.id)}/content`+ return `/managed-agents/sessions/${encodeURIComponent(artifact.sessionId)}/workspace/exports/${encodeURIComponent(artifact.id)}/download`+}++/** Fetches a signed object without sending dashboard credentials to storage. */+export async function fetchManagedAgentWorkspaceObject(+ url: string,+ signal?: AbortSignal,+) {+ const response = await fetch(url, {+ credentials: 'omit',+ redirect: 'error',+ signal,+ })+ if (!response.ok) {+ throw new Error(`Workspace object download failed (${response.status})`)+ }+ return response+}++async function streamManagedWorkspaceDownload(+ download: ManagedWorkspaceDownload,+ write: (chunk: Uint8Array) => Promise<void>,+) {+ const response = await fetchManagedAgentWorkspaceObject(download.url)+ if (!response.body) throw new Error('Workspace file response had no body')+ const reader = response.body.getReader()+ let received = 0+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ received += value.byteLength+ if (received > download.size) {+ throw new Error(`Download exceeded ${download.size} bytes`)+ }+ await write(value)+ }+ } catch (error) {+ await reader.cancel(error).catch(() => undefined)+ throw error+ } finally {+ reader.releaseLock()+ }+ if (received !== download.size) {+ throw new Error(`Downloaded ${received} bytes, expected ${download.size}`)+ }}/**@@ -1730,10 +1816,14 @@ export async function streamManagedAgentWorkspaceArtifact(write: (chunk: Uint8Array) => Promise<void>,signal?: AbortSignal,) {- const response = await apiFetchResponse(- managedAgentWorkspaceArtifactContentPath(artifact),+ const handoff = await apiFetch(+ managedAgentWorkspaceArtifactDownloadPath(artifact),{ signal },+ workspaceDownloadResponseSchema,)+ // This second request is deliberately unauthenticated. The signed query is+ // the authorization; platform cookies and headers must not reach storage.+ const response = await fetchManagedAgentWorkspaceObject(handoff.url, signal)if (!response.body) throw new Error('Artifact response had no body')const hash = new Sha256()let received = 0@@ -1810,31 +1900,40 @@ function archiveBytes(entries: Array<{ path: string; size: number }>) {export async function downloadManagedAgentWorkspaceArchive(name: string,expected: Array<{ path: string; size: number }>,- resolve: () => Promise<ManagedWorkspaceArtifact[]>,+ resolve: (file: {+ path: string+ size: number+ }) => Promise<ManagedWorkspaceDownload>,onProgress?: (done: number, total: number) => void,) {const sink = await openDownloadSink(name)const zip = new ZipWriter(sink)- let artifacts: ManagedWorkspaceArtifact[]+ const downloads: ManagedWorkspaceDownload[] = []try {assertSinkCapacity(sink, archiveBytes(expected))- artifacts = await resolve()- assertSinkCapacity(sink, archiveBytes(artifacts))- for (const [index, artifact] of artifacts.entries()) {- onProgress?.(index, artifacts.length)- await zip.beginEntry(artifact.path, new Date(artifact.exportedAt))- await streamManagedAgentWorkspaceArtifact(artifact, (chunk) =>+ for (const [index, file] of expected.entries()) {+ onProgress?.(index, expected.length)+ const download = await resolve(file)+ if (download.path !== file.path) {+ throw new Error(`Workspace download path changed from ${file.path}`)+ }+ downloads.push(download)+ await zip.beginEntry(+ download.path,+ download.lastModified ? new Date(download.lastModified) : new Date(),+ )+ await streamManagedWorkspaceDownload(download, (chunk) =>zip.write(chunk),)await zip.endEntry()}- onProgress?.(artifacts.length, artifacts.length)+ onProgress?.(expected.length, expected.length)await zip.finish()} catch (error) {await zip.abort(error).catch(() => undefined)throw error}- return artifacts+ return downloads}export async function getManagedAgentSessionEvents(