Metadata-Version: 2.5
Name: agent-jit-runtime
Version: 0.1.1
Summary: A tracing-JIT runtime for tool-using LLM agents
Project-URL: Homepage, https://github.com/Rayyan-Oumlil/agent-jit
Project-URL: Issues, https://github.com/Rayyan-Oumlil/agent-jit/issues
License: Apache-2.0
License-File: LICENSE
Keywords: agents,cost-reduction,jit,llm,tool-use
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# agent-jit

[![CI](https://github.com/Rayyan-Oumlil/agent-jit/actions/workflows/ci.yml/badge.svg)](https://github.com/Rayyan-Oumlil/agent-jit/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/agent-jit-runtime)](https://pypi.org/project/agent-jit-runtime/)
![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue)
[![License](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)

**A tracing JIT compiler for tool-using LLM agents.** agent-jit watches an agent work, spots the
multi-step tasks it repeats, and compiles them into guarded Python that runs without the inner-loop
LLM. When a guard fails mid-run, the job goes back to the agent as already-executed tool history, and
a write-ahead journal at the tool boundary stops a write from running twice.

It is middleware around an existing agent, not a new agent framework. Zero runtime dependencies.

```bash
pip install agent-jit-runtime      # the import name is agent_jit
python -m agent_jit.demo           # end-to-end toy, no API key needed
```

## Results

Every number comes from a script in [`benchmarks/`](benchmarks/) with its command listed in
[docs/evaluation.md](docs/evaluation.md). Compile cost is included in every token figure (it is 0:
the compiler is deterministic code).

| Experiment | Outcome |
|---|---|
| Repeated-request support desk, Claude Haiku 5.5, 3 seeds | Same accuracy as the plain agent (108/108), **24% fewer tokens** (range 19% to 33%), about **6% fewer estimated dollars** |
| Drift test: tools that do not validate, valid and invalid orders mixed (Haiku, 3 seeds) | Guards stopped **12/12** invalid writes; with guards switched off, **12 wrong writes** |
| Reworded traffic (mock, 3 seeds) | Success unchanged; token change from about -29% to +10%, so a saving is not guaranteed when wording does not repeat |
| AppWorld (Haiku, 15 tasks) | **No savings:** nothing compiled because task variants do not repeat |
| Lexical semantic cache and replay baselines | Wrong answers (8/36): "refund order 7867" looks like "refund order 2688" |

The dollar saving is much smaller than the token saving because most of a plain agent's tokens are
cheap cache reads, while the router's prompt is not cached. The desk workload was built to repeat,
so these numbers show what the tool does *when requests repeat*, not how often that happens in a
given system. Details and caveats: [docs/evaluation.md](docs/evaluation.md).

## How it works

```
request ──> router (1 LLM call) ──hit──> compiled skill ──guards ok──> answer
               │                              │
               │ miss                         └─guard fails─> agent continues from synthetic
               v                                              tool history (journal blocks repeats)
          plain agent ──> RecordingTools(JournaledTools(tools)) ──> traces (SQLite)
                                                                       │
                          bind arguments, slice dead reads, synthesize guards, emit Python
```

1. **Record** every run as a trace (`tracer.py`, `store.py`).
2. **Bind** each tool argument to its source: the request (a parameter), an earlier tool output, or
   a constant seen in several traces (`provenance.py`). An argument that cannot be traced makes
   compilation refuse.
3. **Slice** away failed and unused reads (`slicer.py`).
4. **Guard**: invariants that held in every successful trace become runtime checks (`guards.py`).
5. **Compile** to readable Python, validated against an AST whitelist before it runs (`compiler.py`).
6. **Route and run**: one cheap LLM call picks a skill, plain-text checks verify the choice and the
   request's wording, the skill runs, and any failed guard falls back to the agent (`router.py`,
   `runtime.py`, `core.py`).

A generated skill (from the demo):

```python
async def run(ctx, *, order_id):
    s0 = await ctx.call(0, 'get_order', {'order_id': order_id}, GUARDS)
    s1 = await ctx.call(1, 'get_customer', {'customer_id': ctx.get(s0, ('customer_id',), 'identity')}, GUARDS)
    s2 = await ctx.call(2, 'refund_order', {'order_id': order_id, 'amount': ctx.get(s0, ('amount',), 'identity')}, GUARDS)
    ...
```

## Usage

```python
from agent_jit import AgentJIT

jit = AgentJIT("traces.sqlite", min_support=2, skills_dir="skills")

# my_agent(request, llm, tools, history) -> str   (any async agent loop)
# check(trace) -> bool                            (how a run is judged successful)
wrapped = jit.wrap(my_agent, llm, tools, success_check=check)

result = await wrapped.run("Refund order 8821")
result.path   # "plain", "compiled" or "fallback"
```

Tools carry an effect annotation (`read`, `write`, `irreversible`). Unannotated tools are treated as
`write`, and `irreversible` tools are never compiled.

## Safety

- A compiled skill runs no further tool after a failed guard.
- The runtime does not knowingly repeat a mutating call within a run: each one is journaled before it
  runs, and an unknown outcome (timeout, cancellation) stops further writes until a human checks.
- Tool output reaches generated source only through `repr()` of validated literals, and skills are
  re-checked against an AST whitelist when loaded.
- The router can only choose a skill and copy values that literally appear in the request. A skill
  runs only for a request whose wording, with parameter values masked, matches one it was learned from.

This is **not exactly-once**. A crash can leave a call in an unknown state, and resuming after a
process crash is not supported. Full list of limits: [docs/limits.md](docs/limits.md).

## Testing

377 tests: unit tests plus property-based tests (Hypothesis) for the runtime invariants (a mutating
tool never runs after a failed guard; a write is never repeated; a reordered list never makes a
write use the wrong account) and chaos tests for a hostile or sloppy router. CI runs ruff,
`mypy --strict` and pytest on Python 3.11 and 3.12.

```bash
pip install -e ".[dev]"
ruff check . && mypy --strict src tests && pytest
```

## Documentation

| | |
|---|---|
| [docs/evaluation.md](docs/evaluation.md) | Every measured result and the command that reproduces it |
| [docs/blog-post.md](docs/blog-post.md) | Write-up: what worked and what did not ([site](https://rayyan-oumlil.github.io/agent-jit/blog-post)) |
| [docs/limits.md](docs/limits.md) | What the compiler refuses and what it cannot guarantee |
| [docs/ablations.md](docs/ablations.md) | What each safety rule protects, including the drift test |
| [docs/design.md](docs/design.md), [docs/PLAN.md](docs/PLAN.md) | Design decisions and the original plan |
| [docs/prior-work-notes.md](docs/prior-work-notes.md) | Related work, to be read and cited |

## Prior work

Closest published work: TraceCompiler (arXiv 2608.02680), which compiles agent traces offline and
states it has no runtime; ReTrace (2611.14492), AgentPRO (2611.00628) and SkillCache (2611.10022).
See [docs/prior-work-notes.md](docs/prior-work-notes.md).

## License

Apache-2.0.
