# Send and receive files

Upload files, read PDF pages and images, and return previews, downloads, or file changes to your application.

## Before you start

Complete the [Quick start](https://smallworld.sh/docs/guides/quick-start.md). Use [execute](https://smallworld.sh/docs/execute-command.md) to upload files and read them in the terminal. An execution returns changed workspace files in `fileChanges` and files explicitly selected with `view` in `outputFiles`.

## 1. Add backend helpers

Keep the API key on your server. These helpers send a command with optional files and return its final result. `execution.fileChanges` arrives with that final result; while the command runs or waits for approval, it is `null`.

File helpers · server-side TypeScript

```typescript
const baseUrl = "https://api.smallworld.sh/api/v1";
const apiKey = process.env.SMALLWORLD_API_KEY;
if (!apiKey) throw new Error("Set SMALLWORLD_API_KEY on your server");

type FileUpload = {
  path: string;
  content: string;
  encoding?: "utf8" | "base64";
  persistInSession?: boolean;
  sessionOnly?: boolean;
};
type FileChange =
  | {
      path: string;
      operation: "created" | "modified";
      uploaded: boolean;
      encoding: "utf8" | "base64";
      content: string;
    }
  | { path: string; operation: "deleted"; uploaded: boolean };
type ExecutionResult = {
  session: { id: string };
  execution: {
    id: string;
    status: "running" | "requires_approval" | "completed" | "timed_out" | "interrupted";
    stdout: string | null;
    stderr: string | null;
    exitCode: number | null;
    errorCode: string | null;
    fileChanges: FileChange[] | null;
    outputFiles: Array<{
      id: string; kind: "image" | "download"; filename: string;
      mimeType: string; sizeBytes: number; contentPath: string;
      source: { path: string; page?: number }; width?: number; height?: number;
    }> | null;
  };
};
type ExecuteBody = {
  userId: string;
  sessionId?: string;
  command: string;
  files?: FileUpload[];
  fileChanges?: "all" | "uploaded" | "none";
};

async function request<T>(path: string, body?: unknown): Promise<T> {
  const response = await fetch(baseUrl + path, {
    method: body === undefined ? "GET" : "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      ...(body === undefined ? {} : { "Content-Type": "application/json" }),
    },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  const data = await response.json();
  if (!response.ok) throw new Error(`${response.status} ${data.code}: ${data.message}`);
  return data as T;
}

// Runs a command and returns its final result. While it waits for approval,
// decide its tool calls as in Approve a tool call.
async function execute(worldId: string, body: ExecuteBody) {
  let result = await request<ExecutionResult>(
    `/worlds/${encodeURIComponent(worldId)}/execute`,
    body,
  );
  while (["running", "requires_approval"].includes(result.execution.status)) {
    // A read is held while the command runs. While it waits for an approval the
    // read answers at once, so pause before reading again.
    if (result.execution.status === "requires_approval")
      await new Promise((resolve) => setTimeout(resolve, 1000));
    result = await request<ExecutionResult>(
      `/executions/${encodeURIComponent(result.execution.id)}`,
    );
  }
  return result;
}

// The bytes of a created or modified file.
function bytesOf(change: Extract<FileChange, { content: string }>) {
  return Buffer.from(change.content, change.encoding);
}
```

A finished execution keeps its file changes: reading it again returns the same list, even after later commands change the files.

## 2. Send a file with a command

Each upload has a `path` under `/workspace` and its `content`. `encoding` is `utf8` by default; use `base64` for any other bytes. The upload replaces any file at its path before the command runs. Unless `persistInSession` is `true`, the file is removed from the session after this execution, so your application stays the place it is kept.

This keeps an agent’s memory in your database: upload it with every command and save it again when the command changed it.

Upload memory with each command

```typescript
// Reuse execute and bytesOf from above. userId comes from your login session;
// loadMemory, saveMemory, and removeMemory are your application's own storage.
async function runWithMemory(
  userId: string,
  worldId: string,
  sessionId: string | undefined,
  command: string,
) {
  const result = await execute(worldId, {
    userId,
    sessionId,
    command,
    files: [{ path: "/workspace/memory.md", content: await loadMemory(userId) }],
  });
  for (const change of result.execution.fileChanges ?? []) {
    if (change.path !== "/workspace/memory.md") continue;
    if (change.operation === "deleted") await removeMemory(userId);
    else await saveMemory(userId, bytesOf(change).toString("utf8"));
  }
  return result;
}

```

If the saved memory holds the lines `# Memory` and `- Works on Smallworld`, the command `echo '- Prefers short answers' >> /workspace/memory.md` returns the new content with `uploaded: true`:

Response excerpt

```json
{
  "execution": {
    "status": "completed",
    "exitCode": 0,
    "errorCode": null,
    "fileChanges": [
      {
        "path": "/workspace/memory.md",
        "operation": "modified",
        "uploaded": true,
        "encoding": "utf8",
        "content": "# Memory\n- Works on Smallworld\n- Prefers short answers\n"
      }
    ]
  }
}
```

A path you uploaded is compared with the content you sent, so an unchanged upload has no entry. Upload the file again with every command: without `persistInSession`, it isn’t in the session between executions.

## 3. Save the files a command creates

`fileChanges` lists every file the command created, modified, or deleted under `/workspace`, sorted by path, not only the ones you uploaded. Those entries have `uploaded: false`. A command that writes a report, for example, returns it with `operation: "created"`.

Keep created files

```typescript
// Keep the files a command created, for example to offer them as downloads.
// storeFile is your application's own storage.
async function keepCreatedFiles(userId: string, result: ExecutionResult) {
  for (const change of result.execution.fileChanges ?? []) {
    if (change.uploaded || change.operation !== "created") continue;
    await storeFile(userId, change.path, bytesOf(change));
  }
}

```

Contents are complete; unlike stdout, they are never cut at 1 MiB. Text arrives as `utf8` and other bytes as `base64`, so decode each entry with its `encoding`. Deleted files have no content. A rename appears as a deletion and a creation. Directories, modification times, and permissions aren’t reported.

To keep a full copy of a session’s files, apply your uploads and every result’s changes in order, then remove your uploads that weren’t kept in the session.

## 4. Keep a file in the session

For input that later commands need, such as an attachment, set `persistInSession: true`. You can send it with any command, including `true`, which does nothing else.

Keep an attachment in the session

```typescript
// Send a file the user attached and keep it for later commands in this session.
// base64 delivers any bytes unchanged. The command can be true.
async function attach(
  userId: string,
  worldId: string,
  sessionId: string,
  attachment: Buffer,
) {
  return execute(worldId, {
    userId,
    sessionId,
    command: "true",
    files: [
      {
        path: "/workspace/attachments/orders.csv",
        content: attachment.toString("base64"),
        encoding: "base64",
        persistInSession: true,
        sessionOnly: true,
      },
    ],
  });
}

```

Set `sessionOnly: true` on private attachments. If the path overlaps a visible mount, the execution is interrupted with `execution_file_conflict` before any upload in the batch is written.

A kept file becomes an ordinary session file. Later commands that change it report it with `uploaded: false`, because it wasn’t uploaded in their request. Remove it with `rm` when it’s no longer needed. Folders created to hold an upload stay in the session, also when the upload itself isn’t kept.

Session files belong to one session. For files that every session of a user, a group, or the whole workspace shares, such as team docs or a user’s memory, use a [mount](https://smallworld.sh/docs/guides/mounts.md) instead.

## 5. Choose which changes come back

Set `fileChanges` in the request to `"uploaded"` to return only the paths you uploaded, which keeps responses small when commands write scratch files, or to `"none"` for `null`. The default, `"all"`, returns every change.

Returned contents are saved with the execution, including those of files that weren’t kept in the session. If your application can change a file while a command runs, compare its revision before saving returned content: Smallworld doesn’t merge changes.

## 6. Read a document and return a page

`view invoice.pdf` prints the embedded text on page 1. Use `view --pages 3-5 invoice.pdf` for a range with page labels. For a scanned page, a chart, or a table whose layout matters, select one page as an image. Use `view screenshot.png` to see an image and `view --as file report.csv` to deliver an original file for download. `smallworld view` also works in Worlds with an existing integration named `view`.

Read an invoice and show page 2

```typescript
// Reuse execute() from section 1. invoice contains the user's PDF bytes.
const read = await execute(worldId, {
  userId, command: "view invoice.pdf", fileChanges: "none",
  files: [{ path: "/workspace/invoice.pdf", content: invoice.toString("base64"),
            encoding: "base64", persistInSession: true, sessionOnly: true }],
});
if (read.execution.exitCode !== 0) throw new Error(read.execution.stderr ?? "Read failed");
console.log(read.execution.stdout);

const page = await execute(worldId, {
  userId, sessionId: read.session.id, fileChanges: "none",
  command: "view --as image --pages 2 invoice.pdf",
});
const image = page.execution.outputFiles?.find(file => file.kind === "image");
if (!image) throw new Error(page.execution.stderr || "Page unavailable");
const response = await fetch(new URL(image.contentPath, baseUrl), {
  headers: { Authorization: `Bearer ${apiKey}` },
});
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const bytes = Buffer.from(await response.arrayBuffer());
// Send as image input to a compatible model, or serve the bytes to your user.
const modelInput = { type: "input_image", image_url:
  `data:${image.mimeType};base64,${bytes.toString("base64")}` };
```

Each selected output captures the bytes when `view` reads the file, including a temporary upload or a file on a visible mount. A finished execution keeps those bytes even after the path changes. The [output content endpoint](https://smallworld.sh/docs/get-execution-output.md) requires the caller’s API key.

## 7. Handle limits and failures

- One execution can upload 100 files with 8 MiB of decoded content, in a JSON request of at most 12 MiB. Together with the session’s files, uploads must fit 64 MiB and 10,000 files and directories. Beyond these, the request fails with `execution_files_limit_exceeded`, or `request_too_large` for the request size.

- A malformed upload, such as a relative or duplicate path or invalid base64, returns `invalid_request`. An upload that would replace a directory or go inside a file returns `execution_file_conflict`. In both cases nothing runs and the session stays free.

- A command whose changes can’t be kept, because they would exceed the limits or include a symbolic link, keeps none of them, uploads included. Its `errorCode` is `execution_file_changes_discarded` and `fileChanges` is `null`.

- A `timed_out` command keeps and returns the changes it made before the deadline. An `interrupted` command keeps none, and `fileChanges` is `null`.

- Uploading over a session file without keeping the upload replaces that file for good: the earlier version doesn’t come back.
