# Running agents

Your app runs a job with `agents.run`. byoa takes the user's sandbox, loads the user's setup, runs the user's own harness on the user's own plan, and streams its events. To continue a chat, give its jobs one `conversation` id. For a program of your own around the harness, use `agents.session`; for a harness outside byoa's sandboxes, `agents.jobToken`.

## Run a job and stream its events

```ts
for await (const ev of agents.run(userId, {
  harness: 'claude',                   // 'claude' | 'codex' | 'grok' | 'fake'
  task,                                // the user's request
  mcp: ['notion', 'todos'],            // the servers this job gets; default none
  setup: { agentsMd, skills },         // AGENTS.md (and CLAUDE.md for Claude Code); skills: [{ name, files: { 'SKILL.md': '...' } }]
})) {
  // ev.type: 'start' | 'text' | 'tool_call' | 'tool_result' | 'permission' | 'error' | 'turn' | 'end'
}
```

- The events are the same for every harness. The schema is in the [API reference](https://byoa.rippling.computer/docs/api.md#events-one-schema-for-every-harness).
- `run` does not throw when a job fails. It gives `error` events (`code`: `signed-out`, `expired`, `no-plan`, `usage-limit`, `rate-limited`, `harness`, `sandbox`, `mcp` or `conversation`), and always ends with one `end` event (`ok`, `result`, `usage`, and in a conversation `session`). On `signed-out` or `expired`, show the sign-in again (for `plan: 'opencode-go'`, ask for a new key). On `no-plan`, tell the user that the key's workspace has no OpenCode Go plan. On `usage-limit` and `rate-limited`, see [When the plan is used up](#when-the-plan-is-used-up).
- byoa writes skills where each harness reads them (`.claude/skills/`, `.agents/skills/`), AGENTS.md (and CLAUDE.md for Claude Code) from one source, and the MCP config in each harness's own format. `plugins` adds the skills and MCP servers of an Agent Plugins package (`readPlugin(readPluginDir(dir))`).
- byoa installs the pinned version of each harness in each sandbox, so a new pin reaches every user at their next job.
- If the client goes away, stop the loop (or call `return()` on the generator). byoa still ends the job token, takes the login out, and pauses or destroys the sandbox.

## When the plan is used up

Each plan has limits: Claude's and ChatGPT's 5-hour and weekly limits, Grok's plan limit, OpenCode Go's 5-hour, weekly and monthly limits. When the user's plan is used up, the job ends with an `error` of code `usage-limit`. Its `resetsAt` (ms since 1970) is when the plan resets, when the tool says: Claude Code and Codex say it, and for OpenCode Go byoa asks OpenCode's usage meter; Grok Build does not say it. `message` is the tool's own words.

```ts
if (ev.type === 'error' && ev.code === 'usage-limit') {
  show(ev.resetsAt ? `Your plan is used up. It resets at ${new Date(ev.resetsAt).toLocaleString()}.` : ev.message)
}
```

byoa keeps the used-up plan in the store, for that user and harness (with `plan: 'opencode-go'`, for that user and plan, with both harnesses), until `resetsAt`, or for 15 minutes when the tool did not say. Until then, a job of that user and harness ends at once with the same error, and starts no sandbox. To check before a job, with no sandbox:

```ts
const limit = await agents.usageLimit(userId, 'codex')   // undefined, or { message, resetsAt?, until }
if (limit) return show(`Your plan is used up until ${new Date(limit.until).toLocaleString()}.`)
```

A new sign-in (`finishLogin` that says `signed-in`), a new key (`connectKey`), `signOut`, and a job that works end it. One user's plan is one user's: an app that runs every visitor on one user's login (such as byoa's own help agent) gets one check for all of them.

`rate-limited` is a refusal for now: too many requests, or the lab is overloaded. byoa keeps nothing; try again in a moment. A login that the lab refuses is `expired`, as before.

byoa reads each CLI's own code first, and its words only when the code is missing: Claude Code's API error and its `rate_limit_event`, Codex's `codexErrorInfo` and its rate limits, Grok Build's `error_kind`. These checks use output in the shape that each pinned binary writes; no check has run a real plan out.

## What the agent may do

