Use the Sandbox
A sandbox is an isolated Linux machine. An automation can use it to run shell commands, Git, the GitHub CLI, and scripts.
| Automation | Sandbox |
|---|---|
| Instruction automation | The managed agent has its own sandbox. It runs commands, reads and writes files, and runs skill scripts as part of the run. Ask for this work in the instructions. |
| Code automation | Each run has its own sandbox. A code stage calls it with ctx.tools.call and the managed-sandbox service. An agent stage uses the managed agent’s own tools. |
The rest of this page is about the sandbox of a code automation.
Sandbox tools for code
Section titled “Sandbox tools for code”Code stages run in a QuickJS VM with no shell. For shell work, call these managed-sandbox tools:
| Tool | Use it to |
|---|---|
exec_command | Run a shell command and get its output. |
poll_command, kill_command | Wait for, or stop, a command that is still running. |
start_background_command | Start a long command that keeps running after the call returns. |
read_file, write_file, edit_file | Read and change text files. |
list_directory, list_working_directories | Find files and folders. |
To see the arguments of each tool, call ctx.tools.find({ service: "managed-sandbox" }). This does not start the sandbox.
Run a command
Section titled “Run a command”import { TypeApiError } from "@type-dot-com/sdk";import { automation, code, complete, recurringEventSchema,} from "@type-dot-com/sdk/automations";import { err } from "neverthrow";import { z } from "zod";
export default automation({ output: z.object({ text: z.string() }), deployment: { subscriptions: { check: { title: "Check automation workspace", description: "Record output from the isolated automation workspace", source: { kind: "recurring", schedule: { kind: "interval", everySeconds: 3600 }, }, entry: "check", }, }, }, stages: { check: code({ input: recurringEventSchema, transitions: [], async run({ ctx, input: event }) { const result = await ctx.tools.call( { service: "managed-sandbox", name: "exec_command", arguments: { command: "printf automation-ready" }, }, { automationEffectKey: `workspace-check:${event.scheduledAt}` }, ); if (result.isErr()) return err(result.error); if (result.value.isError) return err( new TypeApiError("Workspace check failed", "invalid_response"), ); return complete({ text: result.value.content .filter((block) => block.type === "text") .map((block) => block.text) .join("\n"), }); }, }), },});Read the result
Section titled “Read the result”A sandbox tool returns the standard tool result: { content: [{ type: "text", text }], isError? }. It has no stdout or exitCode fields.
- The text has the command’s combined stdout and stderr.
- If the command exits with a code other than 0,
isErroristrue, and the text ends with[exit code N]. - If the command is still running when the call stops waiting, the text has the output so far and a
sessionId. Callpoll_commandwith thatsessionIdto wait for more. In an automation,exec_commandwaits up to 120 seconds by default.
Check both result.isErr() and result.value.isError. To get structured data, print it with a marker, for example JSON:, and parse that line. The example in Use the GitHub CLI does this.
When a managed agent runs a finite command, Type waits for completion and returns the output to the same tool call. The agent continues in the same response, without a separate completion message or repeated polling. This is automatic; the agent does not need to set resumeOnExit. Long-lived servers and watchers use start_background_command instead. The ctx.tools.call behavior described above still applies to commands run directly by automation code.
The workspace
Section titled “The workspace”- Each live run has its own sandbox. Type creates it at the first sandbox call in the run.
- All stages of the run use the same sandbox, also the stages after an agent stage. A later stage can read the files that an earlier stage wrote.
- Type deletes the sandbox when the run ends. The next run starts with a new sandbox, so clone repositories and install tools again in each run.
- Commands start in
/tmp/type-automation. - Do not use sandbox files as state between runs. Use checkpoints.
- Commands do not get a Type API credential. To call Type, use
ctxin your code.
Use the GitHub CLI
Section titled “Use the GitHub CLI”Type gives sandbox commands fresh GitHub credentials for each GitHub connection that is attached to the Space with full automation access. TYPE_GITHUB_CONNECTIONS is a JSON array, with one entry for each repository:
| Field | Meaning |
|---|---|
fullName | The repository, for example acme/project. |
organizationIntegrationId | The GitHub connection that covers it. |
tokenEnv | The name of the environment variable that has the credential. |
gitAuthConfigured | true if git over HTTPS to this repository is already authenticated. This is the case when exactly one connection covers the repository. |
GH_TOKEN and GITHUB_TOKEN are empty. For a gh command, set GH_TOKEN from the entry’s tokenEnv. An empty array means that the sandbox has no GitHub access.
This automation counts the open pull requests in one repository:
import { TypeApiError } from "@type-dot-com/sdk";import { automation, code, complete, recurringEventSchema,} from "@type-dot-com/sdk/automations";import { err, Result } from "neverthrow";import { z } from "zod";
// A fixed value. Never put event text in a shell command.const repository = "acme/project";
// Find the token for the repository, list its open pull requests,// and print them on one line that starts with "JSON:".const listOpenPullRequests = `token_env=$(printf %s "$TYPE_GITHUB_CONNECTIONS" | jq -er 'first(.[] | select(.fullName == "${repository}") | .tokenEnv)') || { echo "No GitHub connection covers ${repository}" >&2; exit 1; }pulls=$(GH_TOKEN=$(printenv "$token_env") gh api 'repos/${repository}/pulls?state=open&per_page=20' --jq 'map({number, title})') || exit 1printf 'JSON:%s\\n' "$pulls"`;
// JSON.parse throws on bad input. This version returns a Result.const parseJson = Result.fromThrowable( (text: string): unknown => JSON.parse(text), () => new TypeApiError("The command printed invalid JSON", "invalid_response"),);
// The shape of the JSON that the command prints.const openPullRequests = z.array( z.object({ number: z.number(), title: z.string() }),);
export default automation({ output: z.object({ open: z.number() }),
deployment: { subscriptions: { hourly: { title: "Count open pull requests", description: "Read open pull requests with the GitHub CLI", source: { kind: "recurring", schedule: { kind: "interval", everySeconds: 3600 }, }, entry: "count", }, }, },
stages: { // Run the GitHub CLI in the sandbox and count the pull requests. count: code({ input: recurringEventSchema, transitions: [], async run({ ctx, input }) { const commandResult = await ctx.tools.call( { service: "managed-sandbox", name: "exec_command", arguments: { command: listOpenPullRequests }, }, { automationEffectKey: `open-pulls:${input.scheduledAt}` }, ); if (commandResult.isErr()) { return err(commandResult.error); }
const output = commandResult.value.content .map((block) => block.text ?? "") .join("\n"); if (commandResult.value.isError) { return err(new TypeApiError(`The GitHub CLI failed: ${output.slice(0, 300)}`, "invalid_response")); }
const jsonLine = output.split("\n").find((line) => line.startsWith("JSON:")); if (!jsonLine) { return err(new TypeApiError("The command printed no JSON line", "invalid_response")); } const json = parseJson(jsonLine.slice("JSON:".length)); if (json.isErr()) { return err(json.error); } const pullRequests = openPullRequests.safeParse(json.value); if (!pullRequests.success) { return err(new TypeApiError("Unexpected pull request data", "invalid_response")); }
return complete({ open: pullRequests.data.length }); }, }), },});For a connected app that has a CLI, you can also call the type-api tool run_integration_command with ctx.tools.call. It runs the command in this sandbox with that connection’s credentials.
Access rules
Section titled “Access rules”- Sandbox commands run only in live runs. In fixtures, give the result in
toolResponses. A test never starts the sandbox. - If your code runs a
ghcommand, such asgh apiorgh pr, or usesGH_TOKEN,GITHUB_TOKEN, or aTYPE_GITHUB_variable, the deploy fails when the Space has no GitHub connection with full automation access. - Commands get credentials only for connections that are attached to the Space. They do not get the access that an agent has in a chat.
- A shell cannot enforce read-only access. A command with a full-access credential can change data.
Retries and effect keys
Section titled “Retries and effect keys”Give each sandbox call that can change something a stable automationEffectKey, for example built from scheduledAt or the event ID. Type does not require the key. A call with a key is recorded as a write in the run’s call history. Type does not save the key itself.
An effect key does not stop a command from running again if a run fails part of the way. Make commands safe to repeat. For example, check if a branch exists before you create it.
Limits
Section titled “Limits”| Item | Limit |
|---|---|
| One sandbox tool call | 170 seconds |
exec_command output in one result | 32 KiB of new output: the first 8 KiB and the last 24 KiB. The result names a log file in the sandbox that has the full output. |
run_integration_command output | 16 KiB |
| Sandboxes | 1 for each run |
Each sandbox call counts toward the 128 requests that a code stage can send, and the stage’s time limit still applies. Filter output in the command, for example with jq or head. See Limits.