> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gloo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Files and bindings

> The unified files and bindings model: putFile persists bytes and creates a binding, and getFile reads them. It replaces the four legacy artifact and sandbox file calls.

Replaces the legacy `writeArtifact` / `readArtifact` / `copyFileToSandbox` / `importFileFromSandbox` quartet (deleted in PR-8h). New code must use `putFile` and `getFile`; any reference to the old tools is a documentation bug.

Forge stores agent-produced and agent-consumed files through a single, uniform substrate. Two tables back it:

* **`files`** — the bytes plus content metadata (mimeType, sizeBytes, filename).
* **`fileBindings`** — what each file is *for* — workflow output, run scratch, worker-scoped reference material, chat attachment.

Two agent tools span the model:

* **`putFile`** — persist bytes to platform storage and create a binding in the right domain.
* **`getFile`** — read a file the dispatch has access to, either as extracted text, copied into a sandbox VM, or as metadata only.

Both are injected per-node by the workflow orchestrator whenever the executing node declares an input or output of `type: "file"` / `"file[]"`. The orchestrator pre-resolves an authorization struct at injection time; every tool call is checked against that struct. An agent cannot use `putFile` to write under an output key the node did not declare, nor `getFile` to read a file outside the dispatch's input set.

This model replaces the retired `writeArtifact`, `readArtifact`, `copyFileToSandbox`, and `importFileFromSandbox` tools. New code uses `putFile` and `getFile`.

## When the tools are available

`putFile` and `getFile` are **not** in any named tool set. They are injected per-node by the orchestrator at dispatch time:

* A node with at least one `type: "file"` / `"file[]"` **output** declaration receives `putFile`, bound to the declared output keys.
* A node with at least one `type: "file"` / `"file[]"` **input** receives `getFile`, bound to the inbound `fileId` set resolved from upstream.

When no file inputs or outputs are declared, the corresponding tool is not injected and the agent cannot call it. The dispatch's prompt is augmented with a File Inputs / File Outputs section that lists what is reachable.

## `putFile`: the writer

`putFile` is the canonical writer for the unified model. Its surface is *agnostic to how the bytes were produced* — the agent picks a `source` (where the bytes come from) and a `bind` (what domain the resulting binding belongs to). The platform persists the bytes via the `file_hosting` capability, inserts a `files` row, inserts a `fileBindings` row, and returns a `fileId` the agent places into its structured output.

```typescript theme={null}
const PUT_FILE_INPUT_SCHEMA = z.object({
  source: z.discriminatedUnion("kind", [
    /* inline    */ z.object({ kind: z.literal("inline"), content: z.string() /* … */ }),
    /* render    */ z.object({ kind: z.literal("render"), renderer: z.string() /* … */ }),
    /* sandbox   */ z.object({ kind: z.literal("sandbox"), path: z.string() }),
    /* uploadUrl */ z.object({ kind: z.literal("uploadUrl"), path: z.string() /* … */ }),
  ]),
  bind: z.discriminatedUnion("kind", [
    z.object({ kind: z.literal("workflow_output"), outputKey: z.string() }),
    z.object({ kind: z.literal("run_scratch") }),
    z.object({
      kind: z.literal("worker_scope"),
      scopeType: z.string(),
      scopeEntityId: z.string().optional(),
    }),
    z.object({
      kind: z.literal("chat_attachment"),
      channelId: z.string(),
      sessionId: z.string().optional(),
      messageId: z.string().optional(),
    }),
  ]),
  filename: z.string().optional(),
  mimeType: z.string().optional(),
});
```

### `source` — where the bytes come from

| `source.kind` | Use it when |
| - | - |
| `inline` | The agent already has the bytes as a string (a markdown report it just generated, a CSV it built in-thread). |
| `render` | The agent describes a structured payload and a server-side renderer turns it into bytes (a PDF from markdown, an XLSX from a workbook spec, a table renderer). |
| `sandbox` | The bytes live at `path` inside the dispatch's Vercel Sandbox VM (a build artifact, a script output). The platform `stat`s the file and pulls it through the active sandbox capability. |
| `uploadUrl` | Same as `sandbox`, but the agent has already streamed the bytes to a presigned URL — the platform finalizes the upload. |

### `bind` — what domain the file belongs to

| `bind.kind` | What it means | Authorization |
| - | - | - |
| `workflow_output` | The file is the value of a declared `type: "file"` output on the executing node. `outputKey` must match a declared key. | `outputKey ∈ writableOutputKeys` from the injection-time binding. |
| `run_scratch` | A scratch file scoped to the current run — visible to downstream nodes that have it threaded as input. | `scratchAllowed` on the binding. |
| `worker_scope` | A reference file owned by a worker / org-unit / team — survives across runs. | `scopeType + scopeEntityId` must match `writableScope` on the binding. |
| `chat_attachment` | An attachment posted into a chat channel/session/message. | The dispatch must have produced the message in question. |

