# agentdevlabs

JS/TS SDK for Agent Dev Labs Capture & Replay. `adl(client)` records the calls your app makes through an OpenAI or
Anthropic client. Your provider key stays with your app.

```sh
npm install agentdevlabs
```

```ts
import OpenAI from 'openai'
import { adl } from 'agentdevlabs'

const client = adl(new OpenAI())
```

## Set up with a coding agent

To teach your agent this once, for every project, run `npx agentdevlabs skill install`: Claude Code, Codex, Cursor and other agents that read Agent Skills then know the SDK and the CLI.

1. Check that `AGENT_DEV_LABS_TOKEN` is set in `.env`. If it isn't, stop and ask the user for it. Never create a token or write one into code, and never commit `.env`. The SDK reads the process environment, not `.env` itself, so make sure the app loads it. In JavaScript run the app with `node --env-file=.env`.
2. Install `agentdevlabs` and the provider SDK (`openai`, or `@anthropic-ai/sdk` 0.50.1 or later) with the project's own package manager. Needs ESM and Node 22.12 or later. If you move `@anthropic-ai/sdk` from 0.x to 1.x, record again any call that sends `temperature`, `top_p` or `top_k`: a 0.x recording of one replays, but the 1.x API refuses it live.
3. Wrap the provider client where it is created: `adl(new OpenAI())` or `adl(new Anthropic())`. Leave `AGENT_DEV_LABS_MODE` unset unless the user asks, because it outranks the devkit toggle.
4. Run the app twice with `AGENT_DEV_LABS_VERBOSE=1`, letting each run exit on its own (a killed run loses its upload). Every call prints a line starting `[agentdevlabs]`: run 1 should print `captured` and run 2 `replayed`. Unset the setting after.
   - `passed-through`, `failed` or `not-stored`: the reason follows the word; read it. `not-stored` comes after `captured` when the server refused the capture, such as a token that can't capture.
   - `captured` on run 2: read the SDK's warnings, and look for a prompt that changes between runs, such as a date or an id.
   - No line: the call wasn't hooked; read the SDK's warning.
   - Ask the user to look in the console's Traces and Calls only if that doesn't settle it, since you can't sign in.

Settings are environment variables only:

| Variable | Meaning |
| --- | --- |
| `AGENT_DEV_LABS_TOKEN` | Your workspace token. Without it the SDK warns once and records nothing: each call passes through, and its report says `passed-through`, `off` and `disabled`. |
| `AGENT_DEV_LABS_MODE` | `auto`, `capture`, `replay` or `off`, in any case. Overrides the server's mode, except a server `off` for production or the plan limit, which always wins. Any other value runs as `auto`, with one warning naming it. |
| `AGENT_DEV_LABS_DISABLED` | `1`, `true`, `yes` or `on` turns the SDK off; `0`, `false`, `no`, `off` or empty leaves it on. Any other value turns it off, with one warning naming it. Beats every other setting. |
| `AGENT_DEV_LABS_VERBOSE` | `1`, `true`, `yes` or `on` prints one line per call to standard error: `[agentdevlabs] captured`, `replayed`, `passed-through`, `failed` or `not-stored`, the last three with their reason. `0`, `false`, `no`, `off` or empty leaves it off; any other value leaves it off, with one warning naming it. Sends nothing. |
| `AGENT_DEV_LABS_API_URL` | The API to talk to. |
| `AGENT_DEV_LABS_REPLAY_SPEED` | How fast a replayed stream plays: `realtime` (the default), `fast` (10x), `instant`, or a number to divide the recorded pace by. Non-streamed replies are instant unless this is set. |
| `AGENT_DEV_LABS_GROUP` | Names a trace group: calls are captured into it and replays use only its recordings. Letters, digits, `.`, `_`, `/` and `-`, up to 100. |
| `AGENT_DEV_LABS_CACHE_DIR` | Where replayed captures are cached, encrypted. Defaults to your OS cache directory. |

## Apps built on LangChain and similar

LangChain, LangGraph, Deep Agents, the Vercel AI SDK and Mastra build their own provider clients, so there is no client to wrap. Call `init()` once, first in your entry file, before any import that builds a client. It hooks the global `fetch`, so every OpenAI and Anthropic call made after it is recorded and the rest of your app stays as it is. Do not also wrap those clients with `adl`.

```ts
import { init } from 'agentdevlabs'

init({ onCall: (report) => console.log(report.outcome) })
```

- **What it doesn't reach:** a client built before `init()`, or given its own `fetch`. In strict replay such a call goes to the provider. `adl(client)` after `init()` records a client built before it.
- **Versions:** LangChain 1.6, LangGraph 1.7, Deep Agents 1.17, the AI SDK 7 with `openai(…)` or `anthropic(…)` models, not AI Gateway string ids, and Mastra 1.86. Eve works with its own `openai()` and `anthropic()` models; its runs group by inference only.
- **Traces:** wrap a chain, graph, agent, `generateText`, `streamText` or Mastra run in `trace()`. In a server, use one `trace()` per request: without it each Deep Agents subagent starts its own trace.
- **Strict replay:** a call with no capture answers `400`, so the library around the provider does not send it again. `modelRetryMiddleware` turns it into a model message unless you set `onFailure: "error"`: set that in CI.
- **Retries:** a call a library sends again after an error status is a step of the same trace.
- **Callback handlers:** keep them the same between capture and replay. A handler with `handleLLMNewToken` makes `invoke()` stream, which changes the cache key.

## Make one trace from a block

