Metadata-Version: 2.5
Name: tapebox
Version: 0.1.0
Summary: Record an agent's model calls through a gateway, replay them in a sandbox without a model
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Requires-Python: >=3.12
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: host
Requires-Dist: aiohttp>=3.9; extra == 'host'
Description-Content-Type: text/markdown

# TapeBox

Record what an agent does in a sandbox as a tape, then play the tape back in a fresh sandbox
without calling a model.

An agent run is a conversation with a model plus the tool calls the harness ran between model
calls. TapeBox records the conversation by proxying the model calls, and replays it by playing
both sides of the harness: the model (serving recorded responses) and the harness (running the
tool calls those responses contain). The sandbox is the only thing that runs for real, which is
what makes tapes a repeatable workload for container runtimes, microVMs, schedulers and
snapshot/fork mechanisms.

## Components

```
                 record                                   replay
                 ------                                   ------
  sandbox     ┌───────────┐                         ┌───────────────┐
              │  agent    │                         │ tapebox-exec  │  plays the harness:
              │ (harness) │                         │  + harness/   │  tool call -> run -> result
              └─────┬─────┘                         └───────▲───────┘
  model calls       │                      docker exec -i,  │ JSON lines on stdin/stdout
                    ▼                                       │
  host        ┌───────────┐   tape   ┌─────┐   tape   ┌─────┴─────────┐
              │  gateway  │ ───────> │ api │ <─────── │  controller   │  plays the model: walks the
              │  (proxy)  │          └─────┘          │               │  tape, issues its tool calls
              └─────┬─────┘                           └───────────────┘
                    ▼                                   ▲ or speaks the provider API, so a real
              real provider                             │ harness can replay (simulator mode)
```

| Component | Where it runs | Job |
|---|---|---|
| `tapebox/api` | host | the tape format, the controller/executor protocol, provider wire-format adapters, the recorder. Stdlib only. |
| `tapebox/gateway` | host | proxy between the agent and the provider; records every call with timing into one tape file |
| `tapebox/telemetry` | host | samples the container's CPU and memory through the Docker API, 4 times a second, into a CSV next to the tape (`--telemetry`) |
| `tapebox/controller` | host | replays a tape: drives `tapebox-exec` in the sandbox through one exec session (executor mode), or answers a real harness's model calls (simulator mode); optionally records the replay as a new tape |
| `executor/` | sandbox | `tapebox-exec`, a 2 MB static Rust binary on the sandbox PATH, built for x86_64 and aarch64 and bundled in the wheel. Performs tool calls the way the harness would and formats their results likewise. Needs no Python, libc, or network. |
| `executor/src/harness` | sandbox | one module per harness (Claude Code, Codex): tool call -> action, action result -> tool result, plus the policy (concurrency, subagent tools) the binary reports to the controller |

Two separations keep the code reusable:

- **Provider vs. harness.** A provider is an API shape (Anthropic Messages, OpenAI Chat
  Completions and Responses); a harness is the program that used it (Claude Code, Codex).
  Provider adapters live in `tapebox/api/providers` and are shared by gateway and controller.
  Harness modules live in the executor binary and know nothing about bytes on the wire; the
  controller learns the little it needs about a harness (which calls run concurrently, which
  spawn subagents) from the binary's hello reply.
- **Normalized vs. raw.** A tape stores each model call in a provider-independent form (what the
  executor and analysis read) and in the provider's raw form (what the controller streams to a
  real harness in simulator mode). Normalized is always derived from raw.

A tape is one plain JSON object in one file, so a collection of runs can go straight into a
Hugging Face dataset, one tape per row. The file is rewritten after every model call, so a run
that is still going, or that was cut short, is a readable tape.

## Install

```sh
pip install tapebox[host]        # host: gateway, controller, and the bundled executor binaries
```

The wheel carries `tapebox-exec` as static binaries for both Linux architectures, under
`tapebox/bin/`. The sandbox needs nothing installed, not even Python (Claude Code's Bash tool
does need `/bin/bash`). Get the binary onto the sandbox's PATH either way:

```sh
tapebox replay ... --sandbox docker:mybox --install-executor     # copies it into the container
docker cp "$(tapebox exec-binary --arch aarch64)" mybox:/usr/local/bin/tapebox-exec   # by hand
```

From a checkout:

```sh
uv pip install -e ".[host,dev]"  # editable: no binary build
executor/build.sh                # -> executor/dist/tapebox-exec-{x86_64,aarch64} and tapebox-exec (host arch)
```