### Outputs

The tool returns a JSON string. On success:

```json theme={null}
{ "fileId": "k17…", "mimeType": "application/pdf", "sizeBytes": 482 }
```

On authorization, source, or persistence failure:

```json theme={null}
{ "error": "<reason>" }
```

Agent tools return structured refusal data so the model can report or recover according to the operation contract. Procedure SDK helpers raise `ProcedureApiError`; author code should branch on its code rather than message text.

The current agent tool names are `file_put` and `file_get`; `putFile` and `getFile` remain deprecated aliases used by the examples below.

### The fileId contract

A workflow `file` output is structurally a string (`file[]` is an array of strings). After structural parsing, `validateFileOutputBindings` verifies that every returned id matches an authorized binding produced for that dispatch. A plausible-looking identifier is insufficient. The agent satisfies this contract by:

1. Calling `putFile({ source, bind: { kind: "workflow_output", outputKey }, … })`.
2. Reading `fileId` from the tool's JSON result.
3. Placing that `fileId` into the corresponding field in its structured output.

If the agent skips the tool and tries to embed raw file content in the structured output, output schema and binding validation reject it. A separate `generateObject` call occurs only when the structured turn needs repair. **The validator rejects raw content** — the `fileId` is the only legitimate way to satisfy the schema.

## `getFile`: the reader

`getFile` reads a file the dispatch has access to. It has three modes — `text`, `sandbox`, `meta` — that cover the three things an agent needs to do with an inbound file: read the content, hand it to a script, or check whether it's worth reading at all.

```typescript theme={null}
const GET_FILE_INPUT_SCHEMA = z.object({
  fileId: z.string().describe(
    "The id of the files row to read. Must be one of the fileIds this dispatch has access to (see your prompt's File Inputs section).",
  ),
  mode: z.enum(["text", "sandbox", "meta"]).describe(
    'How to surface the file. ' +
    '"text" extracts text by mimeType (text-like, pdf, xlsx, docx, pptx). ' +
    '"sandbox" copies the bytes into the VM at destPath. ' +
    '"meta" returns filename + mimeType + sizeBytes only.',
  ),
  destPath: z.string().optional().describe(
    'Required for mode: "sandbox" — absolute path inside the VM, e.g. "/tmp/input.csv".',
  ),
});
```

### Modes

| Mode | What it returns | When to pick it |
| - | - | - |
| `text` | Extracted text content keyed by mimeType — text/csv/md inline; PDF, XLSX, DOCX, PPTX extracted server-side. Truncated to a cap with `truncated: true` if it overflows. | The agent is going to reason over the content directly. |
| `sandbox` | Streams the bytes into the dispatch's Vercel Sandbox VM at `destPath`. Returns `{ destPath, sizeBytes, mimeType }`. | The agent will run a script (e.g. `pandas`, `pdftotext`, a build step) over the file. |
| `meta` | `{ filename, mimeType, sizeBytes }` only — no extraction, no transfer. | The agent needs to decide whether it's worth opening the file first. |

### Authorization

The injection-time `GetFileBinding` carries the exact `fileId` set the dispatch may read. A `getFile` call with a `fileId` not in that set fails with an authorization error before any storage call is issued. Inbound `fileId`s are pre-resolved from upstream node outputs by the orchestrator — the agent never has to know how upstream files reached its input set.

## End-to-end flow

A workflow with two file-bound nodes — a `produce` node that emits a PDF report, then a downstream node that summarises it.

FILES AND BINDINGS — UPSTREAM produce → DOWNSTREAM consume

<ol />

## Isolation guarantees

* **Per-node authorization.** Both tools are bound at injection time to the executing node's `runId`, `stepId`, and the exact set of declared file inputs/outputs. An agent cannot use `putFile` to write under a key the node did not declare; it cannot use `getFile` to read a `fileId` outside its dispatch's input set.
* **Skill-constraint exemption.** Both tools are added *after* agent composition, so they are not subject to skill allowlist narrowing. Their own per-call authorization (outputKey ∈ writableOutputKeys, fileId ∈ readableFileIds) is stricter than any skill allowlist could express. `load_skill` follows the same pattern.
* **Capability-routed.** Both tools resolve the active `file_hosting` and `sandbox` capabilities at call time via the capability registry (see Capability Architecture). The tool surface is unchanged regardless of which underlying provider holds the bytes.