By default (`access: 'full'`), the agent has every tool of its harness, with no approval: a shell, file changes and the network. This is for a sandbox that is the job's alone. An app whose agent must only use its MCP tools, such as a to-do list or a mail client, gives the job `access: 'read-only'`:

```ts
agents.run(userId, { harness: 'codex', task, mcp: ['mail'], setup: { skills }, access: 'read-only' })
```

The agent can then call the job's MCP tools and read files, so the harness can still read its skills and AGENTS.md. It cannot change a file or reach the network by itself. byoa only sets each CLI's own options: Codex runs in its own sandbox with a read-only permission profile, which also denies its commands Codex's home folder (CODEX_HOME), where its login is, Claude Code gets only its tools that read, and Grok Build gets rules that deny its shell, file changes and web fetch (and its web search finds nothing); each tool a CLI refuses is a `permission` event or an error for the model. Apart from Codex's home folder, `read-only` does not hide files: the agent can read each file that its user can read, also Claude Code's and Grok Build's login files. Use it always with `localSandbox()` on a user's own computer, where the sandbox isolates nothing.

## Sandbox modes

| | Where a job runs | Jobs of one user and harness at the same time |
|---|---|---|
| `sandboxPer: 'user'` (the default) | the user's one kept sandbox for that harness, paused between jobs | one; the others wait in line, in the order they came |
| a `sandboxKey` for each job | one kept sandbox for each key, such as a project or a conversation, each with its own lease | one for each key |
| a `conversation` for each job | one kept sandbox for each conversation, whose `~/work` stays | one for each conversation |
| `sandboxPer: 'job'` | a new sandbox, destroyed after the job | all of them |

```ts
agents.run(userId, { harness: 'claude', task, sandboxKey: projectId })  // one kept sandbox for each project
const agents = createAgents({ ...options, sandboxPer: 'job' })          // a new sandbox for each job; default 'user'
```

A job waits in line with no time limit. To make it fail after a time, set `createAgents({ waitMs })`, for example on a short-lived backend such as a Convex action. [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md) shows each step of each mode, and what each provider does.

## Conversations

A job with a `conversation` id continues the harness's own session of the earlier jobs with that id, so the agent knows what the user said and what it did. Use your chat thread's id:

```ts
// the second job knows what the first was told
const chat = {
  harness: 'claude', conversation: chatId,
} as const
agents.run(userId, { ...chat, task: 'My name is Ann.' })
agents.run(userId, { ...chat, task: 'What is my name?' })
```