`executor/build.sh` compiles in a Docker container (`rust:1-alpine` plus both musl targets), so
the host needs Docker but no Rust toolchain. Both architectures are cross-compiled from either
kind of host; the crate has no C code, so Rust's own linker does the foreign target. An
editable install finds the binaries in `executor/dist/`; `uv build` runs the same script and
bundles the result into the wheel (`hatch_build.py`), so a published package always carries
freshly built binaries. The binaries are never committed.

## Usage

```sh
# record: run the agent with its base URL pointed at the gateway; one run, one JSON file
tapebox gateway --output run.json --listen :8080 --task bench=tb4 --task id=hello-world
ANTHROPIC_BASE_URL=http://host:8080 claude -p "..."
curl -X POST http://host:8080/tapebox/end        # or just stop the gateway

# replay, executor mode: no harness and no model; tapebox-exec is on the container's PATH
tapebox replay --tape run.json --sandbox docker:mybox --cwd /app --output replay.json

# replay, simulator mode: the real harness, no model
tapebox replay --tape run.json --listen :8081 --output replay.json
ANTHROPIC_BASE_URL=http://host:8081 claude -p "..."         # inside the sandbox

tapebox inspect run.json
tapebox compare run.json replay.json
```

Executor mode runs to completion and exits non-zero if some thread of the tape could not be
played to its end. The controller starts `tapebox-exec serve` once per sandbox (`docker exec
-i`) and keeps that session for the whole replay, so a tool call costs a pipe round trip
rather than a process start: about 0.2 ms instead of the 100 ms of a `docker exec` per call.
Several tool calls may be in flight at once, which is how parallel tool calls replay in
parallel. If the executor dies, the session restarts it; background commands keep their
output on the sandbox's disk, so a restarted executor still answers for them.

Simulator mode serves the provider's own paths (`/v1/messages`, `/v1/chat/completions`,
`/v1/responses`). Several harnesses can replay the same tape concurrently through
`/r/<run>/v1/...`; each run's replay tape goes to `<stem>.<run>.json`.

Pacing: the controller reproduces the model's recorded latency, chunk by chunk for streams.
`--speed 2` halves it, `--speed 0` removes it. Tool execution itself always runs as fast as
the sandbox allows.

Identifiers: a harness names sessions, background commands and subagents with fresh random ids
and tells the model about them in tool results. The controller compares each tool result the
replay reports with the recorded one, learns which new id stands for which recorded one, and
substitutes them in the responses it serves from then on.

## Telemetry

`--telemetry` samples the sandbox container's CPU and memory every 250 ms through the Docker
Engine API (`/containers/<id>/stats`, one-shot) and writes them as CSV next to the tape, as
`<output stem>.telemetry.csv`:

```sh
tapebox gateway --output run.json --telemetry --container mybox             # while recording
tapebox replay --tape run.json --sandbox docker:mybox --output replay.json --telemetry   # while replaying
tapebox replay --tape run.json --listen :8081 --output replay.json --telemetry --container mybox
```

| column | meaning |
|---|---|
| `t_ms` | milliseconds on the tape's clock, so rows line up with the steps' `timing` |
| `time` | the sample's wall-clock time, UTC |
| `cpu_percent` | as `docker stats`: 100 means one core busy since the previous sample; empty on the first row |
| `cpu_ms` | cumulative container CPU time |
| `memory_bytes` | memory in use, cgroup usage minus inactive file cache, as `docker stats` shows it |
| `memory_limit_bytes` | the container's limit |
| `pids` | processes in the container |

The Docker endpoint is `DOCKER_HOST`, else the active `docker context`, else
`/var/run/docker.sock`. A missing container fails at start-up; transient API errors are logged
and sampling continues.

## Where tapes are written

Both recording and replay write a tape to the path given with `--output`; nothing is written
anywhere else. Parent directories are created; an existing file is overwritten.

| Command | `--output` | What the file holds |
|---|---|---|
| `tapebox gateway --output run.json` | required | the recording: every model call of the run, with timing |
| `tapebox replay --tape run.json --output replay.json` | optional | the replay, in the same format: the responses served and the tool results the sandbox actually produced, with the replay's own timing and `meta.replay_of` set to the recording's id |

A replay tape is a tape like any other: it can be replayed again, inspected, or put in the
dataset next to its recording. `tapebox compare run.json replay.json` diffs the two step by
step and exits non-zero when the replay did not get to the end.

## The executor protocol

`tapebox-exec serve` reads requests on stdin and writes results on stdout, one JSON object per
line. Logs go to stderr; the process's own stdout is redirected to stderr at start so nothing a
tool prints can corrupt the channel.

