# byoa: the full docs > byoa, short for "bring your own agent", is the simplest way to let your users bring their own AI subscription to power the agents in your app. This file has the full text of byoa's docs, for LLMs: the docs pages (https://byoa.rippling.computer/docs), SPEC.md, the agent skill and the to-do example, from https://github.com/madeyexz/byoa (branch main). The index is https://byoa.rippling.computer/llms.txt. --- Source: https://byoa.rippling.computer/docs # byoa docs **byoa, short for "bring your own agent", is the simplest way to let your users bring their own AI subscription to power the agents in your app.** ## The future of AI-native apps AI-native apps are the future. But an app that buys its AI at API prices must pass that cost on to its users. So it must choose: a frontier model, and a high price for each user, or a cheap model, and a worse agent. AI subscriptions solve this. We bet on a future where everyone has a $20 AI plan, or the same in another form, and that plan powers every app they use. In that future, every app is AI-native, so nobody says "AI-native app" anymore. AI is like electricity, and an AI subscription is like a portable battery pack. Battery packs come in different sizes, and one pack powers all the appliances in your home. This is the economy we bet on. We build byoa to make it come sooner, so that every developer can build on it. Diagram: Where the power comes from and who pays for it. Today: the AI labs sell tokens to each app through its API key, and each app, such as a notes app, a mail app and your app, pays per token and puts that cost in its price. With byoa: each user owns one battery, their own AI plan, and it plugs into every app they use. Your app passes on only the cost of the sandbox. ## What byoa does Each user powers the agent features of your app with their own AI subscription: they sign in to it one time. Today byoa supports Claude (in Claude Code), ChatGPT (in Codex), Grok (in Grok Build) and OpenCode Go (beta), and more are coming soon. When your app has work for the AI, byoa runs that user's own Claude Code, Codex or Grok Build in a sandbox, with the user's tools, and streams the result back. The user's plan pays for the AI. Your app pays only for the sandbox. Diagram: Who brings what. Your app brings the product, the sandbox account, and one call: agents.run. Each user brings their AI plan, such as Claude, ChatGPT or Grok, and their tools, such as Notion or Gmail. byoa puts them together in a new sandbox for each job: it runs the user's own Claude Code, Codex or Grok Build with their tools, and streams the result back to your app. The user's plan pays for the AI. Your app pays only for the sandbox. byoa is an open-source library (Apache 2.0). It runs inside your app's own backend. It is not a hosted service. Start with [Getting started](https://byoa.rippling.computer/docs/getting-started.md). To learn the parts first, read the [Overview](https://byoa.rippling.computer/docs/concepts.md). To see which plans work, read [Supported AI subscriptions](https://byoa.rippling.computer/docs/subscriptions.md). ## What your users pay Your app passes its AI costs on to its users, in its price. So the real question is what each user pays for the same agent: - **Without byoa,** your app buys the AI at API prices. A frontier model gives a good agent and a high price. A cheap open-weight model gives a low price and a worse agent. - **With byoa,** each user brings the AI, on a plan that they already pay for and that powers every app they use. Your app passes on only the cost of the sandbox. Diagram: What each user pays a month for small agent tasks, when your app passes its AI costs on. With your API key, frontier models cost each user a lot, and cheaper models cost less for a weaker agent. With byoa, the user's own plan pays for a frontier model, and your app passes on only the sandbox. The numbers come from the cost tables in the FAQ. For 100 tasks for each user, a month: | How your app gets the AI | Each user pays a month | |---|---| | Your API key: Claude Opus 5.5 (frontier) | $49.00 | | Your API key: GPT-6.2 Sol (frontier) | $24.50 | | Your API key: Kimi K3 (frontier, open-weight) | $43.50 | | Your API key: DeepSeek V4.1 Flash (smaller, open-weight) | $2.97 | | byoa on E2B: the user's own plan, with a frontier model | $1.38 and their plan | | byoa on Daytona: the user's own plan, with a frontier model | $1.38 and their plan | | byoa on Instabox: the user's own plan, with a frontier model | $0.14 and their plan | These are estimates for a small agent task, from the [FAQ](https://byoa.rippling.computer/docs/faq.md#what-does-an-ai-job-cost-with-byoa-and-with-an-api-key). byoa does not make tokens cheaper: it moves them to the user's plan. The plan has limits, and a user who runs many long tasks reaches them. ## Why and when you need byoa You want your app to have an AI agent that does real work for each user: it reads and changes the user's data, calls the user's tools, and writes files. To build this yourself, you need many parts: - an agent loop as good as Claude Code, Codex or Grok Build, and its updates; - a sandbox for each user, which starts, pauses and ends at the right times; - a sign-in to each user's AI plan, and safe storage of that login; - an OAuth connection to each of the user's MCP tools, with the tokens kept out of the agent's reach. And with your own API key, your app buys every token at API prices, and your users pay for them in your price. byoa gives you all of these parts as one library, and the user's own plan pays for the AI. Diagram: Your backend, before and after. Build it yourself: your app, an agent loop, sandbox control, AI sign-in and login storage, and MCP OAuth and token storage, and an AI bill per token, at API prices. With byoa: your app and byoa, one npm install, and no AI bill, because the user's plan pays. Use byoa when: - your users already pay for Claude, ChatGPT, Grok or OpenCode Go, and you do not want to pay for their AI or sell them AI credits; - your app's AI work is agent work, with many steps, tools and files, not one chat answer; - you want Claude Code, Codex or Grok Build as your agent, not a loop of your own; - you want each user's tools, such as Notion or Gmail, in each job, after one connection. You do not need byoa when: - your app needs only one model call at a time, such as a summary or a chat reply: an API key costs less there ([FAQ](https://byoa.rippling.computer/docs/faq.md#what-does-an-ai-job-cost-with-byoa-and-with-an-api-key)); - your agent needs no shell and no files, so an agent loop of your own can run it without a sandbox, such as on AWS Lambda, and a cheap model is good enough for it; - your app pays for the AI itself and does not want the user's plan; - your users do not have an AI plan, or use the agent only a little: a few tasks on a cheap model at API prices cost them less than a $20 plan. These pages are the Markdown files in [docs/](https://github.com/madeyexz/byoa/tree/main/docs) of the repository. The site at https://byoa.rippling.computer/docs shows the same pages, and serves each page as Markdown for LLMs (add `.md` to its address) and all of them in [llms-full.txt](https://byoa.rippling.computer/llms-full.txt). ## Learn - [Overview](https://byoa.rippling.computer/docs/concepts.md): who brings what, what byoa is and is not, how a job runs, and why real tokens never go into the sandbox - [Getting started](https://byoa.rippling.computer/docs/getting-started.md): install byoa, make one `agents` object, serve its two routes, sign a user in and run a first job ## How it works - [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md): every sandbox byoa creates, from creation to removal, what carries over between jobs, what each provider does, and what byoa does when your backend dies - [MCP tools and the proxy](https://byoa.rippling.computer/docs/mcp.md): connect a user's MCP servers once, the proxy and job tokens, your app's own tools, and calls with a user's grant - [Security](https://byoa.rippling.computer/docs/security.md): where each secret is kept, and how to report a problem ## How to - [Sign users in](https://byoa.rippling.computer/docs/ai-login.md): the sign-in on the lab's own page, where the login stays between jobs, one job step by step, jobs at the same time with one login, the OpenCode Go key, and sign-out - [Give the agent tools](https://byoa.rippling.computer/docs/agent-tools.md): your app's own tools, the user's MCP servers, skills, AGENTS.md and plugins, which one to choose, and what the agent can do in its sandbox - [Run agents](https://byoa.rippling.computer/docs/running-agents.md): `agents.run` and its events, what the agent may do, sandbox modes, conversations and more messages to a running job, jobs at the same time, models and effort, `session` and `jobToken` - [Pick a sandbox provider](https://byoa.rippling.computer/docs/providers.md): E2B, Daytona, Instabox and the local sandbox, and how to write an adapter - [Store logins and grants](https://byoa.rippling.computer/docs/stores.md): the store adapter, Postgres, Convex, your own database, and a table of its own for the AI logins - [Test your app](https://byoa.rippling.computer/docs/testing.md): test your app with the fake harness, the local sandbox and the memory store, and run byoa's own tests ## Plans and rules - [Supported AI subscriptions](https://byoa.rippling.computer/docs/subscriptions.md): which Claude, ChatGPT, Grok and OpenCode Go (beta) plans your users can bring, and whether their accounts can get banned - [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md): what Anthropic's, OpenAI's, xAI's and OpenCode's terms allow, and what byoa and each app must do - [FAQ](https://byoa.rippling.computer/docs/faq.md): what byoa is, whether a user's AI account can get banned, many agents of one user, whether the agent remembers earlier jobs, models, and what an AI job costs with byoa and with an API key ## Reference - [API reference](https://byoa.rippling.computer/docs/api.md): every import, method, option and event --- Source: https://byoa.rippling.computer/docs/concepts # Overview **Your app brings the product. Each user brings the agent.** You build the app and pick the sandbox. Each user brings their plan and their tools. byoa runs inside your backend and runs each job in that user's own sandbox. Think of the user's AI subscription as a battery pack, and of your app as an appliance. The user brings the battery. byoa is the plug: it connects the user's plan, and the user's tools, to the agent features of your app. Your app supplies only the place where the agent runs, the sandbox. ## Who brings what Diagram: You build the app and import byoa. You pay only for the sandbox. Each user signs in with their own Claude, ChatGPT or Grok plan, which pays for the AI, and connects their tools once. Your app code calls agents.run. byoa is a library inside your app's backend, and keeps AI logins and MCP grants in your database. Below your backend's edge, byoa drives three things that run outside it: a new sandbox for each job at E2B, Daytona or Instabox on your account, where the user's own Claude Code, Codex or Grok Build runs; the AI labs, whose model calls the user's own plan pays; and the user's MCP servers, which get the real token from byoa's proxy. ```text DEVELOPER · YOU END USER ┌────────────────────────────────────┐ ┌────────────────────────────────────┐ │ builds the app │ │ uses the app │ │ picks the sandbox provider │ │ pays for the AI with a plan: │ │ owns the database │ │ Claude ChatGPT Grok │ │ pays only for the sandbox │ │ has MCP tools and skills │ └──────────────────┬─────────────────┘ └──────────────────┬─────────────────┘ │ imports byoa signs in on the lab's own page │ │ connects each MCP tool once │ ▼ ▼ ┌─ YOUR APP'S BACKEND · you run it ────────────────────────────────────────────────────────────┐ │ your app code your database │ │ │ agents.run(userId, task) ▲ AI logins, MCP grants │ │ ▼ │ │ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │ │ ┃ byoa · open source, Apache 2.0 ┃ │ │ ┃ AI login · harness skills · AGENTS.md MCP OAuth · proxy ┃ │ │ ┃ │ │ ┃ │ └─╂┄┄┄┄┄┄┄┄┄┄┄┄┄┄│┄┄┄┄┄┄┄┄┄┄┄ ▲ your backend · outside it ▼ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄│┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╂─┘ ┃ │ create · run · destroy real token │ ┃ ┃ ▼ ▼ ┃ ┃ ┌─ SANDBOX ────────────────┐ ┌─ AI LABS ────────────────┐ ┌─ MCP SERVERS ────────────┐ ┃ ┃ │ E2B, Daytona or │ │ Anthropic · OpenAI · xAI │ │ Notion · Gmail · … │ ┃ ┃ │ Instabox, │ │ │ │ │ ┃ ┃ │ on your account ├─▶│ model calls, paid by │ │ the user's own accounts │ ┃ ┃ │ runs the user's own │ │ the user's own plan │ │ │ ┃ ┃ │ Claude Code, Codex or │ │ │ │ │ ┃ ┃ │ Grok Build │ │ │ │ │ ┃ ┃ └──────────────────────────┘ └──────────────────────────┘ └──────────────────────────┘ ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` - **You, the developer**, build the app, pick the sandbox provider (E2B, Daytona or Instabox, on your own account) and own the database. You import byoa into your app's backend. - **The end user** uses your app. They have a Claude, ChatGPT or Grok plan, and accounts in tools such as Notion or Gmail. They sign in on the lab's own page one time, and connect each MCP tool one time. - **byoa** is a library in your backend. It keeps the user's AI login and MCP grants in your database, encrypted with your key. For each job, it gets a sandbox at your provider and runs the user's own, unmodified Claude Code, Codex or Grok Build there. - **The AI labs** (Anthropic, OpenAI) get the model calls. The user's own plan pays for them, not your API bill. - **The MCP servers** get the real token from byoa's proxy in your backend, never from the sandbox. ## The problem To make an app AI-native, you run a big lab's harness (Claude Code, Codex or Grok Build) in a sandbox, with the user's own AI plan. For each app, you must build the same connection layer again: - the user's AI login, through the real CLI; - the user's MCP connections and their OAuth tokens, with one refresh owner; - the user's skills and AGENTS.md; - the harness install and its updates; - the code that connects all of this to one sandbox provider. byoa is that layer, as a library, so you do not build it again for each app. ## What byoa is, and what it is not - byoa **is** a library. It runs inside your app's own backend (Node, Bun or Convex). Cloudflare Workers support is planned. - byoa **stores tokens in your own database**, through a store adapter. - byoa **is not** a hosted service. We do not run a server, and we never see your users' tokens. | | Version 1 | Later | |---|---|---| | Agents | Claude Code, Codex, Grok Build | Gemini or Antigravity, maybe | | User plans | Claude, ChatGPT, Grok, OpenCode Go key (beta) | | | Sandboxes | E2B, Daytona, Instabox | other providers | | Backends | Node, Convex actions | Cloudflare Workers | | Token stores | Convex, Postgres, or your own with get, put, delete and compare-and-set | | ## How a job runs Your app calls `agents.run(userId, task)`. byoa takes the user's sandbox, loads the user's setup, and runs the user's own harness on the user's own plan. The [sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md) has every step and every decision. Diagram: One job, from agents.run to the end event 1. Your app calls agents.run. `agents.run(userId, { harness, task, mcp, setup })`. 2. Take the user's sandbox. By default, resume the user's kept sandbox (a conversation has one of its own), or create it for the first job. With `sandboxPer 'job'`, create a new one. 3. Load the setup. The pinned harness, the skills, AGENTS.md, and an MCP config that points to your proxy with a job token. 4. Copy the AI login in. From your database, decrypted in your backend. Login files: login files in. 5. Run the harness. Text, tool calls and permission requests stream back as events. MCP calls go through the proxy. 6. close() This is the end. End the job token, save the login back if the CLI changed it, remove it from the sandbox, then pause or destroy the sandbox. Login files: files removed. The user's AI login and MCP grants stay in your database between jobs. A kept sandbox keeps the files that the app wrote there and the installed harness, but no login. A job of a conversation also continues the harness's session of the earlier jobs, and keeps the job folder ([what carries over](https://byoa.rippling.computer/docs/sandbox-lifecycle.md#what-carries-over-between-jobs)). ## Real tokens never go into the sandbox The agent in the sandbox gets a short-lived job token, for one job and one user. The proxy in your backend adds the real MCP token to each request. Diagram: How an MCP call from the sandbox gets the real token 1. The harness calls an MCP tool. Its MCP config points to your proxy, at `/`, with the job token. It has no real MCP token. 2. Question: Is the job token good for this server? If yes: go on to step 3. - If no: Refuse the call. This is the end. The job ended, or the job did not get this server. 3. Add the real token. From your database, encrypted with your key. byoa refreshes it when it is due, with one refresh owner. 4. Send the request on to the MCP server. This is the end. The answer goes back to the harness. The real token does not. [MCP tools and the proxy](https://byoa.rippling.computer/docs/mcp.md) has the details, and [AI login](https://byoa.rippling.computer/docs/ai-login.md) says where the user's AI login is at each step. --- Source: https://byoa.rippling.computer/docs/getting-started # Getting started New to byoa? Read the [Introduction](https://byoa.rippling.computer/docs/index.md) first. In short: byoa is a library in your app's backend. Each user signs in to their own Claude, ChatGPT or Grok plan one time, and connects each MCP tool one time. When your app has work for the AI, byoa runs that user's own Claude Code, Codex or Grok Build in a sandbox, with the user's tools, and streams the events back to your app. The user's plan pays for the AI, and your app pays for the sandbox. This page takes you from `npm install` to a first agent job: one `agents` object, two routes, a sign-in and a job. A new app needs fewer than 50 lines of its own code for this. The [to-do example](https://github.com/madeyexz/byoa/tree/main/examples/todo), a chat with the agent, uses byoa in 49. ## Install Install byoa from npm. Its package is `@madeyexz/byoa`, because npm does not allow the name `byoa`: ```sh npm install @madeyexz/byoa bun add @madeyexz/byoa ``` Also install the sandbox SDK that your app uses: `e2b` for E2B, `@daytona/sdk` for Daytona. Instabox and the local sandbox need none. byoa needs Node 22.18 or later, or Bun. To use the newest commit on `main` before it is released, install from GitHub: `npm install github:madeyexz/byoa`. ## Get a sandbox API key Your app pays for the sandboxes, so your app needs its own account and API key at one sandbox provider. Make an account, make a key, and put the key in your backend's environment. Do not send the key to the browser. - **E2B**: [sign up](https://console.e2b.dev/sign-up), then copy a key from [API keys](https://console.e2b.dev/?tab=keys). byoa reads `E2B_API_KEY`. The free plan gives $100 of credit one time and runs 10 sandboxes at a time; a paused sandbox does not count. A sandbox runs for 1 hour at most before it must pause, so one job can take at most 1 hour ([billing and limits](https://e2b.dev/docs/billing)). - **Daytona**: [sign up](https://app.daytona.io), then make a key in [API keys](https://app.daytona.io/dashboard/keys). byoa reads `DAYTONA_API_KEY`. A new account gets $200 of compute ([pricing](https://www.daytona.io/pricing)). On Tier 1 and 2, a sandbox can reach only [allowed domains](https://www.daytona.io/docs/en/network-limits). - **Instabox**: [sign up](https://dashboard.instabox.sh), then make a key in [API keys](https://dashboard.instabox.sh/dashboard/api-keys). byoa reads `INSTABOX_API_KEY`. The free plan has 1 sandbox in all, also when it is stopped, so it is enough for 1 user's kept sandbox or 1 job ([limits](https://instabox.sh/docs/account/limits)). ```sh export E2B_API_KEY=e2b_... ``` - With the variable set, `e2b()`, `daytona()` and `instabox()` read the key themselves. To give the key from somewhere else, such as your secret store, pass it: `e2b({ apiKey })`. - A Daytona key needs `write:sandboxes` and `delete:sandboxes`, and for `cliLogin` also `read:volumes`, `write:volumes` and `delete:volumes`. An Instabox key needs `machines:write` and `machines:delete`. - For development and tests, `localSandbox()` needs no key. It isolates nothing. See [Testing](https://byoa.rippling.computer/docs/testing.md). You need no AI key. Each user signs in to their own Claude, ChatGPT or Grok plan, and that plan pays for the AI. To compare the providers, see [Sandbox providers](https://byoa.rippling.computer/docs/providers.md). ## Make one `agents` object Make one `agents` object in your backend: once for each process, or once in each Convex action. ```ts import { createAgents } from '@madeyexz/byoa' import { e2b } from '@madeyexz/byoa/sandbox/e2b' import { postgresStore } from '@madeyexz/byoa/store/postgres' const agents = createAgents({ app: 'myapp', // one app's AI logins are only this app's sandbox: e2b(), // reads E2B_API_KEY store: postgresStore({ query: (sql, args) => pool.query(sql, args) }), encryptionKey, // openssl rand -base64 32; grants and AI logins are encrypted with it proxyUrl: 'https://myapp.example.com/byoa/mcp', // serve agents.proxy here oauth: { redirectUrl: 'https://myapp.example.com/byoa/callback' }, }) ``` - **`app`**: lower-case letters, digits and `-`, at most 24. It names the app's sandboxes and login volumes. - **`sandbox`**: the [sandbox provider](https://byoa.rippling.computer/docs/providers.md). To change the provider, change this one line. - **`store`**: your own database, through a [store adapter](https://byoa.rippling.computer/docs/stores.md). For Postgres, run `POSTGRES_SCHEMA` once. - **`encryptionKey`**: 32 random bytes as base64. Keep it the same between restarts, and keep it secret. - **`proxyUrl`**: a public HTTPS URL. The sandbox must reach it. In development, use a tunnel such as `cloudflared tunnel --url http://localhost:3000`. The default E2B template is named `byoa`, and a new E2B account does not have it. Build it one time with `buildE2BTemplate()`, or pass `e2b({ template: 'base' })`. See [Sandbox providers](https://byoa.rippling.computer/docs/providers.md#e2b). ## Serve two routes byoa's handlers are fetch handlers (`Request` → `Response`). On Node, wrap your app's handler with `toNodeListener` from `@madeyexz/byoa/node`. ```ts if (url.pathname.startsWith('/byoa/mcp/')) return agents.proxy(req) // the MCP proxy: no app session check here if (url.pathname === '/byoa/callback') { // the MCP server's sign-in page sends the browser here const p = url.searchParams await agents.finishMcp({ state: p.get('state') ?? '', code: p.get('code') ?? undefined, error: p.get('error') ?? undefined }) return Response.redirect(`${publicUrl}/`, 302) } ``` - The proxy checks the job token itself. Do not put your app's session check in front of it: the harness in the sandbox has no app session. - Every other route reads the user from your app's own session. The `userId` you give byoa is your app's stable user id. Never take it from a header or a body that the browser controls. ## Sign the user in to their plan The sign-in runs the unmodified CLI in a sandbox. The user signs in on the lab's own page. byoa gives your app only that page's URL and, for Codex and Grok Build, a code. See [AI login](https://byoa.rippling.computer/docs/ai-login.md) for each step. ```ts const claude = await agents.connectLogin(userId, 'claude') // { url }: Anthropic's own sign-in page await agents.finishLogin(userId, 'claude', { code }) // the code that page shows const codex = await agents.connectLogin(userId, 'codex') // { url, code }: OpenAI's page and the code to enter await agents.finishLogin(userId, 'codex', { waitMs: 20_000 }) // call again while the state is 'pending' await agents.cancelLogin(userId, 'codex') // the user closed the sign-in: its sandbox ends now const grok = await agents.connectLogin(userId, 'grok') // { url, code }: xAI's page and the code; finish as for Codex ``` The sign-in's sandbox lives only while your sign-in UI checks in: each `finishLogin` call keeps it for 2 more minutes. For Claude Code, call `finishLogin(userId, 'claude')` with no code about every 30 seconds while the user is on Anthropic's page. A user with an OpenCode Go plan (beta) gives a key instead: `agents.connectKey(userId, 'opencode-go', key)`. See [AI login](https://byoa.rippling.computer/docs/ai-login.md#opencode-go-a-key-not-a-sign-in-beta). ## Connect an MCP tool, one time ```ts const mcp = await agents.connectMcp(userId, 'https://mcp.notion.com/mcp', { name: 'notion' }) // mcp.signInUrl: the server's sign-in page; your redirectUrl route then calls agents.finishMcp({ state, code }) ``` Every later job of this user can have this server. Your app's own data needs no MCP server: give its tools to `createAgents` as functions. See [MCP tools and the proxy](https://byoa.rippling.computer/docs/mcp.md). ## Run a job ```ts for await (const event of agents.run(userId, { harness: 'claude', task, mcp: ['notion'], setup: { agentsMd, skills } })) { // start, text, tool_call, tool_result, permission, error, end: the same events for every harness } ``` `run` does not throw when a job fails. It gives `error` events, then always one `end` event. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md) for the events, what the agent may do, and jobs at the same time. ## Let a coding agent do it [skills/byoa](https://github.com/madeyexz/byoa/tree/main/skills/byoa) is a skill in the [Agent Skills](https://agentskills.io) format. It teaches a coding agent (Claude Code, Codex, Amp and others) to add byoa to an app: the install, `createAgents` with a store and a sandbox adapter, the sign-in, the MCP connections and their routes, `agents.run` and its events, and the lab rules. Its `metadata.version` is the `version` in byoa's package.json next to it. The npm package has the skill in it (from 1.1.0). After you install byoa, link the skill of the installed version into your app's repository for Claude Code, Codex, Amp, Cursor and others, so it always matches the package: ```sh npx skills experimental_sync -y ``` `experimental_sync` is a preview command of the [skills](https://github.com/vercel-labs/skills) CLI. Without it, or with byoa 1.0.0, install the skill of one release from its tag (here 1.1.0; use the tag of your version), or the skill of `main`: - one release: `npx skills add madeyexz/byoa@v1.1.0 --skill byoa` - `main`: `npx skills add madeyexz/byoa`, or for Amp `amp skill add madeyexz/byoa/skills/byoa` For LLMs, the site also serves the docs as [llms.txt](https://byoa.rippling.computer/llms.txt) (an index) and [llms-full.txt](https://byoa.rippling.computer/llms-full.txt) (the docs, SPEC.md, the example and the skill in one file), and each docs page as Markdown (add `.md` to its address). ## Next - Read the [Overview](https://byoa.rippling.computer/docs/concepts.md) to learn who holds what, and where. - Run the [to-do example](https://github.com/madeyexz/byoa/tree/main/examples/todo): an AI-native to-do list, with tests that use the fake harness. - Test your app with no plan and no sandbox: [Testing](https://byoa.rippling.computer/docs/testing.md). - Follow the [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md). Every app on byoa must. --- Source: https://byoa.rippling.computer/docs/sandbox-lifecycle # Sandbox lifecycle This page shows every sandbox byoa creates, from creation to removal, with the default `storedLogin()`. A sandbox has the user's login files only while a sign-in, a job or a sign-out runs. When your backend dies during a job, a watcher in the sandbox removes them. byoa creates four kinds of sandbox: - a **sign-in sandbox** for each sign-in, which byoa never keeps. It ends at `cancelLogin`, or 2 minutes after your app's last `finishLogin` check-in, 15 minutes at most ([AI login](https://byoa.rippling.computer/docs/ai-login.md#sign-in) shows its steps); - a **job sandbox**: by default one kept sandbox for each user, harness and `sandboxKey` (a conversation is a key of its own), paused between jobs; or, with `sandboxPer: 'job'`, a new one for each job; - a **sign-out sandbox**, for 5 minutes, where the CLI signs out ([AI login](https://byoa.rippling.computer/docs/ai-login.md#sign-out)); - a **models sandbox** for each `agents.listModels` call, where the CLI lists the models of the user's plan. byoa destroys it after the list, 10 minutes at most. ## The job sandbox Diagram: A job sandbox, from the start of a job to its end Kept for the user (default): `sandboxPer: 'user'`: byoa keeps one sandbox for each slot, pauses it after a job and resumes it for the next. 1. Pick the user's slot. One for each user, harness and `sandboxKey` (an empty key when none; a conversation's id is its key). `usersandbox////`. Login files: no login files. 2. Question: Does another job run in this slot? If no: go on to step 3. - If yes: Wait in line. The jobs run in the order they came. `onWait` gets `{ for: 'sandbox', ahead }`. Time limit: no limit, unless waitMs. 3. Question: Does the slot have a sandbox? If yes: go on to step 4. If no: see "Create a new kept sandbox" below. 4. Resume it. Time limit: job + 1 min. 5. Question: Does the provider still have it? If yes: go on to step 6. - If no: Create a new kept sandbox. Also when it was gone (SandboxGoneError). Time limit: job + 1 min. Then go on to step 6. 6. Prepare the work folder. `~/work`: nothing of an earlier job stays. In a conversation, the agent's files stay and only byoa's own files are new; in a new sandbox, byoa writes the conversation's stored transcript back. 7. Question: Is the user signed in? a stored login exists. If yes: go on to step 8. - If no: Stop with LoginError. This is the end. The state becomes 'signed-out'. close() still runs. 8. Check the MCP servers, install the pinned harness. 9. Copy the login in. Takes the login lease, decrypts the files, writes them, chmod 600, and writes a loan record. If a dead job's loan record is there, it first saves what that job's CLI left. Starts the watcher. Time limit: waits in line for the lease; lease: job + 5 min; watcher: job + 45 s. Login files: login files in. 10. The harness runs. The CLI may refresh its login and write its files again. byoa saves a change about every 60 s. Login files: login files in. - If backend dies: Warning: If your backend dies here. close() never runs. The watcher removes the files at job + 45 s. See below. 11. close(): save back, remove the files, give the lease back. Ends the job token. Saves the files only if they changed, with compare-and-set. Removes the loan record. In a conversation, keeps the session id and a copy of its transcript, encrypted. Login files: files removed. 12. Question: Did byoa remove the files? any error here counts as no. If yes: go on to step 13. - If no: Destroy it, forget its id. This is the end. The next job of this slot creates a new one. 13. Pause it for the next job. This is the end. E2B: pause. Daytona, Instabox: stop. New for each job: `sandboxPer: 'job'`: byoa creates a sandbox for one job and destroys it after. 1. Create a new sandbox, not kept. A new work folder. Time limit: job + 1 min. Login files: no login files. 2. Question: Is the user signed in? a stored login exists. If yes: go on to step 3. - If no: Stop with LoginError. This is the end. The state becomes 'signed-out'. close() still runs. 3. Check the MCP servers, install the pinned harness. 4. Copy the login in. Takes the login lease, decrypts the files, writes them, chmod 600. Starts the watcher. Time limit: waits in line for the lease; lease: job + 5 min; watcher: job + 45 s. Login files: login files in. 5. The harness runs. The CLI may refresh its login and write its files again. byoa saves a change about every 60 s. Login files: login files in. - If backend dies: Warning: If your backend dies here. close() never runs. The watcher removes the files at job + 45 s, and the provider deletes the sandbox at job + 1 min. 6. close(): save back, remove the files, give the lease back. Ends the job token. Saves the files only if they changed, with compare-and-set. Removes the loan record. Login files: files removed. 7. Destroy the sandbox. This is the end. "Job" is `jobTimeoutMs`, 30 minutes by default. byoa gives each job sandbox job + 1 minute. - **One kept sandbox per user (the default).** The first job of a user and harness creates it. After each job, byoa pauses it, and the next job resumes it, so files that the app wrote there and the installed harness stay. Each job gets a new job folder (`s.work`) with its own setup. One job of a slot runs at a time; the others wait in line and run in the order they came, with no time limit unless you set `waitMs`. When the provider no longer has the sandbox, the next job creates a new one. - **Many kept sandboxes per user.** Give each job a `sandboxKey`, such as a project or a conversation. Each key has its own kept sandbox and its own lease. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md#jobs-at-the-same-time) for the ways to run one user's jobs at the same time. - **A conversation.** Give each job of a chat the same `conversation` id. The conversation has its own kept sandbox, and the agent continues its own session there. See [What carries over between jobs](#what-carries-over-between-jobs). - **A new sandbox for each job.** Set `sandboxPer: 'job'` in `createAgents`. Use it when nothing may stay between jobs. In all three, the user's AI login and MCP grants stay in your database. No real MCP token goes into the sandbox, a job token is refused after its job, and no copy of the AI login stays in the sandbox between jobs. ## What carries over between jobs "Resume" can mean two things. byoa does both: - **Resume the sandbox.** byoa starts the user's paused sandbox again for the next job. The files outside `~/work` and the installed harness are still there. This happens in every kept sandbox. - **Resume the conversation.** Only for a job that names a `conversation`. The harness continues its own session, so the agent knows the earlier messages and what it did. Each CLI does this its own way: Claude Code `--session-id`, then `--resume`; Codex's app server keeps the thread, then resumes it (`thread/resume`); Grok Build's agent mode names a session, then resumes it (`session/resume`). While a job runs, it also takes more messages (`job.send`, see [Running agents](https://byoa.rippling.computer/docs/running-agents.md#more-messages-while-a-job-runs-steering)). | | A job with no `conversation` | A job of a `conversation` | |---|---|---| | The agent's memory of earlier jobs | none: each job is a new session | the harness's session of the earlier jobs | | `~/work` (the job folder) | emptied at the start of each job | kept; only byoa's files (skills, AGENTS.md, the MCP config, the task) are new | | Files outside `~/work`, the installed harness | kept in a kept sandbox | kept: the conversation has its own kept sandbox | | The AI login | never kept in the sandbox: a copy for each job | the same | | When the provider lost the sandbox | a new sandbox | a new sandbox, with the stored copy of the transcript, so the agent still remembers; `~/work` and the other files are gone | After each job of a conversation, byoa keeps the harness's session id and a copy of its session files (the transcript), encrypted in your store, when they are at most `transcriptBytes` (default 700 000 bytes). A longer transcript lives only in the sandbox: when the provider loses that sandbox, the next job says so (an `error` with code `conversation`) and starts a new session. With `sandboxPer: 'job'`, each job of a conversation gets a new sandbox and resumes only from the stored copy. ## When your backend dies during a job `close()` never runs. byoa still loses little, and no login stays in the sandbox: Diagram: A job whose backend dies, with the default storedLogin 1. The job runs. About every 60 s, byoa saves what the CLI changed in its login (a checkpoint), with compare-and-set. The loan record `ailoginloan///` names the stored version this sandbox has. Login files: login files in. 2. Warning: Your backend dies. The checkpoints stop. The CLI may still refresh its login in the sandbox. 3. The watcher removes the login files. The watcher started when the login was copied in. It removes the files only if no later job replaced its marker. Time limit: job + 45 s. Login files: files removed. 4. The provider pauses or ends the sandbox. Kept: E2B pauses it at job + 1 min; Daytona stops it. New for each job: the provider deletes it. See the table below. Time limit: job + 1 min. 5. The slot and the login lease run out. So the user's next job does not wait forever. Time limit: job + 5 min. 6. Question: Does the next job in this kept sandbox find the dead job's loan record? Only with `sandboxPer: 'user'`. If yes: go on to step 7. - If no: Copy the stored login in, as for any job. This is the end. 7. Save what the dead job's CLI left, then copy the login in. This is the end. Only when the stored login has not changed since the loan, and the files are the same account's login and not older. Else the stored login stays. Login files: login files in. - A refresh that the CLI made more than about a minute before your backend died is already saved. Only a refresh in the last minute before the watcher ran can be lost; then the user may have to sign in again. - byoa saves files from a sandbox only when they are the same account's login and not older than the stored one, because the agent of a job can change any file. - A job's waiting place in line also runs out about 30 s after its backend dies, so the jobs after it go on. - The slot's lease: until its harness starts, a job renews it every minute, so a job that waits long for the login keeps its sandbox; from the harness's start it lasts the job timeout + 5 minutes. So the lease of a dead job runs out at most the job timeout + 5 minutes after its backend died. - The job's time starts when it has the login, not when it resumed the sandbox: then byoa sets the sandbox's time again (E2B, and Daytona for a sandbox of one job) and starts the watcher. So a job that waited in line for the login still gets its whole time, and the watcher still runs before the provider pauses the sandbox. ## How each provider pauses and times out | | E2B | Daytona | Instabox | |---|---|---|---| | After a job, a kept sandbox is | paused, with no process of the job kept | stopped | stopped (not Instabox's pause) | | A kept sandbox whose time ends (your backend died) | pauses at job + 1 min | stops after job + 1 min with no activity | has no time limit; pauses itself after 30 min with no activity (default) | | A sandbox that is not kept (sign-in, sign-out, models, new for each job) | killed at its time | deleted when it stops, at the latest after its time | deleted after its time, whatever its state | | A sign-in with no check-in | ends 2 min after the last `finishLogin` | ends 2 min after the last `finishLogin` (whole minutes) | ends after 15 min: Instabox cannot change a sandbox's time after it starts | | Resume after it paused itself | byoa ends any old process first | started again; no old process runs | byoa resumes, stops and starts it, so no old process runs | | A paused kept sandbox stays | with no time limit | until archived, after 7 days stopped | with no time limit | | Volumes for `cliLogin` | yes, when volumes are on for your team | one shared volume, a subpath for each login | none: use `storedLogin()` | ## Removal - `agents.signOut(user, h)` deletes the user's kept sandboxes for that harness, then signs out ([AI login](https://byoa.rippling.computer/docs/ai-login.md#sign-out)). - `agents.deleteSandbox(user, { harness?, sandboxKey? })` on its own destroys each matching kept sandbox. A job in it ends. The login, the MCP grants and the conversations' stored transcripts stay. - `agents.deleteConversation(user, conversation?)` deletes a conversation (or all of the user's): its stored session and transcript, and its kept sandbox. Call it when the user deletes a chat, and with no id when you delete the user. When you delete a user, call `agents.deleteSandbox(userId)`; when you delete a project that had a key, `agents.deleteSandbox(userId, { sandboxKey: projectId })`. - Nothing else removes a paused kept sandbox. --- Source: https://byoa.rippling.computer/docs/mcp # MCP tools and the proxy The user connects each MCP tool one time, and every agent run that your app gives it has it. The real tokens stay in your database. The agent in the sandbox gets only a job token for your proxy. ## Connect a server, one time for each user ```ts // A server with its own sign-in (MCP authorization, OAuth 2.1 with PKCE) const c = await agents.connectMcp(userId, 'https://mcp.notion.com/mcp', { name: 'notion' }) if (!c.connected) return Response.json({ signInUrl: c.signInUrl }) // send the browser there; it comes back to /byoa/callback // A server that takes a token the user pasted await agents.connectMcp(userId, 'https://mcp.example.com/mcp', { name: 'tasks', bearer: token }) await agents.listMcp(userId) // [{ name, url }] await agents.removeMcp(userId, 'notion') ``` - `name`: lower-case letters, digits and `-`, at most 32. A job asks for servers by this name. - The URL must be `https://` (or `http://` on localhost). With `bearer`, byoa checks the token with one MCP `initialize`, and throws if the server refuses it. - byoa uses Client ID Metadata Documents when the server supports them (serve `agents.clientMetadata()` at `oauth.clientMetadataUrl`), and Dynamic Client Registration only when it does not. - The server's sign-in page sends the browser to your `oauth.redirectUrl` route, which calls `agents.finishMcp({ state, code, error })`. It finds the user from the stored `state`, so that route needs no session. A sign-in that does not finish in 15 minutes runs out; call `connectMcp` again. - byoa refreshes each grant itself, with one refresh owner: your backend. Two jobs that need a refresh at the same time cause one refresh request. Do not refresh or read the tokens in your app's code. ## The proxy and job tokens Serve `agents.proxy` at `proxyUrl` and at every path below it (`/`). It is a fetch handler. For each job, byoa writes an MCP config in the sandbox that points to the proxy, with a job token for that one job and one user. - The proxy checks the job token, adds the user's real token, and sends the request on to the MCP server. - It refuses a job token after the job ends, and for a server that the job did not get. - Do not put your app's session check in front of it. Each of its answers has the header `x-byoa-proxy: 1`. - No real MCP token is in the sandbox's environment, files or processes at any time. A test checks this after each job with a real MCP call ([V5](https://github.com/madeyexz/byoa/blob/main/SPEC.md#verification)). The same proxy is also the relay of a job on the user's OpenCode Go key (beta), at `/_plan/opencode-go/…`: it checks the job token, adds the user's key, and sends only the model requests on to OpenCode. So do not filter the paths below `proxyUrl`. See [AI login](https://byoa.rippling.computer/docs/ai-login.md#opencode-go-a-key-not-a-sign-in-beta). A job gets only the servers that your app names in its `mcp`. A server in `mcp` that the user has not connected gives an `error` event with code `mcp`, and the job runs without it. ## When the proxy is down Before the harness starts, byoa checks from the job's sandbox that each MCP server of the job answers through `agents.proxy`. When the sandbox cannot reach the proxy (a wrong `proxyUrl`, a tunnel that ended, a firewall), the job does not start: `run` gives an `error` event with code `mcp` and ends with `ok: false`, and `session` throws `ProxyError`. A server that does not answer gives an `error` event with code `mcp`, and the job runs. Without this check, a harness that cannot reach a server leaves its tools out and still ends well. ## Your app's own tools Give your app's own tools to `createAgents` as functions (`tools`): MCP server name → tool name → `{ description, input, run }`. `input` is the JSON Schema of the arguments. A job gets them by the server's name in `mcp`, as it gets a connected server. The harness calls them through `agents.proxy`, which checks the job token and calls `run(args, { user, job })` in your backend, for the user of that job. So you write no MCP server, keep no token for it, and connect nothing for each user. What `run` returns goes to the agent (a string as it is, other values as JSON); when it throws, the agent gets the message as a failed call. byoa does not check the arguments against `input`: check them in `run`. ```ts const agents = createAgents({ ...options, tools: { todos: { add_todo: { description: 'Add one to-do.', input: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }, run: ({ title }, { user }) => db.addTodo(user, String(title)), }, list_todos: { description: "List the user's to-dos.", run: (_args, { user }) => db.todos(user) }, }, }, }) agents.run(userId, { harness: 'codex', task, mcp: ['todos'] }) ``` ## Move a grant into byoa To move an MCP grant that the user already made elsewhere into byoa, call `agents.importMcp(userId, { name, url, oauth })` with the MCP SDK's state (`client`, `tokens`, `at`). Delete the old copy, so that the grant keeps one refresh owner. ## Call a service's other API with the user's grant Some MCP servers have an API next to the MCP endpoint that is not MCP, such as an export. Your backend calls it with the user's grant through `agents.fetchWithGrant(userId, 'tasks', 'https://mcp.example.com/export')`: byoa adds the current token, refreshed by the one refresh owner, and gives you the response. By default, it sends the token only to the origin of that grant's MCP server. It does not follow redirects, and never gives you the token. When the service's API is on another origin than its MCP server, name that origin in your own configuration, for the MCP server's origin. Only grants of that MCP server can go there, and only to that exact origin: ```ts const agents = createAgents({ ...options, // Margins' MCP server is on margin.rippling.computer; its export is on its Convex site grantOrigins: { 'https://margin.rippling.computer': ['https://helpful-tern-930.convex.site'] }, }) const r = await agents.fetchWithGrant(userId, 'margins', 'https://helpful-tern-930.convex.site/ext/export') ``` The MCP server, the sandbox and the user cannot add an origin. Each one is an exact origin: https, no path, no wildcard. --- Source: https://byoa.rippling.computer/docs/security # Security This page is [SECURITY.md](https://byoa.rippling.computer/docs/security.md) of the repository. byoa handles your users' AI logins and their MCP tokens. A bug in byoa can give an attacker access to a user's Notion, Gmail or AI plan. Please tell us about each security problem that you find. ## Report a problem - Do not open a public issue, pull request or discussion. - Use GitHub's private report: go to the **Security** tab of this repository and click **Report a vulnerability**. - Tell us what the problem is, how to make it occur, and what an attacker can get. - Do not put a real user's tokens or data in the report. Use test accounts. We will reply within 7 days. We will tell you when we fix the problem, and we will give you credit if you want it. ## Supported versions We fix security problems in the latest release on npm (`@madeyexz/byoa`). ## Where secrets are kept This is how byoa must keep each secret (see [SPEC.md](https://github.com/madeyexz/byoa/blob/main/SPEC.md)). If byoa does not do this, it is a security problem. | Secret | Where it is | Where it must never be | |---|---|---| | The user's Claude or ChatGPT login | By default in the app's own database, encrypted with a key that the app gives (R1.4), or as an option in a volume of that one user (R1.5); in a sandbox only while a sign-in, a job or a sign-out runs | In a sandbox between jobs, in another app, or with us | | MCP grants (access and refresh tokens) | In the app's own database, encrypted with a key that the app gives (R2.4) | In the sandbox (R3.3), in logs, or with us | | Job token | In the sandbox's `mcp.json`, for one job and one user (R3.1) | Valid after the job ends (R3.4) | | A conversation's transcript (the harness's own session files) | In the conversation's kept sandbox, and a copy in the app's own database, encrypted with a key that the app gives (R5.9) | In the store without encryption, or in another user's sandbox | The real MCP token goes only from the app's backend to the MCP server, through the proxy (R3.2). byoa is not a hosted service, so we never get your users' tokens. ## What we count as a security problem For example: - A real MCP token is in the sandbox's environment, files or processes (V5). - The proxy accepts a job token after its job ends (V6), or for a different user. - byoa keeps a copy of a user's AI login in a sandbox between jobs, stores it without encryption, or one app can use another app's login. - Two refreshes at the same time revoke a grant, or byoa sends a refresh request from a place other than the app's backend (R2.3). - byoa stores a grant or a conversation's transcript without encryption, or writes a token to a log. - byoa runs a `claude` or `codex` binary that is not the published one (V11). ## What is not ours Report these to their owners: - Bugs in a sandbox provider (E2B, Daytona, Instabox), in Claude Code or Codex, or in an MCP server. - Bugs in an app that uses byoa, for example a leaked encryption key or a database that is open to the internet. The app must keep its encryption key secret and keep the proxy in its own backend. --- Source: https://byoa.rippling.computer/docs/ai-login # AI login A user's AI login stays encrypted in your app's database, and is in a sandbox only while a sign-in, a job or a sign-out runs. This page shows how byoa signs a user in to Claude Code, Codex and Grok Build, keeps the CLI's own login files, and uses them for each job. An OpenCode Go plan (beta) has no sign-in: the user gives a key, which never goes into the sandbox ([below](#opencode-go-a-key-not-a-sign-in-beta)). | The login tokens are in | They are never in | |---|---| | the sign-in sandbox, until byoa destroys it | what byoa returns to your app | | your app's database, encrypted | the job's environment variables | | a job's sandbox, only while the job runs | a kept sandbox between jobs | | | the state, lease, line and loan entries in the store | This is for the default login, `storedLogin()`. With `cliLogin`, the tokens stay in the user's volume instead of the database. byoa never uses the tokens itself and never calls the labs' token endpoints. The unmodified CLI is the only client that sends them to the lab. ## Sign-in Your app calls `agents.connectLogin(user, harness)`. byoa starts a new sandbox, installs the pinned CLI and runs its own sign-in. The user signs in on the lab's page. byoa gives your app only that page's address and, for Codex and Grok Build, a code. The sign-in sandbox lives only while your sign-in UI checks in. Each `finishLogin` call keeps it for 2 more minutes. A sign-in lasts 15 minutes at most, as long as Codex's device code (Grok's code lasts at least 9 minutes). | | Claude Code | Codex | Grok Build | |---|---|---|---| | The CLI's sign-in | `claude auth login` | `codex login --device-auth` | `grok login --device-auth` | | What your app shows | a link on claude.com | a link on auth.openai.com, and a one-time code | a link on accounts.x.ai, and a one-time code | | What the user does | signs in; Anthropic's page shows a code | enters the code on OpenAI's page | enters the code on xAI's page | | How your app finishes | `finishLogin(user, 'claude', { code })` with that code; byoa types it into the CLI and waits up to 60 s | `finishLogin(user, 'codex', { waitMs })`, again until the state is no longer `pending` | the same as Codex, with `'grok'` | | How your app checks in | `finishLogin(user, 'claude')` with no code, about every 30 s while the user is on Anthropic's page; it answers `pending` | each `finishLogin` call; keep `waitMs` short, such as 20 s | the same as Codex | | When the user closes the sign-in | `cancelLogin(user, 'claude')` | `cancelLogin(user, 'codex')` | `cancelLogin(user, 'grok')` | | The files the CLI writes | in `~/.claude` (`CLAUDE_CONFIG_DIR`): `.credentials.json` (the tokens) and `.claude.json` (the account: email, organization, plan) | in `~/.codex` (`CODEX_HOME`): `auth.json` (access token, refresh token, last refresh time) | in `~/.grok` (`GROK_HOME`): `auth.json` (the tokens and the time they end) | Claude Code also writes a copy of `.claude.json` in `backups/` at each start. byoa removes it and does not store it. Diagram: The sign-in sandbox, from connectLogin to the signed-in state 1. Remove an unfinished earlier sign-in. `connectLogin(user, h)` destroys this user's earlier sign-in sandbox for the harness, if one waits. Login files: no login files. 2. Create the sign-in sandbox. storedLogin: no volume. cliLogin: the user's volume at `~/.claude`, `~/.codex` or `~/.grok`. Time limit: 15 min at most. 3. Install the pinned CLI and start its sign-in. `claude auth login`, `codex login --device-auth` or `grok login --device-auth`, in the background. 4. Question: Is the lab's page shown within 30 s? If yes: go on to step 5. - If no: Destroy it, and throw an error. This is the end. Also when the CLI exits at once. 5. The user signs in on the lab's page. Your app shows the link, and the code of Codex or Grok Build. From now on, the sandbox lives only while your app checks in. Time limit: 2 min after the last check-in. 6. Your app calls finishLogin. Claude Code: with the code from Anthropic's page, byoa types it in; with no code, the call only checks in. Each call keeps the sandbox 2 more minutes. Time limit: waits: Claude with a code 60 s, else waitMs (default 0) 7. Question: Has the CLI ended? If yes: go on to step 8. - If no: Answer 'pending'. The sandbox keeps running. Time limit: until 15 min. Then call again: back to step 6. 8. Question: Did the CLI write its token file? Login files: login files in. If yes: go on to step 9. - If no: Destroy it, and return the CLI's error. This is the end. For example, a wrong code. 9. Keep the login. storedLogin: byoa encrypts the files into `ailogin//`. cliLogin: they stay in the volume. 10. Destroy the sandbox. The state is 'signed-in'. This is the end. `login//`. Login files: no login files. - **The user closes the sign-in.** Call `agents.cancelLogin(user, harness)`. byoa destroys the sign-in sandbox at once. Nothing happens when no sign-in runs. `signOut` and a new `connectLogin` for the same user and harness also end an unfinished sign-in. - **Your app stops calling `finishLogin`** (the user left, or your backend died). On E2B and Daytona, the provider ends the sandbox 2 minutes after the last check-in, with any login files in it. Instabox cannot change a sandbox's time after it starts, so there an unfinished sign-in ends after 15 minutes, unless you call `cancelLogin`. - `finishLogin` after the sandbox is gone, or after 15 minutes, answers "the sign-in ran out; start it again". - The to-do example's `page.html` checks in, and sends `cancelLogin` when the user closes the sign-in or the page. - The state (`agents.loginState(user, h)`) is `signed-in`, `signed-out` or `expired`, with no token in it. ## Where the login stays between jobs | | In your app's database (the default, `storedLogin()`) | In a volume of the user (`cliLogin`) | |---|---|---| | How it gets there | byoa reads the CLI's files from the sign-in sandbox and encrypts them together with AES-256-GCM, with your `encryptionKey` or the key you give `storedLogin`. The entry's name is part of the encryption, so the entry cannot be moved to another user. | The sign-in sandbox mounts the user's volume at `~/.claude` or `~/.codex`, and the CLI writes its files there. | | Where it is | one entry for each user and harness, `ailogin//`, as `v1..`. It is the only copy between jobs. | the volume `byoa---`, with the files as the CLI wrote them | | In a job | byoa copies the files in and takes them out again (below). | Every job sandbox of that user and harness mounts the same volume. byoa never reads or copies the files. The store keeps only the state. | | Providers | all | providers with volumes: E2B (when volumes are on for your team) and Daytona, not Instabox | To keep the logins in a table of their own, with a key of their own, so that you can give them their own access rules and backups, see [Stores and Convex](https://byoa.rippling.computer/docs/stores.md#a-table-of-its-own-for-the-ai-logins). To use the volume, pass `login: cliLogin` (from `@madeyexz/byoa`). The labs' published terms limit where these tokens may be stored. Each app checks them: see [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md). ## One job, step by step This is a job with the default `storedLogin()`. First byoa checks that the store has the user's login. If it does not, the job stops with `LoginError` (in `run`, an `error` event with code `signed-out`) and the state becomes `signed-out`. `close()` runs steps 4 to 7, also when the job failed. 1. **Take the lease.** Two sandboxes must not refresh one login at the same time, because the CLIs rotate their refresh tokens. byoa writes the lease `ailoginlease//` with compare-and-set. By default, the jobs of one user and harness share the lease while the login is not due for a refresh (see [Jobs at the same time](#jobs-at-the-same-time-the-shared-login)). When a job must wait, it waits in line, in the order the jobs came (`ailoginline//`), and `onWait` gets `{ for: 'login', ahead }`. It waits with no time limit, unless you set `storedLogin({ waitMs })`. The lease ends by itself after the job timeout + 5 minutes, so a lost backend does not lock it. 2. **Copy the login in.** byoa decrypts the entry in your backend and writes the files into the job's sandbox, `chmod 600`. It remembers which version of the entry it read, and writes a loan record for this sandbox (`ailoginloan///`). It also starts a watcher in the sandbox: at the job timeout + 45 s, the watcher removes the login files, before the provider pauses the sandbox at the job timeout + 1 minute. `CLAUDE_CONFIG_DIR` or `CODEX_HOME` points the CLI at the files: a folder path, not a token. 3. **The CLI runs, and may refresh.** The unmodified CLI uses its tokens to reach the lab. When its access token is due, it refreshes it and writes its own files again. About every 60 s, byoa saves what the CLI changed (a checkpoint), as in step 4. 4. **Save back what changed.** If the files changed, byoa encrypts them and writes them over the entry, only if the entry is still the version from step 2 (compare-and-set). If the user signed in again meanwhile, the newer entry stays. byoa saves files from a sandbox only when they are the same account's login and not older than the stored one, because the agent can change any file. 5. **Remove the files.** byoa deletes the login files, Claude's backups and the loan record. If it cannot delete the files, it destroys the sandbox instead of keeping it. 6. **Give the lease back.** The next job of this user and harness can take it. This also happens when step 4 or 5 fails. 7. **Pause or destroy the sandbox.** With `sandboxPer: 'user'` (the default), byoa pauses the user's kept sandbox for the next job, with no login in it. With `'job'`, it destroys the sandbox. With `cliLogin` there is no lease and no copy. The volume is mounted in the job's sandbox, the CLI refreshes the files in place, and byoa saves nothing back and removes nothing. When your backend dies during step 3, `close()` never runs. The watcher, the checkpoints and the loan record then keep the login safe and up to date: [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md#when-your-backend-dies-during-a-job) shows how. ## Jobs at the same time: the shared login By default, the jobs of one user and harness share the login, for Claude Code, Codex and Grok Build. Each job gets its own copy in its own sandbox (a `sandboxKey` for each job, or `sandboxPer: 'job'`), and the jobs run at the same time. Jobs in one sandbox still run one after the other: see [Running agents](https://byoa.rippling.computer/docs/running-agents.md#jobs-at-the-same-time). Diagram: How a job takes the shared login 1. Question: Will the CLI refresh the login before this job could end? Within the lease time, the job timeout + 5 min. If no: go on to step 2. - If yes, or not known: Hold the login alone. The job marks that it waits, so no new job joins. When the sharing jobs end, it takes the lease alone. The CLI refreshes, step 4 saves the new login, and the jobs after it share again. Time limit: lease: { alone: { id, until } }, after want. 2. Share the login. This is the end. The job adds itself to the lease's shared list and gets its own copy of the login. More jobs can join. Time limit: lease: { shared: { job1: until, job2: until } }. - To answer the question, byoa reads only the time the access token ends from the login files, and no token: `expiresAt` in Claude Code's `.credentials.json`, the token's `exp` in Codex's `auth.json`, `expires_at` in Grok Build's `auth.json`. The CLIs refresh about 5 minutes before their access token ends. Claude Code's token lasts 8 hours, Codex's 10 days, Grok Build's 6 hours. When Codex's `auth.json` has no such time, byoa uses 8 days after the last refresh. When byoa cannot tell, the answer is yes. - If two sharing jobs both save a change, the first save wins (step 4). - One risk stays: the CLIs also refresh when the lab answers 401 to a token that has not run out. If two sandboxes get that answer at the same time, both refresh, one refresh fails, and the user may have to sign in again. - To hold the login one job at a time instead, pass `login: storedLogin({ parallel: false })`. ## OpenCode Go: a key, not a sign-in (beta) **Beta.** No real OpenCode Go key has run this yet. byoa's tests use a stand-in for OpenCode's API, with the real Claude Code and Codex, locally and on E2B. The real check ([V20](https://github.com/madeyexz/byoa/blob/main/SPEC.md#verification)) has not run. OpenCode Go is OpenCode's subscription. byoa uses it as a plan, not a harness: it does not run the `opencode` CLI. It gives open models and others, such as Kimi, GLM, DeepSeek, Qwen and MiniMax, and the job still runs the unmodified `claude` or `codex`. There is no sign-in page. The user creates an API key in [OpenCode's Console](https://opencode.ai/console) (`oc_sk_…`), and your app gives it to byoa one time: ```ts const r = await agents.connectKey(userId, 'opencode-go', key) // { state: 'signed-in' }; or 'no-plan', or an error const models = await agents.listModels(userId, 'opencode-go') // the plan's models, from OpenCode's API: no sandbox agents.run(userId, { harness: 'codex', plan: 'opencode-go', model: 'kimi-k3.1-pro', task }) ``` Diagram: A job on the user's OpenCode Go key 1. Your app gives byoa the key, one time. `connectKey(user, 'opencode-go', key)`. byoa checks the key with OpenCode and keeps it encrypted in your store, as it keeps MCP grants. 2. A job runs with plan 'opencode-go'. The unmodified Claude Code or Codex, with a Go model, and a config folder with no lab login. Claude Code gets `ANTHROPIC_BASE_URL`; Codex gets a model provider for this job only. 3. The harness sends its model requests to your proxy. To `/_plan/opencode-go/…`, with the job token. Only the model APIs go through, and only during the job. 4. The proxy adds the key and sends them on to OpenCode. This is the end. With the harness's own user agent and session id, as OpenCode asks. The key never goes into the sandbox. - **A model of the plan.** A job with a plan needs a Go model: `model` in `run`, or `createAgents({ models: { 'opencode-go': { model } } })`. `listModels(userId, 'opencode-go')` lists them from OpenCode's API with the user's key, with no sandbox. The free models (`…-free`) are not in the list: OpenCode serves them only to its own client. - **States.** `loginState(userId, 'opencode-go')` is `signed-in`; `expired` when OpenCode refuses the key (401: a wrong, revoked or expired key; the user makes a new one); or `no-plan` when the key's workspace has no Go plan (403). A job that gets one of these from OpenCode gives an `error` event with that code. When OpenCode answers 429 and its usage meter says that a limit is used up, the job's error is `usage-limit`, with the meter's `resetsAt` ([When the plan is used up](https://byoa.rippling.computer/docs/running-agents.md#when-the-plan-is-used-up)). `signOut(userId, 'opencode-go')` deletes the key. - **Jobs at the same time.** A key does not rotate, so a user's jobs with it run at the same time, with no lease. - **Terms.** OpenCode's terms say the user uses its services "only for your own internal use, and not on behalf of or for the benefit of any third party". A job with the user's own key for the user's own task is arguably that, but it is not clearly allowed. Ask OpenCode (help@anoma.ly) before your app offers it. See [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md). Sources: [OpenCode Go](https://opencode.ai/docs/console/go), [OpenCode Terms of Use](https://opencode.ai/legal/terms-of-service). ## Sign-out `agents.signOut(user, harness)` deletes the user's kept sandboxes for this harness, signs out with the CLI so that the lab can revoke the login, and deletes the login. Diagram: Sign-out, with the default storedLogin 1. Destroy the user's kept sandboxes for this harness. `signOut(user, h)` calls `deleteSandbox(user, { harness: h })`. A job in one of them ends. Login files: no login files. 2. Question: Is a login stored? `ailogin//`. If yes: go on to step 3. - If no: Skip the CLI sign-out. Then go on to step 5. 3. Sign out with the CLI in a new sandbox. Takes the login lease alone, writes the files in, and runs `claude auth logout`, `codex logout` or `grok logout`, so that the lab can revoke the login. If this fails, byoa goes on. Time limit: 5 min; not kept; waits in line for the lease. Login files: login files in. 4. Destroy it, give the lease back. Login files: no login files. 5. Delete the stored login. The state is 'signed-out'. This is the end. `ailogin//` is deleted. With `cliLogin`, sign-out also destroys an unfinished sign-in sandbox, signs out in a sandbox that mounts the user's volume, and deletes the volume. --- Source: https://byoa.rippling.computer/docs/agent-tools # Give your agent tools The agent in each job is the user's own Claude Code, Codex or Grok Build. You decide what it can do in that job: which tools it can call, what it knows, and what it may do in its sandbox. This page shows each way, and which one to choose. | The agent needs | Give it | Where it runs | Who connects it | |---|---|---|---| | your app's own data and actions (to-dos, mail, documents) | [your app's tools](#your-apps-own-tools), as functions in `createAgents({ tools })` | in your backend | nobody: the job token says which user | | a service where the user has an account (Notion, Gmail) | [the user's MCP server](#the-users-mcp-servers), with `connectMcp` once | at the service | the user, one time | | to know how to do a task, or your app's rules | [skills and AGENTS.md](#skills-and-agentsmd), in `setup` | files in the sandbox | nobody | | skills and MCP servers as one package | [a plugin](#plugins) (Agent Plugins 1.0), in `plugins` | files, and the user's servers | the user, for each server | | a shell, files, packages and the network | [the sandbox itself](#what-the-agent-can-do-in-its-sandbox), with `access: 'full'` | in the sandbox | nobody | Name the tools of each job in its `mcp`. A job gets only the servers that you name, and none by default. ## Which one to choose Diagram: Which way gives the agent an ability 1. Question: Is it your app's own data or action? If no: go on to step 2. - If yes: Your app's own tools. This is the end. `tools: { todos: { add_todo: { description, input, run } } }`, and `mcp: ['todos']` in the job. 2. Question: Does the user have an account at a service with an MCP server? If no: go on to step 3. - If yes: The user's MCP server. This is the end. `connectMcp(user, url, { name })` once, and `mcp: ['notion']` in each job. 3. Question: Is it knowledge, a how-to or a rule, not an action? If no: go on to step 4. - If yes: A skill or AGENTS.md. This is the end. `setup: { agentsMd, skills }`. The harness reads them from the job folder. 4. Question: Does it need a shell, files, packages or the open network? If no: go on to step 5. - If yes: The sandbox, with access: 'full'. This is the end. The default. The agent installs and runs what it needs in its own sandbox. 5. Write it as one of your app's tools. This is the end. An API that your backend can call becomes a function in `tools`. The agent then calls it through the proxy, and your backend keeps every key. Keep secrets out of the sandbox. A key that a tool needs stays in your backend, in the tool's `run` or in the user's grant. Never put a token in `setup`, the task, the environment or a file: the agent can read everything in its sandbox. ## Your app's own tools Give your app's tools to `createAgents` as functions: MCP server name → tool name → `{ description, input, run }`. A job gets a group by its name in `mcp`, as it gets a connected server. You write no MCP server, keep no token for it, and connect nothing for each user. ```ts const agents = createAgents({ ...options, tools: { todos: { add_todo: { description: 'Add one to-do.', input: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }, run: ({ title }, { user }) => db.addTodo(user, String(title)), }, list_todos: { description: "List the user's to-dos.", run: (_args, { user }) => db.todos(user) }, }, }, }) agents.run(userId, { harness: 'codex', task, mcp: ['todos'] }) ``` Diagram: A call to one of your app's tools 1. The agent calls todos.add_todo. The harness sends an MCP `tools/call` to `/todos`, with the job token. 2. Question: Is the job token good, and did the job get todos? If yes: go on to step 3. - If no: Refuse the call. This is the end. The job ended, or its mcp did not name todos. 3. run(args, { user, job }) in your backend. `user` is the job's user, from the token. Never take the user from the arguments. 4. Question: Did run throw? If no: go on to step 5. - If yes: The agent gets a failed call. This is the end. With the error's message. The agent can try again or tell the user. 5. The agent gets the result. This is the end. A string as it is, and any other value as JSON. - `input` is the JSON Schema of the arguments, which the harness shows to the model. byoa does not check the arguments against it: check them in `run`. - Write a `description` that says when to use the tool. The model reads it to choose. - Names: a server is lower-case letters, digits and `-`, at most 32; a tool is letters, digits, `_` and `-`, at most 64. - Give a job only the groups it needs. A to-do job gets `todos`, not your billing tools. ## The user's MCP servers The user connects a service one time, and each job that you give it can use it. The real token stays in your database, and the proxy adds it to each call. [MCP tools and the proxy](https://byoa.rippling.computer/docs/mcp.md) has the sign-in routes and the details. ```ts const c = await agents.connectMcp(userId, 'https://mcp.notion.com/mcp', { name: 'notion' }) if (!c.connected) return Response.json({ signInUrl: c.signInUrl }) // the browser comes back to your redirectUrl route agents.run(userId, { harness: 'claude', task, mcp: ['notion', 'todos'] }) ``` Diagram: A call to the user's MCP server 1. The agent calls notion.search. To `/notion`, with the job token. The sandbox has no Notion token. 2. Question: Is the job token good, and did the job get notion? If yes: go on to step 3. - If no: Refuse the call. This is the end. 3. Take the user's grant. From your database, decrypted in your backend. byoa refreshes it first when it is due, with one refresh owner. 4. Send the call on to Notion's MCP server. This is the end. With the real token. The answer goes back to the agent; the token does not. A server in `mcp` that the user has not connected gives an `error` event with code `mcp`, and the job runs without it. Before the harness starts, byoa checks from the sandbox that each server answers through the proxy ([When the proxy is down](https://byoa.rippling.computer/docs/mcp.md#when-the-proxy-is-down)). ## Skills and AGENTS.md A skill teaches the agent how to do one kind of task, in the [Agent Skills](https://agentskills.io) format: a folder with a `SKILL.md` and any files it needs. AGENTS.md has the rules for every task of the job, such as your app's voice or what the agent must not do. ```ts agents.run(userId, { harness: 'claude', task, mcp: ['todos'], setup: { agentsMd: 'You are the to-do assistant of Acme. Change only the to-dos that the user asks about.', skills: [{ name: 'weekly-review', files: { 'SKILL.md': weeklyReviewSkill } }], }, }) ``` byoa writes them into a new job folder, where each harness reads them: ```text ~/work the job folder, new for each job ├── AGENTS.md setup.agentsMd ├── CLAUDE.md the same text, for Claude Code ├── .claude/skills// the skills, for Claude Code ├── .agents/skills// the skills, for Codex and Grok Build ├── .codex/config.toml Codex's MCP config: each server at the proxy, with the job token ├── .grok/config.toml Grok Build's MCP config: the same (it reads the folder with --trust) └── .byoa/ ├── mcp.json Claude Code's MCP config: the same └── task.md the task ``` ## Plugins A plugin in the Agent Plugins 1.0 format is a folder with `plugin.json`, `skills//` and `mcp.json`. Read it with `readPlugin(readPluginDir(dir))` (`readPluginDir` from `@madeyexz/byoa/node`), and give it to a job in `plugins`: ```ts import { readPlugin } from '@madeyexz/byoa' import { readPluginDir } from '@madeyexz/byoa/node' const plugin = readPlugin(readPluginDir('./plugins/research')) agents.run(userId, { harness: 'codex', task, plugins: [plugin] }) ``` - The job gets the plugin's skills, and each of its MCP servers through the user's grant of the same name. So the user connects each server with `connectMcp` under that name; byoa never gives the plugin's URL to the harness, only the proxy's. - Only Streamable HTTP servers load. A stdio server would run inside the sandbox with no proxy, so byoa skips it and lists it in `plugin.skipped`. ## What the agent can do in its sandbox With `access: 'full'` (the default), the agent has every tool of its harness, with no approval: a shell, file changes and the network. So it can install a package, run a script, clone a repository or call a public API, in a sandbox that is the job's alone. - **Files stay in a kept sandbox.** With the default `sandboxPer: 'user'`, files that the agent writes outside `~/work` are there in the user's next job. The job folder `~/work` is new each time. With `sandboxPer: 'job'`, nothing stays. See [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md). - **Results come back as events.** The agent's answer is the `end` event's `result`, and its tool calls are `tool_call` and `tool_result` events. To get a file out, give the agent a tool that saves it, such as `save_report` in your `tools`, or open the job with `agents.session` and read the file yourself with `s.sandbox.run`. - **Limit it with `access: 'read-only'`** when the agent needs only its MCP tools, such as in a mail client. It can then call the job's MCP tools and read files, but not change a file or reach the network by itself. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md#what-the-agent-may-do). --- Source: https://byoa.rippling.computer/docs/running-agents # 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`. --- Source: https://byoa.rippling.computer/docs/providers # Sandbox providers Each sandbox provider is one adapter with one interface. Version 1 has E2B, Daytona and Instabox, and a local sandbox for development and tests. To change the provider, change the adapter that you give `createAgents`: ```ts import { e2b } from '@madeyexz/byoa/sandbox/e2b' const agents = createAgents({ ...options, sandbox: e2b({ apiKey }) }) // or daytona({ apiKey }), instabox({ apiKey }) ``` `e2b()`, `daytona()` and `instabox()` read their API key from `E2B_API_KEY`, `DAYTONA_API_KEY` or `INSTABOX_API_KEY` when you give none. The sandbox must reach your `proxyUrl`. [Sandbox lifecycle](https://byoa.rippling.computer/docs/sandbox-lifecycle.md#how-each-provider-pauses-and-times-out) compares how each provider pauses and times out. | | E2B | Daytona | Instabox | Local | |---|---|---|---|---| | Import | `@madeyexz/byoa/sandbox/e2b` | `@madeyexz/byoa/sandbox/daytona` | `@madeyexz/byoa/sandbox/instabox` | `@madeyexz/byoa/sandbox/local` | | Package to install | `e2b` | `@daytona/sdk` | none | none | | Between jobs, a kept sandbox is | paused | stopped | stopped | a folder | | Volumes for `cliLogin` | yes, when volumes are on for your team | one shared volume, a subpath for each login | none: use `storedLogin()` | folders | | A sign-in with no check-in ends | 2 min after the last `finishLogin` | 2 min after the last `finishLogin` | after 15 min (no keepAlive) | 2 min after the last `finishLogin` | | Network | every public domain | Tier 1 and 2: allowed domains only | every public domain | this computer | ## E2B Use `e2b({ apiKey?, template?, timeoutMs? })`. It needs the `e2b` package. - The default template is named `byoa`, and a new E2B account does not have it: the first job then fails with `404: template 'byoa' not found`. Build it one time for each pin change with `buildE2BTemplate()`, or pass `e2b({ template: 'base' })`. Any template with Node 20 or later works: byoa then installs the pinned harness in each new sandbox (about 10 seconds). - `pause` ends the sandbox's processes, then takes a full snapshot, with the memory: the next job's resume takes about 0.3 seconds, and node and the harness start warm. When E2B refuses it, because it still saves the sandbox's previous snapshot, byoa takes a snapshot of the files only; the next resume then boots the sandbox again and reads its disk cold, which can add 10 to 20 seconds. E2B keeps a paused sandbox with no time limit, and charges no compute for it. - A kept sandbox that times out (a crash, a lost network) is paused, not killed. When byoa resumes a sandbox that paused itself, it ends any old process first. ## Daytona Use `daytona({ apiKey?, client?, snapshot?, volume?, timeoutMs? })`. It needs `@daytona/sdk`. - `pause` stops the sandbox, and `resume` starts it, also from archived (more slowly). A kept sandbox is not ephemeral and has no time to live; Daytona archives it after 7 days stopped. A sandbox for one job is ephemeral: Daytona deletes it when it stops, and at the latest after its time. - Daytona allows 100 volumes for each organization, so with `cliLogin` the adapter keeps every user's AI login in its own subpath of one shared volume (`byoa` by default). A sandbox mounts only that user's subpath. - On Daytona Tier 1 and Tier 2, a sandbox can reach only [allowed domains](https://www.daytona.io/docs/en/network-limits), so serve `agents.proxy` on one of them (for example `*.convex.site`), or use Tier 3 or higher. `*.workers.dev` is on Daytona's list but does not work: a Worker's address has two labels below it (`..workers.dev`), and Daytona does not resolve those. ## Instabox Use `instabox({ apiKey?, apiUrl?, template?, snapshot?, timeoutMs? })`. It calls Instabox's HTTP API itself, so it needs no package. - Each sandbox starts from the `agent-browser` template (Node 22, user `user`, home `/data/home`), or from a snapshot that you name (`snapshot`). - byoa stops the user's sandbox after each job (not Instabox's pause), so the next job starts it again with its files and no process of the last one. A sandbox that paused itself (idle for 30 minutes, or at the plan's longest run) is booted again. A sandbox for one job is deleted after it, and at the latest at its `timeoutMs`. - byoa gives a sandbox none of your account's Vault items or org Secrets, and leaves its commands out of Instabox's command history, which would otherwise keep their output (and so the AI login that byoa reads back). - Instabox has no volumes, so `cliLogin` does not work there; the default stored login does. Instabox sandboxes reach every public domain, so a tunnel works for `proxyUrl`. - On the free plan, a workspace has one sandbox in all, also when it is stopped (so one user with one kept sandbox, or one job), and three starts a minute (byoa waits when Instabox answers 429). A run starts with 2 hours before Instabox pauses the sandbox, and grows to 8 hours at most while the sandbox is in use ([limits](https://instabox.sh/docs/account/limits)). ## The local sandbox `localSandbox({ root?, volumes?, env? })` is folders on this computer. It isolates nothing: use it only for development and tests, and with `access: 'read-only'` for a harness on a user's own computer. On macOS, the Codex sign-in works in it; the Claude Code sign-in needs Linux. ## Write an adapter An adapter implements one interface ([src/sandbox/types.ts](https://github.com/madeyexz/byoa/blob/main/src/sandbox/types.ts)): create (with volumes), resume, run a command, write a file, pause, destroy, delete a volume, and optionally read a file, set a running sandbox's time again (`Sandbox.setTimeout`), `capabilities`, and keepAlive (a new end time for a sandbox that is not kept: byoa uses it to end a sign-in 2 minutes after the app's last check-in). ```ts interface SandboxProvider { readonly name: string readonly capabilities?: { volumes: boolean } // optional; false: create refuses a volume, and createAgents refuses cliLogin create(opts?: { volumes?: { name: string; path: string }[]; labels?: Record; timeoutMs?: number; keep?: boolean }): Promise resume(id: string, opts?: { timeoutMs?: number }): Promise // starts a paused one; throws SandboxGoneError when it is gone destroy(id: string): Promise // by id, running or paused deleteVolume(name: string): Promise keepAlive?(id: string, ms: number): Promise // optional: a sandbox that is not kept ends ms from now (the sign-in's check-ins) } ``` - `keep: true` is a sandbox that byoa keeps for the user. When it times out, the provider must pause it instead of deleting it, and no process of that job may run when it resumes. - A provider with no volumes refuses `create` with volumes, and says `capabilities: { volumes: false }`. - `run` resolves for a non-zero exit code, and with exit code 137 for a command that runs out of its `timeoutMs`; it does not throw. - `Sandbox.readFile(path)` (optional) reads a file through the provider's file API, or gives null. byoa reads the login files and a conversation's transcript with it; without it, byoa reads them as base64 on a command's output, which a provider may keep in its command history. - `Sandbox.setTimeout(ms)` (optional) sets the provider's time of a running sandbox again, `ms` from now, as `timeoutMs` at create: then a kept sandbox pauses, and another one ends. byoa calls it when a job has the user's AI login, so the time the job waited in line for the login does not count. - `test/helpers/conformance.ts` in byoa's repository checks what byoa needs of an adapter: run it on yours, as `test/fake.test.ts` does for the local one. - The [API reference](https://byoa.rippling.computer/docs/api.md#sandbox-adapter) has the `Sandbox` interface. --- Source: https://byoa.rippling.computer/docs/stores # Stores and Convex byoa keeps its state in your own database, through a store adapter: MCP grants, AI logins (by default), login states, sandbox slots and leases, and conversations (the harness's session id and a copy of its transcript). Grants, AI logins and conversations are encrypted with your `encryptionKey`. ## The store adapter A store is four methods. byoa ships one for Postgres, one for Convex and one in memory for tests. For another database, write your own. ```ts interface Entry { value: string; version: string } interface Store { get(key: string): Promise put(key: string, value: string): Promise // writes whatever is there delete(key: string): Promise cas(key: string, version: string | null, value: string): Promise // null: only if no entry; true if it wrote } ``` The version must change on every write, and a key that is deleted and written again must never get an earlier version back. The one refresh owner of each grant, the login lease and the sandbox slots depend on `cas`. The to-do example's `sqliteStore` in [examples/todo/todos.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todos.ts) is one in 19 lines. ## The keys byoa writes Every key is in one file, [src/keys.ts](https://github.com/madeyexz/byoa/blob/main/src/keys.ts). The values marked sealed are encrypted with your `encryptionKey`, with the key as associated data; the others hold no secret. `` and the sandbox key are URL-encoded. | Key | What it holds | |---|---| | `grant//` | sealed: one MCP grant | | `grants/` | the names and URLs of the user's grants | | `lease//` | the lease of the one refresh of a grant | | `mcpflow/` | sealed: an MCP sign-in that has not come back yet | | `job/`, `jobid/` | a job token, by its hash, and its hash by the job id | | `login//`, `loginjob//` | the state of a lab login; a sign-in that runs now | | `ailogin//` | sealed: the CLI's own login files | | `ailoginlease/…`, `ailoginline/…`, `ailoginloan/…` | who holds the login, the jobs that wait for it, and the sandboxes that have a copy | | `aikey//`, `aikeystate//` | sealed: a plan's key; its state | | `usersandbox////` (and `…/line`) | a kept sandbox: its id and the lease of its job; the jobs that wait for it | | `usersandboxes//` | the user's kept sandboxes | | `conversation///` | sealed: a conversation's session id and its transcript (at most `transcriptBytes`) | | `conversations/` | the user's conversations | A conversation's transcript can be large: with the default `transcriptBytes` (700 000) one entry stays below a Convex document's 1 MiB. Postgres has no such limit. ## Postgres ```ts import { postgresStore, POSTGRES_SCHEMA } from '@madeyexz/byoa/store/postgres' await pool.query(POSTGRES_SCHEMA) // once; or postgresSchema('my_table') const store = postgresStore({ query: (sql, args) => pool.query(sql, args) }) ``` ## Convex In a Convex app, byoa's state is one table and four internal functions in your deployment (`@madeyexz/byoa/store/convex`). Call byoa from actions and HTTP actions, which can make network calls; serve `agents.proxy` from an HTTP action. ```ts // convex/schema.ts import { convexTable } from '@madeyexz/byoa/store/convex' export default defineSchema({ ...yourTables, byoa: convexTable() }) // convex/byoa.ts import { convexFunctions } from '@madeyexz/byoa/store/convex' export const { get, put, remove, cas } = convexFunctions() // in an action or HTTP action import { convexStore } from '@madeyexz/byoa/store/convex' const agents = createAgents({ ...options, store: convexStore(ctx, internal.byoa) }) ``` A Convex action has a time limit, and a job waits in line with no limit by default, so set `waitMs` shorter than the action's limit. On Daytona Tier 1 and 2, `*.convex.site` is an allowed domain for the proxy. ## A table of its own for the AI logins To keep the logins in a table of their own, with a key of their own, so that you can give them their own access rules and backups: ```ts import { createAgents, storedLogin } from '@madeyexz/byoa' // Convex: convex/schema.ts has byoaLogin: convexTable(), and convex/byoaLogin.ts has // export const { get, put, remove, cas } = convexFunctions('byoaLogin') const loginStore = convexStore(ctx, internal.byoaLogin) // Postgres: run postgresSchema('byoa_ai_login') once const loginStore = postgresStore({ query, table: 'byoa_ai_login' }) const agents = createAgents({ ...options, login: storedLogin({ store: loginStore, encryptionKey: loginKey }) }) ``` To keep each login in a volume of that user and app instead, behind the sandbox adapter, pass `login: cliLogin` (from `@madeyexz/byoa`). Your database then never holds the login. This needs a provider with volumes; see [AI login](https://byoa.rippling.computer/docs/ai-login.md#where-the-login-stays-between-jobs). ## Tests Use `memoryStore()` from `@madeyexz/byoa`. See [Testing](https://byoa.rippling.computer/docs/testing.md). --- Source: https://byoa.rippling.computer/docs/testing # Testing ## Test your app without a plan or a sandbox Use `harness: 'fake'`, `localSandbox()` from `@madeyexz/byoa/sandbox/local` and `memoryStore()` from `@madeyexz/byoa`. The fake harness runs no model and needs no login. It reads the same MCP config Claude Code would, and calls MCP tools through the real proxy: each task line `call . ` is one call. So a test proves your app's routes, grants and proxy end to end. ```ts import { createAgents, memoryStore } from '@madeyexz/byoa' import { localSandbox } from '@madeyexz/byoa/sandbox/local' // serve agents.proxy at http://127.0.0.1:3000/byoa/mcp, as in Getting started const agents = createAgents({ app: 'myapp-test', sandbox: localSandbox(), store: memoryStore(), encryptionKey, proxyUrl: 'http://127.0.0.1:3000/byoa/mcp', oauth: { redirectUrl: 'http://127.0.0.1:3000/byoa/callback' }, tools: { todos: todoTools }, }) for await (const ev of agents.run('u1', { harness: 'fake', task: 'call todos.add_todo {"title":"milk"}', mcp: ['todos'] })) { if (ev.type === 'end') assert.ok(ev.ok) } ``` - The fake harness shows the task's first line as one `text` event and skips the other lines. The last call's output is the `end` event's `result`. - In a `conversation`, the fake harness keeps each task in a session file and says how many earlier messages it remembers (`fake harness remembers 1 earlier messages: `), so you test your app's conversations with no model. - With the local sandbox, `proxyUrl` can be `http://127.0.0.1:/byoa/mcp`. - Copy [examples/todo/todo.test.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todo.test.ts). Do not offer `fake` to end users in production. ## Test byoa itself - `npm test` runs V10, V12, the fake-harness tests and the unit tests. `npm run test:v11` runs V11; it downloads about 600 MB. CI runs both on every commit. - `npm test` never starts a paid sandbox, also when the providers' keys are set: each paid check needs its own flag. `npm run test:daytona` checks the Daytona adapter against Daytona and runs V8 there. It needs `DAYTONA_API_KEY`, and with `BYOA_DAYTONA_VOLUMES=1` also checks its volumes; that needs a key with the volume permissions. `npm run test:v4` runs V4 ([test/v4.test.ts](https://github.com/madeyexz/byoa/blob/main/test/v4.test.ts)) with `E2B_API_KEY` and `DAYTONA_API_KEY`; it needs `cloudflared` to give the proxy a public URL. On a Daytona org on Tier 1 or 2, also set `BYOA_V4_RELAY` to a relay on an allowed domain, such as [test/relay](https://github.com/madeyexz/byoa/blob/main/test/relay/convex/http.ts) deployed to a temporary Convex project. - `npm run test:e2b` checks the E2B adapter against E2B and runs V8 there (a user's jobs in one paused and resumed sandbox, and `sandboxPer: 'job'`). It needs `E2B_API_KEY`, and with `BYOA_E2B_VOLUMES=1` also checks volumes, for an E2B team with volumes turned on. - `npm run test:instabox` does the same on Instabox. It needs `INSTABOX_API_KEY`. `BYOA_V4_PROVIDERS=e2b,instabox` runs V4 on E2B and Instabox. - Each of these adapter tests first runs the conformance check, [test/helpers/conformance.ts](https://github.com/madeyexz/byoa/blob/main/test/helpers/conformance.ts); `npm test` runs it on the local sandbox. - `node scripts/v21.ts` runs V21 (conversations and steering with real logins on E2B) in steps, because a person signs in: `login claude|codex|grok`, then `check`, then `cleanup`, which signs out and deletes the sandboxes. It needs `E2B_API_KEY`. - `spec/tla/check.sh` runs V22: TLC checks the TLA+ models of the job lifecycle, the login lease, the sign-in and the store indexes ([spec/tla](https://github.com/madeyexz/byoa/blob/main/spec/tla/README.md)). It needs Java 11 or later, and downloads TLC the first time. CI runs it when the models or the code they model change. The checks V1 to V22 are in [SPEC.md](https://github.com/madeyexz/byoa/blob/main/SPEC.md#verification). --- Source: https://byoa.rippling.computer/docs/subscriptions # Supported AI subscriptions Your users bring an AI subscription that they already pay for. byoa runs it in the lab's own, unmodified CLI: Claude Code, Codex or Grok Build. | Subscription | Plans that work | Can the user's account get banned? | |---|---|---| | [Claude](https://claude.com/pricing), in Claude Code | Pro, Max, Ultra, Team and Enterprise. Not Free. | It can. Anthropic's terms forbid apps to store Claude logins, and Anthropic may act without notice. | | [ChatGPT](https://chatgpt.com/codex/pricing), in Codex | Plus, Pro, Business, Enterprise and Edu. Not Free or Go. | It can. OpenAI's terms want the login kept where the user controls it, and paid or hosted apps must apply to be partners. | | [Grok](https://x.ai/grok), in Grok Build | SuperGrok and X Premium+ | Unclear. xAI's terms forbid sharing an account and "unauthorized automated" access, and say nothing about apps that run Grok Build for their users. | | [OpenCode Go](https://opencode.ai/docs/console/go) **(beta)**, in Claude Code or Codex | Go, Go Plus and Go Teams | It can. OpenCode's terms say "only for your own internal use". | Why, and what to do before you launch: [Can my user's AI account get banned?](https://byoa.rippling.computer/docs/faq.md#can-my-users-ai-account-get-banned) - **Claude, ChatGPT and Grok:** the user signs in on the lab's own page. See [AI login](https://byoa.rippling.computer/docs/ai-login.md). - **OpenCode Go (beta):** the user gives a key from OpenCode's Console, and the key never goes into the sandbox. No real Go key has run it yet. See [AI login](https://byoa.rippling.computer/docs/ai-login.md#opencode-go-a-key-not-a-sign-in-beta). - **Prices and limits:** the labs change them often, so read their own pages, linked in the table. ## What every plan has in common - **The user's plan limits apply.** A job uses the same allowance as the user's own chats and coding: the five-hour and weekly limits are shared. When the user is at a limit, the CLI refuses, and the job ends with an `error` event. - **One plan for each harness.** A user can sign in to each of them, and each job names its harness: `harness: 'claude'`, `'codex'` or `'grok'`. A job on the user's OpenCode Go key also names `plan: 'opencode-go'`. - **The login belongs to your app.** A login that a user made in your app is only for your app. Another app on byoa needs its own sign-in. See [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md). - **The labs' terms apply.** The labs restrict where an app may store the login, and OpenAI asks paid or hosted apps to apply to be partners. Read [the FAQ](https://byoa.rippling.computer/docs/faq.md#can-my-users-ai-account-get-banned) before you launch. ## What byoa does not support - **API keys.** byoa signs in only with a plan. The one key it takes is the user's OpenCode Go key, which is a plan's key. An app that wants to pay for the AI with its own API key does not need byoa for the login. - **Other labs' plans,** such as Gemini or Kimi memberships. byoa runs only Claude Code, Codex and Grok Build in version 1. Gemini or Antigravity may come later. OpenCode is also an agent itself (the `opencode` CLI), but byoa does not run it in version 1: an OpenCode Go plan runs in Claude Code or Codex. - **Sharing one login between apps.** The labs do not allow it, and byoa keeps each app's logins apart (`app` in `createAgents`). --- Source: https://byoa.rippling.computer/docs/lab-rules # Lab rules byoa runs the labs' own CLIs on each user's own plan, so byoa and every app on it follow the labs' published rules. This page has the rules from [SPEC.md](https://github.com/madeyexz/byoa/blob/main/SPEC.md#lab-rules), and what each app must do. ## Rules we follow - We run the real, unmodified `claude`, `codex` and `grok` binaries. We never pretend to be another client. A test checks the hash of the installed binaries against the published packages (V11). - The user signs in through Anthropic's, OpenAI's or xAI's own sign-in page. - One app's AI login is used only by that app. - For OpenCode Go (beta), byoa uses only the user's own key, with OpenCode's documented API and the harness's own user agent, never OpenCode's Console CLI sign-in. OpenCode's terms do not clearly allow an app to run it for its users, so each app asks OpenCode first. - The labs' terms restrict where an AI login may be stored. byoa keeps it in your database by default, so each app checks those terms and signs its own agreements with the labs. ## What the labs' terms say byoa follows the labs' published rules as read on 2026-11-22: - Anthropic ([legal and compliance](https://code.claude.com/docs/en/legal-and-compliance)) allows an end user to sign in to the unmodified Claude Code binary with their own plan, including where a platform hosts Claude Code. It forbids third parties to "collect, store, or intermediate Claude.ai credentials or session tokens", unless Anthropic agrees otherwise. - OpenAI ([Sign in with ChatGPT Terms](https://openai.com/policies/sign-in-with-chatgpt-terms/), effective 2026-11-04) requires that "any persistent storage of Authentication Tokens must be local and under the user's control, not in a remote or managed environment", and that the plan is used "only for the application they connected". Paid or remotely hosted apps must [apply](https://openai.com/form/sign-in-with-chatgpt-interest/) to be partners. - OpenCode ([Terms of Use](https://opencode.ai/legal/terms-of-service), effective 2026-11-08, read on 2026-11-25) says that the user "will only use the Services for your own internal use, and not on behalf of or for the benefit of any third party", and forbids using "multiple accounts to circumvent usage limits". Its [Go docs](https://opencode.ai/docs/console/go) say Go "is designed for OpenCode and other coding agents that produce similar types of requests", and ask each client to send "its own user agent" and "a stable session ID". OpenCode documents a Go key in Claude Code and in Codex. Whether an app may run a user's key for that user's own tasks is arguable, not clearly allowed: the work is the user's own, but the app gains from it too. Ian Hsiao accepted this for version 1 on 2026-11-25. There is no "Sign in with OpenCode" for apps; the user creates the key in OpenCode's Console. - xAI (read on 2026-11-25) publishes Grok Build (`@xai-official/grok`, Apache-2.0) for SuperGrok and X Premium+ subscribers, with a device-code sign-in and a headless mode for scripts. Its [terms of service](https://x.ai/legal/terms-of-service) (2026-10-27) say "You may not share your account credentials or make your account available to anyone else", and its [acceptable use policy](https://x.ai/legal/acceptable-use-policy) forbids "Accessing the Services through unauthorized automated or non-human means". Neither says anything about an app that runs Grok Build for its own users, or that stores their login. Ian Hsiao accepted this when he added Grok Build to version 1; we have not asked xAI. So byoa MUST: - run only unmodified `claude`, `codex` and `grok` binaries, and never pretend to be another client (Codex's app server names byoa as its client: `clientInfo.name` is `byoa`); - send the user to the lab's own sign-in page; - not share one AI login between apps; - for OpenCode Go, use only the user's own key, with OpenCode's documented API and the harness's own user agent, and never OpenCode's Console CLI sign-in, which has OpenCode's own client ID. The labs' terms above restrict where these tokens may be stored. byoa keeps the AI login in the app's database by default (R1.4), and ships a per-user volume as an option (R1.5). Each app checks the labs' terms for its own use. Each app is responsible for its own agreements with the labs. An app that offers OpenCode Go asks OpenCode (help@anoma.ly) before it ships it. We plan to sign agreements for our own apps when they have traction. Our hosted mail demo (https://byoa.rippling.computer/demo, `examples/mail/convex`) is a hosted service for strangers: it keeps each visitor's Claude, ChatGPT or Grok login, encrypted, in its Convex deployment, for at most one hour after the visitor's last request, and then signs it out with the CLI and deletes it; sooner when the visitor clicks Sign out or Delete my data. That is the storage that Anthropic's and OpenAI's terms above restrict. Ian Hsiao accepted this on 2026-11-26, before we have an agreement with Anthropic or OpenAI. The demo's page tells visitors that the job uses their own plan and how long their login stays. Our help agent, the chat in the corner of each page of https://byoa.rippling.computer (`site/help.html`, backend in [madeyexz/byoa-help](https://github.com/madeyexz/byoa-help)), is the one place where we do not follow "each user uses their own plan": every visitor's question runs on Ian Hsiao's own ChatGPT plan, in Codex, signed in once with `codex login --device-auth` and kept, encrypted, in its Convex deployment. OpenAI's [Codex app-server docs](https://learn.chatgpt.com/docs/app-server) say "App-server authentication has never been permitted for commercial or hosted services", and its Terms of Use forbid making an account "available to anyone else". Ian Hsiao accepted that risk to his own account on 2026-11-26. The chat says that it runs on the maintainer's plan, and limits keep its use small. An app on byoa must not do this. ## What your app must do Every app on byoa must follow these rules. If a request breaks one, stop and tell the developer. - Run only the unmodified `claude`, `codex` and `grok` binaries that byoa installs (pinned, and checked in byoa's own tests). Do not patch them, wrap them to change what they send, or set headers or a user agent to pretend to be another client. - Send the user to the lab's own sign-in page, from `connectLogin`. Do not embed, proxy or copy that page, and never ask the user for a password or an API key in place of it. The one key byoa takes is an OpenCode Go key, with `connectKey`, which OpenCode's Console makes for this. - For OpenCode Go, never use OpenCode's Console CLI sign-in (`npx @opencode/console`): it has OpenCode's own client ID. OpenCode's terms say "only for your own internal use, and not on behalf of or for the benefit of any third party", so it is not clearly allowed for an app: tell the developer to ask OpenCode (help@anoma.ly) first. - Never read, export or call the labs' APIs with the user's AI tokens. The CLI is the only client that uses them. Do not call the labs' token endpoints. - One app's AI login is only for that app. Give each app its own `app` name and its own store. Never share a login between apps. - Real MCP tokens never go into the sandbox. Give a job its servers with `mcp: [...]`. Never put a grant's token in `setup`, the task, environment variables or files. - The labs' terms restrict where AI logins may be stored. Anthropic says third parties may not "collect, store, or intermediate Claude.ai credentials or session tokens" without its agreement. OpenAI says stored tokens must be "local and under the user's control", and paid or hosted apps must apply to be partners. xAI's terms forbid sharing an account and "unauthorized automated" access, and say nothing about an app that runs Grok Build for its users. byoa's default keeps the login in the app's database; `cliLogin` keeps it in a per-user volume. Each app checks the terms and makes its own agreements: https://github.com/madeyexz/byoa/blob/main/SPEC.md#lab-rules --- Source: https://byoa.rippling.computer/docs/faq # FAQ ## What is byoa? byoa, short for "bring your own agent", is the simplest way to let your users bring their own AI subscription to power the agents in your app. Each user signs in to their own AI plan one time: Claude (in Claude Code), ChatGPT (in Codex), Grok (in Grok Build) or OpenCode Go (beta). When your app has work for the AI, byoa runs that user's own Claude Code, Codex or Grok Build in a sandbox on your E2B, Daytona or Instabox account, with the user's tools, and streams the result back. The user's plan pays for the AI. Your app pays only for the sandbox. byoa is an open-source library (Apache 2.0), the npm package `@madeyexz/byoa`. It runs inside your app's own backend, on Node or Bun. It is not a hosted service. See [Why and when you need byoa](https://byoa.rippling.computer/docs/index.md#why-and-when-you-need-byoa) and [Getting started](https://byoa.rippling.computer/docs/getting-started.md). ## Can my user's AI account get banned? It can. byoa cannot promise that it will not, because the labs decide, and their terms allow parts of what byoa does but not all of it. byoa is built to stay inside the parts that the labs allow: - **It runs the labs' own CLIs, unmodified.** The agent is the real Claude Code, Codex or Grok Build, installed from the labs' own npm packages, and a test checks the binaries against those packages (V11). byoa never pretends to be another client, and never calls the labs' APIs with the user's tokens. - **The user signs in on the lab's own page,** with the CLI's own sign-in. byoa never sees a password. - **Each user uses their own plan, for their own work,** and one app's login is only for that app. Anthropic's [Claude Code legal and compliance page](https://code.claude.com/docs/en/legal-and-compliance) allows "an end user signing in to the unmodified Claude Code binary with their own Claude subscription, including where a platform hosts Claude Code". But the same page also says: - developers "may not collect, store, or intermediate Claude.ai credentials or session tokens". byoa's default login stores the CLI's login files, encrypted, in your app's database ([AI login](https://byoa.rippling.computer/docs/ai-login.md)). - "Advertised usage limits for Pro, Max, and Ultra plans assume ordinary, individual usage of Claude Code". An app that runs many jobs for one user can go beyond that. - Anthropic "reserves the right to take measures to enforce these restrictions and may do so without prior notice." OpenAI's [Sign in with ChatGPT Terms](https://openai.com/policies/sign-in-with-chatgpt-terms/) say that stored tokens "must be local and under the user's control, not in a remote or managed environment", and that paid or remotely hosted apps must [apply to be partners](https://openai.com/form/sign-in-with-chatgpt-interest/). xAI's [terms of service](https://x.ai/legal/terms-of-service) say "You may not share your account credentials or make your account available to anyone else", and its [acceptable use policy](https://x.ai/legal/acceptable-use-policy) forbids "Accessing the Services through unauthorized automated or non-human means". Neither says anything about an app that runs Grok Build for its users, or that stores their login. So for Grok, the answer is unclear. OpenCode's [Terms of Use](https://opencode.ai/legal/terms-of-service) say the user uses its services "only for your own internal use, and not on behalf of or for the benefit of any third party". So an OpenCode Go key (beta) in your app is arguable, not clearly allowed ([AI login](https://byoa.rippling.computer/docs/ai-login.md#opencode-go-a-key-not-a-sign-in-beta)). So, before you launch: - Read the [Lab rules](https://byoa.rippling.computer/docs/lab-rules.md), and decide where the logins stay: the default stored login, or `cliLogin` in a volume of each user. - Apply to OpenAI's partner program if your app is paid or hosted, and ask Anthropic for an agreement if you store Claude logins. If you offer OpenCode Go, ask OpenCode (help@anoma.ly) first. - Keep each user's jobs to the user's own requests, at a pace that a person would use. - Tell your users that the jobs use their own plan and its limits. ## What happens when the user's plan runs out? The job ends with an `error` of code `usage-limit`, and `resetsAt` when the tool says when the plan resets (Claude Code, Codex and OpenCode Go say it; Grok Build does not). byoa keeps this until the reset, or for 15 minutes when it does not know the time. Until then, a job of that user and harness ends at once and starts no sandbox, so a used-up plan does not cost you a sandbox for each try. `agents.usageLimit(userId, harness)` tells you before a job. A refusal for now, such as a lab that is overloaded, is `rate-limited`: try again in a moment. See [When the plan is used up](https://byoa.rippling.computer/docs/running-agents.md#when-the-plan-is-used-up). ## Can one user run many agents at the same time? Yes, with one sign-in, for Claude Code, Codex and Grok Build. Give each agent its own sandbox: a `sandboxKey` for each, or `sandboxPer: 'job'`. The jobs then share the user's login while it is not due for a refresh. Jobs in one sandbox wait in line instead, and one job can also carry several messages to one agent. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md#jobs-at-the-same-time). All these jobs use the same plan, so they reach the plan's limits sooner. One risk stays with a shared login: when the lab answers 401 to two sandboxes at the same time, both CLIs refresh, one refresh fails, and the user may have to sign in again. `storedLogin({ parallel: false })` turns sharing off ([AI login](https://byoa.rippling.computer/docs/ai-login.md#jobs-at-the-same-time-the-shared-login)). Jobs on an OpenCode Go key have no such risk: a key does not rotate. ## Does the agent remember earlier jobs? Only in a conversation. A job with a `conversation` id continues the harness's own session of the earlier jobs with that id, in the conversation's own kept sandbox, and its job folder (`~/work`) stays. A job with no `conversation` starts a new session, and its job folder is new. byoa keeps a copy of each conversation's transcript, encrypted in your database, so the agent still remembers when the provider loses the sandbox. A running job of each harness also takes more messages (`job.send`): Codex and Grok Build into the turn that runs, Claude Code after it. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md#conversations) and [what carries over between jobs](https://byoa.rippling.computer/docs/sandbox-lifecycle.md#what-carries-over-between-jobs). ## Which model does a job use? The model and effort that you give `run`, else the harness's default from `createAgents({ models })`, else the CLI's own default. `agents.listModels(userId, harness)` lists the models that the user's plan can use, and the efforts of each, as the CLI lists them with the user's login. Pick from that list, because each plan has its own models. A job on an OpenCode Go key (beta) needs a Go model: `agents.listModels(userId, 'opencode-go')` lists them from OpenCode's API, with no sandbox. See [Running agents](https://byoa.rippling.computer/docs/running-agents.md#models-and-effort). ## What does an AI job cost with byoa, and with an API key? Your app passes its AI costs on to its users, in its price, so the question is what each user pays. With an API key, your app buys every token at API prices. With byoa, the user's own plan pays for the model, and your app passes on only the sandbox. For 100 small tasks a month, that takes each user's cost from $24.50 to $49 with a frontier model, or from $3 with a cheap open-weight model and a worse agent, down to $1.38 on E2B, and a frontier agent on the plan they already pay for. ### One small task Take a small task in an AI-native app, such as "add these three to-dos and sort them by date". The agent makes about 20 model calls. Each call sends the conversation so far, so the inputs add up to about 500,000 tokens, of which about 90% are cache hits. The agent writes about 10,000 tokens, with its reasoning. The job takes about 5 minutes of sandbox time, from start to `close()`. These are estimates. To get your own numbers, read the `usage` of each job's `end` event (`input`, `output`, `cached`, and `costUsd` when the CLI reports it). **The model, at API prices** (per million tokens, from the labs' price pages on 25 November 2026): | Model | Kind | 50,000 uncached input | 450,000 cached input | 10,000 output | One task | |---|---|---|---|---|---| | Claude Opus 5.5 ($4.00 in, $0.20 cached, $20.00 out) | frontier | $0.200 | $0.090 | $0.200 | **$0.490** | | GPT-6.2 Sol ($2.00 in, $0.10 cached, $10.00 out) | frontier | $0.100 | $0.045 | $0.100 | **$0.245** | | Kimi K3 ($3.00 in, $0.30 cached, $15.00 out) | frontier, open-weight | $0.150 | $0.135 | $0.150 | **$0.435** | | DeepSeek V4.1 Flash ($0.30 in, $0.006 cached, $1.20 out) | smaller, open-weight | $0.015 | $0.0027 | $0.012 | **$0.0297** | **The sandbox,** 2 vCPU and 4 GiB of memory, for 5 minutes (prices per hour, billed by the second, only while it runs): | Provider | 2 vCPU | 4 GiB | One hour | One task (5 minutes) | |---|---|---|---|---| | E2B ($0.0504 a vCPU, $0.0162 a GiB) | $0.1008 | $0.0648 | $0.1656 | **$0.0138** | | Daytona (the same rates) | $0.1008 | $0.0648 | $0.1656 | **$0.0138** | | Instabox ($0.004 a vCPU, $0.00225 a GiB) | $0.008 | $0.009 | $0.017 | **$0.0014** | Claude Opus 5.5 has a cache write price too ($5.00), which this leaves out. DeepSeek's prices are its weekday peak prices; at other times they are half. Sources: [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing), [OpenAI API pricing](https://developers.openai.com/api/docs/pricing), [Kimi API pricing](https://platform.kimi.ai/docs/pricing/chat), [DeepSeek API pricing](https://api-docs.deepseek.com/quick_start/pricing/), [E2B pricing](https://e2b.dev/pricing), [Daytona pricing](https://www.daytona.io/pricing), [Instabox pricing](https://instabox.sh/pricing). ### For a month What each user pays a month for 100 such tasks, when your app passes its costs on: | | Model at API prices | Sandbox with byoa | |---|---|---| | Claude Opus 5.5 | $49.00 | | | GPT-6.2 Sol | $24.50 | | | Kimi K3 | $43.50 | | | DeepSeek V4.1 Flash | $2.97 | | | E2B or Daytona | | $1.38 | | Instabox | | $0.14 | The user already pays for their own plan, such as $20 a month for Claude Pro or ChatGPT Plus, and the task uses its allowance. To try other numbers of tasks: Diagram: What each user pays a month for small agent tasks, when your app passes its AI costs on. With your API key, frontier models cost each user a lot, and cheaper models cost less for a weaker agent. With byoa, the user's own plan pays for a frontier model, and your app passes on only the sandbox. The numbers come from the cost tables in the FAQ. For 100 tasks for each user, a month: | How your app gets the AI | Each user pays a month | |---|---| | Your API key: Claude Opus 5.5 (frontier) | $49.00 | | Your API key: GPT-6.2 Sol (frontier) | $24.50 | | Your API key: Kimi K3 (frontier, open-weight) | $43.50 | | Your API key: DeepSeek V4.1 Flash (smaller, open-weight) | $2.97 | | byoa on E2B: the user's own plan, with a frontier model | $1.38 and their plan | | byoa on Daytona: the user's own plan, with a frontier model | $1.38 and their plan | | byoa on Instabox: the user's own plan, with a frontier model | $0.14 and their plan | ### What the numbers leave out - **Plan fees at the provider.** E2B's Pro plan is $150 a month, and Instabox's Pro plan is $20 a month with $20 of usage in it. Daytona has no plan fee. - **A kept sandbox between jobs.** A paused or stopped sandbox costs no compute. It can cost a little for its disk: Daytona bills disk past the first 5 GiB. - **The sign-in sandbox,** once for each user and harness, for a few minutes. - **An agent with no sandbox.** An agent that only calls your app's own API, with no shell and no files, can run as an agent loop of your own, such as on AWS Lambda, with no sandbox. Then an API key costs only the tokens. byoa needs a sandbox, because Claude Code, Codex and Grok Build need a shell. - **The user's plan has limits.** A user who runs many long tasks reaches the five-hour or weekly limit of their plan, and the jobs stop until it resets. ### When an API key costs the user less - **The user has no plan.** Then they must buy one, such as $20 a month, before your agent works. - **The user runs only a few tasks.** 10 small tasks on DeepSeek V4.1 Flash cost $0.30 at API prices, much less than a plan. A plan pays off when the user uses it in many apps, or uses your agent a lot. - **The user runs many long tasks.** They reach the limits of their plan. ### What your app gets Your costs do not grow with each user's tokens. You do not have to choose between a good agent and a low price. Your app has no per-user token bill, no usage metering or credits to sell, and no API key for the model to keep secret. --- Source: https://byoa.rippling.computer/docs/api # API reference This page is the agent skill's API reference, [skills/byoa/reference/api.md](https://byoa.rippling.computer/docs/api.md), so a coding agent and you read the same text. This is the API of byoa 1.1.0 (`@madeyexz/byoa` on npm). The source of truth is `src/agents.ts`, `src/index.ts` and the files they import. ## Imports | Import | What it gives | |---|---| | `@madeyexz/byoa` | `createAgents`, `LoginError`, `ProxyError`, `SandboxGoneError`, `memoryStore`, `storedLogin`, `cliLogin`, `readPlugin`, `JOB_TOKEN_ENV`, `PINS`, `clientMetadataDocument`, `PLANS`; types `Agents` (what `createAgents` returns), `AgentsOptions`, `RunOptions`, `Job` (what `run` returns), `RunHarness`, `ConnectResult`, `Session`, `SessionOptions`, `JobToken`, `Store`, `Entry`, `Sandbox`, `SandboxProvider`, `Capabilities`, `AgentEvent`, `Usage`, `AppTools`, `AppTool`, `Access`, `Setup`, `Skill`, `Plugin`, `LoginState`, `LoginStart`, `LoginResult`, `PlanName`, `PlanState` | | `@madeyexz/byoa/sandbox/e2b` | `e2b({ apiKey?, template?, timeoutMs? })`, `buildE2BTemplate(name?, { apiKey?, pins? })`, `e2bTemplate(pins?)`. Needs the `e2b` package. | | `@madeyexz/byoa/sandbox/daytona` | `daytona({ apiKey?, client?, snapshot?, volume?, timeoutMs? })`. Needs `@daytona/sdk`. | | `@madeyexz/byoa/sandbox/instabox` | `instabox({ apiKey?, apiUrl?, template?, snapshot?, timeoutMs? })`. Needs no package. No volumes: use `storedLogin()`, not `cliLogin`. | | `@madeyexz/byoa/sandbox/local` | `localSandbox({ root?, volumes?, env? })`: folders on this computer, for tests and development only. On macOS, the Codex sign-in works in it; the Claude Code sign-in needs Linux. | | `@madeyexz/byoa/store/postgres` | `postgresStore({ query, table? })`, `postgresSchema(table?)`, `POSTGRES_SCHEMA` | | `@madeyexz/byoa/store/convex` | `convexTable()`, `convexFunctions(table?)`, `convexStore(ctx, fns)`. Needs `convex`. | | `@madeyexz/byoa/node` | `toNodeListener(handler)` (a fetch handler as a `node:http` listener), `readPluginDir(dir)` | | `@madeyexz/byoa/verify` | `verifyHarness(sandbox, harness, bin, pins?)`: checks the installed binary against the published npm package | `@madeyexz/byoa` still exports `harnessFiles`, `ensureHarness`, `PACKAGES` and `LOGIN_FILES`, which byoa's own tests use. They are deprecated, and version 2.0 removes them: do not use them in an app. ## createAgents(options) ```ts interface AgentsOptions { app: string // lower-case letters, digits, -; at most 24. Names the app's sandboxes and login volumes. sandbox: SandboxProvider store: Store encryptionKey: string // 32 random bytes as base64. Encrypts MCP grants and, by default, AI logins. proxyUrl: string // public URL where the app serves agents.proxy; each server is at / oauth: { redirectUrl: string; clientMetadataUrl?: string; clientName?: string } pins?: { claude?: string; codex?: string; grok?: string } // default PINS; a harness left out gets its PINS version login?: (deps) => LoginDriver // default storedLogin(); or cliLogin jobTimeoutMs?: number // default 30 minutes sandboxPer?: 'user' | 'job' // default 'user': kept sandboxes, paused between jobs waitMs?: number // sandboxPer 'user': how long a job waits in line for its sandbox; default no limit models?: { claude?: ModelChoice; codex?: ModelChoice; grok?: ModelChoice; 'opencode-go'?: ModelChoice } // each harness's default: { model?, effort? }; 'opencode-go': jobs with that plan grantOrigins?: Record // more exact origins for fetchWithGrant, by MCP server origin tools?: AppTools // the app's own tools: MCP server name → tool name → { description?, input?, run } transcriptBytes?: number // the most bytes of a conversation's transcript kept in the store; default 700 000; 0: none } ``` - `oauth.redirectUrl`: the app's route that calls `finishMcp`. - `oauth.clientMetadataUrl`: an HTTPS URL where the app serves `agents.clientMetadata()` (a Client ID Metadata Document). Without it, byoa uses only Dynamic Client Registration. - `oauth.clientName`: the name the MCP server shows on its consent page. Default: `app`. - `sandboxPer`: `'user'` (the default): the first job of a user and harness creates the user's sandbox; byoa pauses it after each job (E2B pause, Daytona and Instabox stop) and resumes it for the next, with a new job folder. One job of a user and harness at a time; the others wait in line, in the order they came. A job's `sandboxKey` (in `run` and `session`) gives the user one kept sandbox, with its own lease, for each key. A sandbox the provider no longer has is replaced by a new one. `'job'`: a new sandbox for each job, destroyed after it. With the default `storedLogin()`, a user's jobs in different sandboxes run at the same time with one login, for every harness. - `models`: the model and effort a job of each harness gets when it names none. Default: the CLI's own. See `listModels`. - `transcriptBytes`: after each job of a conversation, byoa keeps a copy of the harness's session files (its transcript), encrypted in the store, when they are at most this large, so the conversation goes on when the provider loses its sandbox. Default 700 000 bytes, below a Convex document's 1 MiB. A larger transcript lives only in the conversation's sandbox. - `tools`: the app's own tools, as functions in the backend. `{ todos: { add_todo: { description, input, run } } }` is an MCP server `todos` with one tool. `input`: the JSON Schema of the arguments (an object schema; default: no arguments). `run(args, { user, job })` runs for the user of the job; what it returns goes to the agent (a string as it is, other values as JSON), and what it throws goes to the agent as a failed call. byoa does not check the arguments against `input`. A job gets the server by its name in `mcp`; the proxy serves it at `/`. Server names: lower-case letters, digits and -, at most 32; tool names: letters, digits, _ and -, at most 64. `listMcp` does not list them, and `connectMcp` refuses their names. It returns an object with the methods below. ## AI login | Method | Returns | |---|---| | `connectLogin(user, 'claude' \| 'codex' \| 'grok')` | `{ harness, url, code? }`. `url`: the lab's own sign-in page. `code`: Codex and Grok, the code to enter on OpenAI's or xAI's page. | | `finishLogin(user, h, { code?, waitMs? })` | `{ state: 'signed-in' \| 'signed-out' \| 'expired' \| 'pending', error? }`. Claude: pass `code` (the code Anthropic's page shows); with no code, it only checks in and says `pending`. Codex and Grok: no code; `waitMs` waits that long; call again while `pending`. Each call keeps the sign-in's sandbox alive for 2 more minutes; with no call for 2 minutes it ends (on E2B and Daytona; Instabox ends it after 15 minutes). A sign-in lasts 15 minutes at most. | | `cancelLogin(user, h)` | `void`. Ends a sign-in that has not finished, and its sandbox, at once. Call it when the user closes the sign-in. | | `loginState(user, h)` | `'signed-in' \| 'signed-out' \| 'expired'`. With `h` `'opencode-go'`, also `'no-plan'`. A used-up plan is still `'signed-in'`: see `usageLimit`. | | `usageLimit(user, h)` | `{ message, resetsAt?, until } \| undefined`, with no sandbox. Defined while the user's plan of `h` (a harness, or `'opencode-go'`) is used up, as a job found it: `message` is the tool's words, `resetsAt` (ms since 1970) when the plan resets, when the tool said, `until` when byoa runs this user's jobs of `h` again (`resetsAt`, else 15 minutes after the error). Until then `run` ends at once with a `usage-limit` error and starts no sandbox. A new sign-in (`finishLogin` with `'signed-in'`), `connectKey` with `'signed-in'`, `signOut` and a job that works end it. | | `signOut(user, h)` | `void`. Also deletes the user's sandbox for `h`, and cancels a sign-in that has not finished. With `h` `'opencode-go'`: deletes the user's key only; the proxy refuses the requests of jobs that still run with it. | | `connectKey(user, 'opencode-go', key)` | `{ state, error? }`. Beta: OpenCode Go is not yet checked with a real Go key. Keeps the user's OpenCode Console API key (`oc_sk_…`), encrypted in the store, after it checks the key with OpenCode's usage meter: `'signed-in'`; `'no-plan'` (kept: its workspace has no Go plan yet; jobs work once it has one); or, when OpenCode refuses the key (401: wrong, revoked or expired), the state before and an `error`, and the key is not kept. Throws on another answer. | | `deleteSandbox(user, { harness?, sandboxKey? }?)` | `void`. Deletes the user's kept sandboxes of this app at this provider: all of them (when the app deletes the user), or those of one harness or one sandbox key (when it deletes a project). The login, the grants and the conversations' stored transcripts stay. | | `deleteConversation(user, conversation?)` | `void`. Deletes a conversation (or, with no id, all of the user's): its session ids and stored transcripts, and its kept sandbox. The next job with that id starts a new conversation. Call it when the user deletes a chat, and when the app deletes the user. | Login drivers: - `storedLogin({ store?, encryptionKey?, waitMs?, parallel? })` (default): the CLI's own login files, encrypted in the store. `store` and `encryptionKey` default to the app's. During a job byoa saves a refresh every minute or so; when the backend dies during a job, a watcher in the sandbox removes the files before the provider pauses it, and the next job in that sandbox saves a login that the dead job's CLI refreshed. It saves files from a sandbox only of the same account and not older than the stored login. `waitMs`: how long a job waits in line for the login (default no limit). `parallel` (default true): the jobs of one user and harness share the login, each with a copy in its own sandbox, while the CLI will not refresh it before the job's time runs out (byoa reads the time the access token ends from the login files: the CLIs refresh 5 minutes before it; Codex's token lasts 10 days, Claude Code's 8 hours, Grok's 6 hours). When it is due for a refresh, one job holds it alone: it waits for the other jobs, and the jobs after it wait for it. The risk that stays: the CLIs also refresh when the lab answers 401 to a token that has not run out; two sandboxes that get that answer at the same time both refresh, one fails, and the user may have to sign in again. `parallel: false`: one job of a user and harness holds the login at a time. - `cliLogin`: the login stays in a volume of the user, mounted through the sandbox adapter. Needs a provider with volumes. ## MCP connections | Method | Returns | |---|---| | `connectMcp(user, url, { name, bearer? })` | `{ name, connected: true }` or `{ name, connected: false, signInUrl }`. Send the browser to `signInUrl`. | | `finishMcp({ state, code?, error? })` | `{ user, name }`. Call it in the `oauth.redirectUrl` route with the query parameters. | | `listMcp(user)` | `[{ name, url }]` | | `removeMcp(user, name)` | `void` | | `importMcp(user, { name, url, oauth })` | `{ name }`. Moves a grant made elsewhere into byoa; `oauth` is the MCP SDK's state (`client`, `tokens`, `at`). Delete the old copy, so the grant keeps one refresh owner. | | `fetchWithGrant(user, name, url, init?)` | `Response`. A request with the grant's current token, only to the origin of the grant's MCP server (and `grantOrigins` for it). No redirects. The app never gets the token. | | `clientMetadata()` | The Client ID Metadata Document to serve at `oauth.clientMetadataUrl`. | `name`: lower-case letters, digits and -, at most 32. `url`: `https://`, or `http://` on localhost. ## The proxy `agents.proxy` is a fetch handler (`Request` → `Response`). Serve it at `proxyUrl` and every path below it (`/`). It checks the job token, adds the user's real token, and sends the request to the MCP server; for the app's own `tools`, it calls the tool's `run`. It refuses a job token after the job ends. Do not put the app's session check in front of it. Each of its MCP answers has the header `x-byoa-proxy: 1`. It is also the relay of a job with `plan: 'opencode-go'`, at `/_plan/opencode-go/anthropic/v1/…` and `…/openai/v1/…`: it checks the job token (of a job with that plan), adds the user's key, and streams the request to `https://opencode.ai/inference/go/…` and the answer back, with only the harness's own headers (its user agent, session id, API version and betas; it adds `x-opencode-session` when there is none). It sends on no other header, so a header that the app's own gateway adds stays behind, and no other path. OpenCode's 401 makes the key `expired`, its 403 "OpenCode Go subscription required" `no-plan`. On its 429, the relay asks OpenCode's usage meter (`/v1/usage`, with the user's key) whether a limit is used up; if so, the job's error is `usage-limit` with that limit's `resetsAt`, and byoa keeps it (`usageLimit`); else it is `rate-limited`. ## Jobs ### run(user, options): Job ```ts interface RunOptions { harness: 'claude' | 'codex' | 'grok' | 'fake' task: string | string[] // several messages: one agent gets them all and decides the order setup?: { agentsMd?: string; skills?: { name: string; files: Record }[] } // files must have 'SKILL.md' plugins?: Plugin[] // from readPlugin(readPluginDir(dir)); their skills and MCP servers are added mcp?: string[] // the connected servers this job gets; default none model?: string // Claude Code: an alias (opus, sonnet, ...) or a full name; Codex, Grok: a model name. Default: createAgents' models, else the CLI's effort?: string // Claude Code --effort (low ... max); Codex model_reasoning_effort; Grok --reasoning-effort. Each model's own are in listModels onWait?: (w: { for: 'sandbox' | 'login'; ahead: number }) => void // while the job waits in line sandboxKey?: string // sandboxPer 'user': which of the user's kept sandboxes; default the user's one for the harness access?: 'full' | 'read-only' // what the agent may do; default 'full' plan?: 'opencode-go' // the user's OpenCode Go key (connectKey) in place of the lab login, with claude or codex conversation?: string // the app's id of a conversation (1 to 128 characters): the job continues the harness's session of it } interface Job extends AsyncGenerator { send(message: string): Promise // one more message to the running agent; false once the job ended } ``` - `conversation`: the job continues the harness's own session of the jobs before it with the same id, so the agent has their messages. The conversation has its own kept sandbox (the id is its `sandboxKey`; give no other one), and its job folder stays from job to job: byoa replaces only its own files there (the skills, AGENTS.md, the MCP config, the task). Claude Code: the first job gets `--session-id `, the next ones `--resume `. Codex: the first job starts a thread that is not ephemeral, which its app server names in `thread/started`; the next ones `thread/resume` it. Grok: `session/new` names the session; the next jobs `session/resume` it. Jobs of one conversation run one at a time, in the order they came. After each job byoa keeps the session id and, up to `transcriptBytes`, a copy of the session's files, encrypted in the store; when the provider lost the sandbox, the next job writes them into its new one (Claude Code and Grok keep sessions by the job folder's path, which is the same at one provider; Codex by date). When there is no copy, the job starts the conversation again and says so in an `error` with code `conversation`. With `sandboxPer: 'job'`, each job of a conversation has a new sandbox and a new job folder, and resumes only from the stored copy. Not with `session()`. - `send` (steering): byoa runs each harness under a small driver script (`node .byoa/driver.mjs` in the job folder) that speaks the CLI's own protocol and gives it each message: Claude Code's stream-json input, Codex's app server (`codex app-server`) and Grok's Agent Client Protocol (`grok agent stdio`). Codex (`turn/steer`) and Grok (its `x.ai/interject` extension) take a message into the turn that runs, at the agent's next step; Claude Code takes it when that turn ends. A message that comes after a turn ended starts the next turn, in the same session. Each turn that is not the last gives a `turn` event; the job ends (`end`) after the turn that answers the last message. `send` returns false after the end, and with the fake harness. - `plan`: the harness runs with the user's OpenCode Go plan, through the proxy's relay; the key never enters the sandbox. The job needs a model of the plan (`model`, else `models['opencode-go']` of createAgents; `listModels(user, 'opencode-go')` lists them), else `run` gives an `error` (code `sandbox`). Claude Code gets `ANTHROPIC_BASE_URL` (the relay), `ANTHROPIC_AUTH_TOKEN` (the job token), every model alias set to the job's model, and a `CLAUDE_CONFIG_DIR` of its own with no Claude login; Codex gets `-c` overrides for a model provider `opencode-go` (`wire_api = "responses"`, `env_key = "BYOA_JOB_TOKEN"`) and a `CODEX_HOME` of its own. The user's jobs with a key need no lease, so jobs in different sandboxes run at the same time. With no key, `run` gives an `error` with code `signed-out`. - `mcp`: names of the user's connected servers and of the app's own `tools`. - `access`: `'full'`: every tool of the harness with no approval (Codex: the thread's sandbox `danger-full-access` with the approval policy `never`; Claude Code: `--permission-mode bypassPermissions`; Grok: `--always-approve`), for a sandbox that is the job's alone. `'read-only'`: the job's MCP tools, and reading files, so the harness reads its skills and AGENTS.md; no change to a file, and no network but the job's MCP servers. Codex: the thread's permission profile `byoa-read-only`, which extends Codex's `:read-only`, turns the network off and denies CODEX_HOME (its shell stays, because it reads a skill with `cat`; a command cannot write, open a connection or read the login), with the job's MCP tools approved in its `config.toml`. Claude Code: `--permission-mode dontAsk` with the tools `Read`, `Glob`, `Grep`, `Skill` and the job's MCP servers; each tool it refuses is a `permission` event. Grok: rules in the job's `.grok/config.toml` that deny `Bash`, `Write`, `Edit` and `WebFetch` and allow `MCPTool(*)` (a denied call is an error for the model, and the turn goes on; Grok reads files and loads skills with no prompt), and its web search only for a domain that does not exist (`GROK_CONFIG`, Grok's config overlay); a tool that Grok still asks for is refused (a `permission` event), and Grok then ends the turn. Apart from Codex's home folder, it does not hide files: the agent can read each file its user can read. - Before the harness starts, byoa sends one MCP `initialize` from the sandbox to each of the job's servers, through the proxy. When no request reaches the proxy, the job does not start: an `error` event with code `mcp`, then `end` with `ok: false`. A server that does not answer gives an `error` event with code `mcp`, and the job runs. Each run: the user's sandbox (resumed, or created for the first job; with `sandboxPer: 'job'`, a new one), the user's login, the pinned harness, the setup files in a new job folder (in a conversation, the conversation's folder), the task; then the login is taken out, a conversation's transcript is kept, and the sandbox is paused (or destroyed). Stop the loop (or call `return()`) to end a job early; byoa still cleans up. ### Events (one schema for every harness) ```ts type AgentEvent = | { type: 'start'; harness: string; version: string; sandbox: string; conversation?: string; resumed?: boolean } | { type: 'text'; text: string } | { type: 'tool_call'; id: string; name: string; server?: string; input: unknown } // server: the MCP server | { type: 'tool_result'; id: string; ok: boolean; output: string } | { type: 'permission'; tool: string; decision: 'denied'; input?: unknown } | { type: 'error'; message: string; code?: 'signed-out' | 'expired' | 'no-plan' | 'usage-limit' | 'rate-limited' | 'harness' | 'sandbox' | 'mcp' | 'conversation'; resetsAt?: number } | { type: 'turn'; ok: boolean; result?: string; usage?: Usage } // one turn of a job that has more messages (send) | { type: 'end'; ok: boolean; result?: string; usage?: Usage; session?: string } // session: the harness's session id, in a conversation // Usage: { input: number; output: number; cached?: number; costUsd?: number } ``` `run` does not throw for job failures: it yields `error` events and then exactly one `end`. `signed-out` / `expired`: ask the user to sign in again, or for a new key with `plan: 'opencode-go'` (`loginState` says the same). `no-plan`: the key's workspace has no OpenCode Go plan. `usage-limit`: the user's plan is used up (a 5-hour, weekly, monthly or other limit, or a spend cap); `resetsAt` (ms since 1970) is when it resets, when the tool said (Claude Code and Codex say it, and for OpenCode Go byoa asks OpenCode's usage meter; Grok Build does not), and `usageLimit` says the same until then; byoa reads each CLI's own code (Claude Code's `api_error`, Codex's `codexErrorInfo`, Grok Build's `error_kind`), and its words only when that is missing. `rate-limited`: the lab refused for now (too many requests, or overloaded); byoa keeps nothing. `mcp`: a server is not connected, its grant failed, it did not answer through the proxy, or the sandbox cannot reach the proxy (then the job did not start). `conversation`: the conversation's history is gone (the provider lost its sandbox, and its transcript was larger than `transcriptBytes`); the job runs, as the first of a new session. In `start`, `resumed` is true when the harness continued an earlier session of the conversation. ### listModels(user, h | 'opencode-go'): Promise The models the user's plan can use with `h`, as the unmodified CLI lists them with the user's login (Claude Code: its `initialize` answer; Codex: its app server's `model/list`; Grok: the `initialize` answer of `grok agent stdio`), in a new sandbox that is destroyed after. `ModelInfo`: `{ id, name, description, isDefault, efforts, resolved? }`; `id` is what `model` takes, `efforts` what `effort` takes, `resolved` (Claude Code) the full model name of an alias. Each call starts a sandbox, so keep the list for a while. A Claude Code list waits for the user's running Claude Code jobs. Throws `LoginError` when `h` is not signed in. With `h` `'opencode-go'`: the plan's chat models, from `https://opencode.ai/inference/go/v1/models` with the user's key, in the backend (no sandbox). The free models are left out: OpenCode serves them only to its own client. `efforts` are the model's own, as OpenCode lists them; Claude Code's `--effort` takes `low` to `max`. `isDefault` is false for each: a job names its model. Throws `LoginError` when the user has no key. ### session(user, { harness, setup?, plugins?, mcp?, sandboxKey?, access?, model?, effort?, onWait?, plan? }): Promise For an app that runs its own program around the unmodified harness. It also takes `plan`, as `run` does; `args` then has the plan's flags. Throws `LoginError` when the harness is not signed in (or the user has no key of the plan), and `ProxyError` when the sandbox cannot reach the proxy. The app starts the harness itself, so `access` changes only the files byoa writes (Codex's MCP config). ```ts const s = await agents.session(userId, { harness: 'claude', mcp: ['notion'] }) try { 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 login out, and pauses (or destroys) the sandbox ``` `Session`: `sandbox`, `work` (the job folder with byoa's files), `harness`, `bin` (the pinned binary), `version`, `args` (the harness flags for the job's model and effort, for the app's own command line), `env` (login folder, `BYOA_JOB_TOKEN`, and for Claude Code `MCP_TIMEOUT`; with a plan, the plan's settings above), `token`, `mcp` (`[{ name, url }]` at the proxy), `missing` (servers not connected), `failing` (`[{ name, message }]`: servers that did not answer through the proxy), `reportLogin('signed-in' | 'expired')`, `close()`. ### jobToken(user, { mcp?, ttlMs? }): Promise A job token with no sandbox, for a harness outside byoa's sandboxes (such as on the user's own computer). `{ token, job, mcp, missing, close() }`. Send `token` as `Authorization: Bearer` to each `mcp[].url`. ## Store adapter ```ts interface Entry { value: string; version: string } interface Store { get(key: string): Promise put(key: string, value: string): Promise // writes whatever is there delete(key: string): Promise cas(key: string, version: string | null, value: string): Promise // null: only if no entry; true if it wrote } ``` The version must change on every write, and a key that is deleted and written again must never get an earlier version back. The one refresh owner of each grant depends on `cas`. - Postgres: run `POSTGRES_SCHEMA` once (or `postgresSchema('my_table')`), then `postgresStore({ query: (sql, args) => pool.query(sql, args) })`. - Convex: `convex/schema.ts` has `byoa: convexTable()`; `convex/byoa.ts` has `export const { get, put, remove, cas } = convexFunctions()`; in an action or HTTP action, `store: convexStore(ctx, internal.byoa)`. Call byoa only from actions and HTTP actions, and serve `agents.proxy` from an HTTP action. - Tests: `memoryStore()` from `@madeyexz/byoa`. ## Sandbox adapter ```ts interface SandboxProvider { readonly name: string readonly capabilities?: { volumes: boolean } // optional; false: create refuses a volume, and createAgents refuses cliLogin create(opts?: { volumes?: { name: string; path: string }[]; labels?: Record; timeoutMs?: number; keep?: boolean }): Promise resume(id: string, opts?: { timeoutMs?: number }): Promise // starts a paused one; throws SandboxGoneError when it is gone destroy(id: string): Promise // by id, running or paused deleteVolume(name: string): Promise keepAlive?(id: string, ms: number): Promise // optional: a sandbox that is not kept ends ms from now (the sign-in's check-ins) } interface Sandbox { readonly id: string readonly home: string run(cmd: string, opts?: { cwd?; env?; timeoutMs?; onStdout?; onStderr?; background? }): Promise<{ exitCode; stdout; stderr }> writeFile(path: string, data: string | Uint8Array): Promise readFile?(path: string): Promise // optional; null when it is not there pause(): Promise // keeps the files; resume starts it again setTimeout?(ms: number): Promise // optional: the provider's time again, ms from now (a kept one pauses then) destroy(): Promise } ``` - `keep: true`: a sandbox byoa keeps for the user. When it times out, the provider pauses it instead of deleting it. - `run`: a command that exits with a non-zero code resolves; one that runs out of its `timeoutMs` resolves with exit code 137. - `readFile`: byoa reads the user's login files and a conversation's transcript with it. Without it, byoa reads a file as base64 on a command's stdout, which a provider may keep in its command history. E2B, Daytona, Instabox and the local provider have it. - `setTimeout`: byoa calls it when a job has the user's AI login, so the time the job waited in line for the login does not count. E2B has it, and Daytona for a sandbox of one job. Without it, a job that waited long for the login can reach the sandbox's time before its own ends. - An adapter of the app's own can check itself with the conformance check in byoa's tests (`test/helpers/conformance.ts`). - E2B: `pause` ends the sandbox's processes, then takes a full snapshot, with the memory: the next job's resume takes about 0.3 seconds, and node and the harness start warm. When E2B refuses it, because it still saves the sandbox's previous snapshot, byoa takes a snapshot of the files only; the next resume then boots the sandbox again and reads its disk cold, which can add 10 to 20 seconds. E2B keeps a paused sandbox with no time limit, and charges no compute for it. - E2B: the default template is `byoa`; build it once per pin change with `buildE2BTemplate()`. Any template with Node 20 or later works (byoa installs the pinned harness when it is missing, more slowly). - Daytona: `pause` stops the sandbox; `resume` starts it (also from archived, more slowly). A kept sandbox is not ephemeral and has no time to live; Daytona archives it after 7 days stopped. - Daytona: with `cliLogin`, every user's login is a subpath of one shared volume (`byoa` by default). On Tier 1 and 2 a sandbox reaches only allowed domains, so serve the proxy on one (for example `*.convex.site`, `*.workers.dev`). - Instabox: `pause` stops the sandbox; `resume` starts it, and a sandbox that paused itself (idle for 30 minutes, or at the plan's longest run) is booted again, so no process of an earlier job runs. A kept sandbox has no time limit, and Instabox keeps it until it is deleted; a sandbox for one job is deleted after it, and at the latest at its `timeoutMs`. The home folder is `/data/home`. A sandbox gets none of the account's Vault items or org Secrets, and no command is in Instabox's command history. Sandboxes reach every public domain. `create` with volumes throws. The free plan allows one sandbox at a time and three starts a minute; the adapter waits for a start when Instabox answers 429. ## The fake harness `harness: 'fake'` runs no model and needs no login. It reads the same MCP config Claude Code would. Each task line `call . ` is one MCP call through the real proxy; it shows the task's first line as one `text` event and skips the other lines. The last call's output is the `end` event's `result`. In a conversation it keeps each task in a session file and says, in a `text` event, how many earlier messages it remembers (`fake harness remembers 1 earlier messages: `), so an app tests its conversations with no model. Use it with `localSandbox()` and `memoryStore()` (or the app's own store) in tests. --- Source: https://github.com/madeyexz/byoa/blob/main/SPEC.md # byoa requirements, version 1 **Status:** draft, 2026-11-22. **Owner:** Ian Hsiao. This document says what version 1 of byoa must do and how we check it. It does not say how to build it. "MUST" and "SHOULD" have their usual meanings (RFC 2119). ## Goal A developer makes an app AI-native in one day, not in weeks. The app runs the user's own Claude Code, Codex or Grok Build in any sandbox. The user signs in to ChatGPT, Claude or Grok one time, or gives the key of their OpenCode Go plan one time, and connects each MCP tool one time. ## Users of this library - **App developer.** Imports byoa into their own backend. Does not want to build login, MCP OAuth, skills loading, harness updates or sandbox code. - **End user.** Uses the developer's app. Has a ChatGPT, Claude, Grok (SuperGrok, X Premium+) or OpenCode Go plan, and accounts in tools such as Notion, Gmail or Heptabase. ## Scope In scope for version 1: - Harnesses: Claude Code and Codex, both from the first version, and Grok Build (xAI), added on 2026-11-25. - Plans: the user's Claude, ChatGPT or Grok plan, through the lab's own sign-in; and OpenCode Go, through a key that the user gives, with Claude Code or Codex (R1.8). OpenCode Go is a plan, not a harness. - Sandbox providers: E2B, Daytona and Instabox. - Backends: Node, and Convex actions. Cloudflare Workers SHOULD work if it costs little. - Store adapters: Convex and Postgres. Out of scope for version 1: - A hosted service. byoa never runs a server for other apps. - Sharing one user's AI login between different apps. - Harnesses other than Claude Code, Codex and Grok Build (OpenCode, Amp, Pi, Cursor). OpenCode Go runs in Claude Code and Codex (R1.8), not in OpenCode. - A UI kit. The library gives data and events; the app draws its own UI. ## Requirements ### R1. AI login - **R1.1** byoa MUST sign the user in to Claude Code by running the unmodified `claude` CLI login in the sandbox. The user completes sign-in on Anthropic's own page. - **R1.2** byoa MUST sign the user in to Codex by running the unmodified `codex login --device-auth` in the sandbox, and to Grok Build by running the unmodified `grok login --device-auth`. The user enters the code on the lab's own page (OpenAI's, xAI's). - **R1.3** byoa MUST give the app the sign-in URL and code as data, so the app can show them on any device (for example a phone). - **R1.4** By default, byoa MUST keep the login (the CLI's own login files) in the app's own database, through the store adapter (R6), encrypted with a key that the app gives, for one user of one app. Each job MUST get a copy in its sandbox. After the job, byoa MUST save the files back when the CLI changed them (a token refresh), and MUST remove them from the sandbox, also from a sandbox that it keeps for the user's next job (R5.4). So between jobs the store is the only copy. byoa MUST NOT let two sandboxes refresh one user's login at the same time, so that two token refreshes do not revoke each other. The login is shared by default (`parallel`), for every harness, so that one user's jobs run at the same time: while the login is not due for a refresh before a job's time runs out, the jobs of one user each hold a copy; when it is due, one job MUST hold it alone, after the other jobs end. The app MAY turn sharing off. To know when a login is due, byoa MAY read the time its access token ends from the login files. byoa MUST NOT use a token, and MUST NOT call the lab's token endpoints itself; the CLI is the only client that uses the tokens. A backend can die during a job, so that the job never closes. byoa MUST then lose little: during the job it MUST save what the CLI changed about every minute; the next job in a kept sandbox that a dead job left MUST save the login that job's CLI refreshed, under the lease, before it writes the stored copy, unless the stored login changed since; and byoa MUST remove the files from the sandbox before the provider pauses or ends it, also with no backend. byoa MUST save files from a sandbox only when they are of the same account as the stored login and not older (the agent of a job can change any file), and MAY read the account and the refresh time from them for this. - **R1.5** The login part MUST be replaceable, with no change to R2 to R5. byoa MUST also ship a login that stays in a volume of that one user of that one app, mounted through the sandbox adapter (R5.3), which the app's database never holds. - **R1.6** byoa MUST report login state: `signed-in`, `signed-out`, `expired`; and for the key of a plan (R1.8), also `no-plan`. A plan that is used up (R1.9) is still `signed-in`. - **R1.7** A sign-in that the user leaves MUST NOT keep its sandbox: the app MUST be able to end it at once (`cancelLogin`, also at sign-out), and with no word from the app, the sign-in sandbox MUST end within a few minutes after the app's last check-in (`finishLogin`), on every provider that can change a sandbox's time. A sign-in lasts 15 minutes at most, as long as Codex's device code. - **R1.8** (beta: V20 has not run with a real Go key yet) byoa MUST also run Claude Code and Codex on the user's OpenCode Go plan, with a Console API key of the user (`oc_sk_…`) that the app gives (`connectKey`), instead of a lab login. byoa MUST check the key with OpenCode and keep it through the store adapter (R6), encrypted with a key that the app gives, for one user of one app. The key MUST NOT be in the sandbox's environment, files or processes at any time: the harness sends its model requests with the job token to a relay in the app's proxy (R3), which adds the key and sends them on to OpenCode, with the harness's own user agent and session headers, and refuses the job token after the job (R3.4). The relay MUST send on only the model APIs (`anthropic/v1/…`, `openai/v1/…`), and only for a job that has the plan. When OpenCode answers 401 (a wrong, revoked or expired key), the key is `expired`; when it answers 403 "OpenCode Go subscription required", it is `no-plan`. A key does not rotate, so one user's jobs with it MUST run at the same time, with no lease. byoa MUST use only OpenCode's documented API and its documented settings for each harness (Claude Code: `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN`; Codex: a model provider with the Responses API, for the job only), with a config folder of the job's own that has no lab login. Unlike a lab login (R1.4), the key is used by byoa itself, in the app's backend. - **R1.9** byoa MUST tell the app when the user's plan is used up (its 5-hour, weekly or other limit, or a spend cap), apart from every other failure: an `error` event with code `usage-limit`, and `resetsAt` when the tool says when the plan resets. byoa MUST read it from each CLI's own output, its structured code first, and its text only when that is missing: Claude Code's API error on its assistant message (`api_error` `usage_limit_reached`, with `rate_limit_info.resetsAt`) and its `rate_limit_event`; Codex's `codexErrorInfo` (`usageLimitExceeded`) and the used-up window of its `account/rateLimits/updated`; Grok Build's words and the `error_kind` of its `turn_completed` (Grok says no reset time). For a plan with a key (R1.8), the relay MUST read it from OpenCode's 429 and its documented usage meter (`/v1/usage`). A refusal for now (too many requests, a lab that is overloaded) MUST be `rate-limited`, and a login that the CLI's own code says does not work (Codex's `unauthorized`) MUST be `expired`. After a job ends with `usage-limit`, byoa MUST keep that in the store, for the user and harness (for a plan, the user and plan), until `resetsAt`, or for 15 minutes when the tool did not say. Until then, a job of that user and harness MUST end at once with the same error and start no sandbox, and the app MUST be able to read it with no sandbox (`usageLimit`). A new sign-in, a new key, a sign-out and a job that works end it. ### R2. MCP connections - **R2.1** byoa MUST connect a remote MCP server for one user with MCP authorization (OAuth 2.1 with PKCE). It MUST use Client ID Metadata Documents when the server supports them, and Dynamic Client Registration only when it does not. - **R2.2** byoa MUST also accept a bearer token that the user pastes. - **R2.3** Each grant MUST have exactly one refresh owner: the app's backend. Two jobs that need a refresh at the same time MUST cause one refresh request. - **R2.4** byoa MUST store grants through the store adapter (R6), in the app's own database, encrypted with a key that the app gives. - **R2.5** byoa MUST let the app choose which MCP servers each job gets. (Bookish gives MCP servers only to jobs that the user asked for.) - **R2.6** byoa MUST let the app's backend send a request with a user's grant to an API of the same service that is not MCP (for example an export). By default, the token goes only to the origin of the grant's MCP server. The app's backend MAY name more origins for the grants of one MCP server origin, as exact origins (https, no path, no wildcard), in its own configuration; the MCP server, the sandbox and the user MUST NOT be able to add one. byoa MUST add the token only for those origins, MUST NOT follow redirects, and MUST NOT give the token to the app. (Margins' MCP server is on `margin.rippling.computer`, and its export is on `helpful-tern-930.convex.site`.) - **R2.7** byoa MUST let the app give its own tools as functions in its backend. The proxy (R3) MUST serve them as the tools of an MCP server, only to a job that the app gave them (R2.5), and MUST give each call the user of the job. The app writes no MCP server, and no user connects anything for them. ### R3. MCP proxy: real tokens stay outside the sandbox - **R3.1** The `mcp.json` in the sandbox MUST point to the app's proxy, with a short-lived token for one job and one user. - **R3.2** The proxy MUST add the real token to each request and send it to the MCP server. - **R3.3** No real MCP token MUST be in the sandbox's environment, files or processes at any time. - **R3.4** The proxy MUST refuse a job token after the job ends. - **R3.5** Before the harness starts, byoa MUST check from the job's sandbox that each MCP server of the job answers through the proxy. When the sandbox cannot reach the proxy, the job MUST NOT start, and MUST end with an error. A server that does not answer MUST give an error event. (A harness that cannot reach a server leaves its tools out and still ends well.) ### R4. Skills, AGENTS.md and config - **R4.1** byoa MUST write skills in the Agent Skills format where each harness reads them (for example `.claude/skills/`, `.agents/skills/`). - **R4.2** byoa MUST write AGENTS.md, and CLAUDE.md for Claude Code, from one source. - **R4.3** byoa MUST write MCP config in each harness's own format: JSON for Claude Code, TOML for Codex and Grok Build. - **R4.4** byoa SHOULD read an Agent Plugins 1.0 package (`plugin.json`, `skills/`, `mcp.json`). ### R5. Harness and sandbox - **R5.1** byoa MUST install a pinned version of each harness in each sandbox, or use a provider template with that version. - **R5.2** A new harness version MUST reach every user at their next job. (Bookish had to copy a new core into old sandboxes, because a template reaches only new sandboxes.) - **R5.3** Each sandbox provider MUST be one adapter with one interface: create, resume, run a command, write a file, read a file, mount a volume, pause, destroy. A command that runs out of its time MUST end with exit code 137 on every provider, not throw. Reading a file is optional: without it, byoa reads a file as base64 on a command's output. Setting a running sandbox's time again is optional too: byoa does it when a job has the AI login, so the job's wait in line for the login does not count. A provider says what it can do (`capabilities`): a provider with no volumes (Instabox) refuses a volume, so the volume login of R1.5 does not work on it and createAgents refuses it; the stored login of R1.4 does. One conformance check (`test/helpers/conformance.ts`) MUST pass for each adapter. - **R5.4** The lifecycle MUST be the app's choice, with the same app code on every provider: - **One kept sandbox per user (the default).** Each user has one sandbox of the app for each harness. The first job creates it. After each job, byoa pauses it (E2B: pause; Daytona and Instabox: stop), and the next job resumes it, with a new job folder. One job of a user and harness runs at a time; the others wait in line (R5.8). When the provider no longer has the sandbox (it was deleted, or it expired), the next job creates a new one. A sandbox that times out during a job (a crash, a lost network) is paused, not deleted, and no process of that job runs when it resumes. byoa MUST delete the user's sandbox at sign-out, and MUST give the app a way to delete it, such as when it deletes the user. - **Many kept sandboxes per user (a `sandboxKey` for each job).** The same, but each key that the app gives a job (such as a project), and each conversation (R5.9), has its own sandbox and its own lease, so jobs with different keys run at the same time. With the stored login of R1.4, jobs share the login by default, for every harness. The app MUST be able to delete the sandbox of one key, or all of the user's. - **One sandbox per job (`sandboxPer: 'job'`).** Create a sandbox, load the user's setup, run the job, destroy the sandbox. In all three, the user's AI login (R1.4) and grants (R2) stay in the app's database, and the security properties of R1.4 and R3 do not depend on the choice: no real MCP token goes into the sandbox, a job token is refused after its job, and no copy of the AI login stays in the sandbox between jobs. - **R5.5** `agents.run` MUST stream events (text, tool calls, permission requests, errors, turns, end) in one schema for every harness. - **R5.6** byoa MUST let the app limit what the agent of a job may do, with each CLI's own options only (Lab rules). With `access: 'read-only'`, the agent MUST be able to call the job's MCP tools and to read files, so that the harness can read its skills and AGENTS.md; it MUST NOT be able to change a file, or to reach the network by itself. With Codex, its commands MUST NOT be able to read its home folder (CODEX_HOME), which holds the login. The default (`full`) is every tool of the harness with no approval, for a sandbox that is the job's alone. - **R5.7** byoa MUST let the app choose the model and effort of each job, and of each harness by default, with each CLI's own flags only, and MUST list the models a user's plan can use, as each CLI lists them with that user's login. For a plan with a key (R1.8), byoa MUST list the plan's models from its API with the user's key, with no sandbox, and a job MUST name one of them (or get the app's default for the plan). - **R5.8** One user's many agents MUST be the app's choice, in three patterns that work together: jobs of one sandbox wait in line and run in the order they came, with no time limit unless the app sets one; one job MAY carry several messages to one agent, which decides their order; and jobs with different sandboxes run at the same time (R5.4, R1.4). - **R5.9** A job MAY name a conversation (the app's id, such as a chat thread). Then the job MUST continue the harness's own session of the earlier jobs of that conversation, with each CLI's own flags only (Lab rules): Claude Code `--session-id`, then `--resume`; Codex's app server, a thread that is not ephemeral, its id from the `thread/started` notification, then `thread/resume`; Grok Build's ACP, the session that `session/new` names, then `session/resume`. A conversation MUST have its own kept sandbox (R5.4), whose job folder stays from job to job, except the files byoa writes (R4), which each job gets new. Its jobs run one at a time. The `start` event MUST say whether the job resumed, and the `end` event MUST name the harness's session. After each job, byoa MUST keep the session id and, when it is not larger than the app's limit, a copy of the session's files, encrypted in the store; when the provider lost the sandbox, the next job MUST write that copy into its new sandbox. When there is no copy, the job MUST say so (an `error` with code `conversation`) and start a new session. The app MUST be able to delete a conversation, with its copy and its sandbox. - **R5.10** A running job MUST take more messages from the app (steering), in each CLI's own protocol, through a small driver script that byoa runs in the sandbox beside the unmodified CLI: Claude Code's stream-json input (a message waits for the turn that runs); Codex's app server (`codex app-server`), whose `turn/steer` puts a message into the turn that runs; Grok Build's Agent Client Protocol (`grok agent stdio`), whose `x.ai/interject` extension does the same. A message that comes after a turn ended starts the next turn. Each turn before the last gives a `turn` event, and the job ends after the turn that answers the last message. ### R6. Store adapter - **R6.1** The store adapter MUST be a small interface (get, put, delete, compare-and-set) that an app can write for its own database. - **R6.2** Compare-and-set is needed for R2.3. ### R7. Developer experience - **R7.1** A new app MUST reach its first agent run in under 50 lines of its own code. - **R7.2** byoa MUST include a fake harness for tests, so apps can test without a plan or a sandbox. - **R7.3** byoa SHOULD ship an agent skill in the Agent Skills format (`skills/byoa/`) that teaches a coding agent to add byoa to an app, in the npm package and with the package's version as its `metadata.version`, and its site SHOULD serve the docs for LLMs as `llms.txt` and `llms-full.txt`. Both MUST name only the API that byoa has. ## Lab rules byoa follows the labs' published rules as read on 2026-11-22: - Anthropic ([legal and compliance](https://code.claude.com/docs/en/legal-and-compliance)) allows an end user to sign in to the unmodified Claude Code binary with their own plan, including where a platform hosts Claude Code. It forbids third parties to "collect, store, or intermediate Claude.ai credentials or session tokens", unless Anthropic agrees otherwise. - OpenAI ([Sign in with ChatGPT Terms](https://openai.com/policies/sign-in-with-chatgpt-terms/), effective 2026-11-04) requires that "any persistent storage of Authentication Tokens must be local and under the user's control, not in a remote or managed environment", and that the plan is used "only for the application they connected". Paid or remotely hosted apps must [apply](https://openai.com/form/sign-in-with-chatgpt-interest/) to be partners. - OpenCode ([Terms of Use](https://opencode.ai/legal/terms-of-service), effective 2026-11-08, read on 2026-11-25) says that the user "will only use the Services for your own internal use, and not on behalf of or for the benefit of any third party", and forbids using "multiple accounts to circumvent usage limits". Its [Go docs](https://opencode.ai/docs/console/go) say Go "is designed for OpenCode and other coding agents that produce similar types of requests", and ask each client to send "its own user agent" and "a stable session ID". OpenCode documents a Go key in Claude Code and in Codex. Whether an app may run a user's key for that user's own tasks is arguable, not clearly allowed: the work is the user's own, but the app gains from it too. Ian Hsiao accepted this for version 1 on 2026-11-25. There is no "Sign in with OpenCode" for apps; the user creates the key in OpenCode's Console. - xAI (read on 2026-11-25) publishes Grok Build (`@xai-official/grok`, Apache-2.0) for SuperGrok and X Premium+ subscribers, with a device-code sign-in and a headless mode for scripts. Its [terms of service](https://x.ai/legal/terms-of-service) (2026-10-27) say "You may not share your account credentials or make your account available to anyone else", and its [acceptable use policy](https://x.ai/legal/acceptable-use-policy) forbids "Accessing the Services through unauthorized automated or non-human means". Neither says anything about an app that runs Grok Build for its own users, or that stores their login. Ian Hsiao accepted this when he added Grok Build to version 1; we have not asked xAI. So byoa MUST: - run only unmodified `claude`, `codex` and `grok` binaries, and never pretend to be another client (Codex's app server names byoa as its client: `clientInfo.name` is `byoa`); - send the user to the lab's own sign-in page; - not share one AI login between apps; - for OpenCode Go, use only the user's own key, with OpenCode's documented API and the harness's own user agent, and never OpenCode's Console CLI sign-in, which has OpenCode's own client ID. The labs' terms above restrict where these tokens may be stored. byoa keeps the AI login in the app's database by default (R1.4), and ships a per-user volume as an option (R1.5). Each app checks the labs' terms for its own use. Each app is responsible for its own agreements with the labs. An app that offers OpenCode Go asks OpenCode (help@anoma.ly) before it ships it. We plan to sign agreements for our own apps when they have traction. Our hosted mail demo (https://byoa.rippling.computer/demo, `examples/mail/convex`) is a hosted service for strangers: it keeps each visitor's Claude, ChatGPT or Grok login, encrypted, in its Convex deployment, for at most one hour after the visitor's last request, and then signs it out with the CLI and deletes it; sooner when the visitor clicks Sign out or Delete my data. That is the storage that Anthropic's and OpenAI's terms above restrict. Ian Hsiao accepted this on 2026-11-26, before we have an agreement with Anthropic or OpenAI. The demo's page tells visitors that the job uses their own plan and how long their login stays. Our help agent, the chat in the corner of each page of https://byoa.rippling.computer (`site/help.html`, backend in [madeyexz/byoa-help](https://github.com/madeyexz/byoa-help)), is the one place where we do not follow "each user uses their own plan": every visitor's question runs on Ian Hsiao's own ChatGPT plan, in Codex, signed in once with `codex login --device-auth` and kept, encrypted, in its Convex deployment. OpenAI's [Codex app-server docs](https://learn.chatgpt.com/docs/app-server) say "App-server authentication has never been permitted for commercial or hosted services", and its Terms of Use forbid making an account "available to anyone else". Ian Hsiao accepted that risk to his own account on 2026-11-26. The chat says that it runs on the maintainer's plan, and limits keep its use small. An app on byoa must not do this. ## Verification Version 1 is done when every check below passes. Each check names the requirement it proves. | # | Check | How | Proves | |---|---|---|---| | V1 | Bookish uses byoa | Replace `site/agent/login.ts`, `site/agent/sandbox.ts` and `src/core/connectors.ts` in Bookish with byoa. Bookish's existing e2e tests pass. | R1, R2, R5 | | V2 | A second app uses byoa | A second app (the to-do example in `examples/todo`, Margins, or the mail app) runs its first agent job with byoa, on a real sandbox provider and a real plan, with no code copied from Bookish. Count the app's own lines. | R7.1 | | V3 | Every harness | One test user runs the same task with Claude Code, with Codex and with Grok Build. Each run uses that user's own plan. | R1.1, R1.2, R5.5 | | V4 | Two providers | The same user runs a job on E2B, then on Daytona or Instabox. The second job uses the same MCP grants and skills with no new MCP sign-in. | R5.3, R2 | | V5 | Tokens stay out | After a job with an MCP call, a test searches the sandbox's environment, every file, and `/proc/*/cmdline` and `/proc/*/environ` for each real token. It finds none. | R3.3 | | V6 | Old job tokens fail | A job token is used after its job ends. The proxy refuses it. | R3.4 | | V7 | One refresh | Two jobs start at the same time with an expired access token (with `sandboxPer: 'job'`, so that they run at the same time). The MCP server's token endpoint gets one refresh request, and both jobs succeed. | R2.3, R6.2 | | V8 | Sandbox lifecycle | By default, a user's second job runs in the first job's sandbox, which was paused between them, and jobs with two sandbox keys run in two more sandboxes, of which deleting one key removes only that one. When the provider no longer has a sandbox, the next job works in a new one with no new sign-in, and deleting the user's sandbox removes it at the provider. With `sandboxPer: 'job'`, after a job its sandbox no longer exists at the provider. | R5.4 | | V9 | Harness update | Change the pinned version of a harness (Claude Code, Grok Build). The next job for an existing user runs the new version. | R5.2 | | V10 | Config formats | For a sample plugin, the files byoa writes match the expected files for each harness, byte for byte. | R4 | | V11 | Unmodified binaries | The test checks the hash of the installed `claude`, `codex` and `grok` binaries against the published packages. Grok's own postinstall unpacks its binary from the published `grok.br`: the test unpacks that file too. | Lab rules | | V12 | The docs match the API | A test checks that every `agents.*` method, and every name imported from byoa, in the README, the docs (`docs/`) and the agent skill exists in byoa, that the package ships the skill, and that the skill's `metadata.version` and the README's pinned skill install are the package's version. | R7.3 | | V13 | The app's own tools | A job with a real harness calls a tool that the app gave as a function. The function runs in the backend for the job's user. The app has no MCP server, and the user has no grant. | R2.7 | | V14 | A proxy that is down | A job starts while its sandbox cannot reach the proxy. The harness does not start, and the job ends with an `mcp` error and `ok: false`. | R3.5 | | V15 | Read-only access | A job with a real harness and `access: 'read-only'` reads its skill and calls an MCP tool. A command that writes a file fails, and a command that opens a network connection fails. With Codex, a command that reads CODEX_HOME fails. | R5.6 | | V16 | Jobs at the same time | One user starts three Codex jobs with three sandbox keys. They run at the same time with one sign-in, and the login works after them. | R1.4, R5.4, R5.8 | | V17 | A backend that dies | A job's CLI refreshes its login, and the backend dies before the job closes. The next job in that sandbox uses the refreshed login, and a job after a new sign-in uses the new login. A real check also finds no login file in the sandbox once the provider paused it. | R1.4 | | V18 | A sign-in that is left | A sign-in that the app cancels has no sandbox at the provider right after. A sign-in with no check-in for a few minutes has none either. | R1.7 | | V19 | Models | `listModels` returns, for a real login of each harness, what the CLI lists; a job with a model and effort from that list runs with them. | R5.7 | | V20 | OpenCode Go (beta: not run yet) | One test user with a real Go key runs the same task with Claude Code and with Codex on E2B, through the relay. Three jobs of that user run at the same time; a job gets the model it names; a key that OpenCode refuses is `expired`, and one of a workspace with no Go plan is `no-plan`. A search of each sandbox's environment, files and `/proc/*/cmdline` finds no key. | R1.8, R1.6, R5.7, R5.8 | | V21 | Conversations | With a real login of each harness on E2B, one user's conversation has three jobs. The second job knows what the first was told and finds the file the first wrote in the job folder. The third job runs after the conversation's sandbox was deleted at the provider, and still knows it, from the stored copy. A job of each harness takes a second message while it runs and answers it before it ends. | R5.9, R5.10 | | V22 | Protocol models | TLC checks TLA+ models of the job lifecycle and the slot's lease, the shared login's lease and its refresh, crash recovery, the sign-in sandbox and the store indexes (`spec/tla/`), with backends that die, leases that run out and clocks that differ. Each model says what TLC must find: no error, or the counterexample of a known issue. | R1.4, R1.7, R5.4, R5.8, R5.9 | | V23 | A used-up plan | With output of each pinned CLI for a used-up plan, in the shape that its binary writes, and a stand-in for OpenCode's 429 and usage meter: the job ends with `usage-limit` and the reset that the tool said; the next job of that user and harness ends at once, with no sandbox and no request to OpenCode; after the reset, a job runs. A refusal for now is `rate-limited`, and Codex's `unauthorized` is `expired`. | R1.9 | V1 to V9 and V13 to V21 run against real providers and real plans, so they cost money. They run before each release, not on every commit. V10, V11, V12 and the fake-harness tests run on every commit, and V22 on every commit that changes the models or the code they model; these include V13, V14, V16, V17, V18, V19, V20 and V21 with the fake harness, a stand-in CLI and, for V20, a stand-in for OpenCode's API. V23 runs only so (`test/login.test.ts`, `test/plan.test.ts`): no real check runs a plan out, so the stand-ins' output comes from the pinned binaries (Claude Code's stream-json schema, Codex's `generate-json-schema` and source of 0.171.0, Grok Build's strings) and from OpenCode's docs, not from a plan that ran out. In this repository: `npm test` runs V10, V12 and the fake-harness tests, `npm run test:v11` runs V11, `spec/tla/check.sh` runs V22 (`.github/workflows/tla.yml`), and the job `example-todo` runs the to-do example's fake-harness tests (`.github/workflows/ci.yml`). `npm test` starts no paid sandbox, also when the providers' keys are set: each paid check needs its own flag. `npm run test:v4` runs V4 (`test/v4.test.ts`) with `E2B_API_KEY` and `DAYTONA_API_KEY`; `BYOA_V4_PROVIDERS=e2b,instabox` runs it on E2B and Instabox. `npm run test:e2b` runs V8 on E2B (`test/e2b.test.ts`), `npm run test:daytona` runs V8 on Daytona (`test/daytona.test.ts`), and `npm run test:instabox` runs V8 on Instabox (`test/instabox.test.ts`). `npm run test:v20` runs V20 on E2B (`test/v20.test.ts`), with `OPENCODE_GO_API_KEY` and `E2B_API_KEY` set. V20 has not run yet, so OpenCode Go (R1.8) is in beta: its tests use a stand-in for OpenCode's API, and the real Claude Code and Codex were checked only against that stand-in, locally and on E2B. `node scripts/v21.ts` runs V21 on E2B in steps (`login `, `check`, `cleanup`), because it needs a person to sign in. On an Instabox plan that allows fewer than three sandboxes (the free plan allows one), V8 there checks one sandbox key alone, not two at the same time. ## Open questions - Does the first version support Cloudflare Workers, or only Node and Convex? - How does a Claude login move from one sandbox provider to another without the app holding it? Today the user signs in again. - Do Anthropic, OpenAI and xAI accept the default stored login (R1.4) for apps that run their unmodified CLIs, or does an app need an agreement with them? We will ask them. - Does OpenCode accept an app that runs a user's Go key for that user's own tasks (R1.8), given "only for your own internal use"? We will ask them. - The shared login (R1.4) is the default for every harness. The CLIs also refresh their login when the lab answers 401 to a token that has not run out. Two sandboxes that get that answer at the same time both refresh, and one refresh fails. How often does that occur? - `access: 'read-only'` (R5.6) does not hide files: the agent can read each file that its user can read, also Claude Code's and Grok Build's own login files (Codex's are denied to its commands). Does byoa need a level that lets the agent read only its job folder, for apps that run on the user's own computer? - How long does a user's paused sandbox stay? Today byoa deletes it only at sign-out and when the app calls `deleteSandbox`. E2B and Instabox keep a paused or stopped sandbox with no time limit; Daytona archives a stopped one after 7 days, and the next job restores it more slowly. Does byoa need a limit for users who stop using an app? - Do we write a spec for credential references as an extension of Agent Plugins, and send it to the Agentic AI Foundation? --- Source: https://github.com/madeyexz/byoa/blob/main/skills/byoa/SKILL.md --- name: byoa description: Adds byoa to an app, so the app runs each user's own Claude Code, Codex or Grok Build in a sandbox (E2B, Daytona, Instabox or local), on the user's own Claude, ChatGPT, Grok or OpenCode Go plan, with the user's MCP connections. Use when you add AI agent jobs to an app's backend with byoa, write its sign-in, MCP connect, proxy or callback routes, stream agents.run events to a UI, write a byoa store adapter, or test with byoa's fake harness. metadata: version: "1.1.0" --- # Add byoa to an app byoa is a library. It runs inside the app's own backend (Node, Bun or Convex actions). It is not a hosted service. The app gives it a sandbox adapter and a store adapter. byoa then signs each user in to their own plan, keeps their MCP grants, and runs each job in that user's sandbox (or, as an option, a new sandbox for each job). The reference app is the to-do example: https://github.com/madeyexz/byoa/tree/main/examples/todo. Its `app.ts` holds all of its byoa code: the sign-in, the app's own tools (`tools`), a chat (`conversation`), more messages while a job runs (`job.send`) and `access: 'read-only'`. Its `todos.ts` holds the tools and a SQLite store. Read both before you write the app's code, and copy their patterns. The full API, with every option and event, is in [reference/api.md](https://github.com/madeyexz/byoa/blob/main/skills/byoa/reference/api.md). The rules every app must follow are in "Lab rules" below. Do not skip them. ## 1. Install Install byoa from npm: ```sh npm install @madeyexz/byoa bun add @madeyexz/byoa ``` Also install the sandbox SDK that the app uses: `e2b` for E2B, `@daytona/sdk` for Daytona; Instabox needs none. byoa needs Node 22.18 or later, or Bun. The package is `@madeyexz/byoa`: do not write `npm install byoa` or `import ... from 'byoa'`, and do not install `byoa-sdk`, an unrelated package. `metadata.version` above is the `version` in the package.json next to this skill. The npm package has this skill in it (from 1.1.0), so `npx skills experimental_sync -y` after the install links `node_modules/@madeyexz/byoa/skills/byoa` into the app's skills, and the skill always matches the installed byoa. When the installed version is not `metadata.version`, believe the installed version's types. When a name in this skill is a type error, the installed byoa is older than this skill: update it (`npm install @madeyexz/byoa@latest`), or use only what the installed version's types have. Do not write around the missing types. ## 2. One createAgents Make one `agents` object in the backend. Do it once per process (or once per Convex action). ```ts import { createAgents } from '@madeyexz/byoa' import { e2b } from '@madeyexz/byoa/sandbox/e2b' // or: daytona from '@madeyexz/byoa/sandbox/daytona', instabox from '@madeyexz/byoa/sandbox/instabox' import { postgresStore } from '@madeyexz/byoa/store/postgres' // or: convexStore, or the app's own Store const agents = createAgents({ app: 'myapp', // lower-case letters, digits, -; at most 24 sandbox: e2b({ apiKey: process.env.E2B_API_KEY }), store: postgresStore({ query: (sql, args) => pool.query(sql, args) }), encryptionKey: process.env.BYOA_KEY!, // openssl rand -base64 32; keep it the same between restarts proxyUrl: 'https://myapp.example.com/byoa/mcp', // public HTTPS; serve agents.proxy here and below oauth: { redirectUrl: 'https://myapp.example.com/byoa/callback' }, tools: { todos: todoTools }, // the app's own tools, as functions: see section 5 }) ``` - **Store.** `postgresStore` needs its table once: run `POSTGRES_SCHEMA` (from `@madeyexz/byoa/store/postgres`). For Convex, see reference/api.md. For another database, write a `Store` with four methods: `get`, `put`, `delete`, `cas` (compare-and-set). The example's `sqliteStore` in `examples/todo/todos.ts` is one in 19 lines. A new version on every write is required, and a deleted and rewritten key must never get an old version back. - **Sandbox.** `e2b()`, `daytona()` and `instabox()` read their API key from `E2B_API_KEY` / `DAYTONA_API_KEY` / `INSTABOX_API_KEY` when you give none. Instabox has no volumes, so use the default `storedLogin()` there, not `cliLogin`. The default E2B template is named `byoa`, and a new E2B account does not have it: the first job then fails with `404: template 'byoa' not found`. Build it one time with `buildE2BTemplate()` from `@madeyexz/byoa/sandbox/e2b`, or pass `e2b({ template: 'base' })`: byoa then installs the pinned harness in each new sandbox (about 10 seconds). `localSandbox()` from `@madeyexz/byoa/sandbox/local` is a folder on this computer. It isolates nothing: use it only for development and tests. - **The sandbox must reach `proxyUrl`.** With E2B, Daytona or Instabox it must be a public HTTPS URL (in development, a tunnel such as `cloudflared tunnel --url http://localhost:3000`). On Daytona Tier 1 and 2, only allowed domains work, such as `*.convex.site` or `*.workers.dev`. ## 3. Routes the app must serve The app serves two byoa routes, and its own API routes that call `agents.*`. All handlers are fetch handlers (`Request` → `Response`). On Node, wrap the app's handler with `toNodeListener` from `@madeyexz/byoa/node`. ```ts if (url.pathname.startsWith('/byoa/mcp/')) return agents.proxy(req) // the MCP proxy: no app session check here if (url.pathname === '/byoa/callback') { // the MCP server's sign-in page sends the browser here const p = url.searchParams await agents.finishMcp({ state: p.get('state') ?? '', code: p.get('code') ?? undefined, error: p.get('error') ?? undefined }) return Response.redirect(`${publicUrl}/`, 302) } ``` - The proxy checks the job token itself. Do not put the app's own sign-in check in front of it, because the harness in the sandbox has no app session. - `finishMcp` returns `{ user, name }`. It finds the user from the stored `state`, so the callback needs no session either. - Every other route reads the user from the app's own session. The `userId` you pass to byoa is the app's stable user id. Never take it from a header or a body that the browser controls (the example's `x-user` header is a stand-in only). ## 4. Sign the user in to their plan The sign-in runs the unmodified CLI in a sandbox. The user signs in on the lab's own page. byoa gives the app only that page's URL (and, for Codex and Grok Build, a code). ```ts // Claude: show the URL; the user signs in and pastes the code that Anthropic's page shows const { url } = await agents.connectLogin(userId, 'claude') const r = await agents.finishLogin(userId, 'claude', { code }) // r.state: 'signed-in' or an error // ChatGPT (Codex): show the URL and the code; the user enters the code on OpenAI's page const { url, code } = await agents.connectLogin(userId, 'codex') const r = await agents.finishLogin(userId, 'codex', { waitMs: 20_000 }) // call again while r.state === 'pending' // Grok (Grok Build, for SuperGrok and X Premium+): the same as Codex, on xAI's page const { url, code } = await agents.connectLogin(userId, 'grok') const r = await agents.finishLogin(userId, 'grok', { waitMs: 20_000 }) await agents.cancelLogin(userId, 'codex') // the user closed the sign-in: its sandbox ends now await agents.loginState(userId, 'claude') // 'signed-in' | 'signed-out' | 'expired' await agents.signOut(userId, 'claude') ``` Show `url` as a link or a QR code, so the user can sign in on another device. Keep each request short (for example `waitMs: 20_000`) and let the page call `finishLogin` again while the state is `pending`. This also works from short-lived backends such as Convex actions. The sign-in's sandbox lives only while the page checks in: each `finishLogin` keeps it 2 more minutes. For Claude, have the page call `finishLogin(userId, 'claude')` with no code every 30 seconds while the user is on Anthropic's page. When the user closes the sign-in, call `cancelLogin`. Copy the example's `page.html`. **Where the login stays.** With no `login` option, byoa keeps the CLI's own login files encrypted in the app's store (`storedLogin()`, the default). Each job gets a copy in its sandbox; after the job, byoa saves it back when the CLI refreshed it and removes it from the sandbox. A user's jobs in different sandboxes share the login, for every harness. Options: - `login: storedLogin({ store: loginStore, encryptionKey: loginKey })`: a table and a key of their own. - `login: cliLogin`: a volume of that user, behind the sandbox adapter. The app's database never holds the login. It needs a provider with volumes (E2B volumes must be turned on for the team). Tell the developer that the labs' terms restrict where these tokens may be stored (see Lab rules), and let them choose. Do not choose for them in silence. **OpenCode Go (beta; a key, not a sign-in).** No real Go key has run it yet: tell the developer it is in beta. A user with an OpenCode Go plan runs Claude Code or Codex on it with an API key that they create in OpenCode's Console (`oc_sk_…`). The app takes the key one time (a password field; never in a URL or a log) and gives it to byoa: ```ts const r = await agents.connectKey(userId, 'opencode-go', key) // r.state: 'signed-in', or 'no-plan' (no Go plan yet); with r.error when OpenCode refused it await agents.loginState(userId, 'opencode-go') // 'signed-in' | 'signed-out' | 'expired' | 'no-plan' await agents.signOut(userId, 'opencode-go') // deletes the key ``` byoa keeps the key encrypted in the store. It never goes into the sandbox: `agents.proxy` relays the harness's model requests to OpenCode and adds the key there, so the same proxy route serves it (do not filter paths below `proxyUrl`). Jobs pass `plan: 'opencode-go'` and a `model` (section 6). Tell the developer that OpenCode's terms do not clearly allow an app to run a user's key for them (see Lab rules), and let them choose. ## 5. Connect MCP tools, one time per user ```ts // A server with its own sign-in (MCP authorization, OAuth 2.1 with PKCE) const c = await agents.connectMcp(userId, 'https://mcp.notion.com/mcp', { name: 'notion' }) if (!c.connected) return Response.json({ signInUrl: c.signInUrl }) // send the browser there; it comes back to /byoa/callback // A server that takes a token the user pasted (or the app's own server, with this user's token) await agents.connectMcp(userId, 'https://myapp.example.com/mcp', { name: 'todos', bearer: token }) await agents.listMcp(userId) // [{ name, url }] await agents.removeMcp(userId, 'notion') ``` - `name`: lower-case letters, digits and -, at most 32. The job asks for servers by this name. - The URL must be `https://` (or `http://` on localhost). With `bearer`, byoa checks the token with one MCP `initialize` and throws if the server refuses it. - A sign-in that is not finished in 15 minutes runs out; call `connectMcp` again. - byoa refreshes each grant itself, with one refresh owner. Do not refresh or read the tokens in app code. To call a non-MCP API of the same service (for example an export), use `agents.fetchWithGrant(userId, name, url)`. **The app's own tools.** Do not write an MCP server for the app's own data. Give the tools to `createAgents` as functions, and name the group in the job's `mcp`: ```ts const todoTools = { add_todo: { description: 'Add one to-do.', input: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }, // JSON Schema of the arguments run: ({ title }, { user }) => db.addTodo(user, String(title)), // in the backend, for the job's user }, list_todos: { description: "List the user's to-dos.", run: (_args, { user }) => db.todos(user) }, } const agents = createAgents({ ...options, tools: { todos: todoTools } }) agents.run(userId, { harness, task, mcp: ['todos'] }) ``` - `agents.proxy` serves them at `/todos` and checks the job token. `user` is the user of the job; never take the user from the arguments. - What `run` returns goes to the agent: a string as it is, other values as JSON. When it throws, the agent gets the message as a failed call. byoa does not check the arguments against `input`: check them in `run`. - No user connects anything for them, and `listMcp` does not list them. `connectMcp` refuses their names. ## 6. 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'], // the servers this job gets; default none setup: { agentsMd, skills }, // AGENTS.md (and CLAUDE.md for Claude Code); skills: [{ name, files: { 'SKILL.md': '...' } }] access: 'read-only', // what the agent may do; default 'full' model: 'opus', effort: 'high', // optional; default createAgents({ models }), else the CLI's own // plan: 'opencode-go', // optional: the user's OpenCode Go key in place of the lab login; then model is a Go model })) { // ev.type: 'start' | 'text' | 'tool_call' | 'tool_result' | 'permission' | 'error' | 'turn' | 'end' } ``` - The events are the same for every harness. The full schema is in reference/api.md. - `run` never throws for job failures. It yields `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`). 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 Go plan. - **A used-up plan.** `usage-limit`: the user's plan is used up (a 5-hour, weekly or other limit); `resetsAt` (ms since 1970) is when it resets, when the tool said (Claude Code, Codex, OpenCode Go; not Grok Build). Show it to the user. byoa keeps it until then (15 minutes when the tool gave no time): a job of that user and harness ends at once with the same error and starts no sandbox. `agents.usageLimit(userId, harness)` (or `'opencode-go'`) says so before a job, with no sandbox: check it before you show a chat input or start a job. A new sign-in, a new key or a sign-out ends it. `rate-limited`: the lab refused for now (too many requests, overloaded); try again in a moment. Do not match the error's text: use the code. - A server in `mcp` that the user has not connected gives an `error` with code `mcp`, and the job runs without it. - **The proxy check.** Before the harness starts, byoa checks from the sandbox that each of the job's servers answers through the proxy. When the sandbox cannot reach the proxy, the job does not start: an `error` with code `mcp`, then `end` with `ok: false` (`session` throws `ProxyError`). A server that does not answer gives an `error` with code `mcp`, and the job runs. Show these errors: they mean a wrong `proxyUrl`, a tunnel that ended, or a server that is down. - **What the agent may do (`access`).** With `'full'` (the default), the agent has every tool of its harness with no approval: a shell, file changes and the network. That is for coding agents in a sandbox that is the job's alone. With `'read-only'`, the agent calls the job's MCP tools and reads files (the harness reads its skills this way: do not forbid the shell in AGENTS.md, because Codex reads a skill with `cat`); it cannot change a file or reach the network by itself. Use `'read-only'` when the agent needs only its MCP tools (a to-do list, a mail client), and always with `localSandbox()` on a user's own computer. Apart from Codex's home folder (its login), it does not hide files: the agent can read each file its user can read. Ask the developer which one each kind of job needs. - **The sandbox.** By default (`sandboxPer: 'user'`), each user has one sandbox of the app for each harness: the first job creates it, byoa pauses it after each job and resumes it for the next, with a new job folder. One job of a user and harness runs at a time; the others wait in line, in the order they came, with no limit unless `waitMs` sets one (set it on short-lived backends such as Convex actions). A sandbox the provider lost is replaced by a new one. When one user has many workspaces (projects, conversations), pass `sandboxKey` in `run` or `session`: each key gets its own kept sandbox and lease. `sandboxPer: 'job'` gives each job a new sandbox and destroys it after the job; use it when nothing may stay between jobs. - **Conversations.** For a chat, pass the chat's id as `conversation` in each `run` of it (one harness per conversation). The job continues the harness's own session of the earlier jobs, in the conversation's own kept sandbox, whose `~/work` stays; `start` says `resumed`, `end` names the `session`. byoa keeps the transcript encrypted in the store (up to `transcriptBytes`), so a lost sandbox does not lose the conversation; when it is too large, the next job gives an `error` with code `conversation` and starts again. Call `agents.deleteConversation(userId, chatId)` when the user deletes the chat. A job with no `conversation` remembers nothing of earlier jobs, and its `~/work` is new. - **More messages to a running job (steering).** `run` returns a `Job`; `job.send(text)` gives the running agent one more message, with every harness. Codex and Grok Build take it into the turn that runs; Claude Code after that turn. Each turn before the last gives a `turn` event, and `send` returns false once the job ended: then send it as the next job of the conversation. The recipe below puts both together. - **Many agents of one user.** Three ways, which an app can mix; ask the developer which they want: 1. A queue: jobs of one sandbox run one after the other. `onWait: ({ for, ahead })` tells the app how many are ahead. 2. Several messages to one agent: `task: ['first', 'second']`. The agent reads them all and decides the order. 3. Several sandboxes at once: a `sandboxKey` for each agent, or `sandboxPer: 'job'`. The jobs share the user's login and run at the same time, for every harness. Tell the developer the risk that stays with a shared login (reference/api.md, `storedLogin`); `storedLogin({ parallel: false })` turns sharing off. - **Models.** `agents.listModels(userId, harness)` lists what the user's plan can use (`id`, `efforts`); pass `model` and `effort` in `run`, or defaults in `createAgents({ models })`. Each call starts a sandbox, so keep the list for a while. With `plan: 'opencode-go'`, a job needs a model of the plan: `agents.listModels(userId, 'opencode-go')` lists them from OpenCode's API with no sandbox, and `createAgents({ models: { 'opencode-go': { model } } })` sets the default. - `agents.signOut` deletes the user's sandbox for that harness. When the app deletes a user, call `agents.deleteSandbox(userId)` too; when it deletes a project that had a key, `agents.deleteSandbox(userId, { sandboxKey })`. - If the client goes away, stop the loop (or call `return()` on the generator): byoa then closes the job token and pauses (or destroys) the sandbox. The example's `ndjson()` in `app.ts` streams the events as JSON lines and does this on `cancel`. - To run the app's own program around the unmodified harness, use `agents.session(userId, { harness, mcp })` and call `s.close()` in a `finally`. See reference/api.md. ### A chat with the agent A chat is the most common feature: each message of the user is one job of one `conversation`, and a message that comes while a job runs goes to that job. The routes, as in the example's `app.ts`: ```ts const running = new Map() // the jobs that run now; import { type Job } from '@madeyexz/byoa' // POST /api/ask { chat, task }: one message of the user. The page makes the chat id one time (crypto.randomUUID()) const job = agents.run(userId, { harness, task, conversation: chat, mcp: ['todos'], setup: { agentsMd }, access: 'read-only' }) const id = crypto.randomUUID() running.set(`${userId}/${id}`, job) // stream the events to the page with the job's id (the example's ndjson(), with an `x-job` header), and remove the // job from `running` when the stream ends or the browser goes away // POST /api/ask/send { job, text }: a message while the agent works const j = running.get(`${userId}/${body.job}`) return Response.json({ sent: j ? await j.send(body.text) : false }) // false: the job ended; send it as a new /api/ask // POST /api/chat/delete { chat }: the user deletes the chat or starts a new one await agents.deleteConversation(userId, chat) ``` What the page does with each event: | Event | The page | | --- | --- | | `start` with `resumed: false` | A new session. When the chat had earlier messages, its history is gone (the provider lost the sandbox, and the transcript was larger than `transcriptBytes`): an `error` with code `conversation` comes first. Say so. | | `text`, `tool_call`, `tool_result` | Show them as they come. Refresh the app's data after a `tool_result` that changed it. | | `turn` | One answer ended, and the agent goes on with the message the user sent while it worked. Keep the input open. | | `end` | The job ended. `ok: false` follows an `error`. Close the input for `send`, so the next message is a new job. | | `error` `signed-out` or `expired` | Show the sign-in again (for `plan: 'opencode-go'`, ask for a new key). | | `error` `usage-limit` | The user's plan is used up. Show when it resets (`resetsAt`, else the message), and keep the input closed until then (`agents.usageLimit`). | | `error` `rate-limited` | The lab refused for now. Say so, and let the user try again in a moment. | | `error` `harness` | The CLI failed. Show the message. | - Key `running` by the user too, and read the user from the session, so one user cannot send to another user's job. - `running` is in this process's memory. With more than one backend process, `send` must reach the process that runs the job (sticky sessions, or one process for jobs). - One conversation is one harness's session. When the user changes the harness, start a new chat id. ## 7. Test without a plan or a sandbox Use `harness: 'fake'`, `localSandbox()` from `@madeyexz/byoa/sandbox/local` and `memoryStore()` from `@madeyexz/byoa`. The fake harness runs no model. Each task line `call . ` is one MCP call through the real proxy, so a test proves the app's routes, grants and proxy end to end. With the local sandbox, `proxyUrl` can be `http://127.0.0.1:/byoa/mcp`. Copy `examples/todo/todo.test.ts`. A conversation works with the fake harness: in each job of one, it says `fake harness remembers N earlier messages`, so a test can check that a chat goes on and that a deleted chat starts again. Steering does not: the fake harness takes no message while it runs, so `job.send` returns false. Do not write a test that expects `send` to work with `fake`. Do not offer `fake` to end users in production. ## Lab rules Every app on byoa must follow these rules. If a request breaks one, stop and tell the developer. - Run only the unmodified `claude`, `codex` and `grok` binaries that byoa installs (pinned, and checked in byoa's own tests). Do not patch them, wrap them to change what they send, or set headers or a user agent to pretend to be another client. - Send the user to the lab's own sign-in page, from `connectLogin`. Do not embed, proxy or copy that page, and never ask the user for a password or an API key in place of it. The one key byoa takes is an OpenCode Go key, with `connectKey`, which OpenCode's Console makes for this. - For OpenCode Go, never use OpenCode's Console CLI sign-in (`npx @opencode/console`): it has OpenCode's own client ID. OpenCode's terms say "only for your own internal use, and not on behalf of or for the benefit of any third party", so it is not clearly allowed for an app: tell the developer to ask OpenCode (help@anoma.ly) first. - Never read, export or call the labs' APIs with the user's AI tokens. The CLI is the only client that uses them. Do not call the labs' token endpoints. - One app's AI login is only for that app. Give each app its own `app` name and its own store. Never share a login between apps. - Real MCP tokens never go into the sandbox. Give a job its servers with `mcp: [...]`. Never put a grant's token in `setup`, the task, environment variables or files. - The labs' terms restrict where AI logins may be stored. Anthropic says third parties may not "collect, store, or intermediate Claude.ai credentials or session tokens" without its agreement. OpenAI says stored tokens must be "local and under the user's control", and paid or hosted apps must apply to be partners. xAI's terms forbid sharing an account and "unauthorized automated" access, and say nothing about an app that runs Grok Build for its users. byoa's default keeps the login in the app's database; `cliLogin` keeps it in a per-user volume. Each app checks the terms and makes its own agreements: https://github.com/madeyexz/byoa/blob/main/SPEC.md#lab-rules ## Check your work - The app's byoa code is small: the example's backend, a chat with sign-in, tools and steering, uses byoa in 49 lines. If you write sign-in, OAuth, token refresh or sandbox code yourself, you are rebuilding byoa: use its API. - Run the app's tests with the fake harness and the local sandbox. - Every API name you use is in reference/api.md. If a name is not there, read the source (`src/agents.ts` and `src/job.ts` in https://github.com/madeyexz/byoa) before you use it. --- Source: https://github.com/madeyexz/byoa/blob/main/examples/todo/README.md # AI-native to-do list: an example app on byoa A small to-do app. The user signs in with their own Claude, ChatGPT or Grok (SuperGrok, X Premium+) plan (or saves the key of their OpenCode Go plan), and then chats with the agent about their to-dos ("add buy milk, and mark the oldest one done", then "now the same for tomorrow"). Each message is one job of the chat: byoa resumes the chat's sandbox (or creates it for the first job), continues the user's own, unmodified Claude Code, Codex or Grok Build session in it, and pauses the sandbox after the job. While the agent works, the user can send it one more message. The app has no code from Bookish. It is the second app for check V2 in [SPEC.md](https://github.com/madeyexz/byoa/blob/main/SPEC.md#verification). ## The files | File | What it does | Lines of code | |---|---|---| | [app.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/app.ts) | The backend, as one fetch handler. All of the app's byoa code is here. | 100 | | [todos.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todos.ts) | The app's own data (SQLite), its four to-do tools, and byoa's store adapter for SQLite. | 65 | | [main.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/main.ts) | Starts the server on Node and selects the sandbox provider. | 24 | | [page.html](https://github.com/madeyexz/byoa/blob/main/examples/todo/page.html) | The page: sign in, the chat, the list and more tools, styled after shadcn/ui, with no build step. | 365 | | [todo.test.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todo.test.ts) | Tests with byoa's fake harness. | 108 | "Lines of code" does not count empty lines and comments. Of the backend's 189 lines, 49 in app.ts use byoa: `createAgents`, the routes that call `agents.*`, the chat and its messages while a job runs, the MCP callback, and the stream of events to the page. The SQLite store adapter is 19 more; with byoa's own Postgres or Convex adapter, it is one line. The rest is the to-do app itself. ## How the app uses byoa 1. **One `createAgents`** ([app.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/app.ts)). The app gives byoa its sandbox provider, its own database (through `sqliteStore`, 19 lines in [todos.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todos.ts)), an encryption key, and the URLs where it serves byoa's MCP proxy and the MCP sign-in callback. The app gives no `login` option, so byoa keeps each user's plan login (the CLI's own login files) encrypted in the app's database, and writes a copy into each job's sandbox. After the job, byoa saves the files back when the CLI refreshed them, and removes them from the sandbox. No sandbox volumes are needed. With `login: cliLogin`, the login stays in a volume of the user instead, and the app's database never holds it. The labs' terms restrict where these tokens may be stored: see [SPEC.md](https://github.com/madeyexz/byoa/blob/main/SPEC.md#lab-rules), and check them for your own app. 2. **Sign in to the plan.** `agents.connectLogin(user, 'claude')` runs the real `claude auth login` in a sandbox and gives the URL of Anthropic's own sign-in page. The user signs in there and pastes the code that page shows; `agents.finishLogin` types it into the CLI. For ChatGPT, `codex login --device-auth` gives OpenAI's page and a code to enter there; for Grok, `grok login --device-auth` gives xAI's page and a code. For OpenCode Go, the user makes an API key in OpenCode's Console and saves it on the page: `agents.connectKey(user, 'opencode-go', key)` checks it with OpenCode and keeps it encrypted, and a job with `plan: 'opencode-go'` and a model from `agents.listModels(user, 'opencode-go')` runs Claude Code or Codex on it. The key never goes into the sandbox. 3. **The app's own tools.** The four to-do tools are functions in [todos.ts](https://github.com/madeyexz/byoa/blob/main/examples/todo/todos.ts), given to `createAgents({ tools: { todos } })`. `agents.proxy` serves them at `/todos` to each job that names `todos` in `mcp`, and gives each tool the user of the job, from the job token. So the app writes no MCP server, keeps no token for it, and the user connects nothing. The user can also connect any remote MCP server (for example Notion) with its own sign-in page: `agents.connectMcp`, then byoa does the OAuth and calls `/byoa/callback`. 4. **Chat.** `agents.run(user, { harness, task, mcp, setup: { agentsMd }, access: 'read-only', conversation: chat })` gives a stream of events (`start`, `text`, `tool_call`, `tool_result`, `error`, `turn`, `end`) in one schema for every harness. The app sends them to the page as they come, one JSON object for each line. `conversation` is the page's id of the chat, so each job continues the harness's own session of the chat (`start` says `resumed`). **New chat** calls `agents.deleteConversation`. `access: 'read-only'`: the agent calls its tools and reads files, and cannot change a file or reach the network by itself. 5. **One more message while the agent works.** `run` returns a `Job`. The app keeps the running jobs by an id that it sends to the page (the `x-job` header), and `POST /api/ask/send` calls `job.send(text)`. A turn that is not the last gives a `turn` event. `send` returns false when the job ended, or with the fake harness, which takes no message while it runs. 6. **The proxy.** The harness in the sandbox gets only a job token. Its MCP calls go to `agents.proxy`, which runs the app's tools, or adds the user's real token and sends the call to the MCP server. The real token never goes into the sandbox. ## Run it You need Node 22.18 or later. From the root of this repository: ```sh npm ci # installs and builds byoa cd examples/todo && npm install BYOA_KEY=$(openssl rand -base64 32) FAKE=1 npm start ``` Open http://127.0.0.1:3000, type a name, select **Fake harness**, and ask with lines such as `call todos.add_todo {"title":"Buy milk"}`. The fake harness runs no model: each line `call . ` is one MCP call through the real proxy. Ask again in the same chat, and it says how many earlier messages it remembers. In your own app, install byoa with `npm install @madeyexz/byoa` instead. ### Settings | Variable | Default | What it is | |---|---|---| | `BYOA_KEY` | (required) | 32 random bytes as base64. byoa encrypts the MCP grants, the plan logins and the chats' transcripts with it. Keep it the same between restarts. | | `SANDBOX` | `local` | `local`, `e2b` (needs `E2B_API_KEY`) or `daytona` (needs `DAYTONA_API_KEY`). | | `PUBLIC_URL` | `http://127.0.0.1:$PORT` | Where browsers and sandboxes reach the app. | | `PORT` | `3000` | | | `DB` | `.data/todo.db` | The SQLite file. | | `FAKE` | off | `1` lets jobs use the fake harness. | The local sandbox is a folder on your computer. It isolates nothing, so use it only on your own computer. With Claude Code, Codex or Grok Build in it, the harness runs on your computer with your login. With E2B or Daytona, the sandbox must reach the proxy, so `PUBLIC_URL` must be a public HTTPS URL, for example from `cloudflared tunnel --url http://localhost:3000`. On Daytona Tier 1 and Tier 2, a sandbox reaches only [allowed domains](https://www.daytona.io/docs/en/network-limits). ## Test it ```sh npm test # the fake harness and the local sandbox: no plan, no sandbox provider (steering needs a real harness) npm run typecheck ``` CI runs both on every commit (`.github/workflows/ci.yml`, job `example-todo`). ## What a real app changes - **The user.** The page sends the user's name in an `x-user` header. That is a stand-in, not a sign-in: anyone can type any name. A real app reads the user from its own session. - **The database.** SQLite in one process is enough for one server. For more servers, use byoa's Postgres or Convex store adapter, or write one for your database (four operations: get, put, delete, compare-and-set). --- Source: https://github.com/madeyexz/byoa/blob/main/examples/todo/app.ts