agent-jit-runtime 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agent_jit/journal.py ADDED
@@ -0,0 +1,219 @@
1
+ """Write-ahead journal for mutating tool calls.
2
+
3
+ Before a mutating call runs, a ``pending`` row is committed. Afterwards it becomes ``done``,
4
+ ``failed`` (the tool raised ``ToolRejected``: nothing happened) or ``unknown`` (we cannot tell).
5
+ Once a run has an ``unknown`` or leftover ``pending`` row, it performs no further mutating call.
6
+
7
+ What this guarantees: the runtime never *knowingly* repeats a mutating call within a run. It is
8
+ not exactly-once, and a fallback LLM that repeats a call with different arguments is not caught.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import json
15
+ import sqlite3
16
+ from collections.abc import Iterator, Mapping
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Literal
21
+
22
+ from agent_jit.ir import OutcomeUnknown, ToolRejected
23
+ from agent_jit.tools import ToolCaller, ToolSpec
24
+
25
+ Status = Literal["pending", "done", "failed", "unknown"]
26
+
27
+
28
+ def _normalize(value: Any) -> Any:
29
+ """Spell an integral float (125.0) like the int it equals, so replay sees the same call."""
30
+ if isinstance(value, float) and value.is_integer():
31
+ return int(value)
32
+ if isinstance(value, dict):
33
+ return {k: _normalize(v) for k, v in value.items()}
34
+ if isinstance(value, list):
35
+ return [_normalize(v) for v in value]
36
+ return value
37
+
38
+
39
+ def canonical(args: Mapping[str, Any]) -> str:
40
+ """Stable JSON for an argument mapping; raises ``TypeError`` or ``ValueError`` if not JSON."""
41
+ return json.dumps(
42
+ _normalize(dict(args)), sort_keys=True, separators=(",", ":"), allow_nan=False
43
+ )
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class _DoneRow:
48
+ result: str | None # JSON text, or None when the result could not be stored
49
+
50
+
51
+ class Journal:
52
+ def __init__(self, path: str | Path) -> None:
53
+ self._path = str(path)
54
+ with self._connect() as con:
55
+ con.execute(
56
+ "CREATE TABLE IF NOT EXISTS journal ("
57
+ "run_id TEXT NOT NULL, seq INTEGER NOT NULL, tool TEXT NOT NULL, "
58
+ "args TEXT NOT NULL, status TEXT NOT NULL, result TEXT, "
59
+ "PRIMARY KEY (run_id, seq))"
60
+ )
61
+
62
+ @contextmanager
63
+ def _connect(self) -> Iterator[sqlite3.Connection]:
64
+ con = sqlite3.connect(self._path)
65
+ try:
66
+ with con:
67
+ yield con
68
+ finally:
69
+ con.close()
70
+
71
+ def begin(self, run_id: str, tool: str, args: Mapping[str, Any]) -> int:
72
+ """Commit a ``pending`` row and return its sequence number within the run."""
73
+ text = canonical(args)
74
+ with self._connect() as con:
75
+ row = con.execute(
76
+ "SELECT COALESCE(MAX(seq), -1) + 1 FROM journal WHERE run_id = ?", (run_id,)
77
+ ).fetchone()
78
+ seq = int(row[0])
79
+ con.execute(
80
+ "INSERT INTO journal (run_id, seq, tool, args, status) "
81
+ "VALUES (?, ?, ?, ?, 'pending')",
82
+ (run_id, seq, tool, text),
83
+ )
84
+ return seq
85
+
86
+ def finish(self, run_id: str, seq: int, status: Status, result: str | None = None) -> None:
87
+ with self._connect() as con:
88
+ con.execute(
89
+ "UPDATE journal SET status = ?, result = ? WHERE run_id = ? AND seq = ?",
90
+ (status, result, run_id, seq),
91
+ )
92
+
93
+ def status(self, run_id: str, tool: str, args: Mapping[str, Any]) -> Status | None:
94
+ """Status of the latest row for this exact call, or None if it was never journaled."""
95
+ with self._connect() as con:
96
+ row = con.execute(
97
+ "SELECT status FROM journal WHERE run_id = ? AND tool = ? AND args = ? "
98
+ "ORDER BY seq DESC LIMIT 1",
99
+ (run_id, tool, canonical(args)),
100
+ ).fetchone()
101
+ return None if row is None else _as_status(row[0])
102
+
103
+ def blocked(self, run_id: str) -> bool:
104
+ """True when the run has a row whose outcome is unknown or never finished."""
105
+ with self._connect() as con:
106
+ row = con.execute(
107
+ "SELECT 1 FROM journal WHERE run_id = ? AND status IN ('unknown', 'pending') "
108
+ "LIMIT 1",
109
+ (run_id,),
110
+ ).fetchone()
111
+ return row is not None
112
+
113
+ def find_done(self, run_id: str, tool: str, args: Mapping[str, Any]) -> _DoneRow | None:
114
+ with self._connect() as con:
115
+ row = con.execute(
116
+ "SELECT result FROM journal WHERE run_id = ? AND tool = ? AND args = ? "
117
+ "AND status = 'done' ORDER BY seq DESC LIMIT 1",
118
+ (run_id, tool, canonical(args)),
119
+ ).fetchone()
120
+ return None if row is None else _DoneRow(row[0])
121
+
122
+
123
+ _STATUSES: dict[str, Status] = {
124
+ "pending": "pending",
125
+ "done": "done",
126
+ "failed": "failed",
127
+ "unknown": "unknown",
128
+ }
129
+
130
+
131
+ def _as_status(value: str) -> Status:
132
+ try:
133
+ return _STATUSES[value]
134
+ except KeyError:
135
+ raise ValueError(f"corrupt journal row: unknown status {value!r}") from None
136
+
137
+
138
+ class JournaledTools:
139
+ """A ``ToolCaller`` that journals and de-duplicates the mutating calls of one run."""
140
+
141
+ def __init__(self, inner: ToolCaller, journal: Journal, run_id: str) -> None:
142
+ self._inner = inner
143
+ self._journal = journal
144
+ self._run_id = run_id
145
+ self._replay = False
146
+ self._lock = asyncio.Lock()
147
+
148
+ def start_replay(self) -> None:
149
+ """From now on, a call already ``done`` in this run returns its stored result."""
150
+ self._replay = True
151
+
152
+ def specs(self) -> tuple[ToolSpec, ...]:
153
+ return self._inner.specs()
154
+
155
+ def spec(self, name: str) -> ToolSpec:
156
+ return self._inner.spec(name)
157
+
158
+ async def call(self, name: str, args: Mapping[str, Any]) -> Any:
159
+ spec = self._inner.spec(name)
160
+ if spec.effect == "read":
161
+ return await self._inner.call(name, args)
162
+ canonical(args) # refuse non-JSON arguments before anything can happen
163
+ async with self._lock:
164
+ if self._journal.blocked(self._run_id):
165
+ raise OutcomeUnknown(
166
+ f"run {self._run_id} has a mutating call with an unknown outcome; "
167
+ "a human must check before anything else is written"
168
+ )
169
+ if self._replay:
170
+ done = self._journal.find_done(self._run_id, name, args)
171
+ if done is not None:
172
+ return self._stored(name, done)
173
+ seq = self._journal.begin(self._run_id, name, args)
174
+ return await self._execute(spec, args, seq)
175
+
176
+ def _stored(self, name: str, done: _DoneRow) -> Any:
177
+ if done.result is None:
178
+ raise OutcomeUnknown(f"{name} already ran but its result was not stored")
179
+ return json.loads(done.result)
180
+
181
+ async def _execute(self, spec: ToolSpec, args: Mapping[str, Any], seq: int) -> Any:
182
+ send = dict(args)
183
+ if spec.idempotency_param is not None:
184
+ send[spec.idempotency_param] = f"{self._run_id}:{seq}"
185
+ attempts = 2 if spec.idempotency_param is not None else 1
186
+ for attempt in range(attempts):
187
+ try:
188
+ result = await self._inner.call(spec.name, send)
189
+ except ToolRejected as exc:
190
+ if attempt > 0:
191
+ # An earlier attempt may have gone through, so "rejected" on the retry can
192
+ # be a duplicate-key refusal of a call that already happened.
193
+ self._journal.finish(self._run_id, seq, "unknown")
194
+ raise OutcomeUnknown(
195
+ f"{spec.name} was rejected on retry after an attempt with an unknown "
196
+ "outcome; a human must check"
197
+ ) from exc
198
+ self._journal.finish(self._run_id, seq, "failed")
199
+ raise
200
+ except Exception as exc:
201
+ if attempt + 1 < attempts:
202
+ continue
203
+ self._journal.finish(self._run_id, seq, "unknown")
204
+ raise OutcomeUnknown(
205
+ f"{spec.name} failed with {type(exc).__name__}; its outcome is unknown"
206
+ ) from exc
207
+ except BaseException:
208
+ self._journal.finish(self._run_id, seq, "unknown")
209
+ raise
210
+ self._journal.finish(self._run_id, seq, "done", _dump(result))
211
+ return result
212
+ raise AssertionError("unreachable") # pragma: no cover
213
+
214
+
215
+ def _dump(result: Any) -> str | None:
216
+ try:
217
+ return json.dumps(result, allow_nan=False)
218
+ except (TypeError, ValueError):
219
+ return None
@@ -0,0 +1,460 @@
1
+ """Argument binding: where did each tool argument come from?
2
+
3
+ For every argument of every step, in order of preference: a value found in the request (a skill
4
+ parameter), a value found in an earlier successful tool output (a data dependency), or a value
5
+ equal in every trace (a constant). A binding must reproduce the argument in *every* trace;
6
+ anything else raises ``Refusal``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+ from collections.abc import Callable, Iterator, Mapping, Sequence
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Literal
16
+
17
+ from agent_jit.ir import Effect, Refusal, Trace, TraceStep
18
+
19
+ MIN_REQUEST_MATCH = 3
20
+ _ISO_DATETIME = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}([T ].*)?", re.DOTALL)
21
+ _INTEGER = re.compile(r"-?[0-9]+")
22
+
23
+ Kind = Literal["str", "int", "float"]
24
+ Path = tuple[str | int, ...]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Param:
29
+ name: str
30
+ kind: Kind
31
+ transform: str = "identity"
32
+ # The request text this parameter was found in, per trace (for the request shapes). Not part
33
+ # of the parameter's identity.
34
+ texts: tuple[str, ...] = field(default=(), compare=False)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class FromStep:
39
+ step: int
40
+ path: Path
41
+ transform: str = "identity"
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Const:
46
+ value: Any
47
+
48
+
49
+ Binding = Param | FromStep | Const
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class StepBinding:
54
+ tool: str
55
+ effect: Effect
56
+ args: Mapping[str, Binding]
57
+
58
+
59
+ def _is_number(v: Any) -> bool:
60
+ return isinstance(v, int | float) and not isinstance(v, bool)
61
+
62
+
63
+ def _to_int(v: Any) -> int:
64
+ if isinstance(v, bool) or not isinstance(v, int | str):
65
+ raise TypeError(f"to_int cannot convert {type(v).__name__}")
66
+ if isinstance(v, str) and not _INTEGER.fullmatch(v):
67
+ raise ValueError(f"not an integer: {v!r}")
68
+ return int(v)
69
+
70
+
71
+ def _to_float(v: Any) -> float:
72
+ if isinstance(v, bool) or not isinstance(v, int | float | str):
73
+ raise TypeError(f"to_float cannot convert {type(v).__name__}")
74
+ out = float(v)
75
+ if not math.isfinite(out):
76
+ raise ValueError(f"not a finite number: {v!r}")
77
+ return out
78
+
79
+
80
+ def _to_str(v: Any) -> str:
81
+ if isinstance(v, bool) or not isinstance(v, str | int | float):
82
+ raise TypeError(f"to_str cannot convert {type(v).__name__}")
83
+ return str(v)
84
+
85
+
86
+ def _need_str(v: Any, name: str) -> str:
87
+ if not isinstance(v, str):
88
+ raise TypeError(f"{name} needs a string, got {type(v).__name__}")
89
+ return v
90
+
91
+
92
+ def _iso_date(v: Any) -> str:
93
+ text = _need_str(v, "iso_date")
94
+ if not _ISO_DATETIME.fullmatch(text):
95
+ raise ValueError(f"not an ISO date or datetime: {text!r}")
96
+ return text[:10]
97
+
98
+
99
+ TRANSFORMS: Mapping[str, Callable[[Any], Any]] = {
100
+ "identity": lambda v: v,
101
+ "to_int": _to_int,
102
+ "to_float": _to_float,
103
+ "to_str": _to_str,
104
+ "strip": lambda v: _need_str(v, "strip").strip(),
105
+ "lower": lambda v: _need_str(v, "lower").lower(),
106
+ "upper": lambda v: _need_str(v, "upper").upper(),
107
+ "iso_date": _iso_date,
108
+ }
109
+
110
+
111
+ _PREFIX_TRANSFORM = "removeprefix:"
112
+
113
+
114
+ def get_transform(name: str) -> Callable[[Any], Any]:
115
+ """A transform by name; ``removeprefix:<P>`` strips the exact prefix ``<P>`` from a string."""
116
+ if name in TRANSFORMS:
117
+ return TRANSFORMS[name]
118
+ if name.startswith(_PREFIX_TRANSFORM):
119
+ prefix = name[len(_PREFIX_TRANSFORM) :]
120
+
121
+ def remove(value: Any) -> str:
122
+ text = _need_str(value, "removeprefix")
123
+ if not text.startswith(prefix):
124
+ raise ValueError(f"{text!r} does not start with {prefix!r}")
125
+ return text[len(prefix) :]
126
+
127
+ return remove
128
+ raise KeyError(f"unknown transform: {name}")
129
+
130
+
131
+ def extract(value: Any, path: Path) -> Any:
132
+ """Follow ``path`` into nested dicts and lists; a missing step raises ``LookupError``."""
133
+ current = value
134
+ for key in path:
135
+ if isinstance(key, int) and not isinstance(key, bool):
136
+ if not isinstance(current, list) or not 0 <= key < len(current):
137
+ raise LookupError(f"missing path {path!r}")
138
+ current = current[key]
139
+ else:
140
+ if not isinstance(current, dict) or key not in current:
141
+ raise LookupError(f"missing path {path!r}")
142
+ current = current[key]
143
+ return current
144
+
145
+
146
+ def _walk(value: Any, path: Path = ()) -> Iterator[tuple[Path, Any]]:
147
+ yield path, value
148
+ if isinstance(value, dict):
149
+ for k, v in value.items():
150
+ yield from _walk(v, (*path, k))
151
+ elif isinstance(value, list):
152
+ for i, v in enumerate(value):
153
+ yield from _walk(v, (*path, i))
154
+
155
+
156
+ def strict_eq(a: Any, b: Any) -> bool:
157
+ if type(a) is not type(b):
158
+ return False
159
+ if isinstance(a, dict):
160
+ return a.keys() == b.keys() and all(strict_eq(a[k], b[k]) for k in a)
161
+ if isinstance(a, list):
162
+ return len(a) == len(b) and all(strict_eq(x, y) for x, y in zip(a, b, strict=True))
163
+ return bool(a == b)
164
+
165
+
166
+ def _inside_a_number(request: str, start: int, end: int, needle: str) -> bool:
167
+ """True when digits of ``needle`` are only part of a bigger number: a sign in front, or a
168
+ decimal or group separator joining it to more digits."""
169
+ if needle[0].isdigit() and start > 0:
170
+ before = request[start - 1]
171
+ if before in "+-":
172
+ return True
173
+ if before in ".," and start > 1 and request[start - 2].isdigit():
174
+ return True
175
+ if needle[-1].isdigit() and end < len(request):
176
+ after = request[end]
177
+ if after in ".," and end + 1 < len(request) and request[end + 1].isdigit():
178
+ return True
179
+ return False
180
+
181
+
182
+ def request_shape(request: str, literals: Sequence[tuple[str, str]]) -> str:
183
+ """The request with each parameter's text replaced by ``{name}``, case and spacing folded.
184
+
185
+ ``literals`` pairs a parameter name with the exact text it was found in. Two requests with the
186
+ same shape differ only in their parameter values."""
187
+ spans = []
188
+ for name, literal in literals:
189
+ span = _locate(request, literal, False)
190
+ if span is not None:
191
+ spans.append((span, name))
192
+ ordered = sorted(spans)
193
+ if any(prev[0][1] > nxt[0][0] for prev, nxt in zip(ordered, ordered[1:], strict=False)):
194
+ raise ValueError("parameter spans overlap")
195
+ shaped = request
196
+ for (start, end), name in reversed(ordered):
197
+ shaped = shaped[:start] + "{" + name + "}" + shaped[end:]
198
+ # Punctuation and spacing do not change what is being asked; words do.
199
+ return " ".join(re.sub(r"[^\w{}]+", " ", shaped.casefold()).split())
200
+
201
+
202
+ def literal_fits(texts: Sequence[str], literal: str) -> bool:
203
+ """True when ``literal`` looks like the texts the parameter was learned from.
204
+
205
+ It must have the number of words of one of them and use only their kinds of characters:
206
+ letters and digits only if some learned text had them, and only the punctuation and spaces
207
+ they contained. An id learned as digits cannot become ``9001;cancel-order-5555``."""
208
+ if not texts or len(literal.split()) not in {len(t.split()) for t in texts}:
209
+ return False
210
+ letters = any(c.isalpha() for t in texts for c in t)
211
+ digits = any(c.isdigit() for t in texts for c in t)
212
+ others = {c for t in texts for c in t if not c.isalnum()}
213
+ return all(
214
+ (c.isalpha() and letters) or (c.isdigit() and digits) or c in others for c in literal
215
+ )
216
+
217
+
218
+ def find_in_request(request: str, needle: str, ignore_case: bool) -> str | None:
219
+ """First occurrence of ``needle`` bounded by non-alphanumerics; returns the request's text."""
220
+ span = _locate(request, needle, ignore_case)
221
+ return None if span is None else request[span[0] : span[1]]
222
+
223
+
224
+ def _locate(request: str, needle: str, ignore_case: bool) -> tuple[int, int] | None:
225
+ if len(needle) < MIN_REQUEST_MATCH:
226
+ return None
227
+ haystack = request.lower() if ignore_case else request
228
+ if len(haystack) != len(request):
229
+ return None
230
+ if ignore_case:
231
+ needle = needle.lower()
232
+ start = haystack.find(needle)
233
+ while start != -1:
234
+ end = start + len(needle)
235
+ left_ok = start == 0 or not request[start - 1].isalnum()
236
+ right_ok = end == len(request) or not request[end].isalnum()
237
+ if left_ok and right_ok and not _inside_a_number(request, start, end, needle):
238
+ return start, end
239
+ start = haystack.find(needle, start + 1)
240
+ return None
241
+
242
+
243
+ def _request_options(value: Any) -> list[tuple[str, Kind, str, bool]]:
244
+ """(transform, kind, needle, ignore_case) ways a scalar might appear in the request."""
245
+ if isinstance(value, str):
246
+ options: list[tuple[str, Kind, str, bool]] = [("identity", "str", value, False)]
247
+ if value == value.lower():
248
+ options.append(("lower", "str", value, True))
249
+ if value == value.upper():
250
+ options.append(("upper", "str", value, True))
251
+ return options
252
+ if isinstance(value, int) and not isinstance(value, bool):
253
+ return [("to_int", "int", str(value), False)]
254
+ if isinstance(value, float):
255
+ return [("to_float", "float", repr(value), False)]
256
+ return []
257
+
258
+
259
+ class _ParamTable:
260
+ """Hands out parameters; the same request text and transform reuses one parameter."""
261
+
262
+ def __init__(self) -> None:
263
+ self._by_key: dict[tuple[str, str, tuple[str, ...]], Param] = {}
264
+ self._names: set[str] = set()
265
+
266
+ def get(self, name: str, kind: Kind, transform: str, texts: tuple[str, ...]) -> Param:
267
+ key = (kind, transform, texts)
268
+ if key in self._by_key:
269
+ return self._by_key[key]
270
+ unique, n = name, 1
271
+ while unique in self._names:
272
+ n += 1
273
+ unique = f"{name}_{n}"
274
+ param = Param(unique, kind, transform, texts)
275
+ self._by_key[key] = param
276
+ self._names.add(unique)
277
+ return param
278
+
279
+
280
+ _REQUEST_PREFIX = r"[A-Za-z]{1,8}[-_#]"
281
+
282
+
283
+ def _bind_prefixed(
284
+ name: str, values: Sequence[Any], traces: Sequence[Trace], table: _ParamTable
285
+ ) -> Param | None:
286
+ """A request token like ``ORD-8821`` for the argument ``8821``, with one prefix throughout."""
287
+ if not all(isinstance(v, str) and len(v) >= MIN_REQUEST_MATCH for v in values):
288
+ return None
289
+ prefixes: set[str] = set()
290
+ tokens: list[str] = []
291
+ for trace, value in zip(traces, values, strict=True):
292
+ pattern = rf"(?<![A-Za-z0-9])({_REQUEST_PREFIX}){re.escape(value)}(?![A-Za-z0-9])"
293
+ match = re.search(pattern, trace.request)
294
+ if match is None:
295
+ return None
296
+ token = match.group(1) + value
297
+ if find_in_request(trace.request, token, False) is None:
298
+ return None
299
+ prefixes.add(match.group(1))
300
+ tokens.append(token)
301
+ if len(prefixes) != 1:
302
+ return None
303
+ return table.get(name, "str", f"{_PREFIX_TRANSFORM}{prefixes.pop()}", tuple(tokens))
304
+
305
+
306
+ def _bind_request(
307
+ name: str, values: Sequence[Any], traces: Sequence[Trace], table: _ParamTable
308
+ ) -> Param | None:
309
+ if not all(type(v) is type(values[0]) for v in values):
310
+ return None
311
+ for transform, kind, _, ignore_case in _request_options(values[0]):
312
+ texts: list[str] = []
313
+ for trace, value in zip(traces, values, strict=True):
314
+ needle = next(n for t, _, n, _ in _request_options(value) if t == transform)
315
+ found = find_in_request(trace.request, needle, ignore_case)
316
+ if found is None:
317
+ break
318
+ texts.append(found)
319
+ else:
320
+ return table.get(name, kind, transform, tuple(texts))
321
+ return _bind_prefixed(name, values, traces, table)
322
+
323
+
324
+ def _holds(
325
+ j: int,
326
+ path: Path,
327
+ fn: Callable[[Any], Any],
328
+ values: Sequence[Any],
329
+ traces: Sequence[Trace],
330
+ ) -> bool:
331
+ node_types: set[type] = set()
332
+ for trace, value in zip(traces, values, strict=True):
333
+ step = trace.steps[j]
334
+ if not step.ok:
335
+ return False
336
+ try:
337
+ node = extract(step.result, path)
338
+ produced = fn(node)
339
+ except (LookupError, TypeError, ValueError):
340
+ return False
341
+ node_types.add(type(node))
342
+ if not strict_eq(produced, value):
343
+ return False
344
+ # Guards are type-based; a source whose type varies across traces cannot be guarded.
345
+ return len(node_types) == 1
346
+
347
+
348
+ def _bind_output(
349
+ index: int, values: Sequence[Any], traces: Sequence[Trace], later_items: bool
350
+ ) -> list[FromStep]:
351
+ """Every distinct earlier output location that reproduces ``values`` in all traces.
352
+
353
+ A location inside a list item past the first is offered only when ``later_items`` is set."""
354
+ found: list[FromStep] = []
355
+ for j in range(index):
356
+ if not traces[0].steps[j].ok:
357
+ continue
358
+ for path, _ in _walk(traces[0].steps[j].result):
359
+ if not later_items and any(isinstance(k, int) and k != 0 for k in path):
360
+ continue
361
+ for transform, fn in TRANSFORMS.items():
362
+ if _holds(j, path, fn, values, traces):
363
+ found.append(FromStep(j, path, transform))
364
+ break # one entry per location
365
+ # Prefer a source that needs no list position past the first: the guards cover those natively.
366
+ found.sort(key=lambda f: any(isinstance(k, int) and k != 0 for k in f.path))
367
+ return found
368
+
369
+
370
+ def _is_echo(
371
+ dep: FromStep,
372
+ param: Param,
373
+ values: Sequence[Any],
374
+ traces: Sequence[Trace],
375
+ bound: Sequence[StepBinding],
376
+ ) -> bool:
377
+ """True when the output is a copy of an argument of its own step bound to the same request
378
+ value, so request and output cannot disagree."""
379
+ return any(
380
+ binding == param
381
+ and all(
382
+ strict_eq(trace.steps[dep.step].args[arg_name], value)
383
+ and strict_eq(extract(trace.steps[dep.step].result, dep.path), value)
384
+ for trace, value in zip(traces, values, strict=True)
385
+ )
386
+ for arg_name, binding in bound[dep.step].args.items()
387
+ )
388
+
389
+
390
+ def _bind_one(
391
+ index: int,
392
+ step: TraceStep,
393
+ name: str,
394
+ values: list[Any],
395
+ traces: Sequence[Trace],
396
+ table: _ParamTable,
397
+ bound: Sequence[StepBinding],
398
+ ) -> Binding | None:
399
+ writes = step.effect != "read"
400
+ param: Param | None = None
401
+ if all(isinstance(v, str) or _is_number(v) for v in values):
402
+ param = _bind_request(name, values, traces, table)
403
+ deps: list[FromStep] = []
404
+ if not any(v is None or isinstance(v, bool) for v in values):
405
+ # A write's argument is never taken from a later list item: the likeliest coincidence to
406
+ # bind and the costliest to get wrong. A read may be, because its item is guarded.
407
+ deps = _bind_output(index, values, traces, later_items=not writes)
408
+ if param is not None:
409
+ # A user-typed value must not silently replace one the tools produced when a write is at
410
+ # stake. An echo of the producing step's own input is harmless.
411
+ clash = next((d for d in deps if not _is_echo(d, param, values, traces, bound)), None)
412
+ if writes and clash is not None:
413
+ raise Refusal(
414
+ f"{step.tool}.{name}: ambiguous source, both the request and the output of "
415
+ f"step {clash.step} reproduce it"
416
+ )
417
+ return param
418
+ if deps:
419
+ if writes and len(deps) > 1:
420
+ places = ", ".join(f"step {d.step} {d.path!r}" for d in deps)
421
+ raise Refusal(f"{step.tool}.{name}: ambiguous output source ({places})")
422
+ return deps[0]
423
+ if len(traces) >= 2 and all(strict_eq(values[0], v) for v in values[1:]):
424
+ if writes and all(_is_number(v) for v in values):
425
+ raise Refusal(
426
+ f"{step.tool}.{name}: a numeric constant on a write may be a computed value, "
427
+ "so it is not compiled as a fixed one"
428
+ )
429
+ return Const(values[0])
430
+ return None
431
+
432
+
433
+ def bind_arguments(traces: Sequence[Trace]) -> tuple[StepBinding, ...]:
434
+ if not traces:
435
+ raise Refusal("no traces to bind")
436
+ first = traces[0]
437
+ sequence = tuple(s.tool for s in first.steps)
438
+ for t in traces[1:]:
439
+ if tuple(s.tool for s in t.steps) != sequence:
440
+ raise Refusal(f"tool sequence differs in run {t.run_id}")
441
+ table = _ParamTable()
442
+ bound: list[StepBinding] = []
443
+ for i, step0 in enumerate(first.steps):
444
+ steps = [t.steps[i] for t in traces]
445
+ if any(s.effect != step0.effect for s in steps):
446
+ raise Refusal(f"{step0.tool}: effect differs across traces")
447
+ if any(set(s.args) != set(step0.args) for s in steps):
448
+ raise Refusal(f"{step0.tool}: argument names differ across traces")
449
+ args: dict[str, Binding] = {}
450
+ for name in step0.args:
451
+ values = [s.args[name] for s in steps]
452
+ binding = _bind_one(i, step0, name, values, traces, table, bound)
453
+ if binding is None:
454
+ raise Refusal(
455
+ f"{step0.tool}.{name}: value is not traceable to the request, an earlier "
456
+ "tool output, or a constant seen in at least two traces"
457
+ )
458
+ args[name] = binding
459
+ bound.append(StepBinding(step0.tool, step0.effect, args))
460
+ return tuple(bound)
agent_jit/py.typed ADDED
File without changes
agent_jit/roi.py ADDED
@@ -0,0 +1,20 @@
1
+ """ROI gate: compile only when the saved inner-loop tokens beat the router cost."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from agent_jit.ir import Trace
8
+
9
+ # A starting estimate used before any router call has been observed. It is a configurable
10
+ # default, not a measurement.
11
+ DEFAULT_ROUTER_TOKENS = 100
12
+
13
+
14
+ def worth_compiling(traces: Sequence[Trace], router_tokens: int) -> bool:
15
+ """True when the mean inner-loop tokens of ``traces`` exceed ``router_tokens``."""
16
+ if router_tokens < 0:
17
+ raise ValueError("router_tokens cannot be negative")
18
+ if not traces:
19
+ return False
20
+ return sum(t.tokens for t in traces) / len(traces) > router_tokens