Calls inside `trace(name, fn)` make one trace. The trace ends when its last call finishes, which can be after `fn` returns. Name it with a fixed string such as `checkout`: the name is stored as plain text and shown to your workspace, so never put user data in it. A trace without a name shows its first prompt.

## See what each call did

`adl(client, { onCall })` calls your listener once per provider call with the mode in effect, where it came from, and what happened. A request that raises gets no report: your app gets the error. It sends nothing anywhere.

```ts
const client = adl(new OpenAI(), {
  onCall: (report) => console.log(report.outcome, report.mode, report.modeFrom),
})
```

| Field | Meaning |
| --- | --- |
| `outcome` | `replayed` (a stored capture answered), `captured` (the provider answered and the call is recorded), `passed-through` (the provider answered and nothing was recorded), `failed` (strict replay had no capture, so the provider was not called) or `not-stored` (the server did not store a capture reported as `captured`; `reason` says why). |
| `mode` | The mode this call ran in: `auto`, `capture`, `replay` or `off`. |
| `modeFrom` | `env` (`AGENT_DEV_LABS_MODE`), `server` (the console or devkit toggle, the environment's default, or the token), `default` (the server could not be reached or rejected the token) or `disabled` (`AGENT_DEV_LABS_DISABLED` or no token). |
| `pin` | `{ traceId, setAt }` when the environment's pinned trace answered the call. |
| `traceId`, `step`, `cacheKey` | Which capture the call matched or made. |
| `reason` | Why a call failed or went unrecorded. |

A listener that throws is ignored: the call goes on and the SDK warns once. A report holds ids and reasons, never a prompt, a response or a key. A provider retry is its own call, and an attempt about to be retried gets no report.

## Token counts and cost

An OpenAI chat stream reports token counts only when the request asks for them. Without that, the capture has no counts and its cost shows as unknown. The SDK never sets the option for you, since it adds a final chunk with empty `choices` to the stream your code reads and changes the request's cache key.

```ts
const stream = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages,
  stream: true,
  stream_options: { include_usage: true },
})
```

OpenAI Responses and Anthropic streams report counts on their own.

## Replay in CI

Record a group on your machine, then replay only that group in CI. A call with no recording in the group fails with an error naming the cache key and the group (or saying the group doesn't exist), says it did not go to the provider, and says how to record it, so CI never reaches the provider.

The group name uses letters, digits, `.`, `_`, `/` and `-`, up to 100 characters; anything else fails at startup. `AGENT_DEV_LABS_TOKEN` in CI must be a `replay-only` service token, which an owner or admin creates in the console's Access tokens page.

```sh
AGENT_DEV_LABS_GROUP=checkout-flow AGENT_DEV_LABS_MODE=capture npm test   # once, locally
```

```yaml
# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22 }
      - run: npm ci
      - run: npm test
        env:
          AGENT_DEV_LABS_TOKEN: ${{ secrets.AGENT_DEV_LABS_TOKEN }}
          AGENT_DEV_LABS_GROUP: checkout-flow
          AGENT_DEV_LABS_MODE: replay
```

## Project rules: a worked example

A travel agent's system prompt carries today's date, a session UUID and a request id, so Monday's recording never matches on Tuesday. In the console's Project rules page, three masks make the calls match:

- `[0-9]{4}-[0-9]{2}-[0-9]{2}` masks the date.
- `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}` masks the session UUID.
- `req_[A-Za-z0-9]+` masks the request id.

A mask changes only what matching reads, so the recording still holds the original text. To see which mask a pair of calls needs, open a trace, choose "Why didn't this replay?" on step 1 and "Try this rule" on a suggestion.

A card number the user typed should never be uploaded, so add a redact pattern such as `[0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4}`. The SDK replaces it with `[redacted]` before upload; matching still uses the original, so redacting doesn't stop replays. The page's "Try it" box shows both results on a sample request that never leaves the browser.

Calls already recorded keep the rules they were captured with: after saving a rule, capture them again.

## CLI

`npx agentdevlabs <command>` sets up and runs the SDK from a terminal.

| Command | Does |
|---|---|
| `login [--code]` | Opens the console in your browser to approve the login. `--code` prints a code to type there instead, for SSH, containers and other machines with no local browser. |
| `mode <auto\|capture\|replay\|off\|clear>` | Sets the mode for the environment you logged in to, from the next trace. `AGENT_DEV_LABS_MODE` and production still win. |
| `status` | Prints the environment's mode, where it came from, and the pin. |
| `logs [--follow]` | Prints recent calls; `--follow` keeps printing new ones until Ctrl-C. |
| `replay [--group <name>] -- <command>` | Runs a command in replay mode. Needs `AGENT_DEV_LABS_TOKEN`, normally a `replay-only` service token. |
| `skill install` | Installs a skill that teaches coding agents the SDK and the CLI, in `~/.claude/skills` and `~/.agents/skills`. Run it again after you upgrade. |

`login` stores a personal token for one environment in your OS keychain, or in a `0600` credentials file under your config directory when there is no keychain. The CLI renews it before it expires. Set `AGENT_DEV_LABS_TOKEN` to use a token without logging in. `replay` exits with the command's exit code, so a recording miss fails the run.

## License and privacy

Apache-2.0. The SDK sends nothing beyond the capture and replay events described above: no usage analytics or telemetry.

## Versions

Versions follow semantic versioning. Before 1.0, a minor release (0.1 to 0.2) may break your code; the changelog says how, and the API supports only the latest 0.x minor. From 1.0, the API supports the previous major version for 12 months after a new major ships. See the [changelog](https://agentdevlabs.com/docs/js-changelog.md).
