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/compiler.py ADDED
@@ -0,0 +1,659 @@
1
+ """Compile successful traces into guarded, readable Python source.
2
+
3
+ Every trace or tool value reaches the generated source only through ``repr()`` of a validated
4
+ literal, and ``load_skill`` re-checks the source against a whitelist before running it, so tool
5
+ output can never become executable code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import builtins
12
+ import keyword
13
+ import math
14
+ import re
15
+ from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from agent_jit.branches import Discriminator, find_discriminator, split_index
20
+ from agent_jit.guards import Guard, synthesize
21
+ from agent_jit.ir import Refusal, Trace
22
+ from agent_jit.provenance import (
23
+ Binding,
24
+ FromStep,
25
+ Param,
26
+ Path,
27
+ StepBinding,
28
+ bind_arguments,
29
+ extract,
30
+ request_shape,
31
+ )
32
+ from agent_jit.slicer import slice_trace
33
+ from agent_jit.tools import ToolSpec, schema_hash
34
+
35
+ RESERVED_NAMES = frozenset({"ctx", "GUARDS", "Guard", "str", "run"})
36
+ _LOCAL_NAME = re.compile(r"s[0-9]+")
37
+ _MIN_TEMPLATE_TEXT = 3
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class CompiledSkill:
42
+ name: str
43
+ params: tuple[Param, ...]
44
+ source: str
45
+ tools: tuple[str, ...]
46
+ has_template: bool
47
+ example_request: str
48
+ schema_hashes: Mapping[str, str] = field(default_factory=dict)
49
+ # Requests with their parameter values masked, one per distinct form seen in the traces, and
50
+ # whether the skill changes anything. The router runs a writing skill only for these shapes.
51
+ request_shapes: tuple[str, ...] = ()
52
+ has_writes: bool = True # fail closed: a skill built without the flag is treated as writing
53
+
54
+
55
+ # --------------------------------------------------------------------------- validation
56
+
57
+
58
+ def _check_name(name: str, what: str) -> None:
59
+ if not name.isidentifier() or keyword.iskeyword(name):
60
+ raise Refusal(f"{what} {name!r} is not a usable identifier")
61
+ if name in RESERVED_NAMES or name.startswith(("__", "GUARDS")) or _LOCAL_NAME.fullmatch(name):
62
+ raise Refusal(f"{what} {name!r} is reserved")
63
+
64
+
65
+ def _check_traces(traces: Sequence[Trace], name: str, min_support: int) -> None:
66
+ _check_name(name, "skill name")
67
+ if len(traces) < min_support:
68
+ raise Refusal(f"need at least {min_support} traces, got {len(traces)}")
69
+ for trace in traces:
70
+ if trace.success is not True:
71
+ raise Refusal(f"run {trace.run_id} is not a confirmed success")
72
+ for step in trace.steps:
73
+ if step.effect == "irreversible":
74
+ raise Refusal(f"{step.tool} is irreversible and is never compiled")
75
+
76
+
77
+ def _literal(value: Any) -> str:
78
+ """``repr`` of a JSON-like literal; anything else is refused."""
79
+ if value is None or isinstance(value, bool | int | str):
80
+ return repr(value)
81
+ if isinstance(value, float):
82
+ if not math.isfinite(value):
83
+ raise Refusal("a non-finite float cannot be compiled")
84
+ return repr(value)
85
+ if isinstance(value, list):
86
+ return "[" + ", ".join(_literal(v) for v in value) + "]"
87
+ if isinstance(value, dict):
88
+ if not all(isinstance(k, str) for k in value):
89
+ raise Refusal("a dict constant with non-string keys cannot be compiled")
90
+ return "{" + ", ".join(f"{k!r}: {_literal(v)}" for k, v in value.items()) + "}"
91
+ raise Refusal(f"a constant of type {type(value).__name__} cannot be compiled")
92
+
93
+
94
+ # --------------------------------------------------------------------------- code generation
95
+
96
+
97
+ def _expr(binding: Binding) -> str:
98
+ if isinstance(binding, Param):
99
+ if binding.transform == "identity":
100
+ return binding.name
101
+ return f"ctx.get({binding.name}, (), {binding.transform!r})"
102
+ if isinstance(binding, FromStep):
103
+ return f"ctx.get(s{binding.step}, {binding.path!r}, {binding.transform!r})"
104
+ return _literal(binding.value)
105
+
106
+
107
+ def _params(bindings: Sequence[StepBinding]) -> tuple[Param, ...]:
108
+ seen: dict[str, Param] = {}
109
+ for step in bindings:
110
+ for binding in step.args.values():
111
+ if isinstance(binding, Param):
112
+ _check_name(binding.name, "parameter name")
113
+ seen.setdefault(binding.name, binding)
114
+ return tuple(seen.values())
115
+
116
+
117
+ def _guards_source(guards: Sequence[Guard], name: str = "GUARDS") -> str:
118
+ if not guards:
119
+ return f"{name} = ()"
120
+ lines = [
121
+ f" Guard({g.step!r}, {g.path!r}, {g.kind!r}, {_literal(g.expected)})," for g in guards
122
+ ]
123
+ return f"{name} = (\n" + "\n".join(lines) + "\n)"
124
+
125
+
126
+ def _step_lines(
127
+ bindings: Sequence[StepBinding],
128
+ start: int = 0,
129
+ stop: int | None = None,
130
+ guards: str = "GUARDS",
131
+ indent: str = " ",
132
+ ) -> list[str]:
133
+ lines = []
134
+ for i in range(start, len(bindings) if stop is None else stop):
135
+ step = bindings[i]
136
+ args = ", ".join(f"{k!r}: {_expr(b)}" for k, b in step.args.items())
137
+ call = f"await ctx.call({i}, {step.tool!r}, {{{args}}}, {guards})"
138
+ lines.append(f"{indent}s{i} = {call}")
139
+ return lines
140
+
141
+
142
+ # --------------------------------------------------------------------------- answer template
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class _Piece:
147
+ texts: tuple[str, ...] # the text this expression produced in each trace
148
+ expr: str
149
+
150
+
151
+ def _is_numeric(text: str) -> bool:
152
+ return re.fullmatch(r"-?[0-9]+(\.[0-9]+)?", text) is not None
153
+
154
+
155
+ def _eligible(texts: tuple[str, ...]) -> bool:
156
+ return all(_is_numeric(t) or len(t) >= _MIN_TEMPLATE_TEXT for t in texts)
157
+
158
+
159
+ def _leaves(
160
+ value: Any, path: tuple[str | int, ...] = ()
161
+ ) -> Iterator[tuple[tuple[str | int, ...], Any]]:
162
+ if isinstance(value, dict):
163
+ for k, v in value.items():
164
+ yield from _leaves(v, (*path, k))
165
+ elif isinstance(value, list):
166
+ if value:
167
+ yield from _leaves(value[0], (*path, 0))
168
+ elif value is not None and not isinstance(value, bool):
169
+ yield path, value
170
+
171
+
172
+ def _candidate_pieces(sliced: Sequence[Trace], bindings: Sequence[StepBinding]) -> list[_Piece]:
173
+ ordered: list[_Piece] = []
174
+ for kind in (Param, FromStep):
175
+ for i, step in enumerate(bindings):
176
+ for name, binding in step.args.items():
177
+ if isinstance(binding, kind):
178
+ texts = tuple(str(t.steps[i].args[name]) for t in sliced)
179
+ ordered.append(_Piece(texts, f"str({_expr(binding)})"))
180
+ for j, traced in enumerate(sliced[0].steps):
181
+ for path, _ in _leaves(traced.result):
182
+ try:
183
+ texts = tuple(str(extract(t.steps[j].result, path)) for t in sliced)
184
+ except LookupError:
185
+ continue
186
+ if len(set(texts)) > 1:
187
+ ordered.append(_Piece(texts, f"str(ctx.get(s{j}, {path!r}, 'identity'))"))
188
+ unique: dict[tuple[str, ...], _Piece] = {}
189
+ for piece in ordered:
190
+ if _eligible(piece.texts):
191
+ unique.setdefault(piece.texts, piece)
192
+ return list(unique.values())
193
+
194
+
195
+ def _occurrences(answer: str, piece: _Piece) -> Iterator[tuple[int, int, _Piece]]:
196
+ needle = piece.texts[0]
197
+ start = answer.find(needle)
198
+ while start != -1:
199
+ end = start + len(needle)
200
+ if (start == 0 or not answer[start - 1].isalnum()) and (
201
+ end == len(answer) or not answer[end].isalnum()
202
+ ):
203
+ yield start, end, piece
204
+ start = answer.find(needle, start + 1)
205
+
206
+
207
+ def _build_template(
208
+ sliced: Sequence[Trace], bindings: Sequence[StepBinding]
209
+ ) -> list[str | _Piece] | None:
210
+ answer = sliced[0].answer
211
+ found = [o for p in _candidate_pieces(sliced, bindings) for o in _occurrences(answer, p)]
212
+ found.sort(key=lambda o: (-(o[1] - o[0]), o[0]))
213
+ chosen: list[tuple[int, int, _Piece]] = []
214
+ for start, end, piece in found:
215
+ if all(end <= s or start >= e for s, e, _ in chosen):
216
+ chosen.append((start, end, piece))
217
+ chosen.sort()
218
+ segments: list[str | _Piece] = []
219
+ cursor = 0
220
+ for start, end, piece in chosen:
221
+ if start > cursor:
222
+ segments.append(answer[cursor:start])
223
+ segments.append(piece)
224
+ cursor = end
225
+ if cursor < len(answer):
226
+ segments.append(answer[cursor:])
227
+ for k, trace in enumerate(sliced):
228
+ rendered = "".join(s if isinstance(s, str) else s.texts[k] for s in segments)
229
+ if rendered != trace.answer:
230
+ return None
231
+ return segments
232
+
233
+
234
+ def _return_line(segments: list[str | _Piece] | None, indent: str = " ") -> str:
235
+ if segments is None:
236
+ return f"{indent}return None"
237
+ if not segments:
238
+ return f"{indent}return ''"
239
+ parts = " + ".join(repr(s) if isinstance(s, str) else s.expr for s in segments)
240
+ return f"{indent}return {parts}"
241
+
242
+
243
+ # --------------------------------------------------------------------------- public API
244
+
245
+
246
+ def _read_paths(bindings: Sequence[StepBinding]) -> dict[int, list[Path]]:
247
+ """Output paths the compiled steps read, by producing step, so their guards can be made."""
248
+ reads: dict[int, list[Path]] = {}
249
+ for step in bindings:
250
+ for binding in step.args.values():
251
+ if isinstance(binding, FromStep):
252
+ reads.setdefault(binding.step, []).append(binding.path)
253
+ return reads
254
+
255
+
256
+ def _check_item_identity(
257
+ reads: Mapping[int, Sequence[Path]], guards: Sequence[Guard], run_id: str
258
+ ) -> None:
259
+ """A value taken from a list item past the first is only safe if some field of that item is the
260
+ same in every trace (an ``equals`` guard); otherwise a reordered list binds the wrong item."""
261
+ for step, paths in reads.items():
262
+ for path in paths:
263
+ cut = max(
264
+ (i for i, k in enumerate(path) if isinstance(k, int) and k != 0), default=None
265
+ )
266
+ if cut is None:
267
+ continue
268
+ item = tuple(path[: cut + 1])
269
+ if not any(
270
+ g.kind == "equals" and g.step == step and tuple(g.path[: len(item)]) == item
271
+ for g in guards
272
+ ):
273
+ raise Refusal(
274
+ f"run {run_id}: step {step} item {list(item)!r} has no field that identifies "
275
+ "it across runs, so a reordered list could bind the wrong item"
276
+ )
277
+
278
+
279
+ def _shapes(traces: Sequence[Trace], params: Sequence[Param]) -> set[str]:
280
+ shapes = set()
281
+ for i, trace in enumerate(traces):
282
+ literals = [(p.name, p.texts[i]) for p in params if i < len(p.texts)]
283
+ try:
284
+ shapes.add(request_shape(trace.request, literals))
285
+ except ValueError:
286
+ continue # overlapping spans: no shape, so such a skill is never routed to
287
+ return shapes
288
+
289
+
290
+ def _dropped_steps(sliced: Sequence[Trace], original: Sequence[Trace]) -> bool:
291
+ return any(s.steps != o.steps for s, o in zip(sliced, original, strict=True))
292
+
293
+
294
+ def _slice_all(traces: Sequence[Trace], keep_all: bool = False) -> list[Trace]:
295
+ sliced = list(traces) if keep_all else [slice_trace(t) for t in traces]
296
+ for original, trace in zip(traces, sliced, strict=True):
297
+ if not trace.steps:
298
+ raise Refusal(f"run {original.run_id} has no tool calls worth compiling")
299
+ failed = next((s for s in trace.steps if not s.ok), None)
300
+ if failed is not None:
301
+ raise Refusal(f"run {original.run_id}: {failed.tool} failed; retries are not compiled")
302
+ return sliced
303
+
304
+
305
+ def compile_skill(
306
+ traces: Sequence[Trace],
307
+ name: str,
308
+ min_support: int = 2,
309
+ specs: Sequence[ToolSpec] = (),
310
+ ) -> CompiledSkill:
311
+ """Compile ``traces`` of one request type into a skill, or raise ``Refusal`` saying why."""
312
+ _check_traces(traces, name, min_support)
313
+ sliced = _slice_all(traces)
314
+ bindings = bind_arguments(sliced)
315
+ segments = _build_template(sliced, bindings)
316
+ if segments is None and _dropped_steps(sliced, traces):
317
+ # The answer is not a copy of tool outputs, so the model will have to compute it from the
318
+ # data of the run. A read the slice judged dead may be where that data came from: keep all.
319
+ sliced = _slice_all(traces, keep_all=True)
320
+ bindings = bind_arguments(sliced)
321
+ segments = _build_template(sliced, bindings)
322
+ reads = _read_paths(bindings)
323
+ guards = synthesize(sliced, reads)
324
+ _check_item_identity(reads, guards, sliced[0].run_id)
325
+ params = _params(bindings)
326
+ signature = "ctx, *, " + ", ".join(p.name for p in params) if params else "ctx"
327
+ body = [*_step_lines(bindings), _return_line(segments)]
328
+ by_name = {s.name: s for s in specs}
329
+ used = tuple(dict.fromkeys(step.tool for step in sliced[0].steps))
330
+ hashes = {t: schema_hash(by_name[t]) for t in used if t in by_name}
331
+ source = (
332
+ "from agent_jit.guards import Guard\n\n"
333
+ + _guards_source(guards)
334
+ + f"\n\nSCHEMA_HASHES = {_literal(hashes)}"
335
+ + f"\n\n\nasync def run({signature}):\n"
336
+ + "\n".join(body)
337
+ + "\n"
338
+ )
339
+ try:
340
+ validate_source(source)
341
+ except (ValueError, SyntaxError) as exc:
342
+ raise Refusal(f"generated source was rejected by validation: {exc}") from exc
343
+ return CompiledSkill(
344
+ name=name,
345
+ params=params,
346
+ source=source,
347
+ tools=tuple(s.tool for s in sliced[0].steps),
348
+ has_template=segments is not None,
349
+ example_request=traces[0].request,
350
+ schema_hashes=hashes,
351
+ request_shapes=tuple(sorted(_shapes(sliced, params))),
352
+ has_writes=any(s.effect != "read" for s in sliced[0].steps),
353
+ )
354
+
355
+
356
+ def _test_source(disc: Discriminator, value: str | bool) -> str:
357
+ read = f"ctx.get(s{disc.step}, {disc.path!r}, 'identity')"
358
+ # `is` for booleans: 1 == True in Python, and a stray 1 must not select a branch.
359
+ return f"{read} is {value!r}" if isinstance(value, bool) else f"{read} == {value!r}"
360
+
361
+
362
+ def _shared_prefix_guards(per_group: Sequence[Sequence[Guard]], split: int) -> tuple[Guard, ...]:
363
+ """Prefix guards every group agrees on; per-group differences are the branch test."""
364
+ return tuple(
365
+ g for g in per_group[0] if g.step < split and all(g in other for other in per_group[1:])
366
+ )
367
+
368
+
369
+ def compile_branched(
370
+ groups: Sequence[Sequence[Trace]],
371
+ name: str,
372
+ min_support: int = 2,
373
+ specs: Sequence[ToolSpec] = (),
374
+ ) -> CompiledSkill:
375
+ """Compile several families of traces into one skill that branches on a prefix value.
376
+
377
+ Each group needs ``min_support`` traces. The groups must share parameters and the steps
378
+ before the branch, and a value read in those steps must tell the groups apart; otherwise
379
+ ``Refusal``. A value seen at run time that matches no group fails, running no branch step.
380
+ """
381
+ _check_name(name, "skill name")
382
+ if len(groups) < 2:
383
+ raise Refusal("branching needs at least two groups of traces")
384
+ for group in groups:
385
+ _check_traces(group, name, min_support)
386
+ sliced = [_slice_all(g) for g in groups]
387
+ disc = find_discriminator(sliced)
388
+ if disc is None:
389
+ raise Refusal("ambiguous: no single value in the shared steps tells the groups apart")
390
+ keys = [tuple(s.tool for s in g[0].steps) for g in sliced]
391
+ split = split_index(keys)
392
+ if split is None:
393
+ raise Refusal("ambiguous: the groups do not diverge")
394
+ head = disc.step + 1 # steps up to and including the one that is read to choose a branch
395
+ if any(step.effect != "read" for g in sliced for step in g[0].steps[:head]):
396
+ raise Refusal("a write runs before the branch value is read")
397
+ bound = [bind_arguments(g) for g in sliced]
398
+ param_sets = [_params(b) for b in bound]
399
+ if any(set(p) != set(param_sets[0]) for p in param_sets[1:]):
400
+ raise Refusal("branches disagree on parameters")
401
+ if any(b[:head] != bound[0][:head] for b in bound[1:]):
402
+ raise Refusal("branches disagree on the shared steps")
403
+ params = param_sets[0]
404
+ per_group = [synthesize(g, _read_paths(b)) for g, b in zip(sliced, bound, strict=True)]
405
+ for g, b, pg in zip(sliced, bound, per_group, strict=True):
406
+ _check_item_identity(_read_paths(b), pg, g[0].run_id)
407
+ group_shapes = [_shapes(g, p) for g, p in zip(sliced, param_sets, strict=True)]
408
+ writes = any(s.effect != "read" for g in sliced for t in g for s in t.steps)
409
+ if writes and any(shapes != group_shapes[0] for shapes in group_shapes[1:]):
410
+ # The data picks the branch, the request picks the intent. If the groups are worded
411
+ # differently, "Cancel order N" for a delivered order would run the refund branch.
412
+ raise Refusal(
413
+ "branches that write were learned from differently worded requests; the wording could "
414
+ "disagree with the branch the data selects"
415
+ )
416
+ body = _step_lines(bound[0], 0, head, "GUARDS_P")
417
+ templates: list[list[str | _Piece] | None] = []
418
+ for k, (group, steps) in enumerate(zip(sliced, bound, strict=True)):
419
+ test = _test_source(disc, disc.values[keys[k]])
420
+ segments = _build_template(group, steps)
421
+ templates.append(segments)
422
+ body.append(f" {'if' if k == 0 else 'elif'} {test}:")
423
+ body.extend(_step_lines(steps, head, None, f"GUARDS_{k}", " "))
424
+ body.append(_return_line(segments, " "))
425
+ if any(t is None for t in templates) and _dropped_steps(
426
+ [t for g in sliced for t in g], [t for g in groups for t in g]
427
+ ):
428
+ raise Refusal(
429
+ "the answer is not fully templated and a read it may depend on was sliced away"
430
+ )
431
+ body.extend([" ctx.fail('unknown branch value')", " return None"])
432
+ by_name = {s.name: s for s in specs}
433
+ used = tuple(dict.fromkeys(t for key in keys for t in key))
434
+ hashes = {t: schema_hash(by_name[t]) for t in used if t in by_name}
435
+ guard_defs = [_guards_source(_shared_prefix_guards(per_group, head), "GUARDS_P")] + [
436
+ _guards_source(pg, f"GUARDS_{k}") for k, pg in enumerate(per_group)
437
+ ]
438
+ signature = "ctx, *, " + ", ".join(p.name for p in params) if params else "ctx"
439
+ source = (
440
+ "from agent_jit.guards import Guard\n\n"
441
+ + "\n\n".join(guard_defs)
442
+ + f"\n\nSCHEMA_HASHES = {_literal(hashes)}"
443
+ + f"\n\n\nasync def run({signature}):\n"
444
+ + "\n".join(body)
445
+ + "\n"
446
+ )
447
+ try:
448
+ validate_source(source)
449
+ except (ValueError, SyntaxError) as exc:
450
+ raise Refusal(f"generated source was rejected by validation: {exc}") from exc
451
+ return CompiledSkill(
452
+ name=name,
453
+ params=params,
454
+ source=source,
455
+ tools=used,
456
+ has_template=all(t is not None for t in templates),
457
+ example_request=groups[0][0].request,
458
+ schema_hashes=hashes,
459
+ request_shapes=tuple(sorted(set().union(*group_shapes))),
460
+ has_writes=writes,
461
+ )
462
+
463
+
464
+ # --------------------------------------------------------------------------- loading
465
+
466
+
467
+ _ALLOWED_CALLS = frozenset({"Guard", "str"})
468
+ _ALLOWED_CTX_METHODS = frozenset({"call", "get"})
469
+
470
+
471
+ def _check_expr(node: ast.AST, names: set[str]) -> None:
472
+ if isinstance(node, ast.Constant):
473
+ if not isinstance(node.value, str | int | float | bool | type(None)):
474
+ raise ValueError(f"constant of type {type(node.value).__name__} is not allowed")
475
+ elif isinstance(node, ast.Name):
476
+ if node.id not in names or not isinstance(node.ctx, ast.Load):
477
+ raise ValueError(f"name {node.id!r} is not allowed")
478
+ elif isinstance(node, ast.Tuple | ast.List):
479
+ for item in node.elts:
480
+ _check_expr(item, names)
481
+ elif isinstance(node, ast.Dict):
482
+ items: list[ast.expr | None] = [*node.keys, *node.values]
483
+ for entry in items:
484
+ if entry is None:
485
+ raise ValueError("dict unpacking is not allowed")
486
+ _check_expr(entry, names)
487
+ elif isinstance(node, ast.UnaryOp):
488
+ operand = node.operand
489
+ negative_number = (
490
+ isinstance(node.op, ast.USub)
491
+ and isinstance(operand, ast.Constant)
492
+ and isinstance(operand.value, int | float)
493
+ and not isinstance(operand.value, bool)
494
+ )
495
+ if not negative_number:
496
+ raise ValueError("this unary operation is not allowed")
497
+ elif isinstance(node, ast.BinOp):
498
+ if not isinstance(node.op, ast.Add):
499
+ raise ValueError("only + is allowed")
500
+ _check_expr(node.left, names)
501
+ _check_expr(node.right, names)
502
+ elif isinstance(node, ast.Await):
503
+ _check_expr(node.value, names)
504
+ elif isinstance(node, ast.Call):
505
+ _check_call(node, names)
506
+ else:
507
+ raise ValueError(f"{type(node).__name__} is not allowed")
508
+
509
+
510
+ def _check_call(node: ast.Call, names: set[str]) -> None:
511
+ func = node.func
512
+ allowed = (isinstance(func, ast.Name) and func.id in _ALLOWED_CALLS) or (
513
+ isinstance(func, ast.Attribute)
514
+ and isinstance(func.value, ast.Name)
515
+ and func.value.id == "ctx"
516
+ and func.attr in _ALLOWED_CTX_METHODS
517
+ )
518
+ if not allowed or node.keywords:
519
+ raise ValueError("this call is not allowed")
520
+ for arg in node.args:
521
+ _check_expr(arg, names)
522
+
523
+
524
+ _GUARD_NAME = re.compile(r"GUARDS(_P|_[0-9]+)?")
525
+
526
+
527
+ def _is_ctx_method(node: ast.expr, method: str) -> bool:
528
+ return (
529
+ isinstance(node, ast.Call)
530
+ and isinstance(node.func, ast.Attribute)
531
+ and isinstance(node.func.value, ast.Name)
532
+ and node.func.value.id == "ctx"
533
+ and node.func.attr == method
534
+ )
535
+
536
+
537
+ def _is_fail_call(node: ast.expr) -> bool:
538
+ return (
539
+ _is_ctx_method(node, "fail")
540
+ and isinstance(node, ast.Call)
541
+ and not node.keywords
542
+ and len(node.args) == 1
543
+ and isinstance(node.args[0], ast.Constant)
544
+ and isinstance(node.args[0].value, str)
545
+ )
546
+
547
+
548
+ def _check_test(test: ast.expr, names: set[str]) -> None:
549
+ ok = (
550
+ isinstance(test, ast.Compare)
551
+ and len(test.ops) == 1
552
+ and len(test.comparators) == 1
553
+ and _is_ctx_method(test.left, "get")
554
+ and isinstance(test.comparators[0], ast.Constant)
555
+ and (
556
+ (isinstance(test.ops[0], ast.Eq) and isinstance(test.comparators[0].value, str))
557
+ or (isinstance(test.ops[0], ast.Is) and isinstance(test.comparators[0].value, bool))
558
+ )
559
+ )
560
+ if not ok or not isinstance(test, ast.Compare):
561
+ raise ValueError("this condition is not allowed")
562
+ _check_expr(test.left, names)
563
+
564
+
565
+ def _check_if(node: ast.If, names: set[str]) -> None:
566
+ _check_test(node.test, names)
567
+ _check_body(node.body, set(names))
568
+ if node.orelse:
569
+ if len(node.orelse) != 1 or not isinstance(node.orelse[0], ast.If):
570
+ raise ValueError("else blocks are not allowed")
571
+ _check_if(node.orelse[0], names)
572
+
573
+
574
+ def _check_body(body: Sequence[ast.stmt], names: set[str]) -> None:
575
+ for stmt in body:
576
+ if isinstance(stmt, ast.Assign):
577
+ targets = stmt.targets
578
+ if len(targets) != 1 or not isinstance(targets[0], ast.Name):
579
+ raise ValueError("assignment target is not allowed")
580
+ if not _LOCAL_NAME.fullmatch(targets[0].id):
581
+ raise ValueError(f"local {targets[0].id!r} is not allowed")
582
+ _check_expr(stmt.value, names)
583
+ names.add(targets[0].id)
584
+ elif isinstance(stmt, ast.Return) and stmt.value is not None:
585
+ _check_expr(stmt.value, names)
586
+ elif isinstance(stmt, ast.If):
587
+ _check_if(stmt, names)
588
+ elif isinstance(stmt, ast.Expr) and _is_fail_call(stmt.value):
589
+ continue
590
+ else:
591
+ raise ValueError(f"{type(stmt).__name__} is not allowed")
592
+
593
+
594
+ def _check_function(fn: ast.AsyncFunctionDef, guard_names: set[str]) -> None:
595
+ if fn.decorator_list or fn.returns is not None or getattr(fn, "type_params", None):
596
+ raise ValueError("decorators, annotations and type parameters are not allowed")
597
+ a = fn.args
598
+ if any(x.annotation is not None for x in [*a.args, *a.kwonlyargs]):
599
+ raise ValueError("annotations are not allowed")
600
+ plain = [x.arg for x in a.args]
601
+ if plain != ["ctx"] or a.posonlyargs or a.vararg or a.kwarg or a.defaults:
602
+ raise ValueError("run must take ctx and keyword-only parameters")
603
+ if any(d is not None for d in a.kw_defaults):
604
+ raise ValueError("defaults are not allowed")
605
+ names = {"ctx", "GUARDS", "Guard", "str", *guard_names, *(x.arg for x in a.kwonlyargs)}
606
+ _check_body(fn.body, names)
607
+
608
+
609
+ def validate_source(source: str) -> None:
610
+ """Raise ``ValueError`` unless ``source`` has exactly the shape the compiler emits."""
611
+ tree = ast.parse(source)
612
+ functions = 0
613
+ guard_names: set[str] = set()
614
+ for node in tree.body:
615
+ if isinstance(node, ast.ImportFrom):
616
+ ok = (
617
+ node.module == "agent_jit.guards"
618
+ and node.level == 0
619
+ and [a.name for a in node.names] == ["Guard"]
620
+ and node.names[0].asname is None
621
+ )
622
+ if not ok:
623
+ raise ValueError("this import is not allowed")
624
+ elif isinstance(node, ast.Assign):
625
+ targets = [getattr(t, "id", None) for t in node.targets]
626
+ target = targets[0] if len(targets) == 1 else None
627
+ if target != "SCHEMA_HASHES" and not (
628
+ isinstance(target, str) and _GUARD_NAME.fullmatch(target)
629
+ ):
630
+ raise ValueError("only GUARDS and SCHEMA_HASHES may be assigned at module level")
631
+ _check_expr(node.value, {"Guard"})
632
+ if isinstance(target, str) and target != "SCHEMA_HASHES":
633
+ guard_names.add(target)
634
+ elif isinstance(node, ast.AsyncFunctionDef) and node.name == "run":
635
+ functions += 1
636
+ _check_function(node, guard_names)
637
+ else:
638
+ raise ValueError(f"{type(node).__name__} is not allowed at module level")
639
+ if functions != 1:
640
+ raise ValueError("exactly one run function is required")
641
+
642
+
643
+ def skill_is_current(skill: CompiledSkill, specs: Sequence[ToolSpec]) -> bool:
644
+ """True when every tool the skill uses still has the schema it was compiled against."""
645
+ current = {s.name: schema_hash(s) for s in specs}
646
+ return bool(skill.schema_hashes) and all(
647
+ skill.schema_hashes.get(tool) == current.get(tool) for tool in skill.tools
648
+ )
649
+
650
+
651
+ def load_skill(skill: CompiledSkill) -> Callable[..., Awaitable[str | None]]:
652
+ """Validate and load a skill's ``run`` coroutine function."""
653
+ validate_source(skill.source)
654
+ namespace: dict[str, Any] = {
655
+ "__builtins__": {"__import__": builtins.__import__, "str": str},
656
+ }
657
+ exec(compile(skill.source, f"<skill {skill.name}>", "exec"), namespace)
658
+ run: Callable[..., Awaitable[str | None]] = namespace["run"]
659
+ return run