Metadata-Version: 2.5
Name: agent-jit-runtime
Version: 0.1.0
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

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

> **Status: 0.1.0 (alpha). All four milestones are on `main`: the runtime, safety rules, evaluation
> harness, property and chaos tests, ablations, a drift workload and a write-up.** An end-to-end toy
> demo works with a mock LLM and no API key. On AppWorld nothing compiled (no savings). On a
> repeated-request support-desk workload agent-jit used fewer tokens at equal success; every number,
> its caveats and its command are under "Evaluation" and in
> [docs/support-desk-results.md](docs/support-desk-results.md).
> Design: [docs/PLAN.md](docs/PLAN.md) and
> [docs/superpowers/specs/2026-11-28-agent-jit-design.md](docs/superpowers/specs/2026-11-28-agent-jit-design.md).

## Evaluation (milestone 3)

What exists, all under `src/agent_jit/adapters/`, `src/agent_jit/eval/` and `benchmarks/`:

- `adapters/appworld.py`: exposes AppWorld's APIs as discrete tools (reads: `show_*`, `search_*`,
  `login`; everything else is treated as a write).
- `adapters/anthropic.py`: a client restricted to `claude-haiku-5-5`. It refuses a call whose
  estimated size (about 3 characters per token, plus the largest possible reply) would take the spend
  past the budget, and tracks usage per token kind because cache reads and writes are priced
  differently. The estimate is rough, so the budget is a tight guard, not an exact limit.
- `eval/`: baselines (plain agent, exact-match cache, a lexical semantic cache, a one-shot replay in
  the spirit of LOOP), metrics (net tokens including compile tokens, hit/fallback rate, latency
  percentiles) and an episode harness that scores every episode with the environment's own check.
- `benchmarks/appworld_eval.py --llm mock` runs all of it on real AppWorld worlds with a mock model
  (plumbing only, it never solves a task).

Caveats that apply to any result from this harness: the success signal agent-jit records with is
AppWorld's own ground-truth evaluator (an oracle, which a deployment would not have), the baselines
record runs whether or not they succeeded, the JIT's latency includes that one evaluator call per
run, and the cost of a run is estimated from list prices, not billed.

Measured so far, with the command that reproduces each:

| What | Result | Command |
|---|---|---|
| AppWorld facts: 457 function-calling tools, 256,659 characters of schema, train 90 / dev 57 tasks, scorer accepts the known answer | see the JSON | `python benchmarks/appworld_facts.py` |
| Three local models (gemma4:e4b, qwen3.5:9b, nemotron-3-nano:4b) on 10 AppWorld train tasks each | 0/30 passed | `python benchmarks/appworld_check1.py --models gemma4:e4b qwen3.5:9b nemotron-3-nano:4b` (inside the AppWorld venv) |
| Haiku 5.5 on 5 AppWorld scenarios x 3 tasks, plain agent vs agent-jit | 12/15 passed by both; agent-jit compiled 0 skills (no savings result), see the diagnosis | `python benchmarks/appworld_eval.py --llm haiku --scenarios 5 --systems plain jit --budget-usd 1.0`; details in [docs/appworld-results.md](docs/appworld-results.md) |
| Support-desk workload (36 requests, 6 types), gemma4:e4b, plain vs agent-jit | plain 31/36, 38,976 tokens; jit 33/36, 39% hit, 30,458 tokens (-22%); loose caches 8/36 | `python benchmarks/support_desk_eval.py --llm ollama --model gemma4:e4b`; details in [docs/support-desk-results.md](docs/support-desk-results.md) |
| Same workload on Haiku 5.5, 3 seeds, plain vs agent-jit | 108/108 for both; tokens 99,326 vs 75,016 on average (-24%, range -19% to -33%), but estimated dollars only about -6% (range -4.5% to -8%) because most tokens are cheap cache reads; about $0.04 per pass | `python benchmarks/support_desk_eval.py --llm haiku --budget-usd 0.15 --systems plain jit --seed 11` (also 12, 13) |
| Drift workload (mock policy): tools that do not validate, valid and invalid orders mixed after a warm-up | plain 36/36; agent-jit 36/36 (12/12 invalid requests stopped by a guard, 33% fallbacks); agent-jit with guards switched off 24/36, 12 wrong writes | `python benchmarks/drift_eval.py`; details in [docs/ablations.md](docs/ablations.md) |

Payback chart (Haiku, three seeds; cumulative net tokens, compile cost included, which is 0 here):
![cumulative net tokens, plain vs agent-jit](docs/payback-haiku.svg)
Regenerate with `python benchmarks/plot_payback.py`. The curves flatten once skills compile; the
dollar saving is smaller than this token view suggests (see the results doc).

Also: ablations of the safety rules in [docs/ablations.md](docs/ablations.md), a write-up in
[docs/blog-post.md](docs/blog-post.md), and details and caveats in
[docs/week1-appworld-checks.md](docs/week1-appworld-checks.md).

## Try it (no API key)

```bash
pip install agent-jit-runtime        # (import agent_jit) or, from a checkout: pip install -e ".[dev]"
python -m agent_jit.demo
```

The demo runs a toy refund agent five times against a mock LLM (a deterministic script):

| Run | What happens |
|---|---|
| 1, 2 | The agent runs normally and is recorded. After run 2 the repeated pattern is compiled. |
| 3 | A router (one LLM call) picks the compiled skill; zero inner-loop LLM calls. |
| 4 | A guard fails *after* the refund ran. The agent resumes, asks to refund again, and the journal answers without executing. |
| 5 | A guard fails before any write. The agent finishes without refunding. |

