Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

Add sandbox file download (#51)

pranjaltrvd6fd7506904b6
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.json
index 33a138129..af7e962ba 100644
--- a/fern/openapi/openapi.json
+++ b/fern/openapi/openapi.json
@@ -5182,6 +5182,138 @@
"x-fern-sdk-method-name": "get_turn"
}
},
+ "/api/v1/sessions/{session_id}/turns/{turn_id}/download": {
+ "get": {
+ "description": "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "session_id",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Turn identifier.",
+ "in": "path",
+ "name": "turn_id",
+ "required": true,
+ "schema": {
+ "description": "Turn identifier.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Absolute path of the file inside the sandbox, as listed in the assistant's `sandbox_artifacts` block.",
+ "in": "query",
+ "name": "path",
+ "required": true,
+ "schema": {
+ "description": "Absolute path of the file inside the sandbox, as listed in the assistant's `sandbox_artifacts` block.",
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/octet-stream": {
+ "schema": {
+ "format": "binary",
+ "type": "string"
+ }
+ }
+ },
+ "description": "File contents."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid path, or the path is a directory."
+ },
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Sandbox belongs to another tenant."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session, turn, or file not found."
+ },
+ "410": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Sandbox no longer exists."
+ },
+ "412": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Turn has no sandbox, or no sandbox provider is configured."
+ },
+ "413": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "File exceeds the maximum download size."
+ },
+ "424": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Sandbox infrastructure error."
+ }
+ },
+ "summary": "Download a file from the turn sandbox",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "download_sandbox_file"
+ }
+ },
"/api/v1/sessions/{session_id}/turns/{turn_id}/events": {
"get": {
"description": "Paginated persisted events for a turn (insertion order by default).",
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index 513ea44f0..9d30a9d0b 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -24,7 +24,7 @@
"@assistant-ui/core": "0.2.22",
"@assistant-ui/react": "^0.14.24",
"@assistant-ui/store": "0.2.21",
- "@truefoundry/assistant-ui-runtime": "^0.1.7",
+ "@truefoundry/assistant-ui-runtime": "^0.1.10-rc.1",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
"react": "^19.2.4",
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx
index cbb65bd0a..b72265eed 100644
--- a/packages/frontend/src/App.tsx
+++ b/packages/frontend/src/App.tsx
@@ -30,8 +30,10 @@ function OpenSettingsWelcomeScreen(props: WelcomeScreenProps) {
return <WelcomeScreen {...props} />;
}
+const chatServer = createHarnessChatServer();
+
const server = createTrueFoundryServer<HarnessAgentSpec>({
- chatServer: createHarnessChatServer(),
+ chatServer,
...createHarnessBuilderServer(),
catalog: {
modelCatalog: createModelProviderCatalog(),
@@ -97,7 +99,9 @@ export function App() {
}, []);
const overrides: SlotOverrides = useMemo(
- () => (boot.status === 'ready' && boot.openSettings ? { WelcomeScreen: OpenSettingsWelcomeScreen } : {}),
+ () => ({
+ ...(boot.status === 'ready' && boot.openSettings ? { WelcomeScreen: OpenSettingsWelcomeScreen } : {}),
+ }),
[boot],
);
diff --git a/packages/frontend/src/harnessServer.ts b/packages/frontend/src/harnessServer.ts
index aab10b2cc..0d5828554 100644
--- a/packages/frontend/src/harnessServer.ts
+++ b/packages/frontend/src/harnessServer.ts
@@ -171,8 +171,14 @@ function toHarnessInput(input: TurnInputItem[]): Harness.TurnInputItem[] {
export function createHarnessChatServer(options: CreateHarnessServerOptions = {}): AgentChatServer<HarnessAgentSpec> {
const client =
options.baseUrl === undefined && options.fetch === undefined ? harnessClient : createHarnessClient(options);
-
return {
+ // The sandbox is resolved server-side from the turn, so `sandboxId` is accepted for parity
+ // with hosts that address sandboxes directly and deliberately not forwarded.
+ async downloadSandboxFile({ sessionId, turnId, path }) {
+ const response = await client.sessions.downloadSandboxFile(sessionId, turnId, { path });
+ return response.blob();
+ },
+
async createSession(request) {
if (!request.agentSpec) {
throw new Error('Harness sessions require an agentSpec');
diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.ts
index b6e4678f6..6c47ab0cd 100644
--- a/packages/harness/src/core/index.ts
+++ b/packages/harness/src/core/index.ts
@@ -143,7 +143,7 @@ export type { SandboxExecParams, SandboxInit, SandboxProvider } from './sandbox/
export { TFYSandboxProvider } from './sandbox/provider/TFYSandboxProvider';
export { SKILL_DOWNLOAD_TIMEOUT_SECONDS, Sandbox, buildWriteAndRunScriptCommand } from './sandbox/Sandbox';
export type { SandboxInfo } from './sandbox/Sandbox';
-export { SandboxError } from './sandbox/SandboxErrors';
+export { SandboxError, validateNoPathTraversal, validateSandboxOwnedByTenant } from './sandbox/SandboxErrors';
// Skills: the ISkillMounter seam lets hosts plug in their own skill sources
export { InstructionBuilder } from './InstructionBuilder';
diff --git a/packages/harness/src/core/sandbox/SandboxErrors.ts b/packages/harness/src/core/sandbox/SandboxErrors.ts
index 21b462a6e..5b1dd5388 100644
--- a/packages/harness/src/core/sandbox/SandboxErrors.ts
+++ b/packages/harness/src/core/sandbox/SandboxErrors.ts
@@ -1,5 +1,11 @@
export abstract class SandboxError extends Error {
- abstract readonly statusCode: number;
+ /**
+ * Every sandbox failure is caused by the request itself — a bad path, another tenant's sandbox,
+ * a missing or oversized file — so each subclass carries the status a host should reply with.
+ * Listing the codes in use rather than `number` lets a typed route return this directly; adding
+ * a subclass with a new code means widening this union and declaring it on the route.
+ */
+ abstract readonly statusCode: 400 | 403 | 404 | 410 | 413;
}
export class SandboxFileNotFoundError extends SandboxError {
diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.json
index 4af02da79..54eb8d43d 100644
--- a/packages/sdk/.fern/metadata.json
+++ b/packages/sdk/.fern/metadata.json
@@ -27,7 +27,7 @@
"streamType": "web",
"useDefaultRequestParameterValues": true
},
- "originGitCommit": "a705c065ed5092ed4614fdef53f558dab3e764aa",
+ "originGitCommit": "3c673adf5e6b96c84cd953498f10a3d42a6f948e",
"originGitCommitIsDirty": true,
"invokedBy": "manual",
"requestedVersion": "0.0.0",
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 33bd092b9..53060b708 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -16,6 +16,7 @@ The harness server has no built-in authentication, so point the client at your o
- [Request and Response Types](#request-and-response-types)
- [Exception Handling](#exception-handling)
- [Streaming Response](#streaming-response)
+- [Binary Response](#binary-response)
- [Advanced](#advanced)
- [Subpackage Exports](#subpackage-exports)
- [Additional Headers](#additional-headers)
@@ -102,6 +103,395 @@ for await (const item of response) {
}
```
+## Binary Response
+
+You can consume binary data from endpoints using the `BinaryResponse` type which lets you choose how to consume the data:
+
+```typescript
+const response = await client.sessions.downloadSandboxFile(...);
+const stream: ReadableStream<Uint8Array> = response.stream();
+// const arrayBuffer: ArrayBuffer = await response.arrayBuffer();
+// const blob: Blob = response.blob();
+// const bytes: Uint8Array = response.bytes();
+// You can only use the response body once, so you must choose one of the above methods.
+// If you want to check if the response body has been used, you can use the following property.
+const bodyUsed = response.bodyUsed;
+```
+<details>
+<summary>Save binary response to a file</summary>
+
+<blockquote>
+<details>
+<summary>Node.js</summary>
+
+<blockquote>
+<details>
+<summary>ReadableStream (most-efficient)</summary>
+
+```ts
+import { createWriteStream } from 'fs';
+import { Readable } from 'stream';
+import { pipeline } from 'stream/promises';
+
+const response = await client.sessions.downloadSandboxFile(...);
+
+const stream = response.stream();
+const nodeStream = Readable.fromWeb(stream);
+const writeStream = createWriteStream('path/to/file');
+
+await pipeline(nodeStream, writeStream);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ArrayBuffer</summary>
+
+```ts
+import { writeFile } from 'fs/promises';
+
+const response = await client.sessions.downloadSandboxFile(...);
+
+const arrayBuffer = await response.arrayBuffer();
+await writeFile('path/to/file', Buffer.from(arrayBuffer));
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Blob</summary>
+
+```ts
+import { writeFile } from 'fs/promises';
+
+const response = await client.sessions.downloadSandboxFile(...);
+
+const blob = await response.blob();
+const arrayBuffer = await blob.arrayBuffer();
+await writeFile('output.bin', Buffer.from(arrayBuffer));
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bytes (UIntArray8)</summary>
+
+```ts
+import { writeFile } from 'fs/promises';
+
+const response = await client.sessions.downloadSandboxFile(...);
+
+const bytes = await response.bytes();
+await writeFile('path/to/file', bytes);
+```
+
+</details>
+</blockquote>
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bun</summary>
+
+<blockquote>
+<details>
+<summary>ReadableStream (most-efficient)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const stream = response.stream();
+await Bun.write('path/to/file', stream);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ArrayBuffer</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const arrayBuffer = await response.arrayBuffer();
+await Bun.write('path/to/file', arrayBuffer);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Blob</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const blob = await response.blob();
+await Bun.write('path/to/file', blob);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bytes (UIntArray8)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const bytes = await response.bytes();
+await Bun.write('path/to/file', bytes);
+```
+
+</details>
+</blockquote>
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Deno</summary>
+
+<blockquote>
+<details>
+<summary>ReadableStream (most-efficient)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const stream = response.stream();
+const file = await Deno.open('path/to/file', { write: true, create: true });
+await stream.pipeTo(file.writable);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ArrayBuffer</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const arrayBuffer = await response.arrayBuffer();
+await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Blob</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const blob = await response.blob();
+const arrayBuffer = await blob.arrayBuffer();
+await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bytes (UIntArray8)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const bytes = await response.bytes();
+await Deno.writeFile('path/to/file', bytes);
+```
+
+</details>
+</blockquote>
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Browser</summary>
+
+<blockquote>
+<details>
+<summary>Blob (most-efficient)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const blob = await response.blob();
+const url = URL.createObjectURL(blob);
+
+// trigger download
+const a = document.createElement('a');
+a.href = url;
+a.download = 'filename';
+a.click();
+URL.revokeObjectURL(url);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ReadableStream</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const stream = response.stream();
+const reader = stream.getReader();
+const chunks = [];
+
+while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+}
+
+const blob = new Blob(chunks);
+const url = URL.createObjectURL(blob);
+
+// trigger download
+const a = document.createElement('a');
+a.href = url;
+a.download = 'filename';
+a.click();
+URL.revokeObjectURL(url);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ArrayBuffer</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const arrayBuffer = await response.arrayBuffer();
+const blob = new Blob([arrayBuffer]);
+const url = URL.createObjectURL(blob);
+
+// trigger download
+const a = document.createElement('a');
+a.href = url;
+a.download = 'filename';
+a.click();
+URL.revokeObjectURL(url);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bytes (UIntArray8)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const bytes = await response.bytes();
+const blob = new Blob([bytes]);
+const url = URL.createObjectURL(blob);
+
+// trigger download
+const a = document.createElement('a');
+a.href = url;
+a.download = 'filename';
+a.click();
+URL.revokeObjectURL(url);
+```
+
+</details>
+</blockquote>
+
+</details>
+</blockquote>
+
+</details>
+</blockquote>
+
+<details>
+<summary>Convert binary response to text</summary>
+
+<blockquote>
+<details>
+<summary>ReadableStream</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const stream = response.stream();
+const text = await new Response(stream).text();
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>ArrayBuffer</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const arrayBuffer = await response.arrayBuffer();
+const text = new TextDecoder().decode(arrayBuffer);
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Blob</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const blob = await response.blob();
+const text = await blob.text();
+```
+
+</details>
+</blockquote>
+
+<blockquote>
+<details>
+<summary>Bytes (UIntArray8)</summary>
+
+```ts
+const response = await client.sessions.downloadSandboxFile(...);
+
+const bytes = await response.bytes();
+const text = new TextDecoder().decode(bytes);
+```
+
+</details>
+</blockquote>
+
+</details>
+
## Advanced
### Subpackage Exports
diff --git a/packages/sdk/pnpm-lock.yaml b/packages/sdk/pnpm-lock.yaml
index e76571160..f587bbc5a 100644
--- a/packages/sdk/pnpm-lock.yaml
+++ b/packages/sdk/pnpm-lock.yaml
@@ -25,7 +25,7 @@ importers:
version: 5.9.3
vitest:
specifier: ^4.1.1
webpack:
specifier: ^5.105.4
version: 5.109.2
@@ -857,8 +857,8 @@ packages:
peerDependencies:
browserslist: '>= 4.21.0'
- resolution: {integrity: sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==}
+ resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
@@ -1174,14 +1174,14 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.1
dependencies:
'@vitest/spy': 4.1.10
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.2.0(@types/[email protected])([email protected])
+ vite: 8.2.1(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -1666,7 +1666,7 @@ snapshots:
escalade: 3.2.0
picocolors: 1.1.1
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.5
@@ -1678,10 +1678,10 @@ snapshots:
fsevents: 2.3.3
terser: 5.49.2
dependencies:
'@vitest/expect': 4.1.10
'@vitest/pretty-format': 4.1.10
'@vitest/runner': 4.1.10
'@vitest/snapshot': 4.1.10
@@ -1698,7 +1698,7 @@ snapshots:
tinyexec: 1.3.0
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
- vite: 8.2.0(@types/[email protected])([email protected])
+ vite: 8.2.1(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 20.19.43
diff --git a/packages/sdk/reference.md b/packages/sdk/reference.md
index c734ecf35..a4665b2e2 100644
--- a/packages/sdk/reference.md
+++ b/packages/sdk/reference.md
@@ -1434,6 +1434,87 @@ await client.sessions.getTurn("session_id", "turn_id");
</dl>
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">downloadSandboxFile</a>(session_id, turn_id, { ...params }) -> core.BinaryResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.downloadSandboxFile("session_id", "turn_id", {
+ path: "x"
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**session_id:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**turn_id:** `string` — Turn identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.DownloadSandboxFileSessionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
</dd>
</dl>
</details>
diff --git a/packages/sdk/src/api/errors/ContentTooLargeError.ts b/packages/sdk/src/api/errors/ContentTooLargeError.ts
new file mode 100644
index 000000000..a83d8c42e
--- /dev/null
+++ b/packages/sdk/src/api/errors/ContentTooLargeError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueForge from "../index.js";
+
+export class ContentTooLargeError extends errors.TrueForgeError {
+ public declare readonly body: TrueForge.RequestErrorResponse;
+
+ constructor(body: TrueForge.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "ContentTooLargeError",
+ statusCode: 413,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "ContentTooLargeError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/FailedDependencyError.ts b/packages/sdk/src/api/errors/FailedDependencyError.ts
new file mode 100644
index 000000000..1fecf4de5
--- /dev/null
+++ b/packages/sdk/src/api/errors/FailedDependencyError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueForge from "../index.js";
+
+export class FailedDependencyError extends errors.TrueForgeError {
+ public declare readonly body: TrueForge.RequestErrorResponse;
+
+ constructor(body: TrueForge.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "FailedDependencyError",
+ statusCode: 424,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "FailedDependencyError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/ForbiddenError.ts b/packages/sdk/src/api/errors/ForbiddenError.ts
new file mode 100644
index 000000000..023f504d1
--- /dev/null
+++ b/packages/sdk/src/api/errors/ForbiddenError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueForge from "../index.js";
+
+export class ForbiddenError extends errors.TrueForgeError {
+ public declare readonly body: TrueForge.RequestErrorResponse;
+
+ constructor(body: TrueForge.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "ForbiddenError",
+ statusCode: 403,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "ForbiddenError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/GoneError.ts b/packages/sdk/src/api/errors/GoneError.ts
new file mode 100644
index 000000000..059654476
--- /dev/null
+++ b/packages/sdk/src/api/errors/GoneError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueForge from "../index.js";
+
+export class GoneError extends errors.TrueForgeError {
+ public declare readonly body: TrueForge.RequestErrorResponse;
+
+ constructor(body: TrueForge.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "GoneError",
+ statusCode: 410,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "GoneError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/index.ts b/packages/sdk/src/api/errors/index.ts
index a527471c6..5388d473c 100644
--- a/packages/sdk/src/api/errors/index.ts
+++ b/packages/sdk/src/api/errors/index.ts
@@ -1,6 +1,10 @@
export * from "./BadGatewayError.js";
export * from "./BadRequestError.js";
export * from "./ConflictError.js";
+export * from "./ContentTooLargeError.js";
+export * from "./FailedDependencyError.js";
+export * from "./ForbiddenError.js";
+export * from "./GoneError.js";
export * from "./InternalServerError.js";
export * from "./NotFoundError.js";
export * from "./PreconditionFailedError.js";
diff --git a/packages/sdk/src/api/resources/sessions/client/Client.ts b/packages/sdk/src/api/resources/sessions/client/Client.ts
index 77517ca35..eda85c2ee 100644
--- a/packages/sdk/src/api/resources/sessions/client/Client.ts
+++ b/packages/sdk/src/api/resources/sessions/client/Client.ts
@@ -1213,6 +1213,161 @@ export class SessionsClient {
);
}
+ /**
+ * Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.
+ *
+ * @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
+ * @throws {@link TrueForge.NotFoundError}
+ * @throws {@link TrueForge.GoneError}
+ * @throws {@link TrueForge.PreconditionFailedError}
+ * @throws {@link TrueForge.ContentTooLargeError}
+ * @throws {@link TrueForge.FailedDependencyError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ */
+ public downloadSandboxFile(
+ session_id: string,
+ turn_id: string,
+ request: TrueForge.DownloadSandboxFileSessionsRequest,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<core.BinaryResponse> {
+ return core.HttpResponsePromise.fromPromise(
+ this.__downloadSandboxFile(session_id, turn_id, request, requestOptions),
+ );
+ }
+
+ private async __downloadSandboxFile(
+ session_id: string,
+ turn_id: string,
+ request: TrueForge.DownloadSandboxFileSessionsRequest,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<core.BinaryResponse>> {
+ const { path } = request;
+ const _queryParams: Record<string, unknown> = {
+ path,
+ };
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)<core.BinaryResponse>({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `api/v1/sessions/${core.url.encodePathParam(session_id)}/turns/${core.url.encodePathParam(turn_id)}/download`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ responseType: "binary-response",
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return { data: _response.body, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueForge.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueForge.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 410:
+ throw new TrueForge.GoneError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 412:
+ throw new TrueForge.PreconditionFailedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 413:
+ throw new TrueForge.ContentTooLargeError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 424:
+ throw new TrueForge.FailedDependencyError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "GET",
+ "/api/v1/sessions/{session_id}/turns/{turn_id}/download",
+ );
+ }
+
/**
* Paginated persisted events for a turn (insertion order by default).
*
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/DownloadSandboxFileSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/DownloadSandboxFileSessionsRequest.ts
new file mode 100644
index 000000000..ad9bc6fd0
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/DownloadSandboxFileSessionsRequest.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {
+ * path: "x"
+ * }
+ */
+export interface DownloadSandboxFileSessionsRequest {
+ /** Absolute path of the file inside the sandbox, as listed in the assistant's `sandbox_artifacts` block. */
+ path: string;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/index.ts b/packages/sdk/src/api/resources/sessions/client/requests/index.ts
index 3c7edcb44..5299c014d 100644
--- a/packages/sdk/src/api/resources/sessions/client/requests/index.ts
+++ b/packages/sdk/src/api/resources/sessions/client/requests/index.ts
@@ -2,6 +2,7 @@ export type { CancelSessionRequest } from "./CancelSessionRequest.js";
export type { CreateSessionRequest } from "./CreateSessionRequest.js";
export type { CreateTurnSessionsRequest } from "./CreateTurnSessionsRequest.js";
export type { CreateTurnSessionsStreamRequest } from "./CreateTurnSessionsStreamRequest.js";
+export type { DownloadSandboxFileSessionsRequest } from "./DownloadSandboxFileSessionsRequest.js";
export type { ListEventsSessionsRequest } from "./ListEventsSessionsRequest.js";
export type { ListSessionsRequest } from "./ListSessionsRequest.js";
export type { ListTurnEventsSessionsRequest } from "./ListTurnEventsSessionsRequest.js";
diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.ts
index b8a3562c4..7e2090d97 100644
--- a/packages/server/src/apis/turns.ts
+++ b/packages/server/src/apis/turns.ts
@@ -19,6 +19,8 @@ import {
isAgentInputUserMessage,
isFileContentPart,
McpConnectionError,
+ SandboxError,
+ validateSandboxOwnedByTenant,
VercelAILLM,
} from '@truefoundry/utils-core/core';
import type { Context } from 'hono';
@@ -34,6 +36,7 @@ import type { ISkillStore } from '../db/skillStore';
import type { IOAuthTokenStore } from '../mcp/auth/types';
import {
createAndExecuteTurnRoute,
+ downloadSandboxFileRoute,
getTurnRoute,
listTurnEventsRoute,
listTurnsRoute,
@@ -42,6 +45,7 @@ import {
import type { ActiveTurnRegistry } from '../runtime/activeTurns';
import { StreamGoneError, type EventSubscription, type EventSubscriptionRegistry } from '../runtime/event-subscription';
import { mintPeeredTurnId } from '../runtime/peeringIds';
+import { validateSandboxFilePath } from '../runtime/sandboxFilePath';
import {
buildTurnSandbox,
getMcpConnection,
@@ -62,6 +66,37 @@ export function toWireTurn(record: TurnRecordWithoutSnapshot): Turn {
};
}
+/**
+ * Copies into a standalone ArrayBuffer for the response body: a pooled Buffer's
+ * backing store is shared and typed as ArrayBufferLike, which is not a body.
+ * Bounded by SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD.
+ */
+function toArrayBuffer(content: Buffer): ArrayBuffer {
+ const buffer = new ArrayBuffer(content.byteLength);
+ new Uint8Array(buffer).set(content);
+ return buffer;
+}
+
+/**
+ * Builds the Content-Disposition telling the browser to save the file under its sandbox name.
+ *
+ * A sandbox file can be named in any script, but an HTTP header can only carry bytes, so a name
+ * like `中文.csv` cannot be written into the header as-is — doing so throws when the response is
+ * constructed. RFC 6266's `filename*` exists for this: percent-encode the UTF-8 name so the value
+ * stays plain ASCII, and the client decodes it back. Encoding also defuses quotes and newlines,
+ * which could otherwise close the value or inject another header.
+ */
+export function toContentDisposition(path: string): string {
+ // Trailing separators are dropped so a path ending in `/` still yields its last real segment.
+ const fileName = path.split('/').filter(Boolean).pop() ?? 'download';
+ // encodeURIComponent covers everything except these four, which RFC 5987 also disallows here.
+ const encoded = encodeURIComponent(fileName).replace(
+ /['()*]/g,
+ char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
+ );
+ return `attachment; filename*=UTF-8''${encoded}`;
+}
+
export interface TurnsRouterDeps {
sessions: Sessions;
sessionStore: ISessionStore;
@@ -323,6 +358,65 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
return c.json({ data: toWireTurn(turn.record) }, 200);
};
+ const downloadSandboxFileHandler: RouteHandler<typeof downloadSandboxFileRoute> = async c => {
+ const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
+ const { path } = c.req.valid('query');
+
+ let sandboxId: string | undefined;
+ try {
+ // Cheapest first: a malformed path costs no store read and no provider round-trip.
+ validateSandboxFilePath(path);
+
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ if (!session) {
+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
+ }
+
+ // Loading the turn through the session is also the ownership check: a turn id from another
+ // session cannot be used to reach this session's sandbox.
+ const turn = await session.getTurn(turnId);
+ if (!turn) {
+ return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
+ }
+ sandboxId = turn.record.snapshot.sandbox_info?.sandbox_id;
+ if (sandboxId === undefined) {
+ return c.json({ error: { message: `Turn has no sandbox: ${turnId}` } }, 412);
+ }
+
+ const provider = await resolveSandboxProvider({
+ tenant_id: TENANT_ID,
+ store: deps.sandboxProviderStore,
+ logger: deps.logger,
+ });
+ if (provider === undefined) {
+ return c.json({ error: { message: 'No sandbox provider configured' } }, 412);
+ }
+
+ validateSandboxOwnedByTenant(sandboxId, TENANT_ID);
+ // TODO: stream the body instead of buffering the whole file in memory.
+ const content = await provider.downloadFile({ sandboxId, path });
+ return c.body(toArrayBuffer(content), 200, {
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Length': String(content.byteLength),
+ 'Content-Disposition': toContentDisposition(path),
+ 'Cache-Control': 'private, no-store',
+ });
+ } catch (error) {
+ // Every guard and the provider itself raise SandboxError, whose statusCode is the contract.
+ if (error instanceof SandboxError) {
+ return c.json({ error: { message: error.message } }, error.statusCode);
+ }
+ deps.logger.error('Sandbox file download failed', {
+ ...extractErrorLogFields(error),
+ sessionId,
+ turnId,
+ sandboxId,
+ path,
+ });
+ return c.json({ error: { message: 'Failed to download file from sandbox' } }, 424);
+ }
+ };
+
const listTurnEventsHandler: RouteHandler<typeof listTurnEventsRoute> = async c => {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
const query = c.req.valid('query');
@@ -532,6 +626,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
router.openapi(createAndExecuteTurnRoute, createAndExecuteTurnHandler);
router.openapi(listTurnsRoute, listTurnsHandler);
router.openapi(getTurnRoute, getTurnHandler);
+ router.openapi(downloadSandboxFileRoute, downloadSandboxFileHandler);
router.openapi(listTurnEventsRoute, listTurnEventsHandler);
router.openapi(subscribeTurnRoute, subscribeTurnHandler);
return router;
diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.ts
index cd090c346..b3872521f 100644
--- a/packages/server/src/routes/turnRoutes.ts
+++ b/packages/server/src/routes/turnRoutes.ts
@@ -8,6 +8,7 @@ import { RequestErrorResponseSchema } from '../schemas/errors';
import { TurnStreamingEventSchema } from '../schemas/events';
import {
CreateTurnRequestSchema,
+ DownloadSandboxFileRequestQuerySchema,
GetTurnResponseSchema,
ListTurnEventsRequestQuerySchema,
ListTurnEventsResponseSchema,
@@ -76,6 +77,55 @@ export const getTurnRoute = createRoute({
},
});
+export const downloadSandboxFileRoute = createRoute({
+ method: 'get',
+ path: '/{session_id}/turns/{turn_id}/download',
+ tags: [SESSIONS_TAG],
+ summary: 'Download a file from the turn sandbox',
+ description:
+ "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.",
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'download_sandbox_file',
+ request: {
+ params: TurnIdParamsSchema,
+ query: DownloadSandboxFileRequestQuerySchema,
+ },
+ responses: {
+ 200: {
+ content: { 'application/octet-stream': { schema: z.string().openapi({ format: 'binary' }) } },
+ description: 'File contents.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid path, or the path is a directory.',
+ },
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Sandbox belongs to another tenant.',
+ },
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Session, turn, or file not found.',
+ },
+ 410: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Sandbox no longer exists.',
+ },
+ 412: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Turn has no sandbox, or no sandbox provider is configured.',
+ },
+ 413: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'File exceeds the maximum download size.',
+ },
+ 424: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Sandbox infrastructure error.',
+ },
+ },
+});
+
export const listTurnEventsRoute = createRoute({
method: 'get',
path: '/{session_id}/turns/{turn_id}/events',
diff --git a/packages/server/src/runtime/sandboxFilePath.ts b/packages/server/src/runtime/sandboxFilePath.ts
new file mode 100644
index 000000000..d4c55168b
--- /dev/null
+++ b/packages/server/src/runtime/sandboxFilePath.ts
@@ -0,0 +1,45 @@
+/**
+ * Validation for caller-supplied sandbox download paths. This is an HTTP concern — the harness
+ * library only guards its own file operations — so it lives with the route that accepts the path.
+ */
+import { SandboxError, validateNoPathTraversal } from '@truefoundry/utils-core/core';
+
+class SandboxInvalidPathError extends SandboxError {
+ readonly statusCode = 400;
+
+ constructor({ path, reason }: { path: string; reason: string }) {
+ super(`Path ${reason}: ${path}`);
+ this.name = 'SandboxInvalidPathError';
+ }
+}
+
+/**
+ * Past these the kernel rejects the path before any file is opened. PATH_MAX (4096) counts the
+ * terminating NUL, so the longest usable path is one byte shorter; NAME_MAX (255) does not.
+ */
+const MAX_PATH_BYTES = 4095;
+const MAX_SEGMENT_BYTES = 255;
+
+/**
+ * Every check a caller-supplied download path must pass before it reaches a provider. Shape
+ * violations are caught here because a provider reports them as opaque backend failures,
+ * indistinguishable from a real outage.
+ */
+export function validateSandboxFilePath(path: string): void {
+ if (!path.startsWith('/')) {
+ throw new SandboxInvalidPathError({ path, reason: 'must be absolute' });
+ }
+ if (path.includes('\0')) {
+ throw new SandboxInvalidPathError({ path, reason: 'must not contain a NUL byte' });
+ }
+ if (Buffer.byteLength(path) > MAX_PATH_BYTES) {
+ throw new SandboxInvalidPathError({ path, reason: `must be at most ${String(MAX_PATH_BYTES)} bytes` });
+ }
+ if (path.split('/').some(segment => Buffer.byteLength(segment) > MAX_SEGMENT_BYTES)) {
+ throw new SandboxInvalidPathError({
+ path,
+ reason: `must not have a segment longer than ${String(MAX_SEGMENT_BYTES)} bytes`,
+ });
+ }
+ validateNoPathTraversal(path);
+}
diff --git a/packages/server/src/schemas/turn.ts b/packages/server/src/schemas/turn.ts
index f92a82569..6a8c41007 100644
--- a/packages/server/src/schemas/turn.ts
+++ b/packages/server/src/schemas/turn.ts
@@ -80,3 +80,14 @@ export const ListTurnEventsResponseSchema = z
pagination: TokenPaginationSchema,
})
.openapi('ListTurnEventsResponse');
+
+export const DownloadSandboxFileRequestQuerySchema = z
+ .object({
+ path: z
+ .string()
+ .min(1)
+ .describe(
+ "Absolute path of the file inside the sandbox, as listed in the assistant's `sandbox_artifacts` block.",
+ ),
+ })
+ .openapi('DownloadSandboxFileRequestQuery');
diff --git a/packages/server/tests/unit/apis/sandboxFileDownload.test.ts b/packages/server/tests/unit/apis/sandboxFileDownload.test.ts
new file mode 100644
index 000000000..d04d8dc35
--- /dev/null
+++ b/packages/server/tests/unit/apis/sandboxFileDownload.test.ts
@@ -0,0 +1,147 @@
+import { OpenAPIHono } from '@hono/zod-openapi';
+import type { AgentSpec } from '@truefoundry/utils-core/agent-session';
+import { AgentSpecSchema, Sessions } from '@truefoundry/utils-core/agent-session';
+import { createLogger } from 'winston';
+import { TENANT_ID } from '../../../src/apis/sessions';
+import { createTurnsRouter, toContentDisposition } from '../../../src/apis/turns';
+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
+import { createSqliteDb } from '../../../src/db/sqlite/client';
+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
+import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';
+import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';
+import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';
+import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';
+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';
+import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';
+import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription';
+
+/** Parsed rather than built literally, so config defaults match what the create route stores. */
+function agentSpec(): AgentSpec {
+ return AgentSpecSchema.parse({
+ model: { name: 'openai/gpt-4o' },
+ config: { sandbox: { enabled: true } },
+ });
+}
+
+async function buildApp() {
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const sessionStore = new SqliteSessionStore(db);
+ const sessions = new Sessions({ sessionStore });
+ const app = new OpenAPIHono();
+
+ app.route(
+ '/',
+ createTurnsRouter({
+ sessions,
+ sessionStore,
+ activeTurns: new ActiveTurnRegistry(),
+ modelProviderStore: new SqliteModelProviderStore(db),
+ mcpServerStore: new SqliteMcpServerStore(db),
+ tokenStore: new SqliteOAuthTokenStore(db),
+ skillStore: new SqliteSkillStore(db),
+ agentStore: new SqliteAgentStore(db),
+ eventSubscriptions: new EventSubscriptionRegistry(undefined),
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ logger: createLogger({ silent: true }),
+ }),
+ );
+
+ return { app, sessions };
+}
+
+function downloadUrl({
+ sessionId,
+ turnId = 'turn-1',
+ path,
+}: {
+ sessionId: string;
+ turnId?: string;
+ path: string;
+}): string {
+ return `http://localhost/${sessionId}/turns/${turnId}/download?path=${encodeURIComponent(path)}`;
+}
+
+describe('GET /{session_id}/turns/{turn_id}/download', () => {
+ it('rejects a malformed path before touching the session', async () => {
+ const { app } = await buildApp();
+
+ for (const path of [
+ 'report.pdf',
+ '/a/../../etc/passwd',
+ '/tmp/nul\0.txt',
+ `/tmp/${'a'.repeat(300)}`,
+ `/${'a/'.repeat(3000)}b`,
+ ]) {
+ const response = await app.request(downloadUrl({ sessionId: 'missing', path }));
+
+ expect(response.status).toBe(400);
+ }
+ });
+
+ // PATH_MAX counts the terminating NUL, so 4096 is already too long for the kernel and must be
+ // rejected here rather than reaching the provider as an opaque backend failure.
+ it('rejects a path at PATH_MAX but allows one byte shorter', async () => {
+ const { app } = await buildApp();
+ // Short segments so the length that trips is the whole path, not NAME_MAX.
+ const pathOfLength = (length: number) => {
+ let path = '/tmp';
+ while (path.length < length) path += `/${'a'.repeat(Math.min(50, length - path.length - 1))}`;
+ return path.slice(0, length);
+ };
+
+ expect((await app.request(downloadUrl({ sessionId: 'missing', path: pathOfLength(4096) }))).status).toBe(400);
+ // Not 400: the shape is fine, so it fails later on the session lookup instead.
+ expect((await app.request(downloadUrl({ sessionId: 'missing', path: pathOfLength(4095) }))).status).toBe(404);
+ });
+
+ it('returns 404 for an unknown session', async () => {
+ const { app } = await buildApp();
+
+ const response = await app.request(downloadUrl({ sessionId: 'missing', path: '/workspace/report.pdf' }));
+
+ expect(response.status).toBe(404);
+ });
+
+ it('returns 404 for a turn that does not exist in the session', async () => {
+ const { app, sessions } = await buildApp();
+ const session = await sessions.create({
+ tenant_id: TENANT_ID,
+ session_id: 'no-turn',
+ agent: { type: 'value', agent_spec: agentSpec() },
+ });
+
+ const response = await app.request(downloadUrl({ sessionId: session.session_id, path: '/workspace/report.pdf' }));
+
+ expect(response.status).toBe(404);
+ });
+});
+
+describe('toContentDisposition', () => {
+ it('names the file after the last path segment', () => {
+ expect(toContentDisposition('/workspace/out/report.pdf')).toBe(`attachment; filename*=UTF-8''report.pdf`);
+ });
+
+ it('falls back when the path has no usable segment', () => {
+ expect(toContentDisposition('/')).toBe(`attachment; filename*=UTF-8''download`);
+ });
+
+ it('percent-encodes a name that cannot be written into a header directly', () => {
+ expect(toContentDisposition('/w/中文.csv')).toBe(`attachment; filename*=UTF-8''%E4%B8%AD%E6%96%87.csv`);
+ });
+
+ it('encodes the characters RFC 5987 disallows but encodeURIComponent keeps', () => {
+ expect(toContentDisposition(`/w/quote'(1)*.txt`)).toBe(`attachment; filename*=UTF-8''quote%27%281%29%2A.txt`);
+ });
+
+ it('produces a header the Response constructor accepts for any name', () => {
+ for (const path of ['/w/中文报告.csv', '/w/emoji-🎉.txt', '/w/a\r\nX-Injected: 1.txt', '/w/a"b\\c.txt']) {
+ const header = toContentDisposition(path);
+
+ expect(new Response('x', { headers: { 'Content-Disposition': header } }).headers.get('content-disposition')).toBe(
+ header,
+ );
+ }
+ });
+});
diff --git a/packages/trueforge-ui-sdk/package.json b/packages/trueforge-ui-sdk/package.json
index 7ad7fd38a..9423fe039 100644
--- a/packages/trueforge-ui-sdk/package.json
+++ b/packages/trueforge-ui-sdk/package.json
@@ -82,7 +82,7 @@
"@openuidev/react-headless": "^0.9.4",
"@openuidev/react-lang": "^0.2.9",
"@openuidev/react-ui": "^0.13.2",
- "@truefoundry/assistant-ui-runtime": "^0.1.9",
+ "@truefoundry/assistant-ui-runtime": "^0.1.10-rc.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"monaco-editor": "^0.56.0",
diff --git a/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.test.tsx b/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.test.tsx
index 6207e1813..04cb45d48 100644
--- a/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.test.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.test.tsx
@@ -1,7 +1,13 @@
// @vitest-environment jsdom
-import { ThreadPrimitive, type ThreadMessageLike } from '@assistant-ui/react';
-import { render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
+import {
+ AssistantRuntimeProvider,
+ ThreadPrimitive,
+ useExternalStoreRuntime,
+ type ThreadMessageLike,
+} from '@assistant-ui/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { trueFoundryExtras } from '@truefoundry/assistant-ui-runtime';
+import { describe, expect, it, vi } from 'vitest';
import type { MarkdownProps } from '../atoms/Markdown.js';
import { SlotsProvider } from '../theme/SlotsProvider.js';
@@ -58,4 +64,54 @@ describe('AssistantTextContainer', () => {
expect(screen.getByTestId('artifact-download-handler')).toHaveTextContent('function');
});
+
+ it('downloads an artifact through the turn that produced the message', async () => {
+ const downloadSandboxFile = vi.fn(async () => new Blob(['hello harness']));
+
+ function ExtrasHarness() {
+ const runtime = useExternalStoreRuntime({
+ messages: [
+ {
+ role: 'assistant',
+ content: ['Files ready:', '', '```sandbox_artifacts', '[report.txt](/tmp/report.txt)', '```'].join('\n'),
+ metadata: { custom: { turnId: 'turn-42', sandboxId: 'sbx-1' } },
+ } satisfies ThreadMessageLike,
+ ],
+ isRunning: false,
+ convertMessage: (m: ThreadMessageLike) => m,
+ onNew: async () => {},
+ extras: trueFoundryExtras.provide({
+ pendingApprovals: [],
+ pendingToolResponses: [],
+ pendingMcpAuth: null,
+ sandboxId: 'sbx-1',
+ respondToToolApproval: () => {},
+ respondToToolResponse: () => {},
+ resumeMcpAuth: async () => {},
+ downloadSandboxFile,
+ cancel: async () => {},
+ resetFromTurn: async () => {},
+ reload: () => {},
+ hasOlderHistory: false,
+ isLoadingOlderHistory: false,
+ loadOlderHistory: async () => {},
+ draft: null,
+ }),
+ });
+
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <ThreadPrimitive.Messages>{() => <AssistantMessageContainer />}</ThreadPrimitive.Messages>
+ </AssistantRuntimeProvider>
+ );
+ }
+
+ render(<ExtrasHarness />);
+
+ fireEvent.click(await screen.findByText('report.txt'));
+
+ await waitFor(() => {
+ expect(downloadSandboxFile).toHaveBeenCalledWith({ turnId: 'turn-42', path: '/tmp/report.txt' });
+ });
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.tsx b/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.tsx
index a0899e73f..f98ea3708 100644
--- a/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/AssistantTextContainer.tsx
@@ -29,13 +29,12 @@ function triggerBrowserDownload(blob: Blob, filename: string) {
export function AssistantTextContainer() {
const Markdown = useSlot('Markdown');
- // Runtime download fn is unstable; refs keep onDownloadArtifact stable so OpenUI doesn't remount.
- const downloadSandboxFile = useTrueFoundryDownloadSandboxFile();
const errorToaster = useErrorToasterOptional();
- const downloadSandboxFileRef = useRef(downloadSandboxFile);
- const errorToasterRef = useRef(errorToaster);
- downloadSandboxFileRef.current = downloadSandboxFile;
- errorToasterRef.current = errorToaster;
+ const downloadSandboxFile = useTrueFoundryDownloadSandboxFile();
+ // The download closure changes as the turn streams; a ref keeps onDownloadArtifact stable so
+ // OpenUI does not remount.
+ const downloadRef = useRef({ downloadSandboxFile, errorToaster });
+ downloadRef.current = { downloadSandboxFile, errorToaster };
const partState = useAuiState(s => s.part as MessagePartState & (TextMessagePart | ReasoningMessagePart));
const smoothedPart = useSmooth(partState, {
drainMs: 300,
@@ -46,21 +45,18 @@ export function AssistantTextContainer() {
const text = smoothedPart.text;
// true while network stream is active OR while reveal is still catching up
const isStreaming = smoothedPart.status?.type === 'running';
- const handleDownloadArtifact = useCallback(
- (path: string) =>
- downloadSandboxFileRef
- .current(path)
- .then(blob => triggerBrowserDownload(blob, filenameFromPath(path)))
- .catch(error => {
- const toaster = errorToasterRef.current;
- if (toaster != null) {
- toaster.showError(error);
- } else {
- console.error('Failed to download sandbox artifact', error);
- }
- }),
- [],
- );
+ const handleDownloadArtifact = useCallback(async (path: string) => {
+ const { downloadSandboxFile, errorToaster } = downloadRef.current;
+ try {
+ triggerBrowserDownload(await downloadSandboxFile(path), filenameFromPath(path));
+ } catch (error) {
+ if (errorToaster != null) {
+ errorToaster.showError(error);
+ } else {
+ console.error('Failed to download sandbox artifact', error);
+ }
+ }
+ }, []);
return <Markdown content={text} isStreaming={isStreaming} onDownloadArtifact={handleDownloadArtifact} />;
}
diff --git a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.test.tsx b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.test.tsx
index d330a7d3d..e53b29e66 100644
--- a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.test.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.test.tsx
@@ -22,7 +22,6 @@ vi.mock('@truefoundry/assistant-ui-runtime', () => ({
hasMore: false,
loadMore: vi.fn(),
}),
- useTrueFoundryDownloadSandboxFile: () => vi.fn(),
useTrueFoundryAgentSpec: () => ({
agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
}),
diff --git a/packages/trueforge-ui-sdk/src/index.ts b/packages/trueforge-ui-sdk/src/index.ts
index 717bd49bb..09f1c6fe9 100644
--- a/packages/trueforge-ui-sdk/src/index.ts
+++ b/packages/trueforge-ui-sdk/src/index.ts
@@ -204,6 +204,7 @@ export {
useTrueFoundryMcpAuth,
useTrueFoundryRespondToToolApproval,
useTrueFoundryToolResponses,
+ useTrueFoundryTurnId,
useTrueFoundryUpdateAgentSpec,
} from '@truefoundry/assistant-ui-runtime';
export type {
diff --git a/packages/trueforge-ui-sdk/src/server/types.ts b/packages/trueforge-ui-sdk/src/server/types.ts
index b365c93fb..73f9137e4 100644
--- a/packages/trueforge-ui-sdk/src/server/types.ts
+++ b/packages/trueforge-ui-sdk/src/server/types.ts
@@ -311,7 +311,12 @@ export interface AgentChatServer<
afterSequenceNumber?: number;
}): AsyncIterable<TurnStreamData<TStreamEvent>>;
- downloadSandboxFile?(sandboxId: string, req: { path: string }): Promise<unknown>;
+ /**
+ * Reads a file the agent wrote inside its sandbox. Hosts whose download route is scoped to a
+ * turn resolve the sandbox from `turnId` and ignore `sandboxId`; hosts addressing sandboxes
+ * directly use `sandboxId`.
+ */
+ downloadSandboxFile?(req: { sessionId: string; turnId: string; sandboxId: string; path: string }): Promise<Blob>;
}
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a1d68c871..f3e815d85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -55,8 +55,8 @@ importers:
specifier: 0.2.21
'@truefoundry/assistant-ui-runtime':
- specifier: ^0.1.7
+ specifier: ^0.1.10-rc.1
'@truefoundry/trueforge-ui':
specifier: workspace:*
version: link:../trueforge-ui-sdk
@@ -301,8 +301,8 @@ importers:
specifier: ^0.13.2
'@truefoundry/assistant-ui-runtime':
- specifier: ^0.1.9
+ specifier: ^0.1.10-rc.1
clsx:
specifier: ^2.1.1
version: 2.1.1
@@ -3206,20 +3206,8 @@ packages:
'@types/react-dom':
optional: true
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-Gy0QWdsbTwPV3SkLPI2OXUh9RqxgBOmK7Hv8/+WnjReHZw0KtwvAHAKSvzf/O1Fgyw3Sr5WzQjkPWKP7HmcPwQ==}
- peerDependencies:
- '@types/react': '*'
- react: ^18 || ^19
- truefoundry-gateway-sdk: ^0.4.0-rc.6
- peerDependenciesMeta:
- '@types/react':
- optional: true
- truefoundry-gateway-sdk:
- optional: true
-
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-2LjsIHbWOtJI+oSF28SvgcJ8WpUUr74/LYJ84UyKfOLnFutgJZPAwFp9a3uYmIdwVahnwk9pF6FD3zFyVVDB/Q==}
+ '@truefoundry/[email protected]':
+ resolution: {integrity: sha512-NqX+2BV3MUA/Zre2xtJxj6yCYl+mWLuhhzIzpeD+MgMDjYp+N8gQhw99k0PQXqwG706xB9zb25KYSFWHXrFtMA==}
peerDependencies:
'@types/react': '*'
react: ^18 || ^19
@@ -9833,22 +9821,7 @@ snapshots:
'@types/react': 19.2.17
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])
- react: 19.2.8
- optionalDependencies:
- '@types/react': 19.2.17
- truefoundry-gateway-sdk: 0.4.0
- transitivePeerDependencies:
- - '@assistant-ui/tap'
- - assistant-cloud
- - ioredis
- - redis
- - zustand
-
dependencies:
'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])