# Sandbox for local agents

> A local AI agent that Osevel runs on your machine, in a container that can reach nothing but its LLM provider.

Source: https://osevel.com/docs/guides/sandbox/

A local agent is an agent osevel runs itself, on your machine,
in a container that can reach nothing but its LLM provider.

```bash
osevel llm key set anthropic
osevel agent add auditor --ide other --access read --profile sealed --auditor
osevel task add auditor "Audit who can write and which grants are unused"
osevel agent run auditor            # Docker needed; builds two small images once
osevel report list
```

`agent run` starts the sandbox, serves the osevel MCP server to the agent over the
container's stdio and waits until the agent has done its open tasks (or 15 minutes). The agent
goes through the same rules as an IDE agent: its access level, its profile (local agents must be
sealed), its capabilities, and the auditor role for an auditor. Approvals it needs go to the
terminal or the dashboard; there is no human in its client. `--model` picks the model (default
`claude-sonnet-5-5`).


## Layout

Each run gets its own Docker network and two containers (`packages/sandbox`):

- **Internal network** (`docker network create --internal`): no route out, no external DNS.
- **Gateway** (`docker/gateway.Dockerfile`): on the internal network and one egress network. It
  forwards only `POST /v1/messages` and `POST /v1/messages/count_tokens` to one provider origin,
  JSON bodies up to 4 MiB, and adds the API key itself. Other paths, methods, query strings,
  absolute-URL (forward proxy) requests and `CONNECT` tunnels get `403`. It passes on only a few
  request and response headers, so neither the agent's own credentials nor a header echoing the
  key gets through. It reads the key from its stdin at start, so the key is in no environment
  that `docker inspect` shows, and it never logs bodies.
