Skip to content

An open-source, faster Devin alternative

TypeScript

Session workspace files: export + verified download in dashboard and @opencomputer/cli (#790)

devin-ai-integration[bot]86be47a0cf8c
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 0fb16ce6..a5c3e604 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.7.10",
+ "version": "0.7.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.7.10",
+ "version": "0.7.11",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
diff --git a/cli/package.json b/cli/package.json
index ca0ac6cb..eb5a8dbf 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.7.10",
+ "version": "0.7.11",
"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.ts
index a0b502d5..210a946d 100644
--- a/cli/src/api.test.ts
+++ b/cli/src/api.test.ts
@@ -9,11 +9,20 @@ import { APIError, OpenComputerClient } from "./api.js";
// second resource instead of the conflict the key promises.
test("mutations derive idempotency headers from the caller's key and the target only", 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);
- return Response.json({ id: "project", agents: [], environments: [], session: { id: "ses" } });
- });
+ context.mock.method(
+ globalThis,
+ "fetch",
+ async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ return Response.json({
+ id: "project",
+ agents: [],
+ environments: [],
+ session: { id: "ses" },
+ });
+ },
+ );
const client = new OpenComputerClient(
{ apiUrl: "https://app.opencomputer.dev", apiKey: "test" },
"retry-42",
@@ -25,15 +34,56 @@ test("mutations derive idempotency headers from the caller's key and the target
await client.createSession("muse@development");
await client.projects();
- const keys = requests.map((request) => request.headers.get("idempotency-key"));
+ const keys = requests.map((request) =>
+ request.headers.get("idempotency-key"),
+ );
assert.ok(keys[0]);
assert.equal(keys[0], keys[1]);
assert.equal(keys[0], keys[2], "a different body is the same operation");
- assert.notEqual(keys[0], keys[3], "a different target is a different operation");
+ assert.notEqual(
+ keys[0],
+ keys[3],
+ "a different target is a different operation",
+ );
assert.equal(keys[4], null, "reads carry no key");
assert.equal(keys[0]?.includes("retry-42"), false);
});
+test("workspace exports derive one idempotency key per workspace path", async (context) => {
+ const requests: Request[] = [];
+ const artifact = {
+ id: "wsart_1",
+ sessionId: "ses",
+ path: "a.txt",
+ size: 1,
+ sha256: "0".repeat(64),
+ receipt: { etag: null, sourceEtag: null, sourceVersionId: null },
+ exportedAt: "2026-09-10T12:00:00.000Z",
+ };
+ context.mock.method(
+ globalThis,
+ "fetch",
+ async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ return Response.json({ export: null, artifact });
+ },
+ );
+ const client = new OpenComputerClient(
+ { apiUrl: "https://app.opencomputer.dev", apiKey: "test" },
+ "retry-42",
+ );
+ await client.exportWorkspaceFile("ses", "a.txt");
+ await client.exportWorkspaceFile("ses", "a.txt");
+ await client.exportWorkspaceFile("ses", "b.txt");
+ const keys = requests.map((request) =>
+ request.headers.get("idempotency-key"),
+ );
+ assert.ok(keys[0]);
+ assert.equal(keys[0], keys[1], "same path retries under the same key");
+ assert.notEqual(keys[0], keys[2], "each path is its own export operation");
+});
+
test("memory documents travel with their ETag and send it back as a precondition", async (context) => {
const requests: Request[] = [];
const document = {
@@ -48,12 +98,17 @@ test("memory documents travel with their ETag and send it back as a precondition
updatedAt: "2026-09-10T12:00:00.000Z",
writer: { kind: "owner" },
};
- context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
- const request = new Request(input, init);
- requests.push(request);
- if (request.method === "DELETE") return new Response(null, { status: 204 });
- return Response.json(document, { headers: { etag: '"rev-1"' } });
- });
+ context.mock.method(
+ globalThis,
+ "fetch",
+ async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ if (request.method === "DELETE")
+ return new Response(null, { status: 204 });
+ return Response.json(document, { headers: { etag: '"rev-1"' } });
+ },
+ );
const client = new OpenComputerClient({
apiUrl: "https://app.opencomputer.dev",
apiKey: "test",
@@ -72,8 +127,16 @@ test("memory documents travel with their ETag and send it back as a precondition
});
assert.equal(created.etag, '"rev-1"');
assert.equal(created.document.revision, "rev-1");
- await client.replaceMemoryDocument({ ...target, etag: created.etag, text: "Node 22" });
- await client.patchMemoryDocument({ ...target, etag: created.etag, agentWrites: "disabled" });
+ await client.replaceMemoryDocument({
+ ...target,
+ etag: created.etag,
+ text: "Node 22",
+ });
+ await client.patchMemoryDocument({
+ ...target,
+ etag: created.etag,
+ agentWrites: "disabled",
+ });
await client.deleteMemoryDocument({ ...target, etag: created.etag });
await client.memoryDocuments({ ...target, cursor: "c2" });
@@ -108,7 +171,12 @@ test("memory documents travel with their ETag and send it back as a precondition
test("memory precondition failures surface the API's code", async (context) => {
context.mock.method(globalThis, "fetch", async () =>
Response.json(
- { error: { code: "precondition_failed", message: "The document changed." } },
+ {
+ error: {
+ code: "precondition_failed",
+ message: "The document changed.",
+ },
+ },
{ status: 412 },
),
);
@@ -199,7 +267,8 @@ test("model connections and routes use write-only connection input and project r
async (input: string | URL | Request, init?: RequestInit) => {
const request = new Request(input, init);
requests.push(request);
- if (request.method === "DELETE") return new Response(null, { status: 204 });
+ if (request.method === "DELETE")
+ return new Response(null, { status: 204 });
if (request.url.endsWith("/model-access/connections")) {
return Response.json({
id: "mac_scx",
@@ -264,14 +333,26 @@ test("model connections and routes use write-only connection input and project r
test("database queries use the project read endpoint with positional parameters", async (context) => {
let request: Request | undefined;
- context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
- request = new Request(input, init);
- return Response.json({
- environment: "production",
- result: { columns: ["id"], rows: [{ id: 7 }], rowsAffected: 0, truncated: false },
- });
+ context.mock.method(
+ globalThis,
+ "fetch",
+ async (input: string | URL | Request, init?: RequestInit) => {
+ request = new Request(input, init);
+ return Response.json({
+ environment: "production",
+ result: {
+ columns: ["id"],
+ rows: [{ id: 7 }],
+ rowsAffected: 0,
+ truncated: false,
+ },
+ });
+ },
+ );
+ const client = new OpenComputerClient({
+ apiUrl: "https://app.opencomputer.dev",
+ apiKey: "test",
});
- const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev", apiKey: "test" });
const result = await client.databaseQuery({
projectId: "prj_1",
@@ -282,7 +363,10 @@ test("database queries use the project read endpoint with positional parameters"
assert.deepEqual(result.rows, [{ id: 7 }]);
assert.ok(request);
- assert.equal(request.url, "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/database/query");
+ assert.equal(
+ request.url,
+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/database/query",
+ );
assert.equal(request.method, "POST");
assert.deepEqual(await request.json(), {
environment: "production",
diff --git a/cli/src/api.ts b/cli/src/api.ts
index e4e6e1e4..d186fd26 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -330,8 +330,7 @@ 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 {
@@ -432,6 +431,26 @@ export class OpenComputerClient {
private readonly idempotencyKey?: string,
) {}
+ /**
+ * The caller's key scoped to one operation. Extra `parts` distinguish
+ * operations that share a URL but target different resources (one export
+ * per workspace path), so a stable key still retries each of them.
+ */
+ private derivedIdempotencyKey(
+ method: string,
+ path: string,
+ ...parts: string[]
+ ): string {
+ const hash = createHash("sha256")
+ .update(this.idempotencyKey ?? "")
+ .update("\0")
+ .update(method)
+ .update("\0")
+ .update(path);
+ for (const part of parts) hash.update("\0").update(part);
+ return hash.digest("hex");
+ }
+
private async response(
path: string,
init: RequestInit = {},
@@ -454,23 +473,19 @@ export class OpenComputerClient {
// backend compares under that key. Hashing the body in would make a
// retry with different inputs a new operation instead of the conflict
// the key promises.
- if (this.idempotencyKey && method !== "GET" && method !== "HEAD") {
- headers.set(
- "idempotency-key",
- createHash("sha256")
- .update(this.idempotencyKey)
- .update("\0")
- .update(method)
- .update("\0")
- .update(path)
- .digest("hex"),
- );
+ if (
+ this.idempotencyKey &&
+ method !== "GET" &&
+ method !== "HEAD" &&
+ !headers.has("idempotency-key")
+ ) {
+ headers.set("idempotency-key", this.derivedIdempotencyKey(method, path));
}
const response = await fetch(`${this.config.apiUrl}${path}`, {
...init,
headers,
redirect: "manual",
- signal: AbortSignal.timeout(30_000),
+ signal: init.signal ?? AbortSignal.timeout(30_000),
});
if (!response.ok) {
const body: unknown = await response.json().catch(() => undefined);
@@ -1390,4 +1405,132 @@ export class OpenComputerClient {
{ method: "POST" },
);
}
+
+ private workspacePath(sessionId: string, suffix: string) {
+ return `/api/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace${suffix}`;
+ }
+
+ /** Every file under the session's /workspace, across all list pages. */
+ async workspaceFiles(sessionId: string): Promise<WorkspaceFile[]> {
+ const files: WorkspaceFile[] = [];
+ let cursor: string | null = null;
+ do {
+ const query: string = cursor
+ ? `?cursor=${encodeURIComponent(cursor)}`
+ : "";
+ const page: WorkspaceFilePage = await this.request<WorkspaceFilePage>(
+ this.workspacePath(sessionId, `/files${query}`),
+ );
+ files.push(...page.files);
+ cursor = page.nextCursor;
+ } while (cursor);
+ return files;
+ }
+
+ async workspaceArtifacts(sessionId: string): Promise<WorkspaceArtifact[]> {
+ const result = await this.request<{ artifacts: WorkspaceArtifact[] }>(
+ this.workspacePath(sessionId, "/exports"),
+ );
+ return result.artifacts;
+ }
+
+ /** Provider-side export: retains and hashes the file, returns its manifest. */
+ async exportWorkspaceFile(
+ sessionId: string,
+ path: string,
+ ): Promise<WorkspaceArtifact> {
+ const result = await this.request<{
+ export?: WorkspaceExport;
+ artifact: WorkspaceArtifact | null;
+ }>(this.workspacePath(sessionId, "/exports"), {
+ method: "POST",
+ body: JSON.stringify({ path }),
+ ...(this.idempotencyKey
+ ? {
+ headers: {
+ "idempotency-key": this.derivedIdempotencyKey(
+ "POST",
+ this.workspacePath(sessionId, "/exports"),
+ path,
+ ),
+ },
+ }
+ : {}),
+ });
+ if (!result.artifact) {
+ throw new APIError(
+ `Export of ${path} is still in progress (${result.export?.id ?? "unknown export"}); retry shortly`,
+ 202,
+ "export_in_progress",
+ );
+ }
+ return result.artifact;
+ }
+
+ /**
+ * Raw bytes of a retained artifact; callers verify size and SHA-256. The
+ * request always carries the one-hour deadline, combined with `signal`.
+ */
+ workspaceArtifactContent(
+ artifact: Pick<WorkspaceArtifact, "sessionId" | "id">,
+ signal?: AbortSignal,
+ ): Promise<Response> {
+ return this.response(
+ this.workspacePath(
+ artifact.sessionId,
+ `/exports/${encodeURIComponent(artifact.id)}/content`,
+ ),
+ { signal: workspaceContentSignal(signal) },
+ );
+ }
+}
+
+/** Large artifacts stream for a while; the default 30 s budget is for JSON. */
+export const WORKSPACE_CONTENT_TIMEOUT_MS = 60 * 60 * 1000;
+
+/** The one-hour content deadline, also aborting when `signal` does. */
+export function workspaceContentSignal(signal?: AbortSignal): AbortSignal {
+ const timeout = AbortSignal.timeout(WORKSPACE_CONTENT_TIMEOUT_MS);
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
}
+
+export type WorkspaceFile = {
+ path: string;
+ size: number;
+ lastModified: string | null;
+ etag: string | null;
+};
+
+type WorkspaceFilePage = {
+ files: WorkspaceFile[];
+ nextCursor: string | null;
+};
+
+export type WorkspaceExport = {
+ id: string;
+ sessionId: string;
+ path: string;
+ state: "snapshotting" | "delivered" | "failed" | "expired";
+ idempotencyKey: string | null;
+ artifactId: string | null;
+ error: { code: string; message: string; retrySafe: boolean } | null;
+ createdAt: string;
+ completedAt: string | null;
+};
+
+export type WorkspaceArtifact = {
+ id: string;
+ exportId?: string;
+ sessionId: string;
+ path: string;
+ size: number;
+ sha256: string;
+ mediaType?: string;
+ snapshotId?: string;
+ receipt: {
+ etag: string | null;
+ sourceEtag: string | null;
+ sourceVersionId: string | null;
+ };
+ exportedAt: string;
+};
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index b4ea512b..0825c72f 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -34,6 +34,15 @@ import {
parseSessionCommand,
resolveProjectAgent,
} from "./session-command.js";
+import {
+ type DownloadResult,
+ downloadWorkspace,
+ downloadWorkspaceFile,
+ formatSize,
+ listWorkspaceFiles,
+ normalizeWorkspacePath,
+ resolveSingleDestination,
+} from "./session-files.js";
import { formatSessionEvent } from "./session-prompt.js";
import {
buildTemplateProject,
@@ -247,10 +256,7 @@ function consumeModelAccessProvider(
args[0] === "openai-compatible"
) {
return args.shift() as
- | "claude"
- | "codex"
- | "openrouter"
- | "openai-compatible";
+ "claude" | "codex" | "openrouter" | "openai-compatible";
}
return "codex";
}
@@ -2417,8 +2423,7 @@ export async function runCommand(
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
const current = await client.memoryDocument(target);
let edited:
- | Awaited<ReturnType<typeof editMemoryTextInEditor>>
- | undefined;
+ Awaited<ReturnType<typeof editMemoryTextInEditor>> | undefined;
const text =
supplied ??
(edited = await editMemoryTextInEditor(
@@ -2582,6 +2587,11 @@ export async function runCommand(
await tailSession(client, sessionId, after, follow, globals.json);
return;
}
+ if (args[0] === "files") {
+ args.shift();
+ await runSessionFiles(client, args, globals.json);
+ return;
+ }
const session = parseSessionCommand(args);
const sessionArgs = session.args;
if (session.action === "list") {
@@ -2721,3 +2731,78 @@ export async function runCommand(
throw new Error(`Unknown command: ${command}`);
}
+
+/**
+ * `session files <ls|download|cp> <session-id> ...`. A bare
+ * `session files <session-id>` lists, so the common case stays short.
+ */
+async function runSessionFiles(
+ client: OpenComputerClient,
+ args: string[],
+ json: boolean,
+) {
+ const printDownload = (result: DownloadResult) => {
+ process.stdout.write(
+ `${result.path} -> ${result.destination} (${formatSize(result.size)}, sha256 ${result.sha256})\n`,
+ );
+ };
+ const action =
+ args[0] === "ls" ||
+ args[0] === "list" ||
+ args[0] === "download" ||
+ args[0] === "cp"
+ ? (args.shift() as "ls" | "list" | "download" | "cp")
+ : "ls";
+ if (action === "ls" || action === "list") {
+ const sessionId = args.shift();
+ if (!sessionId) throw new Error("A session ID is required.");
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const files = await listWorkspaceFiles(client, sessionId);
+ if (json) printJSON({ sessionId, files });
+ else if (!files.length) process.stdout.write("No workspace files.\n");
+ else {
+ for (const file of files) {
+ process.stdout.write(
+ `${(file.lastModified ?? "").padEnd(24)} ${formatSize(file.size).padStart(10)} ${file.path}\n`,
+ );
+ }
+ }
+ return;
+ }
+ const all = flag(args, "--all");
+ const sessionId = args.shift();
+ if (!sessionId) throw new Error("A session ID is required.");
+ if (all) {
+ const root = args.shift() ?? sessionId;
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const results = await downloadWorkspace(
+ client,
+ sessionId,
+ root,
+ (result) => {
+ if (!json) printDownload(result);
+ },
+ );
+ if (json) printJSON({ sessionId, root, files: results });
+ else if (!results.length) process.stdout.write("No workspace files.\n");
+ return;
+ }
+ const remote = args.shift();
+ if (!remote) {
+ throw new Error("A workspace file path is required (or pass --all).");
+ }
+ const workspacePath = normalizeWorkspacePath(remote);
+ const destination = await resolveSingleDestination(
+ args.shift(),
+ workspacePath,
+ );
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const result = await downloadWorkspaceFile(
+ client,
+ sessionId,
+ workspacePath,
+ destination,
+ );
+ if (json) printJSON({ sessionId, ...result });
+ else printDownload(result);
+}
diff --git a/cli/src/index.ts b/cli/src/index.ts
index 8a87084d..aedb95c4 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -69,6 +69,12 @@ Usage:
opencomputer session attach <session-id>
opencomputer session send <session-id> <prompt> [--keep]
opencomputer session end <session-id>
+ opencomputer session files [ls] <session-id>
+ lists the files under the session's /workspace
+ opencomputer 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
+ verifies size and SHA-256 against the manifest before saving; "cp" is an alias
opencomputer secrets set <name> --value-stdin [--environment development|production] [--agent <agent>|current]
opencomputer secrets list [--environment development|production] [--agent <agent>|current]
opencomputer secrets remove <name> [--environment development|production] [--agent <agent>|current]
diff --git a/cli/src/session-files.test.ts b/cli/src/session-files.test.ts
new file mode 100644
index 00000000..75bcce50
--- /dev/null
+++ b/cli/src/session-files.test.ts
@@ -0,0 +1,260 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import {
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ symlink,
+} from "node:fs/promises";
+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 {
+ VerificationError,
+ downloadWorkspace,
+ downloadWorkspaceFile,
+ formatSize,
+ localPathFor,
+ normalizeWorkspacePath,
+ resolveSingleDestination,
+ type WorkspaceClient,
+} from "./session-files.js";
+
+const sessionId = "ses-1";
+
+function sha256(bytes: Uint8Array): string {
+ return createHash("sha256").update(bytes).digest("hex");
+}
+
+type Fixture = { path: string; bytes: Uint8Array; served?: Uint8Array };
+
+function fakeClient(fixtures: Fixture[]): WorkspaceClient & {
+ exports: string[];
+} {
+ const byPath = new Map(fixtures.map((fixture) => [fixture.path, fixture]));
+ const files: WorkspaceFile[] = fixtures.map((fixture, index) => ({
+ path: fixture.path,
+ size: fixture.bytes.length,
+ lastModified: "2026-01-01T00:00:00.000Z",
+ etag: `etag-${index}`,
+ }));
+ const exports: string[] = [];
+ const artifactFor = (fixture: Fixture): WorkspaceArtifact => ({
+ id: `art-${fixture.path}`,
+ sessionId,
+ path: fixture.path,
+ size: fixture.bytes.length,
+ sha256: sha256(fixture.bytes),
+ receipt: { etag: null, sourceEtag: null, sourceVersionId: null },
+ exportedAt: "2026-01-01T00:00:00.000Z",
+ });
+ return {
+ exports,
+ async workspaceFiles() {
+ return files;
+ },
+ async workspaceArtifacts() {
+ return fixtures.map(artifactFor);
+ },
+ async exportWorkspaceFile(_session, filePath) {
+ const fixture = byPath.get(filePath);
+ if (!fixture) throw new Error(`no such file ${filePath}`);
+ exports.push(filePath);
+ return artifactFor(fixture);
+ },
+ async workspaceArtifactContent(artifact) {
+ const fixture = fixtures.find((f) => `art-${f.path}` === artifact.id);
+ if (!fixture) throw new Error("unknown artifact");
+ const body = fixture.served ?? fixture.bytes;
+ return new Response(new Uint8Array(body), {
+ headers: { "content-type": "application/octet-stream" },
+ });
+ },
+ };
+}
+
+async function withDirectory<T>(run: (dir: string) => Promise<T>): Promise<T> {
+ const dir = await mkdtemp(path.join(tmpdir(), "oc-files-"));
+ try {
+ return await run(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("normalizeWorkspacePath accepts /workspace-prefixed and relative paths", () => {
+ assert.equal(
+ normalizeWorkspacePath("/workspace/out/report.pdf"),
+ "out/report.pdf",
+ );
+ assert.equal(normalizeWorkspacePath("out/report.pdf"), "out/report.pdf");
+ assert.equal(normalizeWorkspacePath("/my file.txt"), "my file.txt");
+ assert.equal(normalizeWorkspacePath(" padded .txt "), " padded .txt ");
+ for (const bad of [
+ "../etc/passwd",
+ "a/../b",
+ "./a",
+ "a//b",
+ "",
+ "/workspace",
+ ]) {
+ assert.throws(() => normalizeWorkspacePath(bad));
+ }
+});
+
+test("localPathFor never escapes the destination root", () => {
+ const root = path.resolve("dest");
+ assert.equal(localPathFor(root, "a/b.txt"), path.join(root, "a", "b.txt"));
+ assert.equal(localPathFor(root, "..settings"), path.join(root, "..settings"));
+ assert.throws(() => localPathFor(root, "../x"), /outside/);
+ assert.throws(() => localPathFor(root, "a/../../x"), /outside/);
+});
+
+test("download exports first, then saves the verified bytes", async () => {
+ const bytes = new TextEncoder().encode("hello evidence");
+ const client = fakeClient([{ path: "out/a.txt", bytes }]);
+ await withDirectory(async (dir) => {
+ const destination = path.join(dir, "a.txt");
+ const result = await downloadWorkspaceFile(
+ client,
+ sessionId,
+ "out/a.txt",
+ destination,
+ );
+ assert.deepEqual(client.exports, ["out/a.txt"]);
+ assert.equal(result.size, bytes.length);
+ assert.equal(result.sha256, sha256(bytes));
+ assert.equal(await readFile(destination, "utf8"), "hello evidence");
+ assert.deepEqual(await readdir(dir), ["a.txt"]);
+ });
+});
+
+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) {
+ test(`${name} content is rejected and leaves nothing on disk`, async () => {
+ const bytes = new TextEncoder().encode("hello evidence");
+ const client = fakeClient([{ path: "a.txt", bytes, served }]);
+ await withDirectory(async (dir) => {
+ const destination = path.join(dir, "a.txt");
+ await assert.rejects(
+ downloadWorkspaceFile(client, sessionId, "a.txt", destination),
+ VerificationError,
+ );
+ assert.deepEqual(await readdir(dir), []);
+ });
+ });
+}
+
+test("--all mirrors the workspace layout under the destination", async () => {
+ const client = fakeClient([
+ { path: "b/deep/two.bin", bytes: new Uint8Array([1, 2, 3]) },
+ { path: "one.txt", bytes: new TextEncoder().encode("one") },
+ ]);
+ await withDirectory(async (dir) => {
+ const results = await downloadWorkspace(client, sessionId, dir);
+ assert.deepEqual(
+ results.map((result) => result.path),
+ ["b/deep/two.bin", "one.txt"],
+ );
+ assert.deepEqual(
+ await readFile(path.join(dir, "b", "deep", "two.bin")),
+ Buffer.from([1, 2, 3]),
+ );
+ assert.equal(await readFile(path.join(dir, "one.txt"), "utf8"), "one");
+ });
+});
+
+test("an ended session falls back to its retained artifacts", async () => {
+ const bytes = new TextEncoder().encode("kept");
+ const base = fakeClient([{ path: "kept.txt", bytes }]);
+ const gone = () =>
+ Promise.reject(
+ new APIError("workspace gone", 410, "workspace_unavailable"),
+ );
+ const client: WorkspaceClient = {
+ ...base,
+ workspaceFiles: gone,
+ exportWorkspaceFile: gone,
+ };
+ await withDirectory(async (dir) => {
+ const single = await downloadWorkspaceFile(
+ client,
+ sessionId,
+ "kept.txt",
+ path.join(dir, "single.txt"),
+ );
+ assert.equal(single.artifactId, "art-kept.txt");
+ assert.equal(await readFile(path.join(dir, "single.txt"), "utf8"), "kept");
+ const all = await downloadWorkspace(
+ client,
+ sessionId,
+ path.join(dir, "all"),
+ );
+ assert.deepEqual(
+ all.map((result) => result.path),
+ ["kept.txt"],
+ );
+ await assert.rejects(
+ downloadWorkspaceFile(
+ client,
+ sessionId,
+ "never.txt",
+ path.join(dir, "n"),
+ ),
+ (error: unknown) =>
+ error instanceof APIError && error.code === "workspace_unavailable",
+ );
+ });
+});
+
+test("--all refuses to follow a symlinked directory out of the root", async () => {
+ const client = fakeClient([
+ { path: "link/escaped.txt", bytes: new TextEncoder().encode("x") },
+ ]);
+ await withDirectory(async (dir) => {
+ const root = path.join(dir, "root");
+ const outside = path.join(dir, "outside");
+ await mkdir(root);
+ await mkdir(outside);
+ await symlink(outside, path.join(root, "link"));
+ await assert.rejects(downloadWorkspace(client, sessionId, root), /outside/);
+ assert.deepEqual(await readdir(outside), []);
+ });
+});
+
+test("resolveSingleDestination follows cp semantics", async () => {
+ await withDirectory(async (dir) => {
+ assert.equal(
+ await resolveSingleDestination(dir, "out/report.pdf"),
+ path.join(dir, "report.pdf"),
+ );
+ assert.equal(
+ await resolveSingleDestination(`${dir}${path.sep}`, "x.txt"),
+ path.join(dir, "x.txt"),
+ );
+ assert.equal(
+ await resolveSingleDestination(
+ path.join(dir, "renamed.pdf"),
+ "out/report.pdf",
+ ),
+ path.join(dir, "renamed.pdf"),
+ );
+ assert.equal(
+ await resolveSingleDestination(undefined, "out/report.pdf"),
+ path.resolve("report.pdf"),
+ );
+ });
+});
+
+test("formatSize is human readable", () => {
+ assert.equal(formatSize(512), "512 B");
+ assert.equal(formatSize(1536), "1.5 KiB");
+ assert.equal(formatSize(3 * 1024 * 1024), "3.0 MiB");
+});
diff --git a/cli/src/session-files.ts b/cli/src/session-files.ts
new file mode 100644
index 00000000..411219f6
--- /dev/null
+++ b/cli/src/session-files.ts
@@ -0,0 +1,322 @@
+import { createHash, randomBytes } from "node:crypto";
+import { createWriteStream } from "node:fs";
+import { mkdir, realpath, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { pipeline } from "node:stream/promises";
+import { Readable, Transform } from "node:stream";
+import {
+ APIError,
+ workspaceContentSignal,
+ type WorkspaceArtifact,
+ type WorkspaceFile,
+} from "./api.js";
+
+/** The client surface this module needs; `OpenComputerClient` satisfies it. */
+export type WorkspaceClient = {
+ workspaceFiles(sessionId: string): Promise<WorkspaceFile[]>;
+ workspaceArtifacts(sessionId: string): Promise<WorkspaceArtifact[]>;
+ exportWorkspaceFile(
+ sessionId: string,
+ path: string,
+ ): Promise<WorkspaceArtifact>;
+ workspaceArtifactContent(
+ artifact: Pick<WorkspaceArtifact, "sessionId" | "id">,
+ signal?: AbortSignal,
+ ): Promise<Response>;
+};
+
+const INTERRUPT_SIGNALS = ["SIGINT", "SIGTERM"] as const;
+
+/**
+ * Turns SIGINT/SIGTERM into an abort for the duration of `run` so the
+ * in-flight stream rejects and its cleanup runs before the process exits.
+ */
+async function withInterruptAbort<T>(
+ run: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ const controller = new AbortController();
+ let interrupted: (typeof INTERRUPT_SIGNALS)[number] | undefined;
+ const onSignal = (signal: (typeof INTERRUPT_SIGNALS)[number]) => {
+ interrupted = signal;
+ controller.abort(new Error(`Interrupted by ${signal}.`));
+ };
+ const handlers = INTERRUPT_SIGNALS.map(
+ (signal) => [signal, () => onSignal(signal)] as const,
+ );
+ for (const [signal, handler] of handlers) process.on(signal, handler);
+ try {
+ return await run(controller.signal);
+ } finally {
+ for (const [signal, handler] of handlers) process.off(signal, handler);
+ if (interrupted) process.kill(process.pid, interrupted);
+ }
+}
+
+export type DownloadResult = {
+ path: string;
+ destination: string;
+ artifactId: string;
+ size: number;
+ sha256: string;
+};
+
+export class VerificationError extends Error {}
+
+/**
+ * Normalises a user-supplied /workspace path to the relative form the API
+ * expects, rejecting anything that could point outside the workspace.
+ */
+export function normalizeWorkspacePath(input: string): string {
+ let value = input.replace(/\\/g, "/");
+ if (value.startsWith("/workspace/"))
+ value = value.slice("/workspace/".length);
+ else if (value === "/workspace") value = "";
+ value = value.replace(/^\/+/, "");
+ if (!value) throw new Error("A workspace file path is required.");
+ const segments = value.split("/");
+ for (const segment of segments) {
+ if (segment === "" || segment === "." || segment === "..") {
+ throw new Error(`Unsafe workspace path: ${input}`);
+ }
+ if (/[\0-\x1f\x7f]/.test(segment)) {
+ throw new Error(`Unsafe workspace path: ${input}`);
+ }
+ }
+ return segments.join("/");
+}
+
+/**
+ * Where a workspace file lands under `root`, refusing any resolution that
+ * escapes it (the server already rejects such paths; this is defence in depth).
+ */
+export function localPathFor(root: string, workspacePath: string): string {
+ const resolvedRoot = path.resolve(root);
+ const target = path.resolve(resolvedRoot, ...workspacePath.split("/"));
+ const relative = path.relative(resolvedRoot, target);
+ if (
+ !relative ||
+ path.isAbsolute(relative) ||
+ relative.split(path.sep).includes("..")
+ ) {
+ throw new Error(
+ `Refusing to write outside ${resolvedRoot}: ${workspacePath}`,
+ );
+ }
+ return target;
+}
+
+export async function listWorkspaceFiles(
+ client: WorkspaceClient,
+ sessionId: string,
+): Promise<WorkspaceFile[]> {
+ const files = await client.workspaceFiles(sessionId);
+ return [...files].sort((a, b) => a.path.localeCompare(b.path));
+}
+
+/**
+ * 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.
+ */
+export async function downloadWorkspaceFile(
+ client: WorkspaceClient,
+ sessionId: string,
+ workspacePath: string,
+ destination: string,
+ root?: string,
+): Promise<DownloadResult> {
+ let artifact: WorkspaceArtifact;
+ try {
+ artifact = await client.exportWorkspaceFile(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, artifact, destination, root);
+}
+
+/**
+ * Once a session's workspace is gone (ended session, storage released) the
+ * live listing and fresh exports fail, but retained artifacts stay
+ * downloadable. Fall back to those in that case only.
+ */
+function isWorkspaceGone(error: unknown): boolean {
+ return (
+ error instanceof APIError &&
+ (error.code === "workspace_unavailable" ||
+ error.code === "artifact_not_found")
+ );
+}
+
+async function latestRetainedArtifacts(
+ client: WorkspaceClient,
+ sessionId: string,
+): Promise<Map<string, WorkspaceArtifact>> {
+ const latest = new Map<string, WorkspaceArtifact>();
+ for (const artifact of await client.workspaceArtifacts(sessionId)) {
+ const current = latest.get(artifact.path);
+ if (!current || current.exportedAt < artifact.exportedAt) {
+ latest.set(artifact.path, artifact);
+ }
+ }
+ return latest;
+}
+
+/**
+ * After the destination's directories exist, confirms that following any
+ * symlinks among them still lands inside `root`.
+ */
+async function assertResolvedWithin(root: string, destination: string) {
+ const resolvedRoot = await realpath(root);
+ const resolvedParent = await realpath(path.dirname(destination));
+ if (
+ resolvedParent !== resolvedRoot &&
+ !resolvedParent.startsWith(resolvedRoot + path.sep)
+ ) {
+ throw new Error(
+ `Refusing to write outside ${resolvedRoot}: ${destination} resolves to ${resolvedParent}`,
+ );
+ }
+}
+
+export async function downloadArtifact(
+ client: WorkspaceClient,
+ artifact: WorkspaceArtifact,
+ destination: string,
+ root?: string,
+): Promise<DownloadResult> {
+ await mkdir(path.dirname(destination), { recursive: true });
+ if (root !== undefined) await assertResolvedWithin(root, destination);
+ const temporary = `${destination}.${randomBytes(6).toString("hex")}.part`;
+ await withInterruptAbort(async (signal) => {
+ try {
+ await streamVerified(client, artifact, temporary, signal);
+ signal.throwIfAborted();
+ // Commit point: once renamed, the verified file stays even if an
+ // interrupt lands during the rename itself.
+ await rename(temporary, destination);
+ } catch (error) {
+ await rm(temporary, { force: true }).catch(() => undefined);
+ throw error;
+ }
+ });
+ return {
+ path: artifact.path,
+ destination,
+ artifactId: artifact.id,
+ size: artifact.size,
+ sha256: artifact.sha256,
+ };
+}
+
+async function streamVerified(
+ client: WorkspaceClient,
+ artifact: WorkspaceArtifact,
+ temporary: string,
+ interrupt: AbortSignal,
+): Promise<void> {
+ const signal = workspaceContentSignal(interrupt);
+ const response = await client.workspaceArtifactContent(artifact, signal);
+ if (!response.body) throw new VerificationError("Empty artifact response.");
+ const hash = createHash("sha256");
+ let received = 0;
+ const verify = new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ received += chunk.length;
+ if (received > artifact.size) {
+ callback(
+ new VerificationError(
+ `Received more than the manifest size of ${artifact.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 !== artifact.size) {
+ throw new VerificationError(
+ `Received ${received} bytes but the manifest says ${artifact.size}.`,
+ );
+ }
+ const digest = hash.digest("hex");
+ if (digest !== artifact.sha256.toLowerCase()) {
+ throw new VerificationError(
+ "Downloaded bytes do not match the manifest SHA-256.",
+ );
+ }
+}
+
+/** Downloads every workspace file into `root`, mirroring the workspace layout. */
+export async function downloadWorkspace(
+ client: WorkspaceClient,
+ sessionId: string,
+ root: string,
+ onFile?: (result: DownloadResult) => void,
+): Promise<DownloadResult[]> {
+ let paths: string[];
+ let retained: Map<string, WorkspaceArtifact> | undefined;
+ try {
+ paths = (await listWorkspaceFiles(client, sessionId)).map((f) => f.path);
+ } catch (error) {
+ if (!isWorkspaceGone(error)) throw error;
+ retained = await latestRetainedArtifacts(client, sessionId);
+ paths = [...retained.keys()].sort((a, b) => a.localeCompare(b));
+ }
+ await mkdir(root, { recursive: true });
+ const results: DownloadResult[] = [];
+ for (const filePath of paths) {
+ const destination = localPathFor(root, filePath);
+ const artifact = retained?.get(filePath);
+ const result = artifact
+ ? await downloadArtifact(client, artifact, destination, root)
+ : await downloadWorkspaceFile(
+ client,
+ sessionId,
+ filePath,
+ destination,
+ root,
+ );
+ results.push(result);
+ onFile?.(result);
+ }
+ return results;
+}
+
+/** `aws s3 cp` semantics: a directory destination keeps the file's basename. */
+export async function resolveSingleDestination(
+ destination: string | undefined,
+ workspacePath: string,
+): Promise<string> {
+ const basename = path.posix.basename(workspacePath);
+ if (!destination) return path.resolve(basename);
+ const endsWithSeparator = /[\\/]$/.test(destination);
+ const existingDirectory = await stat(destination)
+ .then((info) => info.isDirectory())
+ .catch(() => false);
+ if (endsWithSeparator || existingDirectory) {
+ return localPathFor(destination, basename);
+ }
+ return path.resolve(destination);
+}
+
+export function formatSize(bytes: number): string {
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${units[unit]}`;
+}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 4b2dde96..472d1241 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -357,6 +357,250 @@ describe("managed agents proxy", () => {
expect(response.headers.get("x-storage-provider")).toBeNull();
});
+ it("shapes workspace artifact manifests and streams their bytes with the verification headers", async () => {
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ };
+ const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
+ const artifact = {
+ id: "wsart_1",
+ exportId: "wsexp_1",
+ sessionId: "sess_1",
+ projectId: "proj_1",
+ agentId: "acme/evidence",
+ deploymentId: "dep_1",
+ environment: "production",
+ path: "evidence/capture.har",
+ size: 12,
+ sha256: "a".repeat(64),
+ mediaType: "application/json",
+ snapshotId: '"s"',
+ receipt: {
+ bucket: "private-bucket",
+ key: "accounts/org_test/sessions/sess_1/workspace-artifacts/x",
+ etag: '"e"',
+ sourceEtag: '"s"',
+ sourceVersionId: null,
+ },
+ retention: { policy: "until_deleted", expiresAt: null },
+ exportedAt: "2026-01-01T00:00:00.000Z",
+ };
+ const exportRecord = {
+ id: "wsexp_1",
+ sessionId: "sess_1",
+ projectId: "proj_1",
+ agentId: "acme/evidence",
+ deploymentId: "dep_1",
+ environment: "production",
+ path: "evidence/capture.har",
+ state: "delivered",
+ idempotencyKey: "k-1",
+ requestDigest: "f".repeat(64),
+ expected: { bytes: 12 },
+ artifactId: "wsart_1",
+ error: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ completedAt: "2026-01-01T00:00:01.000Z",
+ };
+ const upstreamHeaders: Array<Record<string, string>> = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (target: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(target);
+ if (url.endsWith("/workspace/exports")) {
+ upstreamHeaders.push(
+ Object.fromEntries(new Headers(init?.headers).entries()),
+ );
+ return Response.json(
+ { export: exportRecord, artifact },
+ { status: 201 },
+ );
+ }
+ if (url.endsWith("/workspace/exports/wsart_1/content")) {
+ return new Response("har contents", {
+ headers: {
+ "content-type": "application/octet-stream",
+ "content-disposition": "attachment; filename*=UTF-8''capture.har",
+ "x-workspace-artifact-id": "wsart_1",
+ "x-workspace-artifact-sha256": artifact.sha256,
+ "x-workspace-artifact-size": "12",
+ "x-storage-provider": "private",
+ },
+ });
+ }
+ throw new Error(`unexpected upstream ${url}`);
+ }),
+ );
+
+ const exported = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
+ {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "idempotency-key": "k-1",
+ },
+ body: JSON.stringify({
+ path: "evidence/capture.har",
+ expected: { bytes: 12 },
+ }),
+ },
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(exported.status).toBe(201);
+ expect(upstreamHeaders[0]?.["idempotency-key"]).toBe("k-1");
+ const { requestDigest: _digest, ...publicExport } = exportRecord;
+ expect(await exported.json()).toEqual({
+ export: publicExport,
+ artifact: {
+ id: "wsart_1",
+ exportId: "wsexp_1",
+ sessionId: "sess_1",
+ projectId: "proj_1",
+ agentId: "acme/evidence",
+ deploymentId: "dep_1",
+ environment: "production",
+ path: "evidence/capture.har",
+ size: 12,
+ sha256: artifact.sha256,
+ mediaType: "application/json",
+ snapshotId: '"s"',
+ receipt: {
+ etag: '"e"',
+ sourceEtag: '"s"',
+ sourceVersionId: null,
+ },
+ retention: { policy: "until_deleted", expiresAt: null },
+ exportedAt: artifact.exportedAt,
+ },
+ });
+
+ const content = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/content",
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(content.status).toBe(200);
+ expect(await content.text()).toBe("har contents");
+ expect(content.headers.get("x-workspace-artifact-sha256")).toBe(
+ artifact.sha256,
+ );
+ expect(content.headers.get("x-workspace-artifact-size")).toBe("12");
+ expect(content.headers.get("cache-control")).toBe("private, no-store");
+ expect(content.headers.get("x-storage-provider")).toBeNull();
+
+ const blocked = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/content",
+ { method: "DELETE" },
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(blocked.status).toBe(404);
+ });
+
+ it("passes workspace export refusals through with their code, retry safety and export id", async () => {
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ };
+ const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ {
+ error: {
+ code: "artifact_digest_mismatch",
+ message:
+ "s3://managed-agents-artifacts/accounts/acc/pending/x does not match",
+ retrySafe: false,
+ exportId: `wsexp_${"0".repeat(32)}`,
+ bucket: "leaked",
+ },
+ },
+ { status: 412 },
+ ),
+ ),
+ );
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ path: "evidence/capture.har",
+ expected: { sha256: "b".repeat(64) },
+ }),
+ },
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(412);
+ expect(await response.json()).toEqual({
+ error: {
+ code: "artifact_digest_mismatch",
+ message: "The workspace file digest differs from the expected SHA-256.",
+ retrySafe: false,
+ exportId: `wsexp_${"0".repeat(32)}`,
+ },
+ });
+ });
+
+ it("collapses unrecognized workspace export codes to the generic one", async () => {
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ };
+ const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ {
+ error: {
+ code: "artifact_pending_acc_sess_1_x_rejected",
+ message: "s3://managed-agents-artifacts/accounts/acc/x",
+ retrySafe: true,
+ },
+ },
+ { status: 409 },
+ ),
+ ),
+ );
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ path: "x" }),
+ },
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(409);
+ const body = await response.json<{ error: Record<string, unknown> }>();
+ expect(body.error.code).toBe("workspace_export_failed");
+ expect(body.error.retrySafe).toBe(true);
+ expect(JSON.stringify(body)).not.toMatch(/acc_sess_1|accounts\/acc|s3:/);
+ });
+
it("reads BYOK eligibility from an active Autumn subscription", async () => {
vi.stubGlobal(
"fetch",
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index 6969faa4..77025162 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -181,6 +181,31 @@ const SLACK_SETUP_ERROR_MESSAGES: Record<string, string> = {
"This setup no longer owns the connection. Use Set up manually or start again.",
};
+/** Fixed public wording per workspace export code; upstream messages may
+ * name buckets or object keys and are never forwarded. */
+const WORKSPACE_EXPORT_ERROR_MESSAGES: Record<string, string> = {
+ artifact_path_invalid: "The workspace path is not exportable.",
+ artifact_not_found: "The workspace file was not found.",
+ artifact_symlink_rejected: "Symbolic links are not exported.",
+ artifact_not_regular_file: "Only regular files can be exported.",
+ artifact_too_large: "The workspace file is too large to export.",
+ artifact_changed_during_snapshot:
+ "The workspace file changed during export; retry.",
+ artifact_size_mismatch:
+ "The workspace file size differs from the expected byte count.",
+ artifact_digest_mismatch:
+ "The workspace file digest differs from the expected SHA-256.",
+ artifact_media_type_mismatch:
+ "The workspace file media type differs from the expected one.",
+ export_idempotency_conflict:
+ "The Idempotency-Key was already used for a different export request.",
+ export_in_progress: "An export with this Idempotency-Key is still running.",
+ export_expired:
+ "The export expired before completing; use a new Idempotency-Key.",
+ workspace_unavailable: "The session workspace is not available.",
+ workspace_export_failed: "The workspace export failed.",
+};
+
async function publicErrorResponse(upstream: Response): Promise<Response> {
const body: unknown = await upstream.json().catch(() => null);
const backendError =
@@ -206,9 +231,18 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
backendCode === "template_sync_failed" &&
backendMessage.includes("oc-template.toml") &&
backendMessage.includes("expected a regular file");
+ const workspaceExportError =
+ backendCode.startsWith("artifact_") ||
+ backendCode.startsWith("export_") ||
+ backendCode.startsWith("workspace_");
+ // Only the documented export codes pass through; anything else from that
+ // family collapses to the generic code so no upstream detail leaks.
const publicCode = missingTemplateManifest
? "template_manifest_missing"
- : backendCode;
+ : workspaceExportError &&
+ !Object.hasOwn(WORKSPACE_EXPORT_ERROR_MESSAGES, backendCode)
+ ? "workspace_export_failed"
+ : backendCode;
let message = "The agent request could not be completed.";
const slackSetupMessage = Object.hasOwn(
SLACK_SETUP_ERROR_MESSAGES,
@@ -279,8 +313,25 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
/^[A-Za-z0-9_-]{1,128}$/.test(backendError.setupId)
? { setupId: backendError.setupId }
: {};
+ // Workspace export refusals say whether the same Idempotency-Key may be
+ // retried and which export record the refusal was written to.
+ const exportOutcome: Record<string, unknown> = {};
+ if (workspaceExportError) {
+ if (typeof backendError?.retrySafe === "boolean") {
+ exportOutcome.retrySafe = backendError.retrySafe;
+ }
+ if (
+ typeof backendError?.exportId === "string" &&
+ /^wsexp_[a-f0-9]{32}$/.test(backendError.exportId)
+ ) {
+ exportOutcome.exportId = backendError.exportId;
+ }
+ message = WORKSPACE_EXPORT_ERROR_MESSAGES[publicCode];
+ }
return new Response(
- JSON.stringify({ error: { code: publicCode, message, ...setupId } }),
+ JSON.stringify({
+ error: { code: publicCode, message, ...setupId, ...exportOutcome },
+ }),
{ status: upstream.status, headers },
);
}
@@ -1849,9 +1900,140 @@ function publicSuccessBody(
) {
return publicSessionSnapshot(body);
}
+ if (
+ method === "GET" &&
+ /^\/sessions\/[^/]+\/workspace\/files$/.test(suffix)
+ ) {
+ return {
+ files: Array.isArray(body.files)
+ ? body.files.map(publicWorkspaceFile)
+ : [],
+ nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null,
+ };
+ }
+ if (
+ method === "GET" &&
+ /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)
+ ) {
+ return {
+ artifacts: Array.isArray(body.artifacts)
+ ? body.artifacts.map(publicWorkspaceArtifact)
+ : [],
+ exports: Array.isArray(body.exports)
+ ? body.exports.map(publicWorkspaceExport)
+ : [],
+ };
+ }
+ if (
+ (method === "POST" &&
+ /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)) ||
+ (method === "GET" &&
+ /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+$/.test(suffix))
+ ) {
+ return {
+ ...(body.export !== undefined
+ ? { export: publicWorkspaceExport(body.export) }
+ : {}),
+ artifact: body.artifact ? publicWorkspaceArtifact(body.artifact) : null,
+ };
+ }
throw new Error("Unsupported managed agents response");
}
+function publicWorkspaceFile(value: unknown): Record<string, unknown> {
+ const file = record(value) ?? {};
+ return {
+ path: file.path,
+ size: file.size,
+ lastModified: file.lastModified ?? null,
+ etag: file.etag ?? null,
+ };
+}
+
+/** The manifest a caller verifies against: id, path, size, sha256 and the
+ * retained object's etags. Where the provider retains it (bucket and object
+ * key) is not part of the public contract. */
+function publicWorkspaceArtifact(value: unknown): Record<string, unknown> {
+ const artifact = record(value) ?? {};
+ const receipt = record(artifact.receipt) ?? {};
+ const retention = record(artifact.retention);
+ return {
+ id: artifact.id,
+ exportId: artifact.exportId ?? null,
+ sessionId: artifact.sessionId,
+ projectId: artifact.projectId ?? null,
+ agentId: artifact.agentId ?? null,
+ deploymentId: artifact.deploymentId ?? null,
+ environment: artifact.environment ?? null,
+ path: artifact.path,
+ size: artifact.size,
+ sha256: artifact.sha256,
+ mediaType: artifact.mediaType ?? "application/octet-stream",
+ snapshotId:
+ artifact.snapshotId ??
+ receipt.sourceVersionId ??
+ receipt.sourceEtag ??
+ null,
+ receipt: {
+ etag: receipt.etag ?? null,
+ sourceEtag: receipt.sourceEtag ?? null,
+ sourceVersionId: receipt.sourceVersionId ?? null,
+ },
+ retention: retention
+ ? { policy: retention.policy, expiresAt: retention.expiresAt ?? null }
+ : { policy: "until_deleted", expiresAt: null },
+ exportedAt: artifact.exportedAt,
+ };
+}
+
+/** One export attempt: its state, what the caller expected, the artifact it
+ * produced or the error it ended in. The request digest is internal. */
+function publicWorkspaceExport(value: unknown): Record<string, unknown> {
+ const exported = record(value) ?? {};
+ const error = record(exported.error);
+ const expected = record(exported.expected);
+ return {
+ id: exported.id,
+ sessionId: exported.sessionId,
+ projectId: exported.projectId ?? null,
+ agentId: exported.agentId ?? null,
+ deploymentId: exported.deploymentId ?? null,
+ environment: exported.environment ?? null,
+ path: exported.path,
+ state: exported.state,
+ idempotencyKey: exported.idempotencyKey ?? null,
+ expected: expected
+ ? {
+ ...(expected.bytes !== undefined ? { bytes: expected.bytes } : {}),
+ ...(expected.sha256 !== undefined ? { sha256: expected.sha256 } : {}),
+ ...(expected.mediaType !== undefined
+ ? { mediaType: expected.mediaType }
+ : {}),
+ }
+ : null,
+ artifactId: exported.artifactId ?? null,
+ error: error
+ ? {
+ code:
+ typeof error.code === "string" &&
+ Object.hasOwn(WORKSPACE_EXPORT_ERROR_MESSAGES, error.code)
+ ? error.code
+ : "workspace_export_failed",
+ message:
+ (typeof error.code === "string" &&
+ WORKSPACE_EXPORT_ERROR_MESSAGES[error.code]) ||
+ WORKSPACE_EXPORT_ERROR_MESSAGES.workspace_export_failed,
+ retrySafe: error.retrySafe === true,
+ }
+ : null,
+ createdAt: exported.createdAt,
+ completedAt: exported.completedAt ?? null,
+ };
+}
+
+const WORKSPACE_ARTIFACT_CONTENT_ROUTE =
+ /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+\/content$/;
+
async function publicSuccessResponse(
upstream: Response,
method: string,
@@ -2220,6 +2402,24 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {
return true;
}
+ if (
+ method === "GET" &&
+ /^\/sessions\/[^/]+\/workspace\/files$/.test(suffix)
+ ) {
+ return true;
+ }
+ if (
+ (method === "GET" || method === "POST") &&
+ /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)
+ ) {
+ return true;
+ }
+ if (
+ method === "GET" &&
+ /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+(?:\/content)?$/.test(suffix)
+ ) {
+ return true;
+ }
return (
method === "POST" &&
/^\/sessions\/[^/]+\/(turns|suspend|resume|end|terminate|interrupt)$/.test(
@@ -2754,13 +2954,19 @@ export async function proxyManagedAgents(
if (memoryRoute) return memoryResponse(upstream, method, suffix);
if (!upstream.ok) return publicErrorResponse(upstream);
if (upstream.status === 204) return new Response(null, { status: 204 });
- if (/^\/projects\/[^/]+\/source-archive$/.test(suffix)) {
+ if (
+ /^\/projects\/[^/]+\/source-archive$/.test(suffix) ||
+ WORKSPACE_ARTIFACT_CONTENT_ROUTE.test(suffix)
+ ) {
const responseHeaders = new Headers();
for (const name of [
"content-type",
"content-length",
"content-disposition",
"etag",
+ "x-workspace-artifact-id",
+ "x-workspace-artifact-sha256",
+ "x-workspace-artifact-size",
]) {
const value = upstream.headers.get(name);
if (value) responseHeaders.set(name, value);
diff --git a/create-start/package.json b/create-start/package.json
index ba0ed3c1..3c803118 100644
--- a/create-start/package.json
+++ b/create-start/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/create-start",
- "version": "0.7.10",
+ "version": "0.7.11",
"description": "Create a hello-world OpenComputer agent application.",
"type": "module",
"bin": {
@@ -18,7 +18,7 @@
"node": ">=22.0.0"
},
"dependencies": {
- "@opencomputer/cli": "0.7.10"
+ "@opencomputer/cli": "0.7.11"
},
"publishConfig": {
"access": "public"
diff --git a/docs/agents/playground.mdx b/docs/agents/playground.mdx
index f47a76f5..6de7a08d 100644
--- a/docs/agents/playground.mdx
+++ b/docs/agents/playground.mdx
@@ -25,6 +25,9 @@ The inspector shows the information needed to explain a turn:
- selected model
- tools and MCP capabilities available to that render
- tool activity and errors
+- workspace files the agent wrote under `/workspace`, with verified download of
+ a single file or the whole workspace as a zip (see
+ [Workspace files](/agents/sessions#workspace-files))
OpenComputer's private platform instructions and credentials are intentionally
not shown. The inspector describes your deployed agent configuration, not the
diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdx
index bf7af81f..81cca2b3 100644
--- a/docs/agents/sessions.mdx
+++ b/docs/agents/sessions.mdx
@@ -135,6 +135,39 @@ npx --package @opencomputer/cli opencomputer session "Draft a response"
Use `--keep` on supported commands when the session should remain active after
the command exits.
+### Workspace files
+
+Files 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.
+
+```bash
+# List the files in the session's /workspace
+opencomputer session files <session-id>
+opencomputer session files ls <session-id>
+
+# Download one file (dest may be a file path or an existing directory)
+opencomputer session files download <session-id> report/summary.md
+opencomputer session files download <session-id> /workspace/captures/run.har ./evidence/
+
+# Download the whole workspace, mirroring its layout
+opencomputer session files download <session-id> --all ./workspace-copy
+
+# Machine-readable output with artifactId, size and sha256 per file
+opencomputer 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 workspace
+are 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
+[playground debug inspector](/agents/playground).
+
## From an application
Applications create sessions with the [management API](/agents/api): `POST
diff --git a/web/src/managed-agents/DebugInspector.tsx b/web/src/managed-agents/DebugInspector.tsx
index b452cd95..b5f12237 100644
--- a/web/src/managed-agents/DebugInspector.tsx
+++ b/web/src/managed-agents/DebugInspector.tsx
@@ -15,6 +15,7 @@ import {
type ManagedAgentEvent,
type ManagedAgentRenderDebug,
} from './api'
+import { WorkspaceFilesInspector } from './SessionFiles'
export function modelRouteForRender(
events: ManagedAgentEvent[],
@@ -195,9 +196,14 @@ function RenderChanges({
export function DebugInspector({
events,
deploymentId,
+ sessionId,
+ sessionLive = false,
}: {
events: ManagedAgentEvent[]
deploymentId?: string
+ /** When set, the agent's /workspace files are listed for download. */
+ sessionId?: string
+ sessionLive?: boolean
}) {
const renders = events.flatMap((event) => {
const render = managedAgentRenderDebug(event)
@@ -412,6 +418,9 @@ export function DebugInspector({
</div>
</>
)}
+ {sessionId ? (
+ <WorkspaceFilesInspector sessionId={sessionId} live={sessionLive} />
+ ) : null}
<RuntimeActivity events={activity} />
</div>
</aside>
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 86109720..28faa854 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -522,6 +522,8 @@ function PlaygroundChat({
<DebugInspector
events={debugEvents.data ?? events}
deploymentId={session?.deploymentId}
+ sessionId={liveSessionId}
+ sessionLive={agentWorking}
/>
</div>
)
diff --git a/web/src/managed-agents/Session.tsx b/web/src/managed-agents/Session.tsx
index ef68ec4d..babc6f85 100644
--- a/web/src/managed-agents/Session.tsx
+++ b/web/src/managed-agents/Session.tsx
@@ -1,6 +1,13 @@
import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { ArrowLeft, Bot, Clock3, Loader2, TerminalSquare } from 'lucide-react'
+import {
+ ArrowLeft,
+ Bot,
+ Clock3,
+ FolderDown,
+ Loader2,
+ TerminalSquare,
+} from 'lucide-react'
import { Link, useParams, useSearchParams } from 'react-router-dom'
import { EmptyState } from '@/components/empty-state'
import { PageHeader } from '@/components/page-header'
@@ -19,6 +26,7 @@ import {
getManagedProject,
} from './api'
import { AgentMarkdown } from './AgentMarkdown'
+import { SessionFiles } from './SessionFiles'
import {
turnAssistantText,
turnFailureReason,
@@ -33,9 +41,9 @@ export default function ManagedSessionDetail() {
const { projectId = '', sessionId = '' } = useParams()
const queryClient = useQueryClient()
const [searchParams] = useSearchParams()
- const [activeTab, setActiveTab] = useState<'conversation' | 'events'>(
- 'conversation',
- )
+ const [activeTab, setActiveTab] = useState<
+ 'conversation' | 'events' | 'files'
+ >('conversation')
const project = useQuery({
queryKey: ['managed-project', projectId],
queryFn: () => getManagedProject(projectId),
@@ -201,6 +209,15 @@ export default function ManagedSessionDetail() {
{events.data?.length ?? 0}
</span>
</Button>
+ <Button
+ role="tab"
+ aria-selected={activeTab === 'files'}
+ variant={activeTab === 'files' ? 'default' : 'ghost'}
+ size="sm"
+ onClick={() => setActiveTab('files')}
+ >
+ <FolderDown className="size-3.5" /> Files
+ </Button>
</div>
{activeTab === 'conversation' ? (
@@ -284,6 +301,11 @@ export default function ManagedSessionDetail() {
)}
</PanelContent>
</Panel>
+ ) : activeTab === 'files' ? (
+ <SessionFiles
+ sessionId={session.data.id}
+ live={session.data.status !== 'ended'}
+ />
) : (
<Panel>
<PanelHeader>
diff --git a/web/src/managed-agents/SessionFiles.tsx b/web/src/managed-agents/SessionFiles.tsx
new file mode 100644
index 00000000..f6099625
--- /dev/null
+++ b/web/src/managed-agents/SessionFiles.tsx
@@ -0,0 +1,555 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import {
+ ChevronRight,
+ Download,
+ FileCheck2,
+ FolderDown,
+ Loader2,
+ RefreshCw,
+} from 'lucide-react'
+import {
+ Panel,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import {
+ downloadManagedAgentWorkspaceArchive,
+ downloadManagedAgentWorkspaceArtifact,
+ exportManagedAgentWorkspaceFile,
+ getManagedAgentWorkspaceArtifacts,
+ getManagedAgentWorkspaceFiles,
+ type ManagedWorkspaceArtifact,
+ type ManagedWorkspaceFile,
+} from './api'
+import { DownloadCancelled } from './workspace-download'
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ const units = ['KB', 'MB', 'GB']
+ let value = bytes / 1024
+ let unit = 0
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024
+ unit += 1
+ }
+ 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) return
+ notifyError("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.
+ */
+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}`),
+ ),
+ onSuccess: (retained) =>
+ notifySuccess(`Downloaded ${retained.length} verified 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,
+ }
+}
+
+/**
+ * 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.
+ */
+export function SessionFiles({
+ sessionId,
+ live,
+}: {
+ sessionId: string
+ /** 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)
+
+ return (
+ <div className="space-y-5">
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Workspace</PanelTitle>
+ <PanelDescription className="mt-1">
+ Files under <code>/workspace</code> as last synced from the
+ sandbox. Downloading retains a verified copy first.
+ </PanelDescription>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy || !files.data?.length}
+ onClick={() => downloadAll.mutate(files.data ?? [])}
+ >
+ {downloadAll.isPending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <FolderDown className="size-3.5" />
+ )}
+ {archiveProgress ?? 'Download all'}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => void files.refetch()}
+ disabled={files.isFetching}
+ aria-label="Refresh workspace files"
+ >
+ <RefreshCw
+ className={
+ files.isFetching ? 'size-3.5 animate-spin' : 'size-3.5'
+ }
+ />
+ </Button>
+ </div>
+ </PanelHeader>
+ {files.isLoading ? (
+ <div className="flex min-h-24 items-center justify-center">
+ <Loader2 className="text-muted-foreground size-4 animate-spin" />
+ </div>
+ ) : files.isError ? (
+ <p className="text-status-error px-5 py-4 text-sm">
+ Workspace listing is unavailable for this session.
+ </p>
+ ) : (files.data ?? []).length === 0 ? (
+ <p className="text-muted-foreground px-5 py-4 text-sm">
+ The agent has not written any files yet.
+ </p>
+ ) : (
+ <div className="divide-y text-sm">
+ {(files.data ?? []).map((file: ManagedWorkspaceFile) => {
+ const retained = retainedFor(file)
+ const working = busy && busyPath === file.path
+ return (
+ <div
+ key={file.path}
+ className="flex flex-wrap items-center gap-x-4 gap-y-1 px-5 py-3"
+ >
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">
+ {file.path}
+ </span>
+ <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}`}
+ >
+ <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
+ </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.
+ */
+export function WorkspaceFilesInspector({
+ sessionId,
+ live,
+}: {
+ sessionId: string
+ live: boolean
+}) {
+ const {
+ files,
+ artifacts,
+ retainedFor,
+ download,
+ exportThenDownload,
+ downloadAll,
+ archiveProgress,
+ busy,
+ busyPath,
+ } = 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">
+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium [&::-webkit-details-marker]:hidden">
+ <FolderDown className="size-3.5" /> Workspace files
+ <span className="text-muted-foreground font-mono text-[9px]">
+ {list.length}
+ </span>
+ <ChevronRight className="ml-auto size-3.5 transition-transform group-open:rotate-90" />
+ </summary>
+ <div className="border-t">
+ <div className="flex items-center gap-2 px-3 py-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy || !list.length}
+ onClick={() => downloadAll.mutate(list)}
+ >
+ {downloadAll.isPending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <FolderDown className="size-3.5" />
+ )}
+ {archiveProgress ?? 'Download all'}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => void files.refetch()}
+ disabled={files.isFetching}
+ aria-label="Refresh workspace files"
+ >
+ <RefreshCw
+ className={
+ files.isFetching ? 'size-3.5 animate-spin' : 'size-3.5'
+ }
+ />
+ </Button>
+ </div>
+ <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.
+ </p>
+ ) : (
+ <div className="divide-y">
+ {list.map((file: ManagedWorkspaceFile) => {
+ const retained = retainedFor(file)
+ const working = busy && busyPath === file.path
+ return (
+ <div
+ key={file.path}
+ className="flex items-center gap-2 px-3 py-1.5"
+ >
+ <span
+ className="min-w-0 flex-1 truncate font-mono text-[10px]"
+ title={retained ? `sha256 ${retained.sha256}` : 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" />
+ ) : (
+ <Download className="size-3.5" />
+ )}
+ </Button>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ </details>
+ )
+}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index b0d46372..378793ad 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -1,5 +1,12 @@
import { z } from 'zod'
import { apiFetch, apiFetchResponse, validate } from '@/api/client'
+import {
+ Sha256,
+ ZipWriter,
+ assertSinkCapacity,
+ zipOverheadBytes,
+ openDownloadSink,
+} from './workspace-download'
const agentSchema = z.object({
id: z.string(),
@@ -1628,6 +1635,211 @@ export async function collectManagedAgentEventPages(
}
}
+const workspaceFileSchema = z.object({
+ path: z.string(),
+ size: z.number(),
+ lastModified: z.string().nullable(),
+ etag: z.string().nullable(),
+})
+const workspaceFilesResponseSchema = z.object({
+ files: z.array(workspaceFileSchema),
+ nextCursor: z.string().nullable(),
+})
+const workspaceArtifactSchema = z.object({
+ id: z.string(),
+ exportId: z.string().nullish(),
+ sessionId: z.string(),
+ path: z.string(),
+ size: z.number(),
+ sha256: z.string(),
+ mediaType: z.string().nullish(),
+ snapshotId: z.string().nullish(),
+ receipt: z.object({
+ etag: z.string().nullable(),
+ sourceEtag: z.string().nullable(),
+ sourceVersionId: z.string().nullable(),
+ }),
+ exportedAt: z.string(),
+})
+const workspaceArtifactsResponseSchema = z.object({
+ artifacts: z.array(workspaceArtifactSchema),
+})
+const workspaceExportResponseSchema = z.object({
+ export: z.object({ id: z.string(), state: z.string() }).optional(),
+ artifact: workspaceArtifactSchema.nullable(),
+})
+
+export type ManagedWorkspaceFile = z.infer<typeof workspaceFileSchema>
+export type ManagedWorkspaceArtifact = z.infer<typeof workspaceArtifactSchema>
+
+/** Every file the agent wrote under /workspace, across all list pages. */
+export async function getManagedAgentWorkspaceFiles(sessionId: string) {
+ const files: ManagedWorkspaceFile[] = []
+ let cursor: string | null = null
+ do {
+ const query: string = cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''
+ const page: z.infer<typeof workspaceFilesResponseSchema> = await apiFetch(
+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/files${query}`,
+ undefined,
+ workspaceFilesResponseSchema,
+ )
+ files.push(...page.files)
+ cursor = page.nextCursor
+ } while (cursor)
+ return files
+}
+
+export async function getManagedAgentWorkspaceArtifacts(sessionId: string) {
+ return (
+ await apiFetch(
+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/exports`,
+ undefined,
+ workspaceArtifactsResponseSchema,
+ )
+ ).artifacts
+}
+
+/** Provider-side export: retains and hashes the file, returns its manifest. */
+export async function exportManagedAgentWorkspaceFile(
+ sessionId: string,
+ path: string,
+) {
+ const result = await apiFetch(
+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/exports`,
+ { method: 'POST', body: JSON.stringify({ path }) },
+ workspaceExportResponseSchema,
+ )
+ if (!result.artifact) {
+ throw new Error(`Export of ${path} is still in progress; try again shortly`)
+ }
+ return result.artifact
+}
+
+export function managedAgentWorkspaceArtifactContentPath(
+ artifact: Pick<ManagedWorkspaceArtifact, 'sessionId' | 'id'>,
+) {
+ return `/managed-agents/sessions/${encodeURIComponent(artifact.sessionId)}/workspace/exports/${encodeURIComponent(artifact.id)}/content`
+}
+
+/**
+ * Streams a retained artifact chunk by chunk into `write`, hashing and
+ * counting as it goes, and rejects once the stream ends unless the bytes
+ * match the manifest's size and SHA-256. Callers must discard what they
+ * wrote when this throws; nothing is buffered here, so a 1 GiB artifact
+ * costs one chunk of memory at a time.
+ */
+export async function streamManagedAgentWorkspaceArtifact(
+ artifact: ManagedWorkspaceArtifact,
+ write: (chunk: Uint8Array) => Promise<void>,
+ signal?: AbortSignal,
+) {
+ const response = await apiFetchResponse(
+ managedAgentWorkspaceArtifactContentPath(artifact),
+ { signal },
+ )
+ if (!response.body) throw new Error('Artifact response had no body')
+ const hash = new Sha256()
+ let received = 0
+ const reader = response.body.getReader()
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ received += value.byteLength
+ if (received > artifact.size) {
+ throw new Error(
+ `Download exceeded the manifest size of ${artifact.size} bytes`,
+ )
+ }
+ hash.update(value)
+ await write(value)
+ }
+ } catch (error) {
+ await reader.cancel(error).catch(() => undefined)
+ throw error
+ } finally {
+ reader.releaseLock()
+ }
+ if (received !== artifact.size) {
+ throw new Error(
+ `Downloaded ${received} bytes, manifest says ${artifact.size}`,
+ )
+ }
+ if (hash.hex() !== artifact.sha256) {
+ throw new Error('Downloaded bytes do not match the manifest SHA-256')
+ }
+}
+
+/**
+ * Downloads a verified artifact to the browser under `name`; on any
+ * mismatch the partial output is discarded and nothing is saved. The sink
+ * is opened before `resolve` runs because the save dialog needs the click's
+ * user activation, which an export round-trip would outlive.
+ */
+export async function downloadManagedAgentWorkspaceArtifact(
+ name: string,
+ expectedBytes: number,
+ resolve: () => Promise<ManagedWorkspaceArtifact>,
+) {
+ const sink = await openDownloadSink(name)
+ let artifact: ManagedWorkspaceArtifact
+ try {
+ assertSinkCapacity(sink, expectedBytes)
+ artifact = await resolve()
+ assertSinkCapacity(sink, artifact.size)
+ await streamManagedAgentWorkspaceArtifact(artifact, (chunk) =>
+ sink.write(chunk),
+ )
+ await sink.close()
+ } catch (error) {
+ await sink.abort(error).catch(() => undefined)
+ throw error
+ }
+ return artifact
+}
+
+function archiveBytes(entries: Array<{ path: string; size: number }>) {
+ return (
+ entries.reduce((sum, entry) => sum + entry.size, 0) +
+ zipOverheadBytes(entries)
+ )
+}
+
+/**
+ * Streams several verified artifacts into a single stored zip named `name`.
+ * Each entry is hashed while it is written; a mismatch aborts the whole
+ * archive rather than leaving an unverifiable file behind.
+ */
+export async function downloadManagedAgentWorkspaceArchive(
+ name: string,
+ expected: Array<{ path: string; size: number }>,
+ resolve: () => Promise<ManagedWorkspaceArtifact[]>,
+ onProgress?: (done: number, total: number) => void,
+) {
+ const sink = await openDownloadSink(name)
+ const zip = new ZipWriter(sink)
+ let artifacts: ManagedWorkspaceArtifact[]
+ 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) =>
+ zip.write(chunk),
+ )
+ await zip.endEntry()
+ }
+ onProgress?.(artifacts.length, artifacts.length)
+ await zip.finish()
+ } catch (error) {
+ await zip.abort(error).catch(() => undefined)
+ throw error
+ }
+ return artifacts
+}
+
export async function getManagedAgentSessionEvents(
sessionId: string,
after = 0,
diff --git a/web/src/managed-agents/workspace-download.test.ts b/web/src/managed-agents/workspace-download.test.ts
new file mode 100644
index 00000000..f9e558f2
--- /dev/null
+++ b/web/src/managed-agents/workspace-download.test.ts
@@ -0,0 +1,258 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ BLOB_URL_GRACE_MS,
+ DownloadTooLarge,
+ IN_MEMORY_DOWNLOAD_MAX_BYTES,
+ Sha256,
+ ZipWriter,
+ safeZipEntryName,
+ assertSinkCapacity,
+ crc32Update,
+ openDownloadSink,
+ zipOverheadBytes,
+ type ByteSink,
+} from './workspace-download'
+
+async function subtleHex(bytes: Uint8Array<ArrayBuffer>) {
+ return Array.from(
+ new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)),
+ (b) => b.toString(16).padStart(2, '0'),
+ ).join('')
+}
+
+function memorySink() {
+ const chunks: Uint8Array[] = []
+ let closed = false
+ let aborted = false
+ const sink: ByteSink = {
+ capacity: null,
+ write: (chunk) => {
+ chunks.push(chunk.slice())
+ return Promise.resolve()
+ },
+ close: () => {
+ closed = true
+ return Promise.resolve()
+ },
+ abort: () => {
+ aborted = true
+ chunks.length = 0
+ return Promise.resolve()
+ },
+ }
+ return {
+ sink,
+ bytes: () => {
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0))
+ let at = 0
+ for (const c of chunks) {
+ out.set(c, at)
+ at += c.length
+ }
+ return out
+ },
+ closed: () => closed,
+ aborted: () => aborted,
+ }
+}
+
+describe('Sha256', () => {
+ it('matches known vectors', () => {
+ expect(new Sha256().hex()).toBe(
+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
+ )
+ const abc = new Sha256()
+ abc.update(new TextEncoder().encode('abc'))
+ expect(abc.hex()).toBe(
+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
+ )
+ })
+
+ it('agrees with crypto.subtle regardless of chunk boundaries', async () => {
+ const data = new Uint8Array(200_003)
+ for (let i = 0; i < data.length; i++) data[i] = (i * 31 + 7) & 0xff
+ const expected = await subtleHex(data)
+ for (const step of [1, 3, 55, 64, 65, 1000, 65_536]) {
+ const hash = new Sha256()
+ for (let at = 0; at < data.length; at += step) {
+ hash.update(data.subarray(at, at + step))
+ }
+ expect(hash.hex(), `chunk ${step}`).toBe(expected)
+ }
+ })
+})
+
+describe('crc32Update', () => {
+ it('matches the standard check value', () => {
+ expect(
+ crc32Update(0, new TextEncoder().encode('123456789')).toString(16),
+ ).toBe('cbf43926')
+ const a = crc32Update(0, new TextEncoder().encode('12345'))
+ expect(crc32Update(a, new TextEncoder().encode('6789')).toString(16)).toBe(
+ 'cbf43926',
+ )
+ })
+})
+
+describe('assertSinkCapacity', () => {
+ it('rejects oversized downloads for bounded sinks only', () => {
+ const bounded = {
+ ...memorySink().sink,
+ capacity: IN_MEMORY_DOWNLOAD_MAX_BYTES,
+ }
+ expect(() =>
+ assertSinkCapacity(bounded, IN_MEMORY_DOWNLOAD_MAX_BYTES),
+ ).not.toThrow()
+ expect(() =>
+ assertSinkCapacity(bounded, IN_MEMORY_DOWNLOAD_MAX_BYTES + 1),
+ ).toThrow(DownloadTooLarge)
+ expect(() =>
+ assertSinkCapacity(memorySink().sink, Number.MAX_SAFE_INTEGER),
+ ).not.toThrow()
+ })
+})
+
+describe('openDownloadSink fallback', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('counts live Blob URLs against the budget and releases them later', async () => {
+ vi.useFakeTimers()
+ const revoked: string[] = []
+ vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:x')
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation((url) => {
+ revoked.push(url)
+ })
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+
+ const first = await openDownloadSink('a.bin')
+ expect(first.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES)
+ await first.write(new Uint8Array(1000))
+ await first.close()
+ expect(revoked).toEqual([])
+
+ const second = await openDownloadSink('b.bin')
+ expect(second.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES - 1000)
+ await expect(
+ second.write(new Uint8Array(IN_MEMORY_DOWNLOAD_MAX_BYTES - 999)),
+ ).rejects.toBeInstanceOf(DownloadTooLarge)
+ await second.write(new Uint8Array(500))
+
+ // An open sink's buffered bytes are reserved too.
+ const overlapping = await openDownloadSink('c.bin')
+ expect(overlapping.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES - 1500)
+ await second.abort()
+ expect((await openDownloadSink('d.bin')).capacity).toBe(
+ IN_MEMORY_DOWNLOAD_MAX_BYTES - 1000,
+ )
+
+ vi.advanceTimersByTime(BLOB_URL_GRACE_MS)
+ expect(revoked).toEqual(['blob:x'])
+ const third = await openDownloadSink('e.bin')
+ expect(third.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES)
+ })
+
+ it('enforces the shared budget across sinks opened concurrently', async () => {
+ const a = await openDownloadSink('a.bin')
+ const b = await openDownloadSink('b.bin')
+ expect(a.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES)
+ expect(b.capacity).toBe(IN_MEMORY_DOWNLOAD_MAX_BYTES)
+ const half = IN_MEMORY_DOWNLOAD_MAX_BYTES / 2
+ await a.write(new Uint8Array(half))
+ await b.write(new Uint8Array(half))
+ // Each sink is within its own snapshot, but together they are full.
+ await expect(a.write(new Uint8Array(1))).rejects.toBeInstanceOf(
+ DownloadTooLarge,
+ )
+ await a.abort()
+ await b.abort()
+ })
+})
+
+describe('safeZipEntryName', () => {
+ it('keeps relative paths and rejects escapes', () => {
+ expect(safeZipEntryName('evidence/http 1.har')).toBe('evidence/http 1.har')
+ for (const bad of ['../x', '/etc/passwd', 'a//b', './a', 'C:/x', 'a\u0000b']) {
+ expect(() => safeZipEntryName(bad)).toThrow(/Unsafe archive entry/)
+ }
+ })
+})
+
+describe('zipOverheadBytes', () => {
+ it('is at least what ZipWriter actually emits', async () => {
+ const entries = [
+ { path: 'a.txt', size: 3 },
+ { path: 'nested/dir/ünïcode.bin', size: 5 },
+ ]
+ const mem = memorySink()
+ const zip = new ZipWriter(mem.sink)
+ for (const entry of entries) {
+ await zip.beginEntry(entry.path)
+ await zip.write(new Uint8Array(entry.size))
+ await zip.endEntry()
+ }
+ await zip.finish()
+ const content = entries.reduce((sum, entry) => sum + entry.size, 0)
+ expect(mem.bytes().length - content).toBeLessThanOrEqual(
+ zipOverheadBytes(entries),
+ )
+ })
+})
+
+describe('ZipWriter', () => {
+ it('writes a stored archive with a readable central directory', async () => {
+ const mem = memorySink()
+ const zip = new ZipWriter(mem.sink)
+ const encoder = new TextEncoder()
+ await zip.beginEntry('a/report.txt', new Date(2026, 0, 2, 3, 4, 6))
+ await zip.write(encoder.encode('hello '))
+ await zip.write(encoder.encode('world'))
+ await zip.endEntry()
+ await zip.beginEntry('empty.bin')
+ await zip.endEntry()
+ await zip.finish()
+ expect(mem.closed()).toBe(true)
+
+ const bytes = mem.bytes()
+ const view = new DataView(bytes.buffer)
+ // local header + name + data + descriptor
+ expect(view.getUint32(0, true)).toBe(0x04034b50)
+ const nameLength = view.getUint16(26, true)
+ expect(new TextDecoder().decode(bytes.subarray(30, 30 + nameLength))).toBe(
+ 'a/report.txt',
+ )
+ const dataStart = 30 + nameLength
+ expect(
+ new TextDecoder().decode(bytes.subarray(dataStart, dataStart + 11)),
+ ).toBe('hello world')
+ const descriptor = dataStart + 11
+ expect(view.getUint32(descriptor, true)).toBe(0x08074b50)
+ expect(view.getUint32(descriptor + 4, true)).toBe(
+ crc32Update(0, encoder.encode('hello world')),
+ )
+ expect(view.getBigUint64(descriptor + 8, true)).toBe(11n)
+
+ // end of central directory
+ const eocd = bytes.length - 22
+ expect(view.getUint32(eocd, true)).toBe(0x06054b50)
+ expect(view.getUint16(10 + eocd, true)).toBe(2)
+ const centralStart = view.getUint32(eocd + 16, true)
+ expect(view.getUint32(centralStart, true)).toBe(0x02014b50)
+ expect(view.getUint32(centralStart + 20, true)).toBe(11)
+ expect(view.getUint32(centralStart + 42, true)).toBe(0)
+ })
+
+ it('discards everything on abort', async () => {
+ const mem = memorySink()
+ const zip = new ZipWriter(mem.sink)
+ await zip.beginEntry('x')
+ await zip.write(new Uint8Array([1, 2, 3]))
+ await zip.abort(new Error('mismatch'))
+ expect(mem.aborted()).toBe(true)
+ expect(mem.bytes().length).toBe(0)
+ expect(mem.closed()).toBe(false)
+ })
+})
diff --git a/web/src/managed-agents/workspace-download.ts b/web/src/managed-agents/workspace-download.ts
new file mode 100644
index 00000000..3c8f4ded
--- /dev/null
+++ b/web/src/managed-agents/workspace-download.ts
@@ -0,0 +1,522 @@
+/**
+ * Streaming primitives for verified workspace downloads: an incremental
+ * SHA-256 (crypto.subtle only digests whole buffers), CRC-32 for zip
+ * entries, a store-only zip writer, and a byte sink that streams to disk
+ * when the browser allows it and otherwise falls back to a Blob.
+ */
+
+const K = new Uint32Array([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+])
+
+export class Sha256 {
+ private readonly state = new Uint32Array([
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,
+ 0x1f83d9ab, 0x5be0cd19,
+ ])
+ private readonly block = new Uint8Array(64)
+ private readonly words = new Uint32Array(64)
+ private blockLength = 0
+ private totalLength = 0
+ private finished = false
+
+ update(chunk: Uint8Array) {
+ if (this.finished) throw new Error('Sha256 already finalized')
+ this.totalLength += chunk.length
+ let offset = 0
+ if (this.blockLength > 0) {
+ const take = Math.min(64 - this.blockLength, chunk.length)
+ this.block.set(chunk.subarray(0, take), this.blockLength)
+ this.blockLength += take
+ offset = take
+ if (this.blockLength < 64) return
+ this.compress(this.block, 0)
+ this.blockLength = 0
+ }
+ for (; offset + 64 <= chunk.length; offset += 64) {
+ this.compress(chunk, offset)
+ }
+ if (offset < chunk.length) {
+ this.block.set(chunk.subarray(offset))
+ this.blockLength = chunk.length - offset
+ }
+ }
+
+ /** Lowercase hex digest. */
+ hex() {
+ if (!this.finished) {
+ const bitLength = this.totalLength * 8
+ this.block[this.blockLength++] = 0x80
+ if (this.blockLength > 56) {
+ this.block.fill(0, this.blockLength)
+ this.compress(this.block, 0)
+ this.blockLength = 0
+ }
+ this.block.fill(0, this.blockLength)
+ const view = new DataView(this.block.buffer)
+ view.setUint32(56, Math.floor(bitLength / 0x100000000))
+ view.setUint32(60, bitLength >>> 0)
+ this.compress(this.block, 0)
+ this.finished = true
+ }
+ return Array.from(this.state, (word) =>
+ word.toString(16).padStart(8, '0'),
+ ).join('')
+ }
+
+ private compress(data: Uint8Array, offset: number) {
+ const w = this.words
+ for (let i = 0; i < 16; i++) {
+ const j = offset + i * 4
+ w[i] =
+ (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | data[j + 3]
+ }
+ for (let i = 16; i < 64; i++) {
+ const w15 = w[i - 15]
+ const w2 = w[i - 2]
+ const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3)
+ const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10)
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0
+ }
+ let [a, b, c, d, e, f, g, h] = this.state
+ for (let i = 0; i < 64; i++) {
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
+ const ch = (e & f) ^ (~e & g)
+ const t1 = (h + S1 + ch + K[i] + w[i]) | 0
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
+ const maj = (a & b) ^ (a & c) ^ (b & c)
+ const t2 = (S0 + maj) | 0
+ h = g
+ g = f
+ f = e
+ e = (d + t1) | 0
+ d = c
+ c = b
+ b = a
+ a = (t1 + t2) | 0
+ }
+ const s = this.state
+ s[0] = (s[0] + a) | 0
+ s[1] = (s[1] + b) | 0
+ s[2] = (s[2] + c) | 0
+ s[3] = (s[3] + d) | 0
+ s[4] = (s[4] + e) | 0
+ s[5] = (s[5] + f) | 0
+ s[6] = (s[6] + g) | 0
+ s[7] = (s[7] + h) | 0
+ }
+}
+
+function rotr(x: number, n: number) {
+ return (x >>> n) | (x << (32 - n))
+}
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256)
+ for (let n = 0; n < 256; n++) {
+ let c = n
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
+ table[n] = c >>> 0
+ }
+ return table
+})()
+
+export function crc32Update(crc: number, chunk: Uint8Array) {
+ let c = ~crc >>> 0
+ for (let i = 0; i < chunk.length; i++) {
+ c = CRC_TABLE[(c ^ chunk[i]) & 0xff] ^ (c >>> 8)
+ }
+ return ~c >>> 0
+}
+
+/**
+ * Most a memory-backed download may hold; beyond this the tab is likely to
+ * die before the Blob is built, so callers fail fast instead.
+ */
+export const IN_MEMORY_DOWNLOAD_MAX_BYTES = 512 * 1024 * 1024
+
+/**
+ * How long a finished fallback download keeps its Blob URL alive. The
+ * anchor click only schedules the download, so the URL must outlive the
+ * click briefly; browsers pick the Blob up well within this window.
+ */
+export const BLOB_URL_GRACE_MS = 5_000
+
+interface LiveBlobUrl {
+ url: string
+ bytes: number
+ timer: ReturnType<typeof setTimeout>
+}
+
+// Bytes held in memory by fallback sinks: buffered by open sinks plus the
+// Blobs behind URLs still in their grace period. Shared across all sinks so
+// overlapping or back-to-back downloads cannot stack up gigabytes.
+let reservedFallbackBytes = 0
+const liveBlobUrls = new Set<LiveBlobUrl>()
+
+function releaseBlobUrl(live: LiveBlobUrl) {
+ clearTimeout(live.timer)
+ liveBlobUrls.delete(live)
+ reservedFallbackBytes -= live.bytes
+ URL.revokeObjectURL(live.url)
+}
+
+/** Where verified bytes go: the user's disk when possible, else memory. */
+export interface ByteSink {
+ /** Upper bound on total bytes this sink can take, or null if unbounded. */
+ capacity: number | null
+ write(chunk: Uint8Array): Promise<void>
+ close(): Promise<void>
+ /** Drop everything written so far; nothing is exposed to the user. */
+ abort(reason?: unknown): Promise<void>
+}
+
+interface SaveFilePickerWindow {
+ showSaveFilePicker?: (options: {
+ suggestedName?: string
+ }) => Promise<SaveFileHandle>
+}
+
+interface SaveFileHandle {
+ createWritable(): Promise<WritableStream<Uint8Array>>
+ getFile(): Promise<{ size: number }>
+ /** Chromium-only; deletes the file the picker created or truncated. */
+ remove?: () => Promise<void>
+}
+
+/**
+ * Opens a sink for a download named `name`. Browsers with the File System
+ * Access API stream straight to disk, which is what makes multi-hundred-MB
+ * artifacts feasible; others buffer and save a Blob at the end.
+ */
+export async function openDownloadSink(name: string): Promise<ByteSink> {
+ const picker = (window as SaveFilePickerWindow).showSaveFilePicker
+ if (picker) {
+ let handle
+ try {
+ handle = await picker.call(window, { suggestedName: name })
+ } catch (error) {
+ if (error instanceof DOMException && error.name === 'AbortError') {
+ throw new DownloadCancelled()
+ }
+ throw error
+ }
+ let writable: WritableStream<Uint8Array>
+ try {
+ writable = await handle.createWritable()
+ } catch (error) {
+ // The picker may already have truncated the file; drop the empty shell.
+ try {
+ if ((await handle.getFile()).size === 0) await handle.remove?.()
+ } catch {
+ // Best effort.
+ }
+ throw error
+ }
+ const writer = writable.getWriter()
+ return {
+ capacity: null,
+ write: (chunk) => writer.write(chunk),
+ close: () => writer.close(),
+ // Chromium truncates the picked file to zero bytes as soon as the
+ // picker resolves; after discarding the swap file, drop that empty
+ // shell. A file that still has content (another engine preserved it)
+ // is left alone.
+ abort: async (reason) => {
+ await writer.abort(reason)
+ try {
+ if ((await handle.getFile()).size === 0) await handle.remove?.()
+ } catch {
+ // Cleanup is best effort; the verification error is what matters.
+ }
+ },
+ }
+ }
+ const chunks: Uint8Array<ArrayBuffer>[] = []
+ const capacity = IN_MEMORY_DOWNLOAD_MAX_BYTES - reservedFallbackBytes
+ let held = 0
+ let settled = false
+ const release = () => {
+ if (settled) return
+ settled = true
+ reservedFallbackBytes -= held
+ chunks.length = 0
+ }
+ return {
+ capacity,
+ write: (chunk) => {
+ if (held + chunk.byteLength > capacity) {
+ return Promise.reject(
+ new DownloadTooLarge(held + chunk.byteLength, capacity),
+ )
+ }
+ // Another sink may have consumed the shared budget since this one was
+ // opened; the cap is on total memory, not per sink.
+ if (
+ reservedFallbackBytes + chunk.byteLength >
+ IN_MEMORY_DOWNLOAD_MAX_BYTES
+ ) {
+ return Promise.reject(
+ new DownloadTooLarge(
+ held + chunk.byteLength,
+ Math.max(
+ 0,
+ IN_MEMORY_DOWNLOAD_MAX_BYTES - (reservedFallbackBytes - held),
+ ),
+ ),
+ )
+ }
+ held += chunk.byteLength
+ reservedFallbackBytes += chunk.byteLength
+ chunks.push(chunk.slice())
+ return Promise.resolve()
+ },
+ close: () => {
+ if (settled) return Promise.resolve()
+ const url = URL.createObjectURL(new Blob(chunks))
+ const live: LiveBlobUrl = {
+ url,
+ bytes: held,
+ timer: setTimeout(() => releaseBlobUrl(live), BLOB_URL_GRACE_MS),
+ }
+ liveBlobUrls.add(live)
+ settled = true
+ chunks.length = 0
+ const anchor = document.createElement('a')
+ anchor.href = url
+ anchor.download = name
+ anchor.click()
+ return Promise.resolve()
+ },
+ abort: () => {
+ release()
+ return Promise.resolve()
+ },
+ }
+}
+
+export class DownloadTooLarge extends Error {
+ constructor(bytes: number, capacity: number) {
+ const mb = (n: number) => Math.ceil(n / (1024 * 1024))
+ super(
+ `This browser can only download up to ${mb(capacity)} MB right now (${mb(bytes)} MB requested). Use a Chromium-based browser to stream larger downloads to disk, wait a few seconds after a previous download, or download files individually.`,
+ )
+ this.name = 'DownloadTooLarge'
+ }
+}
+
+/** Fails fast when `bytes` cannot fit the sink, before anything streams. */
+export function assertSinkCapacity(sink: ByteSink, bytes: number) {
+ if (sink.capacity !== null && bytes > sink.capacity) {
+ throw new DownloadTooLarge(bytes, sink.capacity)
+ }
+}
+
+export class DownloadCancelled extends Error {
+ constructor() {
+ super('Download cancelled')
+ this.name = 'DownloadCancelled'
+ }
+}
+
+/**
+ * Upper bound on the bytes `ZipWriter` adds around the file contents of
+ * `entries` (local headers, data descriptors, central directory with zip64
+ * extras, end records), so capacity preflights cover the whole archive.
+ */
+export function zipOverheadBytes(entries: Array<{ path: string }>) {
+ const encoder = new TextEncoder()
+ let total = 22 + 76 // end of central directory (+ zip64 end + locator)
+ for (const entry of entries) {
+ const name = encoder.encode(entry.path).length
+ total += 30 + name + 24 + 46 + name + 28
+ }
+ return total
+}
+
+interface ZipEntry {
+ name: Uint8Array
+ crc: number
+ size: number
+ offset: number
+ dosTime: number
+ dosDate: number
+}
+
+/**
+ * Minimal streaming zip writer (method 0 / stored, data descriptors, zip64
+ * where offsets or sizes need it). Entries are written as they arrive so
+ * nothing is buffered beyond the current chunk.
+ */
+/**
+ * Entry names are relative, forward-slash paths with no `.`/`..` segments,
+ * so an extractor cannot be steered outside its target directory.
+ */
+export function safeZipEntryName(path: string): string {
+ const segments = path.replace(/\\/g, '/').split('/')
+ if (
+ segments.length === 0 ||
+ segments.some(
+ (segment) =>
+ segment === '' ||
+ segment === '.' ||
+ segment === '..' ||
+ // eslint-disable-next-line no-control-regex
+ /[\0-\x1f\x7f]/.test(segment) ||
+ /^[A-Za-z]:/.test(segment),
+ )
+ ) {
+ throw new Error(`Unsafe archive entry name: ${path}`)
+ }
+ return segments.join('/')
+}
+
+export class ZipWriter {
+ private readonly entries: ZipEntry[] = []
+ private offset = 0
+ private current: ZipEntry | null = null
+
+ constructor(private readonly sink: ByteSink) {}
+
+ async beginEntry(path: string, modified?: Date) {
+ if (this.current) throw new Error('Previous zip entry still open')
+ const name = new TextEncoder().encode(safeZipEntryName(path))
+ const [dosTime, dosDate] = dosDateTime(modified ?? new Date())
+ const entry: ZipEntry = {
+ name,
+ crc: 0,
+ size: 0,
+ offset: this.offset,
+ dosTime,
+ dosDate,
+ }
+ const header = new Uint8Array(30 + name.length)
+ const view = new DataView(header.buffer)
+ view.setUint32(0, 0x04034b50, true)
+ view.setUint16(4, 45, true) // version needed: zip64-capable
+ view.setUint16(6, 0x0808, true) // data descriptor + utf-8 names
+ view.setUint16(8, 0, true) // stored
+ view.setUint16(10, dosTime, true)
+ view.setUint16(12, dosDate, true)
+ // crc/sizes live in the data descriptor
+ view.setUint16(26, name.length, true)
+ view.setUint16(28, 0, true)
+ header.set(name, 30)
+ await this.emit(header)
+ this.current = entry
+ }
+
+ async write(chunk: Uint8Array) {
+ if (!this.current) throw new Error('No open zip entry')
+ this.current.crc = crc32Update(this.current.crc, chunk)
+ this.current.size += chunk.length
+ await this.emit(chunk)
+ }
+
+ async endEntry() {
+ const entry = this.current
+ if (!entry) throw new Error('No open zip entry')
+ const descriptor = new Uint8Array(24)
+ const view = new DataView(descriptor.buffer)
+ view.setUint32(0, 0x08074b50, true)
+ view.setUint32(4, entry.crc, true)
+ view.setBigUint64(8, BigInt(entry.size), true)
+ view.setBigUint64(16, BigInt(entry.size), true)
+ await this.emit(descriptor)
+ this.entries.push(entry)
+ this.current = null
+ }
+
+ async finish() {
+ if (this.current) throw new Error('Zip entry still open')
+ const centralStart = this.offset
+ for (const entry of this.entries) {
+ const zip64 = entry.size >= 0xffffffff || entry.offset >= 0xffffffff
+ const extra = zip64 ? 28 : 0
+ const record = new Uint8Array(46 + entry.name.length + extra)
+ const view = new DataView(record.buffer)
+ view.setUint32(0, 0x02014b50, true)
+ view.setUint16(4, 45, true)
+ view.setUint16(6, 45, true)
+ view.setUint16(8, 0x0808, true)
+ view.setUint16(10, 0, true)
+ view.setUint16(12, entry.dosTime, true)
+ view.setUint16(14, entry.dosDate, true)
+ view.setUint32(16, entry.crc, true)
+ view.setUint32(20, zip64 ? 0xffffffff : entry.size, true)
+ view.setUint32(24, zip64 ? 0xffffffff : entry.size, true)
+ view.setUint16(28, entry.name.length, true)
+ view.setUint16(30, extra, true)
+ view.setUint32(42, zip64 ? 0xffffffff : entry.offset, true)
+ record.set(entry.name, 46)
+ if (zip64) {
+ const at = 46 + entry.name.length
+ view.setUint16(at, 0x0001, true)
+ view.setUint16(at + 2, 24, true)
+ view.setBigUint64(at + 4, BigInt(entry.size), true)
+ view.setBigUint64(at + 12, BigInt(entry.size), true)
+ view.setBigUint64(at + 20, BigInt(entry.offset), true)
+ }
+ await this.emit(record)
+ }
+ const centralSize = this.offset - centralStart
+ const count = this.entries.length
+ const needZip64 =
+ count >= 0xffff || centralSize >= 0xffffffff || centralStart >= 0xffffffff
+ if (needZip64) {
+ const zip64End = new Uint8Array(56 + 20)
+ const view = new DataView(zip64End.buffer)
+ view.setUint32(0, 0x06064b50, true)
+ view.setBigUint64(4, 44n, true)
+ view.setUint16(12, 45, true)
+ view.setUint16(14, 45, true)
+ view.setBigUint64(24, BigInt(count), true)
+ view.setBigUint64(32, BigInt(count), true)
+ view.setBigUint64(40, BigInt(centralSize), true)
+ view.setBigUint64(48, BigInt(centralStart), true)
+ view.setUint32(56, 0x07064b50, true)
+ view.setBigUint64(64, BigInt(this.offset), true)
+ view.setUint32(72, 1, true)
+ await this.emit(zip64End)
+ }
+ const end = new Uint8Array(22)
+ const view = new DataView(end.buffer)
+ view.setUint32(0, 0x06054b50, true)
+ view.setUint16(8, Math.min(count, 0xffff), true)
+ view.setUint16(10, Math.min(count, 0xffff), true)
+ view.setUint32(12, Math.min(centralSize, 0xffffffff), true)
+ view.setUint32(16, Math.min(centralStart, 0xffffffff), true)
+ await this.emit(end)
+ await this.sink.close()
+ }
+
+ abort(reason?: unknown) {
+ return this.sink.abort(reason)
+ }
+
+ private async emit(bytes: Uint8Array) {
+ await this.sink.write(bytes)
+ this.offset += bytes.length
+ }
+}
+
+function dosDateTime(date: Date): [number, number] {
+ const year = Math.max(1980, date.getFullYear())
+ const time =
+ (date.getHours() << 11) |
+ (date.getMinutes() << 5) |
+ (date.getSeconds() >> 1)
+ const day =
+ ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()
+ return [time, day]
+}