Give your agent a shell
This guide builds an agent loop whose shell tool runs commands in your VM. Files that one call writes are there for the next call.
Before you start
Section titled “Before you start”- An approved account and an API key from the API keys page.
- Python 3.12 with
requests, or Node 22, for the loop. The curl tab needs only curl. - Your model SDK, if your agent has one. The loop below picks its commands from a list. The comment in the code marks where your model call goes.
1. Create a VM
Section titled “1. Create a VM”Create one VM for each agent session. The first request to it starts it.
export SI_API_KEY=si_...curl -sS -X POST "https://api.slashinfra.com/svms" \ -H "Authorization: Bearer $SI_API_KEY" -H "Content-Type: application/json" \ -d '{"name":"agent-shell"}'API reference: Control API operation
import os, requests
res = requests.post( "https://api.slashinfra.com/svms", headers={"Authorization": f"Bearer {os.environ['SI_API_KEY']}"}, json={"name": "agent-shell"},)res.raise_for_status()print(res.json()["id"])const res = await fetch('https://api.slashinfra.com/svms', { method: 'POST', headers: { Authorization: `Bearer ${process.env.SI_API_KEY!}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'agent-shell' }),})if (!res.ok) throw new Error(`create failed: ${res.status}`)const svm = (await res.json()) as { id: string }console.log(svm.id){"id":"6f1c0f0e8a","generation":1,...}Set VM to the id in the reply. Keep the VM id in your session record.
export VM=6f1c0f0e8a2. Define the tool
Section titled “2. Define the tool”The tool sends one command to /bin/bash and returns the output and the exit code. Each tab does the same thing: it sends mkdir and a file write as one request.
curl -sS -i -X POST "https://$VM.slashinfra.dev/bin/bash" \ -H "Authorization: Bearer $SI_API_KEY" \ --data-binary "mkdir -p /home/user/notes && echo 'draft 1' > /home/user/notes/plan.txt"import os, requests
VM_URL = f"https://{os.environ['VM']}.slashinfra.dev"
def run_command(command: str) -> tuple[str, int]: res = requests.post( f"{VM_URL}/bin/bash", headers={"Authorization": f"Bearer {os.environ['SI_API_KEY']}"}, data=command.encode(), ) res.raise_for_status() return res.text, int(res.headers["X-Exit-Code"])type CommandResult = { output: string; exitCode: number }
async function runCommand(command: string): Promise<CommandResult> { const res = await fetch(`https://${process.env.VM!}.slashinfra.dev/bin/bash`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.SI_API_KEY!}` }, body: command, }) const exitHeader = res.headers.get('X-Exit-Code') if (!res.ok || exitHeader === null) throw new Error(`VM request failed: ${res.status}`) return { output: await res.text(), exitCode: Number(exitHeader) }}HTTP/2 200X-Exit-Code: 0The tool takes one string, the command. A non-zero exit code is a result the agent can read, so return it instead of raising an error. Raise an error only when the request itself fails. Keep the key in your application’s configuration, out of model inputs, tool results and logs.
3. Run the loop
Section titled “3. Run the loop”The loop runs each command, prints its output and exit code, then moves on. The second command starts a new shell and reads the file the first one wrote.
import os, requests
VM_URL = f"https://{os.environ['VM']}.slashinfra.dev"
def run_command(command: str) -> tuple[str, int]: res = requests.post( f"{VM_URL}/bin/bash", headers={"Authorization": f"Bearer {os.environ['SI_API_KEY']}"}, data=command.encode(), ) res.raise_for_status() return res.text, int(res.headers["X-Exit-Code"])
# The model chooses each command from the output so far. This list stands in for it.commands = [ "mkdir -p /home/user/notes && echo 'draft 1' > /home/user/notes/plan.txt", "cat /home/user/notes/plan.txt",]
for command in commands: output, exit_code = run_command(command) print(output, end="") print(f"exit {exit_code}")type CommandResult = { output: string; exitCode: number }
const vmUrl = `https://${process.env.VM!}.slashinfra.dev`
async function runCommand(command: string): Promise<CommandResult> { const res = await fetch(`${vmUrl}/bin/bash`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.SI_API_KEY!}` }, body: command, }) const exitHeader = res.headers.get('X-Exit-Code') if (!res.ok || exitHeader === null) throw new Error(`VM request failed: ${res.status}`) return { output: await res.text(), exitCode: Number(exitHeader) }}
// The model chooses each command from the output so far. This list stands in for it.const commands = ["mkdir -p /home/user/notes && echo 'draft 1' > /home/user/notes/plan.txt", 'cat /home/user/notes/plan.txt']
for (const command of commands) { const result = await runCommand(command) process.stdout.write(result.output) console.log(`exit ${result.exitCode}`)}exit 0draft 1exit 0The first call makes the file and prints nothing. The second call prints its contents. Both calls reached the same files, because the VM keeps them between requests. To connect a model, pass each command’s output to the model and run the command it returns, in place of the list.
Check it works
Section titled “Check it works”You should see draft 1 on the second line of output, after the first exit 0. Both calls end with exit 0.
If it doesn’t work
Section titled “If it doesn’t work”| Symptom | Cause | Fix |
|---|---|---|
401 unauthorized |
The key is missing, wrong or deleted. | Set SI_API_KEY to a key from the API keys page. |
404 not_found on every call |
The VM id is wrong, or the VM is deleted. | Check VM against the id from step 1. |
X-Truncated: 1 in the reply |
The output passed 1 MiB and was cut. | Have the command write its output to a file, then read that file in a later call. |
Scroll horizontally to see all columns.
Clean up
Section titled “Clean up”curl -sS -i -X DELETE "https://api.slashinfra.com/svms/$VM" \ -H "Authorization: Bearer $SI_API_KEY"API reference: Control API operation
import os, requests
res = requests.delete( f"https://api.slashinfra.com/svms/{os.environ['VM']}", headers={"Authorization": f"Bearer {os.environ['SI_API_KEY']}"},)res.raise_for_status()print(res.status_code)const res = await fetch(`https://api.slashinfra.com/svms/${process.env.VM!}`, { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.SI_API_KEY!}` },})if (!res.ok) throw new Error(`delete failed: ${res.status}`)console.log(res.status)HTTP/2 204Set up a coding agent
Section titled “Set up a coding agent”For an agent with a shell and HTTP access, set SVM_URL and SVM_KEY as its environment variables and give it the prompt below. Keep the key out of the prompt itself.
You have an SVM (a Linux workspace) at the URL in SVM_URL. Read https://slashinfra.com/docs/reference/limits.md before choosing timeouts, upload sizes or concurrency. Do not print SVM_KEY or include it in logs or source files.
Send Authorization: Bearer $SVM_KEY to the SVM API. The URL alone grants no access. These requests operate on the same files and processes:
Run a script: curl -sS -D - -H "Authorization: Bearer $SVM_KEY" --data-binary @- "$SVM_URL/bin/bash" <<'SCRIPT'cd /home/user && pwdSCRIPT
Read a file: curl -fsS -H "Authorization: Bearer $SVM_KEY" "$SVM_URL/home/user/result.txt"
Write a file; its parent directory must exist: curl -fsS -T input.txt -H "Authorization: Bearer $SVM_KEY" "$SVM_URL/home/user/input.txt"
Check X-Exit-Code on command replies: HTTP 200 can contain a command failure. If X-Truncated is 1, write results to a file and read that file. For long work, use a background job and poll its log rather than repeating a command that may still be running.
Each request starts a new shell. Keep reusable state in files. The workspace retains files across sleep and can retain idle processes through hibernation. Use the existing SVM unless the task requires a separate workspace. Ask before deleting a workspace that contains useful work.
Task guides:https://slashinfra.com/docs/build/files-and-programs.mdhttps://slashinfra.com/docs/build/background-work.mdhttps://slashinfra.com/docs/platform/browser-and-desktop.md
Treat HTTP 401 as a credential problem, 404 as an unavailable path or SVM, and 429 as a reason to wait for Retry-After. Read https://slashinfra.com/docs/reference/errors.md for other failures. Keep commands safe to retry when they affect external systems.- Files and programs over HTTP: the requests this tool sends, one at a time.
- MCP server: give an MCP client the same commands and files, with a grant you choose.
- Background work: run a command that outlives one request.
- Commands and jobs: the command, terminal and job operations behind this tool.