- **Rule-based agents** ([rules.md](https://osevel.com/docs/guides/rule-based-agents/)) get no gateway and no network at all: the agent
  container runs with `--network none`, its stdio as the only channel.
- **Agent** (`docker/agent.Dockerfile`, Node standard library only): a minimal MCP client on its
  stdio and a decision loop (`engine.ts`). The loop lists the server's tools, asks a **decision
  engine** for the next calls, runs them and hands back the results; it calls only tools the
  server listed (anything else is refused before the server sees it), at most 16 per turn. The
  first engine is an LLM in the Anthropic Messages format through the gateway
  (`AnthropicEngine`, `AR_ENGINE=anthropic`); rule, ML and local-model engines (Phase 4)
  implement the same interface. It starts with
  `next_task`, works through its tools and ends with `complete_task`; at most 24 turns. It holds
  no credential. On the internal network only. Read-only root, all Linux capabilities dropped,
  `no-new-privileges`, user `65534`, a 16 MB `noexec` `/tmp`, memory, CPU and process limits, no
  host directory and no Docker socket. Its stdin and stdout are the MCP channel to the host
  (`docker run -i`), so no host socket is mounted into it either.

`stop()` removes both containers and the network; `cleanupSandboxes()` removes anything a crash
left behind (label `dev.osevel.sandbox`).

## Images

Both images are built on your machine from `packages/sandbox/docker/*.Dockerfile`, on
`node:22.22.0-alpine` **pinned by digest** (a re-pushed tag cannot change the base). Each built
image carries the SHA-256 of its own sources (Dockerfile and compiled files) in the label
`dev.osevel.source`; before every run the label is compared with the sources, and an image
that does not match (stale, or something else under the same tag) is rebuilt.

## From a template (`agent create`)

```bash
osevel agent templates
osevel agent create --template auditor --project shop             # quick: the template's name, schedule and task
osevel agent create --template security-scanner --project shop --advanced   # asks for each
osevel agent create --template rule-keeper --project shop \
  --grant low_stock_products,flag_order --rules rules.yaml --every 1d --task "Check stock"
```

| Template           | Engine           | Access | Schedule | What it does                                                                                 |
| ------------------ | ---------------- | ------ | -------- | -------------------------------------------------------------------------------------------- |
| `auditor`          | LLM              | read   | 7d       | Audits who can do what (metadata only) and writes a report                                   |
| `security-scanner` | LLM              | read   | 1d       | Reports risky privileges: unused raw-write rights, never-called grants, stale agents, PUBLIC |
| `anomaly-watch`    | ML (no model)    | read   | 1d       | Flags unusual agent activity from hourly counts: no model, no key, no network                |
| `keeper`           | checks (no model)| read   | 1d       | Health checks with a proposed fix each (FK without index, no primary key, unvalidated constraints, sequences near their limit, unclassified columns, duplicate indexes, orphan rows); applies nothing |
| `rule-keeper`      | rules (no model) | write  | 1d       | Runs your [rules](https://osevel.com/docs/guides/rule-based-agents/): no model, no key, no network                                    |

The dashboard has the same cards (Agents & sessions, "New local agent"): quick create or an
advanced form, then one passkey confirmation. It can create only the sealed read-only templates
(`auditor`, `security-scanner`); the database enforces that (journal v10, `agents_guard`).

One confirmation code. The agent (sealed, the template's access level, the auditor role for the
first two), its capability grants and its rule set are created in one database transaction: a
rule set naming a tool the agent would not have creates nothing. Then the watcher entry
(`watch add`) is added on this machine. The agent's MCP token is not shown: a local agent never
needs it.

## Running by themselves (`watch`)

```bash
osevel watch add auditor --project shop                       # runs when it has tasks
osevel watch add auditor --project shop --every 7d --task "Weekly access audit"
osevel watch list
osevel watch run          # the watcher in the foreground (every 60 s)
osevel watch install      # start it at login (LaunchAgent / systemd user unit)
osevel watch remove auditor --project shop
```

The watcher leaves a scheduled task when it is due (as the approver role, like `task add`), then
runs each added agent that has open tasks, one at a time, exactly like `agent run`. Only sealed
agents added with `watch add` run by themselves: a sealed agent that also serves an IDE keeps its
tasks for the IDE. The list lives in `<configDir>/auto-agents.json`.

The watcher runs as **your** OS user, never inside the daemon: starting containers needs Docker
(root-equivalent on Linux) and the LLM key is in your keychain, and the daemon's user gets
neither. `watch install` refuses to run as root.

## Anomaly watch (classic ML)

`agent create --template anomaly-watch`, or any auditor agent with `--engine anomaly` on `agent
run` / `watch add`. It reads `audit_activity_hourly` (hourly counts per agent: changes, writes,
rows changed, refused or denied statements; never SQL text or row data) and `audit_agents`, then
compares each agent's last 24 hours with its own previous days:

- a robust z-score (median and MAD) of the day's changes, rows changed and refused statements,
  from 3.5 and above a minimum (10 changes, 100 rows, 3 refused);
- an hour of the day with 5 or more changes that the agent was never active in before.

An agent with fewer than 3 active days of history is not judged. It saves a report (`report
list`) and closes its task. The model is robust statistics, not a trained network; it runs like
the rule engine, without a model, a key or any network. The dashboard does not offer this
template yet (its template list knows only LLM and rule engines).

## Providers

| Provider    | Key                     | Gateway route                                    | Engine format |
| ----------- | ----------------------- | ------------------------------------------------ | ------------- |
| `anthropic` | yours, `x-api-key`      | `POST /v1/messages`, `/v1/messages/count_tokens` | Anthropic     |
| `openai`    | yours, `Authorization`  | `POST /v1/chat/completions`                      | OpenAI        |
| `gemini`    | yours, `x-goog-api-key` | `POST /v1beta/models/<model>:generateContent`    | Gemini        |
| `ollama`    | none                    | `POST /v1/chat/completions` on this machine      | OpenAI        |

```bash
osevel agent run auditor --provider openai --model <model> --project shop
osevel watch add auditor --provider ollama --model <model> --every 7d --task "..." --project shop
osevel agent create --template auditor --provider gemini --model <model> --project shop
```

Anthropic is the default (its default model); the others need `--model`. Ollama runs on your
machine (`host.docker.internal:11434`): only the gateway reaches it, through one OpenAI-compatible
route; the agent still reaches nothing but the gateway. The gate test runs once per provider
(the allowed route, the right credential header, nothing else). Calls to the real OpenAI, Gemini
and Ollama were not tested yet: there was no key or local model on the test machine.

## LLM keys

Local agents use your own provider key (Phase 3, work package 4), or our service (below).

```bash
osevel llm key set anthropic      # or openai, gemini; hidden prompt, or one line on stdin
osevel llm key status             # set or not, and where; never the key
osevel llm key remove anthropic
```

The key goes to the OS keychain (service `osevel`, account `llm:anthropic`) or, with
`--file` or without a keychain, to `<configDir>/llm-keys/anthropic.json` (mode 0600, not
encrypted at rest). It is per user, not per project. Only the sandbox gateway receives it, on its
stdin; the agent, the panel and the cloud never do.

The gateway knows its providers by name (`GATEWAY_PROVIDERS`: origin and allowed routes). The
runner picks one with `provider`; the agent cannot choose where its calls go.

## Our service (Anthropic, no key of yours)

Without an Anthropic key, and with the bridge paired to a cloud that offers it, `agent run` and
the watcher use our service (Phase 4, work package 8); `--llm key` or `--llm service` forces one.
No long-lived key exists anywhere:

1. this process asks the cloud for a grant (`POST /api/connector/llm-grant`, the connector
   token, the model). The cloud checks your plan: a credit amount, credit left this month, the
   model priced and of a size the plan includes. Otherwise it refuses and nothing starts. The
   free plan includes no model through our service (Standard and Pro do);
2. the cloud signs a 5-minute, single-use JWT (ES256; its issuer is the cloud, its subject
   `osevel:account:<id>`, no email);
3. the gateway exchanges it at Anthropic's `/v1/oauth/token` (Workload Identity Federation) for a
   token of minutes and calls with it as a bearer. Calls must use the granted model, may not
   stream, and get `max_tokens` capped by your remaining credit;
4. after each reply the gateway reports the token counts (cache tokens count as input); this
   process sends them to the cloud (`POST /api/connector/usage`). The cloud sees counts only;
5. before the token ends, the gateway asks for the next grant. When the credit is used up the
   cloud refuses it, and calls fail (HTTP 402 from the gateway) once the token has ended.

The gateway, not the agent, holds the grant and the token. The bridge config must be the same
user's (`<configDir>/bridge`); a daemon-mode bridge of another user is not used. Not tried against
the real Anthropic yet; the e2e test uses a stand-in that verifies grants like Anthropic does.

## The gate test

`e2e/sandbox/gate.test.ts` runs a probe image in place of an agent. The probe tries every way
out and reports. The test passes only if:

- it cannot resolve external names or reach a public IP, the host, or `host.docker.internal`;
- through the gateway, only the allowed call works, and the provider receives the gateway's key,
  not the agent's;
- other paths, absolute URLs and `CONNECT` are refused;
- it is not root, has no capabilities and no Docker socket, and cannot write its root file
  system;
- the API key appears in nothing it can see (its environment, every process's environment and
  command line, the gateway's replies);
- its stdio works as a channel.

It needs a Docker-compatible CLI (Docker, OrbStack, Podman) and is skipped without one.

## What it does not cover

- A user on the host who is root or in the `docker` group can read and change the containers.
- What the agent sends to the provider (prompts, query results) goes to the provider. The sandbox
  guarantees that it goes nowhere else.
- The images are built on your machine and not signed; there is no published image yet.