The token counts it prints, including the final `stats` line, come from the mock script; they are
not measurements.

## 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 is stored as a trace (`tracer.py`, `store.py`).
2. **Bind**: each tool argument is traced to the request (a parameter), an earlier tool output (a
   data dependency) or a constant seen in at least two traces (`provenance.py`). An argument that
   cannot be traced makes compilation refuse.
3. **Slice**: failed reads and reads nothing depends on after the last write are dropped; a
   successful read before a write is always kept (`slicer.py`).
4. **Guard**: invariants that held in every successful trace become checks (`guards.py`).
5. **Compile**: readable Python source, validated against a whitelist before it ever runs
   (`compiler.py`).
6. **Run and fall back**: `runtime.py`, `router.py`, `core.py`.

Around that loop, milestone 2 adds four guards on *when* a skill may run:

- **Schema invalidation**: every tool's schema, effect and idempotency key are hashed
  (`schema_hash`). A skill whose tools changed is no longer offered to the router, and traces
  recorded under an older schema never feed a new compile (`Wrapped.disabled` says why).
- **Circuit breaker**: a skill that fell back on more than half of its recent runs (default: at
  least 5 runs, window 10) is switched off for good (`stats.py`).
- **ROI gate**: a group is compiled only if its mean inner-loop tokens exceed the router's
  per-request cost (`roi.py`); declined groups appear in `Wrapped.skipped`. The router cost is
  `router_token_estimate`, else the mean seen so far, else `DEFAULT_ROUTER_TOKENS` (100). That
  default is a placeholder, **not a measurement**: set the estimate for your own router.
- **Branches**: when two kinds of request start with the same tool but diverge later, one skill can
  branch on a value read before they diverge (`branches.py`, `compile_branched`). A run whose value
  matches no known branch stops and falls back. Each branch re-checks its own guards on the shared
  steps before any of its tools run.

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)
    ...
```

## Safety guarantees (and what they are not)

- Compiled code runs no further tool after a failed guard. What happens next is up to the agent
  that takes over (in the demo's run 4 it asks to refund again, and the journal blocks the repeat).
  Unannotated tools are treated as `write`; `irreversible` tools are never compiled.
- **The runtime does not knowingly repeat a mutating call within a run.** Each mutating call is
  journaled before it runs. If its outcome is unknown (timeout, cancellation, unclassified error),
  the run performs no further write and says a human must check.
- Tool output and trace data reach generated source only through `repr()` of validated literals, and
  skills are re-checked against an AST whitelist at load time.
- The router can only choose a skill and copy values that literally appear in the request.

**This is not exactly-once.** See the limits below.

## Limits

- Not exactly-once: a crash can leave a call `unknown`, and resuming after a process crash is not
  supported.
- A fallback agent that repeats a write with *different* arguments is not caught.
- A condition the traces never read cannot be guarded. Numbers are guarded only by type and sign,
  so a threshold such as "under 30 days" read from a tool is not checked.
- With few traces a value can coincide by chance. Writes refuse the cases it can detect (a request
  value that also appears in an earlier output, two output fields with the same value, a numeric
  constant), but a coincidence across only two traces can still bind to the wrong source.
- An id written with a prefix (`ORD-9001` for tool value `9001`) binds only when every trace uses
  the same prefix. Numbers written like `1,234` are not matched in requests, so those requests go
  to the plain agent.
- Traces recorded before milestone 2 carry no schema hashes, so they are never used for compiling.
- Branching refuses when two different values both separate the groups (a coincidence is likelier
  than a decision) or when a write happens before the branch value is read.
- Branches need a categorical discriminator: a boolean or a short, digit-free string read in a step
  before the groups diverge. A request kind whose tool sequence is a strict prefix of another's
  cannot be separated and is refused as ambiguous. The router runs a skill only for a request whose
  wording (with parameter values masked) matches one it was learned from, and a branched skill with
  a writing branch is refused unless all its groups were worded alike, so a paraphrase goes to the
  plain agent. Fallback runs are never compiled.
- Loops over lists are not compiled. A *read* argument may be taken from a list item past the first
  (for example the password of one account in a list of accounts); the item's fields are then guarded
  so a reordered list fails a guard. This is refused unless some field of the item is identical in
  every trace. The item is still found by position: if two items share that identifying value, the
  guard cannot tell them apart (a known limitation). A *write* argument is never taken from a later
  list item directly.
- A value the model computed itself (a maximum, a sum, a choice among items) is not traceable to any
  tool output, so a step that passes it on is refused.
- Retried runs (a failed step followed by a retry) are not compiled.
- A request value that also appears in an earlier tool output is refused for writes (the source is
  ambiguous), except when the output merely echoes the request value.
- Bookkeeping that fails after a run's tools already ran (an unsavable trace, a compile error) is
  reported in `Wrapped.problems` / `Wrapped.refusals`, never raised.
- Skills live as long as the `Wrapped` object; one database file is assumed to serve one agent.
- A tripped circuit breaker is not re-armed by hand; only new evidence (a new request kind or a
  schema change) produces a new skill. The router cost used by the ROI gate is an estimate until
  real runs have been observed.

## Results

See the measured-results table under "Evaluation" above. Every number there comes from a script in
`benchmarks/` with its command; the compiler spends no tokens (it is deterministic Python).

## Development

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

## Prior work

Closest published work, to be read and cited, not claimed missing: 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.