```
controller -> executor                                  executor -> controller
{"op":"hello","harness":"claude-code","cwd":"/app",     {"op":"hello","ok":true,"version":"0.1.0","protocol":1,
 "env":{},"state_dir":null}                              "harness":"claude-code","cwd":"/app",
                                                         "policy":{"parallel_tool_calls":true,
                                                                   "spawning_tools":["Agent","Task"]},
                                                         "platform":"linux-6.8.0-x86_64"}
{"op":"call","id":"7","call":{"id":"toolu_01",          {"op":"result","id":"7","result":{"tool_call_id":"toolu_01",
 "name":"Bash","input":{"command":"ls"}},                "content":[{"type":"text","text":"..."}],
 "recorded":{...} | null}                                "is_error":false,"duration_ms":12}}
{"op":"bye"}                                            {"op":"bye","ok":true}
                                                        {"op":"error","id":"7"|null,"message":"..."}
```

`hello` comes first and sets up the sandbox (harness module, working directory, environment).
Its reply carries the harness's policy: whether the tool calls of one response run concurrently,
and which tools spawn a subagent. Spawning calls never reach the executor; the controller plays
the child thread and hands its final text back as the result. Any number of `call` requests may
be in flight; results come back in completion order and are matched by `id`. `recorded` is the
tape's result for the call, used for tools whose effect is not in the sandbox (replayed
verbatim). `call` and `result` carry the tape's own `ToolCall` and `ToolResult` records.
`tapebox-exec call --harness NAME --cwd DIR` runs a single `call` request from stdin without a
session, for debugging. The full definition is the docstring of `tapebox/api/protocol.py`.

Background commands (`run_in_background`) are detached with their output, pid and exit code
written under `<cwd>/.tapebox/tasks/`, so a restarted executor still answers for them.

## The tape

```
tape
  version        1
  meta           tape_id, harness, harness_version, provider, model, started_at, task{}, replay_of, labels{}
  threads[]      one per conversation: the main agent, then each subagent
    id, parent   parent = [thread id, tool call id] that spawned it, null for the main thread
    steps[]      one per model call
      request    system, messages[], tools[], params{}, stream, raw{}, headers{}, path
      response   content[] (text | thinking | tool_use), stop_reason, usage{}, raw{}, chunks[] (at_ms, data), status
      tool_calls[]    id, name, input{}           parsed from the response
      tool_results[]  tool_call_id, content[], is_error, duration_ms   taken from the thread's next request
      timing     request_at, first_byte_at, last_byte_at, next_request_at   (ms since meta.started_at)
```

`tapebox/api/tape.py` is the source of truth, `tapebox/api/schema.json` the JSON Schema.

## Adding a harness

Write one module under `executor/src/harness/` implementing the `Harness` trait (`policy`,
`to_action`, `to_result`), add it to `get` in `executor/src/harness/mod.rs`, rebuild, and
record tapes with `--harness <name>`. The actions a harness can map to are in
`executor/src/actions.rs`: Shell, TaskOutput, ReadFile, WriteFile, EditFile, Glob, Grep,
ApplyPatch, Noop. Tools with no sandbox effect (todo lists, web fetches, MCP tools) map to Noop
with the recorded result replayed verbatim. Nothing on the host changes.

## Layout

```
tapebox/                                              the host side (Python)
  api/            tape.py  io.py  recorder.py  protocol.py  schema.json  providers/{base,anthropic,openai}.py
  gateway/        server.py  upstream.py
  telemetry.py    CPU and memory of the container every 250 ms, as CSV next to the tape
  controller/     driver.py  sandbox.py  session.py  simulator.py  server.py  cursor.py  matcher.py  pacing.py  identifiers.py  compare.py
  cli.py                                              (tapebox)
executor/                                             the sandbox side (Rust, static binaries)
  src/            main.rs  protocol.rs  actions.rs
    harness/      mod.rs  claude_code.rs  codex.rs
  build.sh  Dockerfile.build  Cargo.toml              -> dist/tapebox-exec-{x86_64,aarch64}
hatch_build.py                                        bundles them into the wheel as tapebox/bin/
tests/
```

## Tests

```sh
uv pip install -e ".[host,dev]"
PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 pytest
```

The tests drive the real `tapebox-exec` binary and build both architectures first if they are
missing or stale (so they need Docker). The end-to-end test records a scripted run (a fake provider, a mini
harness that runs its Bash calls for real and spawns a subagent) through the gateway, then
replays the tape in executor mode (locally, and in a `debian:bookworm-slim` container with no
Python in it when that image is available) and in simulator mode, and checks that the sandbox
ends up in the same state and the replay tapes compare identical.

## License

Apache 2.0.