## Direct transfer and retention

Direct transfer specifications report the provider's actual URL expiry and which requested
restrictions it enforces. The internal provider has a fixed upload-URL lifetime and download URLs
without expiry. Consumers enforce their own byte and time limits and verify measured size and
content digest before publishing a file binding. A dispatched upload whose result is unknown is
recorded as unknown; it does not automatically mint another URL and upload a second copy.
Upload and download bearer URLs and headers travel through private, cleaned-up curl configuration
files inside the sandbox. They stay out of process arguments and ordinary error diagnostics.

File evidence follows its owning workflow or debug attempt. Existing run retention keeps completed
and failed runs for 180 days and cancelled runs for 30 days, and waits for step-result cleanup.
Declared `file` and `file[]` launch inputs acquire consumer-owned `run_scratch` retention leases
in the run-creation transaction, including draft and replay launches. A prepared debug attempt
acquires its `debug_input` bindings in the preparation transaction. Each lease reads canonical
file existence, so producer expiry either preserves the admitted consumer's input or wins first
and causes admission to fail. These references retain bytes; existing typed-input and file-read
authorization still govern access. File-shaped strings inside JSON do not create leases.

Inputs of runs and debug attempts that existed before these leases are given leases in the
background. Run and debug cleanup stay paused until that backfill has finished for both. Until
then, nothing is deleted: runs, attempts, bindings, metadata, and bytes are all kept, and an
interrupted backfill resumes where it stopped. New runs and debug attempts acquire their leases
as usual while the backfill runs.

The run backfill uses the recorded immutable version's input schema, including terminal runs still
inside retention. Historical draft runs have no frozen input schema. For those runs, or when the
recorded version/schema cannot be recovered, it conservatively retains existing canonical file IDs
anywhere in persisted arguments, including JSON. This fallback grants no read authority. Hard bounds
on argument traversal and canonical lookups fail the page rather than silently skipping dependencies.
Debug backfill uses frozen typed resolved inputs, recovering IDs from their stored values when the
optional projection is absent. After both passes succeed, the existing retention periods and bounded
cleanup release leases normally. Bindings whose producer run already disappeared remain unowned
unknown references; this rollout does not perform historical orphan collection.
At expiry, bounded cleanup drains that run's output and scratch bindings before removing the run.
Debug-attempt expiry removes its own bindings under its existing policy. After the final binding
disappears, cleanup deletes unowned internal-provider bytes and metadata in the same transaction.
Any surviving binding or independent external owner keeps the file alive. A binding writer checks
the canonical file still exists, so a stale writer cannot reattach already deleted evidence.

This owner-driven cleanup does not identify arbitrary orphan objects after an upload response is
lost. Failed or unacknowledged uploads stay unresolved when atomic, reference-safe deletion cannot
be proven. Each upload attempt has a distinct claim identity; replaying a previously claimed object
cannot adopt or delete it. A returned object ID, matching size, or digest alone never authorizes
cleanup of storage bytes.

## Migration from the legacy quartet

The legacy tools — `writeArtifact`, `readArtifact`, `copyFileToSandbox`, `importFileFromSandbox` — were deleted in PR-8h. The mapping is straightforward:

| Legacy call | Today |
| - | - |
| `writeArtifact({ outputKey, content, mimeType })` | `putFile({ source: { kind: "inline", content, mimeType }, bind: { kind: "workflow_output", outputKey } })` |
| `readArtifact({ fileId })` | `getFile({ fileId, mode: "text" })` |
| `copyFileToSandbox({ fileId, destPath })` | `getFile({ fileId, mode: "sandbox", destPath })` |
| `importFileFromSandbox({ path, outputKey })` | `putFile({ source: { kind: "sandbox", path }, bind: { kind: "workflow_output", outputKey } })` |

Each legacy operation maps cleanly to one `putFile` or `getFile` call. The unified surface adds three things the legacy quartet did not have:

1. **`render` source** — server-side document/table/workbook rendering without the agent having to materialize bytes in-thread.
2. **`bind: "run_scratch" | "worker_scope" | "chat_attachment"`** — first-class binding domains the legacy quartet did not express.
3. **`mode: "meta"`** — an agent can decide whether to open a file before paying the extraction cost.

***

## Related

* [Vercel Sandbox](https://docs.gloo.com/forge/build/configure-sandbox.md#vercel-sandbox-provider)
* [Agent composition](https://docs.gloo.com/forge/architecture/flows/workflow-execution.md#2-composition)
* [HTTP API — Files](https://docs.gloo.com/forge/reference/http-api/files)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.