# AI SDK

Give an AI SDK agent tools that run commands and files in a Sandcovery sandbox.

This guide gives an [AI SDK](https://ai-sdk.dev) agent three tools that work in one Sandcovery sandbox: run a shell command, write a file, and read a file. The sandbox runs on a provider account you connected.

## Before you start

- Create an API key and add at least one provider credential, as the [quickstart](/docs/quickstart) shows, and set `SANDCOVERY_API_KEY`.
- Use Node.js 24.14 or later, which the `sandcovery` package needs.
- Hold a key for the model you call. This guide calls a model through OpenRouter with `OPENROUTER_API_KEY`.

## Install the packages

```bash
npm install ai sandcovery @openrouter/ai-sdk-provider
```

## Define the tools and the run

```ts title="agent.ts"
import { generateText, isStepCount, jsonSchema, tool } from 'ai'
import type { LanguageModel } from 'ai'
import type { Sandcovery } from 'sandcovery'

const MAX_STEPS = 10

const sandboxTools = (sandcovery: Sandcovery, sandboxId: string) => ({
  readFile: tool({
    description: 'Read a UTF-8 text file in the sandbox.',
    execute: async ({ path }, { abortSignal }) =>
      new TextDecoder().decode(
        await sandcovery.sandboxes.readFile(sandboxId, path, {
          signal: abortSignal,
        })
      ),
    inputSchema: jsonSchema<{ path: string }>({
      properties: { path: { type: 'string' } },
      required: ['path'],
      type: 'object',
    }),
  }),
  runCommand: tool({
    description:
      'Run a shell command in the sandbox and return its exit code, stdout, and stderr.',
    execute: async ({ command }, { abortSignal }) =>
      await sandcovery.sandboxes.exec(
        sandboxId,
        { command, cwd: null, env: null, timeout_seconds: null },
        { signal: abortSignal }
      ),
    inputSchema: jsonSchema<{ command: string }>({
      properties: { command: { type: 'string' } },
      required: ['command'],
      type: 'object',
    }),
  }),
  writeFile: tool({
    description:
      'Write a text file in the sandbox, creating its parent directories.',
    execute: async ({ content, path }, { abortSignal }) =>
      await sandcovery.sandboxes.writeFile(sandboxId, path, content, {
        signal: abortSignal,
      }),
    inputSchema: jsonSchema<{ content: string; path: string }>({
      properties: {
        content: { type: 'string' },
        path: { type: 'string' },
      },
      required: ['content', 'path'],
      type: 'object',
    }),
  }),
})

export const runAgent = async ({
  model,
  prompt,
  sandcovery,
}: {
  model: LanguageModel
  prompt: string
  sandcovery: Sandcovery
}) => {
  const sandbox = await sandcovery.sandboxes.create({
    api_key_id: null,
    disk_mib: null,
    egress: null,
    env: null,
    gpu: null,
    idle_timeout_seconds: null,
    image: null,
    os: null,
    ports: null,
    provider: null,
    region: null,
    slug: 'sandcovery/2x4',
    slugs: null,
    snapshot_id: null,
    ttl_seconds: 600,
  })

  try {
    const { text } = await generateText({
      model,
      prompt,
      stopWhen: isStepCount(MAX_STEPS),
      tools: sandboxTools(sandcovery, sandbox.id),
    })

    return text
  } finally {
    await sandcovery.sandboxes.destroy(sandbox.id)
  }
}
```

- `runAgent` creates one sandbox for the run. `sandcovery/2x4` starts it on the [candidate](/docs/routing#how-a-create-is-routed) with the lowest hourly price among the providers that bill by use at 2 vCPU and 4 GiB, and falls back to the next candidate when a create fails.
- Each tool calls the [sandbox API](/docs/sandboxes) on that sandbox. `exec` returns the exit code, stdout, stderr, and duration, and `writeFile` creates parent directories.
- A command runs for up to 300 seconds, or for the longest command its provider runs when that is shorter, unless its request sets `timeout_seconds`.
- `isStepCount(10)` ends the run after 10 model steps.
- `finally` destroys the sandbox after the answer or a failure. If your process exits first, Sandcovery destroys the sandbox when its `ttl_seconds` ends.
- `jsonSchema` keeps the example free of a schema library. A Zod schema works in its place.

## Run the agent

```ts title="main.ts"
import { openrouter } from '@openrouter/ai-sdk-provider'
import { Sandcovery } from 'sandcovery'

import { runAgent } from './agent.ts'

const answer = await runAgent({
  model: openrouter('anthropic/claude-sonnet-5.5'),
  prompt: 'Print the first 10 primes with a Python script.',
  sandcovery: new Sandcovery(),
})

console.log(answer)
```

## Next steps

- [Routing](/docs/routing): rank providers by start latency or uptime instead, such as with `sandcovery/2x4:fastest`.
- [API keys](/docs/keys): cap the spend, providers, and concurrency of the key the agent uses.