- The first job's `start` event has `resumed: false`, the next ones `resumed: true`. The `end` event has `session`, the harness's own session id.
- The conversation has its own kept sandbox (its id is the `sandboxKey`; give no other one), so its jobs run one at a time, and its `~/work` stays from job to job: the agent finds the files it wrote. byoa replaces only its own files there.
- byoa keeps a copy of the transcript, encrypted in your store, so the conversation goes on when the provider loses the sandbox. A transcript longer than `createAgents({ transcriptBytes })` (default 700 000 bytes) is not kept; then a lost sandbox loses the conversation, and the next job gives an `error` with code `conversation` and starts again.
- `agents.deleteConversation(userId, chatId)` deletes it, with its sandbox. [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md#what-carries-over-between-jobs) has what carries over between jobs.
- The harness must be the same for each job of a conversation: each harness has its own sessions.

### More messages while a job runs (steering)

`run` returns a `Job`. `job.send(message)` gives the running agent one more message, with each harness:

```ts
const job = agents.run(userId, { harness: 'codex', task, conversation: chatId })
for await (const ev of job) {
  if (ev.type === 'turn') show(ev.result)     // one turn ended; the agent now reads the next message
  if (ev.type === 'end') show(ev.result)      // the turn that answered the last message
}
// from another request of the user, while the job runs:
await job.send('Also add the dates.')         // true; false once the job ended
```

Codex and Grok Build take a message that comes during a turn into that turn: the agent reads it at its next step, and answers both in the same turn. Claude Code takes it when the turn ends, as the next turn. A message that comes after a turn ended starts the next turn. byoa uses only each CLI's own protocol, through a small driver script in the sandbox: Claude Code's stream-json input, Codex's app server (`turn/steer`) and Grok Build's Agent Client Protocol (`x.ai/interject`). Once the job ended, `send` returns false: send the message as the next job of the conversation.

## Jobs at the same time

Your app chooses how one user's agents run. It can mix the three ways:

```ts
// 1. A queue: jobs of one sandbox run one after the other, in the order they came
agents.run(userId, { harness: 'claude', task, onWait: ({ for: what, ahead }) => show(`${ahead} jobs before yours (${what})`) })

// 2. Several messages to one agent, which reads them all and decides the order itself
agents.run(userId, { harness: 'codex', task: ['water the plants', 'call mom', 'plan the week'] })

// 3. Several sandboxes at once: a sandbox key for each agent (or sandboxPer: 'job')
const jobs = projects.map((p) => agents.run(userId, { harness: 'codex', task, sandboxKey: p.id }))  // read each stream; they run together
```

- **A queue.** `onWait` gets `{ for, ahead }` each time the number of jobs ahead changes. `for` is `'sandbox'` while the job waits for its sandbox, and `'login'` while it waits for the AI login.
- **Several messages.** byoa gives the agent all of them in one task, with a line that tells it to read them all first and then decide the order. It is one job, in one sandbox.
- **Several sandboxes.** Jobs of one user in different sandboxes run at the same time with one sign-in, for every harness. They share the login while it is not due for a refresh. One risk stays, and `storedLogin({ parallel: false })` turns sharing off: see [AI login](https://byoa.rippling.computer/docs/ai-login.md#jobs-at-the-same-time-the-shared-login).

## Models and effort

`run(userId, { harness, task, model, effort })` runs the harness with that model and effort, with each CLI's own flags: Claude Code's `--model` (an alias such as `opus`, or a full name) and `--effort` (`low` to `max`), Codex's `-m` and `model_reasoning_effort`, Grok Build's `-m` and `--reasoning-effort`. Without them, a job gets the harness's default from `createAgents({ models })`, else the CLI's own.

```ts
const agents = createAgents({ ...options, models: { claude: { model: 'opus' }, codex: { effort: 'high' } } })

const models = await agents.listModels(userId, 'codex')   // [{ id: 'gpt-6.2-sol', isDefault: true, efforts: ['low', ...] }, ...]
agents.run(userId, { harness: 'codex', task, model: models[0].id, effort: 'high' })
```

`agents.listModels(userId, harness)` lists the models that the user's plan can use, as the CLI lists them with the user's login: `[{ id, name, description, isDefault, efforts, resolved? }]`. `id` is what `model` takes, and `efforts` what `effort` takes; `resolved` (Claude Code) is the full name of an alias. Each call starts a sandbox, so keep the list for a while. It throws `LoginError` when the harness is not signed in. With `session`, `s.args` has the flags for the job's model and effort, for your own command line.

A job on the user's OpenCode Go key (beta) passes `plan: 'opencode-go'` and a Go model; `listModels(userId, 'opencode-go')` lists them with no sandbox. See [AI login](https://byoa.rippling.computer/docs/ai-login.md#opencode-go-a-key-not-a-sign-in-beta).

## A program of your own around the harness

An app that runs its own program around the unmodified harness (for example its own server, which starts `claude`, `codex` or `grok` itself) opens the job with `agents.session` instead. It gets the same sandbox, login, pinned harness and job token, and runs its own command:

```ts
const s = await agents.session(userId, { harness: 'claude', mcp: ['notion'] })
try {
  // s.bin: the pinned claude binary; s.env: its login folder, the job token and its MCP start timeout; s.mcp: [{ name, url }] at the proxy
  await s.sandbox.run(`my-server --claude ${s.bin}`, { cwd: s.work, env: s.env })
} finally { await s.close() }  // ends the job token, takes the AI login out, and pauses the user's sandbox
```

`session` throws `LoginError` when the harness is not signed in, and `ProxyError` when the sandbox cannot reach the proxy.

## A harness outside byoa's sandboxes

A program outside byoa's sandboxes, such as a harness on the user's own computer, gets a job token with no sandbox: `const t = await agents.jobToken(userId, { mcp: ['notion'] })` gives `t.token` and `t.mcp` (the proxy URLs), with the same rules as a job's token, until `t.close()`. Send `t.token` as `Authorization: Bearer` to each `t.mcp[].url`.
