python-yama 0.3.0__py3-none-any.whl → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-yama
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A reproducible evaluation runner for tool-using Agent skills
5
5
  Project-URL: Repository, https://github.com/world-sim-dev/yama
6
6
  Project-URL: Issues, https://github.com/world-sim-dev/yama/issues
@@ -75,7 +75,7 @@ outcome:
75
75
 
76
76
  - `description` (optional) is a one-line summary of what the Case tests; it is shown in the CLI output and the HTML report.
77
77
  - `context.tools` is the tool schema sent to the model; `mocks.tools` is how the runner responds when a tool call arrives. The two sets of tool names must match exactly.
78
- - To use a Skill, declare it by name under `context.skills` and also declare `{builtin: skill}` under `context.tools`; the model reads the Skill body via `skill(name, file?)`.
78
+ - To use a Skill, declare it by name under `context.skills` and also declare `{builtin: skill}` under `context.tools`; the model reads the Skill body via `skill(name, file?, call_reason?)`.
79
79
  - To simulate command-line tools, declare `{builtin: bash}` and configure per-command output under `mocks.cli`.
80
80
  - `steps[].assert.hard` are deterministic checks (nine types, including `tool_called`, `tool_arguments`, and `assistant_contains`); add `assert.judge` for LLM scoring.
81
81
 
@@ -93,6 +93,7 @@ uv run --project yama yama --plugin dingding-simple --report
93
93
  | `--plugin-root PATH` | Use the given path as the single plugin root |
94
94
  | `--plugin NAME` (repeatable) | Select plugins by name from `yama.toml` |
95
95
  | `--all-plugins` | Run every plugin configured in `yama.toml` |
96
+ | `-k, --filter PATTERN` (repeatable) | Only run cases whose case key (path relative to the plugin root) matches — a substring, or an fnmatch glob when the pattern contains `*` `?` `[`; with several patterns a case runs if any matches |
96
97
  | `--result-dir PATH` | Override the artifact root (default `<plugin_root>/.yama/runs`) |
97
98
  | `--concurrency N` | Maximum number of cases running in parallel (default 10; `1` runs cases one at a time) |
98
99
  | `--report [PATH]` | Also generate a single-file HTML report (default `.yama/reports/latest.html`) |
@@ -0,0 +1,27 @@
1
+ yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
+ yama/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ yama/assertions.py,sha256=_PXx-yCTbTqVI-upyPFVxDu3EQC1aSoGtTP3A10q47k,21968
4
+ yama/cli.py,sha256=rTccf7nXKnxvY2Wc311zEgyN5GHAG7ZEBCM3DSqm7kU,24952
5
+ yama/llm.py,sha256=F_9HoFvLisKhTc8kREVvdqf3XN3JHE-Zy-1mW7O8DbQ,14627
6
+ yama/mocks.py,sha256=YyiU6Y7NgttxHYJBsqGPILKYlTsM4IMTIilMNRkUuzs,14973
7
+ yama/models.py,sha256=0BMCWku5zWDOESrFUibiJShlfEhOAGlVKaNxfPB-9OM,4020
8
+ yama/report.py,sha256=vYvqt6I0NXCgp1Cbr-FnHNDAc8oJc_4mrLfZ7DTybU8,40172
9
+ yama/runner.py,sha256=Sp8DbIrFPQtLyNbeauJjcX29AD_yS1-BdRpObMNApvI,25542
10
+ yama/workspace.py,sha256=4GAe36Uj1-gjROMPwrQfTIg1TkzEIk9-gHEuezjbY_I,4614
11
+ yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
12
+ yama/loaders/case.py,sha256=5uUpXm1t9EOmee2BZe7vDGXCrc4CSgcFGApSkuFe5tc,13954
13
+ yama/loaders/common.py,sha256=Fg71_vcnu5339QI_itvYPvRbk9LtBgEnzoA3t4Krb4U,754
14
+ yama/loaders/tool_loader.py,sha256=AaJwrFEjmfdUhKqXIlfl_jyvaKQ4ZoPPOpT8Wg5xuNU,12574
15
+ yama/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ yama/tools/base.py,sha256=ONFuGzTSWVsA0k4-UUREncqAHmyQI2uHpVOU2Dh_XiQ,446
17
+ yama/tools/bash/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ yama/tools/bash/_cli_shim.py,sha256=f3Rom5UipW0dA0KRYavqIa9HJDKT336ssDZGWeVmkvo,2494
19
+ yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
20
+ yama/tools/bash/fs.py,sha256=GChDwGe_Sgn73btZJDNp5nOwlVDhLfZyaMVqWSQwfOw,21859
21
+ yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ yama/tools/skill/skill.py,sha256=H2KdIBLkYhecYX7M2xbn79csDpDvougpRcAmlrwigEM,2235
23
+ python_yama-0.4.0.dist-info/METADATA,sha256=ankApENSDGGbFE4OkxO9g1713UyGD4a3Y8WBZVi2JRs,6083
24
+ python_yama-0.4.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
25
+ python_yama-0.4.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
26
+ python_yama-0.4.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
27
+ python_yama-0.4.0.dist-info/RECORD,,
yama/assertions.py CHANGED
@@ -574,4 +574,8 @@ async def run_judge(
574
574
  passed = False
575
575
  judged["overall"] = weighted / total_weight
576
576
  judged["passed"] = passed
577
+ if response.usage is not None:
578
+ # Judge calls bypass the runner's per-request records, so their
579
+ # token usage rides on the judge result to reach run aggregation.
580
+ judged["usage"] = deepcopy(response.usage)
577
581
  return judged
yama/cli.py CHANGED
@@ -27,7 +27,7 @@ from .workspace import (
27
27
  from .llm import LLMError, LiteLLMClient
28
28
  from .loaders import CollectionError, resolve_case
29
29
  from .report import write_html_report
30
- from .runner import YamaRunner
30
+ from .runner import YamaRunner, combine_usage
31
31
 
32
32
  DEFAULT_REPORT = Path("__yama_default_report__")
33
33
 
@@ -38,6 +38,20 @@ def _status(passed: bool, *, compact: bool = False) -> Text:
38
38
  return Text("✗" if compact else "FAIL", style="bold red")
39
39
 
40
40
 
41
+ def _usage_label(usage: dict[str, int] | None, *, split: bool = False) -> str:
42
+ """`tokens 12,345`-style suffix for labels and captions; empty when no
43
+ LLM call reported usage (scripted replays, runs that died early)."""
44
+ if not usage:
45
+ return ""
46
+ label = f"tokens {usage['total_tokens']:,}"
47
+ if split:
48
+ label += (
49
+ f" (in {usage['prompt_tokens']:,}"
50
+ f" / out {usage['completion_tokens']:,})"
51
+ )
52
+ return label
53
+
54
+
41
55
  def _summary_case_key(case_key: str) -> str:
42
56
  prefix = "__evals__/cases/"
43
57
  return case_key.removeprefix(prefix)
@@ -128,17 +142,22 @@ def build_case_tree(result: Any) -> Tree:
128
142
  (result.case_key, "bold"),
129
143
  (f" {result.pass_rate:.0%}", "dim"),
130
144
  )
145
+ case_usage = result.usage()
146
+ if case_usage:
147
+ case_label.append(f" {_usage_label(case_usage, split=True)}", style="dim")
131
148
  if result.description:
132
149
  case_label.append(f"\n{result.description}", style="dim")
133
150
  tree = Tree(case_label, guide_style="dim")
134
151
  for run in result.runs:
135
- run_node = tree.add(
136
- Text.assemble(
137
- _status(run.passed, compact=True),
138
- " ",
139
- (f"Run {run.run_index}", "bold"),
140
- )
152
+ run_label = Text.assemble(
153
+ _status(run.passed, compact=True),
154
+ " ",
155
+ (f"Run {run.run_index}", "bold"),
141
156
  )
157
+ run_usage = run.usage()
158
+ if run_usage:
159
+ run_label.append(f" {_usage_label(run_usage)}", style="dim")
160
+ run_node = tree.add(run_label)
142
161
  if run.error:
143
162
  run_node.add(Text.assemble(("Error: ", "bold red"), (run.error, "red")))
144
163
  run_node.children.extend(build_step_tree(step) for step in run.steps)
@@ -157,6 +176,7 @@ def build_summary_table(results: list[Any]) -> Table:
157
176
  table.add_column("Case", ratio=1, overflow="fold")
158
177
  table.add_column("Runs", justify="right", no_wrap=True)
159
178
  table.add_column("Pass rate", justify="right", no_wrap=True)
179
+ table.add_column("Tokens", justify="right", no_wrap=True)
160
180
 
161
181
  passed_runs = 0
162
182
  total_runs = 0
@@ -167,11 +187,13 @@ def build_summary_table(results: list[Any]) -> Table:
167
187
  case_cell = Text(_summary_case_key(result.case_key))
168
188
  if result.description:
169
189
  case_cell.append(f"\n{result.description}", style="dim")
190
+ usage = result.usage()
170
191
  table.add_row(
171
192
  _status(result.passed),
172
193
  case_cell,
173
194
  f"{case_passed_runs}/{len(result.runs)}",
174
195
  f"{result.pass_rate:.0%}",
196
+ f"{usage['total_tokens']:,}" if usage else "–",
175
197
  )
176
198
 
177
199
  passed_cases = sum(result.passed for result in results)
@@ -179,6 +201,9 @@ def build_summary_table(results: list[Any]) -> Table:
179
201
  f"{passed_cases}/{len(results)} cases passed • "
180
202
  f"{passed_runs}/{total_runs} runs passed"
181
203
  )
204
+ total_usage = combine_usage(result.usage() for result in results)
205
+ if total_usage:
206
+ table.caption += f" • {_usage_label(total_usage, split=True)}"
182
207
  table.caption_style = "green" if passed_cases == len(results) else "red"
183
208
  return table
184
209
 
@@ -264,16 +289,19 @@ class ProgressPrinter:
264
289
  elif event == "case_end":
265
290
  result = payload["result"]
266
291
  passed_runs = sum(run.passed for run in result.runs)
292
+ meta = (
293
+ f" {passed_runs}/{len(result.runs)} runs passed"
294
+ f" {result.pass_rate:.0%}"
295
+ )
296
+ usage = result.usage()
297
+ if usage:
298
+ meta += f" {_usage_label(usage)}"
267
299
  self.console.print(
268
300
  Text.assemble(
269
301
  _status(result.passed, compact=True),
270
302
  " ",
271
303
  (result.case_key, "bold"),
272
- (
273
- f" {passed_runs}/{len(result.runs)} runs passed"
274
- f" {result.pass_rate:.0%}",
275
- "dim",
276
- ),
304
+ (meta, "dim"),
277
305
  )
278
306
  )
279
307
  self.console.print()
@@ -366,16 +394,16 @@ class ParallelProgressPrinter:
366
394
  else:
367
395
  result = row["result"]
368
396
  passed_runs = sum(run.passed for run in result.runs)
397
+ meta = (
398
+ f" {passed_runs}/{len(result.runs)} runs"
399
+ f" {result.pass_rate:.0%}"
400
+ )
401
+ usage = result.usage()
402
+ if usage:
403
+ meta += f" {_usage_label(usage)}"
369
404
  grid.add_row(
370
405
  _status(result.passed, compact=True),
371
- Text.assemble(
372
- (case_key, "bold"),
373
- (
374
- f" {passed_runs}/{len(result.runs)} runs"
375
- f" {result.pass_rate:.0%}",
376
- "dim",
377
- ),
378
- ),
406
+ Text.assemble((case_key, "bold"), (meta, "dim")),
379
407
  )
380
408
  return grid
381
409
 
@@ -457,6 +485,18 @@ def _parser() -> argparse.ArgumentParser:
457
485
  parser.add_argument(
458
486
  "--all-plugins", action="store_true", help="Run all configured plugins"
459
487
  )
488
+ parser.add_argument(
489
+ "-k",
490
+ "--filter",
491
+ action="append",
492
+ dest="filters",
493
+ metavar="PATTERN",
494
+ help=(
495
+ "Only run cases whose case key (path relative to the plugin root)"
496
+ " matches PATTERN -- a substring, or an fnmatch glob when it"
497
+ " contains * ? [. Repeatable; a case runs if any pattern matches."
498
+ ),
499
+ )
460
500
  parser.add_argument("--result-dir", type=Path, help="Override artifact directory")
461
501
  parser.add_argument(
462
502
  "--concurrency",
@@ -518,6 +558,7 @@ async def _run(args: argparse.Namespace) -> int:
518
558
  workspace,
519
559
  plugin_config,
520
560
  explicit_paths=args.paths or None,
561
+ filters=args.filters,
521
562
  )
522
563
  for path in paths:
523
564
  collected.append(resolve_case(path, plugin_root, workspace, plugin_config))
@@ -526,7 +567,12 @@ async def _run(args: argparse.Namespace) -> int:
526
567
  print(case.case_key)
527
568
  return 0
528
569
  if not collected:
529
- Console(stderr=True).print("[bold red]No eval cases collected.[/bold red]")
570
+ message = (
571
+ "No eval cases matched the case filter."
572
+ if args.filters
573
+ else "No eval cases collected."
574
+ )
575
+ Console(stderr=True).print(f"[bold red]{message}[/bold red]")
530
576
  return 2
531
577
 
532
578
  # With --json, stdout must stay valid JSON, so live progress moves to
yama/llm.py CHANGED
@@ -185,6 +185,30 @@ def _value(item: Any, key: str, default: Any = None) -> Any:
185
185
  return getattr(item, key, default)
186
186
 
187
187
 
188
+ def _normalized_usage(value: Any) -> dict[str, int] | None:
189
+ """Reduce a provider usage payload to plain int token counters.
190
+
191
+ Providers attach extra detail blocks (`prompt_tokens_details`, cache
192
+ counters, ...) with shapes that vary per provider; only the three
193
+ OpenAI-style counters are kept so downstream aggregation can sum
194
+ them blindly. Returns None when the payload carries none of them.
195
+ """
196
+ if value is None:
197
+ return None
198
+ usage: dict[str, int] = {}
199
+ for key in ("prompt_tokens", "completion_tokens", "total_tokens"):
200
+ raw = _value(value, key)
201
+ if isinstance(raw, (int, float)) and not isinstance(raw, bool):
202
+ usage[key] = int(raw)
203
+ if not usage:
204
+ return None
205
+ usage.setdefault(
206
+ "total_tokens",
207
+ usage.get("prompt_tokens", 0) + usage.get("completion_tokens", 0),
208
+ )
209
+ return usage
210
+
211
+
188
212
  class LiteLLMClient(LLMClient):
189
213
  def __init__(
190
214
  self,
@@ -269,7 +293,12 @@ class LiteLLMClient(LLMClient):
269
293
  raw = (
270
294
  response.model_dump() if hasattr(response, "model_dump") else str(response)
271
295
  )
272
- return LLMResponse(content=content, tool_calls=calls, raw=raw)
296
+ return LLMResponse(
297
+ content=content,
298
+ tool_calls=calls,
299
+ raw=raw,
300
+ usage=_normalized_usage(_value(response, "usage")),
301
+ )
273
302
 
274
303
 
275
304
  class ScriptedLLMClient(LLMClient):
@@ -329,6 +358,7 @@ class ScriptedLLMClient(LLMClient):
329
358
  content=str(scripted.get("content", "")),
330
359
  tool_calls=calls,
331
360
  raw=deepcopy(scripted),
361
+ usage=_normalized_usage(scripted.get("usage")),
332
362
  )
333
363
 
334
364
  def _check_expectation(self, expectation: Any, request: dict[str, Any]) -> None:
yama/loaders/case.py CHANGED
@@ -8,10 +8,10 @@ from typing import Any
8
8
 
9
9
  import yaml
10
10
 
11
- from ..workspace import WorkspaceConfig
11
+ from ..workspace import WorkspaceConfig, case_key_for_path
12
12
  from ..models import LoadedSkill, ResolvedCase
13
13
  from .common import CollectionError, load_yaml, sha256_file
14
- from .tool_loader import load_tool
14
+ from .tool_loader import load_tool, resolve_builtin_handlers
15
15
 
16
16
 
17
17
  def _load_skill(
@@ -287,35 +287,18 @@ def resolve_case(
287
287
  tool_items = context.get("tools", [])
288
288
  if not isinstance(tool_items, list):
289
289
  raise CollectionError("context.tools must be a list")
290
- tools = [
291
- load_tool(
292
- evals_root,
293
- item,
294
- skills=skills,
295
- conventions=conventions,
296
- mocks=mocks,
297
- )
298
- for item in tool_items
299
- ]
300
- if skills and not any(
301
- isinstance(item, dict) and item.get("builtin") == "skill"
302
- for item in tool_items
303
- ):
304
- raise CollectionError(
305
- "context.tools must include {builtin: skill} when context.skills "
306
- "is non-empty"
307
- )
290
+ tools = [load_tool(evals_root, item, skills=skills) for item in tool_items]
308
291
  tool_names = [tool.name for tool in tools]
309
292
  if len(tool_names) != len(set(tool_names)):
310
293
  raise CollectionError("context.tools contains duplicate names")
311
- if "cli" in mocks:
312
- raise CollectionError(
313
- "mocks.cli requires context.tools to include {builtin: bash}"
314
- )
315
- if "fs" in mocks:
316
- raise CollectionError(
317
- "mocks.fs requires context.tools to include {builtin: bash}"
318
- )
294
+ resolve_builtin_handlers(
295
+ tool_items,
296
+ tools,
297
+ mocks,
298
+ evals_root=evals_root,
299
+ skills=skills,
300
+ conventions=conventions,
301
+ )
319
302
 
320
303
  fixture_manifest: list[dict[str, Any]] = []
321
304
  initial_messages: list[dict[str, Any]] = [
@@ -361,13 +344,9 @@ def resolve_case(
361
344
  execution = deepcopy(workspace.defaults["execution"])
362
345
  execution.update(plugin_config.get("execution", {}))
363
346
  execution.update(raw.get("execution", {}))
364
- try:
365
- case_key = path.resolve().relative_to(plugin_root.resolve()).as_posix()
366
- except ValueError:
367
- case_key = path.name
368
347
  return ResolvedCase(
369
348
  path=path.resolve(),
370
- case_key=case_key,
349
+ case_key=case_key_for_path(path, plugin_root),
371
350
  description=description,
372
351
  plugin_root=plugin_root.resolve(),
373
352
  evals_root=evals_root,
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from copy import deepcopy
3
4
  from pathlib import Path
4
5
  from typing import Any
5
6
 
@@ -9,14 +10,20 @@ from ..tools.bash.bash import normalize_cli_config
9
10
  from ..tools.bash.fs import normalize_fs_config
10
11
  from .common import CollectionError, load_yaml
11
12
 
13
+ # Argument each builtin handler reads from the tool call; a custom schema wired
14
+ # to that handler must declare it as a required property so the model actually
15
+ # sends it.
16
+ _BUILTIN_HANDLER_CONTRACTS = {
17
+ "skill": "name",
18
+ "bash": "command",
19
+ }
20
+
12
21
 
13
22
  def load_tool(
14
23
  evals_root: Path,
15
24
  item: Any,
16
25
  *,
17
26
  skills: list[LoadedSkill],
18
- conventions: dict[str, str],
19
- mocks: dict[str, Any],
20
27
  ) -> ToolSchema:
21
28
  if not isinstance(item, dict) or sum(
22
29
  key in item for key in ("builtin", "file", "inline")
@@ -28,9 +35,14 @@ def load_tool(
28
35
  if set(item) != {"builtin"}:
29
36
  raise CollectionError("builtin tool entries cannot contain other fields")
30
37
  if item["builtin"] == "skill":
31
- return _resolve_builtin_skill_tool(skills, conventions, mocks)
38
+ if not skills:
39
+ raise CollectionError(
40
+ "context.tools builtin skill requires at least one "
41
+ "context.skills entry"
42
+ )
43
+ return _skill_tool_schema()
32
44
  if item["builtin"] == "bash":
33
- return _resolve_builtin_bash_tool(mocks, evals_root)
45
+ return _bash_tool_schema()
34
46
  raise CollectionError(f"unknown builtin tool: {item['builtin']!r}")
35
47
  source_path: Path | None = None
36
48
  if "file" in item:
@@ -54,120 +66,259 @@ def load_tool(
54
66
  return ToolSchema(name, description, parameters, source_path)
55
67
 
56
68
 
57
- def _skill_tool_schema(skills: list[LoadedSkill]) -> ToolSchema:
58
- names = [skill.name for skill in skills]
69
+ def resolve_builtin_handlers(
70
+ tool_items: list[Any],
71
+ tools: list[ToolSchema],
72
+ mocks: dict[str, Any],
73
+ *,
74
+ evals_root: Path,
75
+ skills: list[LoadedSkill],
76
+ conventions: dict[str, str],
77
+ ) -> None:
78
+ """Wire builtin tool declarations and expand ``handler: {builtin: ...}``.
79
+
80
+ ``{builtin: x}`` entries in ``context.tools`` get a default
81
+ ``handler: {builtin: x}`` mock unless the case already configured one.
82
+ Every ``mocks.tools`` entry whose handler is ``{builtin: skill|bash}`` is
83
+ then expanded in place into the framework's Python handler plus its
84
+ derived config (skill: enabled set and directory conventions; bash: the
85
+ normalized ``mocks.cli`` / ``mocks.fs`` execution config).
86
+ """
87
+ declared = {
88
+ tool.name: item["builtin"]
89
+ for item, tool in zip(tool_items, tools)
90
+ if isinstance(item, dict) and "builtin" in item
91
+ }
92
+ if declared and "tools" not in mocks:
93
+ mocks["tools"] = {}
94
+ mock_tools = mocks.get("tools", {})
95
+ if not isinstance(mock_tools, dict):
96
+ raise CollectionError("mocks.tools must be an object")
97
+ for name, kind in declared.items():
98
+ mock_tools.setdefault(name, {"handler": {"builtin": kind}})
99
+
100
+ tools_by_name = {tool.name: tool for tool in tools}
101
+ builtin_entries: list[tuple[str, dict[str, Any], str]] = []
102
+ for name, entry in mock_tools.items():
103
+ if not isinstance(entry, dict):
104
+ continue
105
+ handler = entry.get("handler")
106
+ if not isinstance(handler, dict) or "builtin" not in handler:
107
+ continue
108
+ if set(handler) != {"builtin"}:
109
+ raise CollectionError(
110
+ f"mocks.tools.{name} handler {{builtin: ...}} cannot contain "
111
+ "other fields"
112
+ )
113
+ kind = handler["builtin"]
114
+ if kind not in _BUILTIN_HANDLER_CONTRACTS:
115
+ raise CollectionError(
116
+ f"unknown builtin handler for mocks.tools.{name}: {kind!r}"
117
+ )
118
+ tool = tools_by_name.get(name)
119
+ if tool is None:
120
+ raise CollectionError(
121
+ f"mocks.tools.{name} uses handler {{builtin: {kind}}} but "
122
+ f"context.tools has no tool named {name!r}"
123
+ )
124
+ _validate_builtin_contract(kind, tool)
125
+ builtin_entries.append((name, entry, kind))
126
+
127
+ used_builtins = set(declared.values()) | {kind for _, _, kind in builtin_entries}
128
+ if skills and "skill" not in used_builtins:
129
+ raise CollectionError(
130
+ "context.tools must include {builtin: skill} (or a tool whose "
131
+ "mocks.tools entry uses handler: {builtin: skill}) when "
132
+ "context.skills is non-empty"
133
+ )
134
+
135
+ bash_entries = [entry for _, entry, kind in builtin_entries if kind == "bash"]
136
+ if bash_entries:
137
+ cli_raw = mocks.pop("cli", {})
138
+ fs_raw = mocks.pop("fs", None)
139
+ if cli_raw and fs_raw is not None:
140
+ raise CollectionError("mocks.cli cannot be combined with mocks.fs")
141
+ try:
142
+ if fs_raw is not None:
143
+ handler_with: dict[str, Any] = {
144
+ "fs": normalize_fs_config(
145
+ fs_raw, base_dir=evals_root, root=evals_root.parent
146
+ )
147
+ }
148
+ else:
149
+ handler_with = {
150
+ "cli": normalize_cli_config(
151
+ cli_raw, base_dir=evals_root, root=evals_root.parent
152
+ )
153
+ }
154
+ except MockConfigurationError as exc:
155
+ raise CollectionError(str(exc)) from exc
156
+ for entry in bash_entries:
157
+ entry["handler"] = {
158
+ "python": "yama.tools.bash.bash:run_bash",
159
+ "with": deepcopy(handler_with),
160
+ }
161
+
162
+ for name, entry, kind in builtin_entries:
163
+ if kind != "skill":
164
+ continue
165
+ if not skills:
166
+ raise CollectionError(
167
+ f"mocks.tools.{name} handler {{builtin: skill}} requires at "
168
+ "least one context.skills entry"
169
+ )
170
+ entry.setdefault(
171
+ "match",
172
+ {"arguments": {"name": {"one_of": [skill.name for skill in skills]}}},
173
+ )
174
+ entry["handler"] = {
175
+ "python": "yama.tools.skill.skill:read_skill",
176
+ "with": {
177
+ "enabled": [skill.name for skill in skills],
178
+ "skills_dir": conventions["skills_dir"],
179
+ "skill_entry": conventions["skill_entry"],
180
+ },
181
+ }
182
+
183
+ for field in ("cli", "fs"):
184
+ if field not in mocks:
185
+ continue
186
+ if declared.get("bash") == "bash":
187
+ # {builtin: bash} is declared but its mock was overridden with a
188
+ # custom respond/python handler, so nothing consumes mocks.cli/fs.
189
+ raise CollectionError(
190
+ f"mocks.{field} cannot be combined with a custom "
191
+ "mocks.tools.bash handler; use handler: {builtin: bash} to "
192
+ "keep the builtin execution"
193
+ )
194
+ raise CollectionError(
195
+ f"mocks.{field} requires a builtin bash handler: declare "
196
+ "{builtin: bash} in context.tools or set handler: {builtin: bash} "
197
+ "in the tool's mocks.tools entry"
198
+ )
199
+
200
+
201
+ def _validate_builtin_contract(kind: str, tool: ToolSchema) -> None:
202
+ argument = _BUILTIN_HANDLER_CONTRACTS[kind]
203
+ properties = tool.parameters.get("properties")
204
+ required = tool.parameters.get("required")
205
+ if (
206
+ not isinstance(properties, dict)
207
+ or argument not in properties
208
+ or not isinstance(required, list)
209
+ or argument not in required
210
+ ):
211
+ raise CollectionError(
212
+ f"tool {tool.name!r} uses handler {{builtin: {kind}}} so its "
213
+ f"parameters must declare a required {argument!r} property"
214
+ )
215
+
216
+
217
+ _SKILL_DESCRIPTION = """\
218
+ Execute a registered skill inside the current conversation.
219
+
220
+ Use this tool when the user's request or workstep matches an available skill.
221
+
222
+ Important:
223
+ - If a registered skill matches the user's request, call this tool BEFORE using other tools or giving detailed task guidance.
224
+ - Only call skills that are explicitly available in the current session.
225
+ - Do NOT guess skill names.
226
+ - Do NOT use this tool for built-in CLI commands that are not implemented as skills.
227
+ - If the skill is already loaded in the current context, do not call this tool again; follow the loaded instructions instead.
228
+
229
+ Returns:
230
+ - `content` with file text, or `is_error`/`error` when skill/file is missing, path escapes skill directory, or target is not a text file
231
+ """
232
+
233
+
234
+ def _skill_tool_schema() -> ToolSchema:
59
235
  return ToolSchema(
60
236
  name="skill",
61
- description="Read an enabled Skill entry or one file inside that Skill directory.",
237
+ description=_SKILL_DESCRIPTION,
62
238
  parameters={
63
- "type": "object",
64
239
  "properties": {
65
240
  "name": {
241
+ "description": "Skill directory name under workspace/skills.",
66
242
  "type": "string",
67
- "enum": names,
68
- "description": "Enabled Skill name.",
69
243
  },
70
244
  "file": {
245
+ "default": "",
246
+ "description": (
247
+ "Optional relative file path inside the skill directory; "
248
+ "reads SKILL.md when empty."
249
+ ),
71
250
  "type": "string",
72
- "description": "Optional path relative to the selected Skill directory.",
251
+ },
252
+ "call_reason": {
253
+ "anyOf": [
254
+ {
255
+ "anyOf": [{"type": "string"}, {"type": "null"}],
256
+ "description": (
257
+ "one-sentence reason for calling this tool "
258
+ "(prefer <=120 chars; longer values are accepted)"
259
+ ),
260
+ },
261
+ {"type": "null"},
262
+ ],
263
+ "default": None,
73
264
  },
74
265
  },
75
266
  "required": ["name"],
76
- "additionalProperties": False,
267
+ "type": "object",
77
268
  },
78
269
  )
79
270
 
80
271
 
81
- def _resolve_builtin_skill_tool(
82
- skills: list[LoadedSkill],
83
- conventions: dict[str, str],
84
- mocks: dict[str, Any],
85
- ) -> ToolSchema:
86
- if not skills:
87
- raise CollectionError(
88
- "context.tools builtin skill requires at least one context.skills entry"
89
- )
272
+ _BASH_DESCRIPTION = """\
273
+ Execute bash commands in the current working directory.
90
274
 
91
- mock_tools = mocks.setdefault("tools", {})
92
- if not isinstance(mock_tools, dict):
93
- raise CollectionError("mocks.tools must be an object")
94
- if "skill" not in mock_tools:
95
- mock_tools["skill"] = {
96
- "match": {
97
- "arguments": {
98
- "name": {"one_of": [skill.name for skill in skills]},
99
- }
100
- },
101
- "handler": {
102
- "python": "yama.tools.skill.skill:read_skill",
103
- "with": {
104
- "enabled": [skill.name for skill in skills],
105
- "skills_dir": conventions["skills_dir"],
106
- "skill_entry": conventions["skill_entry"],
107
- },
108
- },
109
- }
110
- return _skill_tool_schema(skills)
275
+ Use this tool to run short, focused shell commands for inspection, debugging, or project workflows.
276
+
277
+ When to use:
278
+ - You need to inspect files, directories, environment values, or process status.
279
+ - You need to run project-scoped commands (for example tests, linters, formatters, scripts).
280
+ - You need command output to verify assumptions before deciding next steps.
281
+
282
+ Arguments:
283
+ - command (str, required): Shell command to execute via `bash -c`.
284
+ - timeout_seconds (int, optional): Maximum runtime in seconds before timeout.
285
+ - call_reason (str, optional, max 120 chars): Why planner is calling this tool in current step. Keep concise and action-oriented.
286
+
287
+ Execution behavior:
288
+ - Command runs in the current workspace directory.
289
+ - Returns stdout, stderr and the exit code.
290
+ - If command times out or fails, returns an error.
291
+
292
+ Safety constraints:
293
+ - Prefer read-only or minimally invasive commands when possible.
294
+ - Do not run destructive commands (e.g. `rm -rf`, force reset) unless explicitly required and understood.
295
+ - Do not launch long-running background daemons.
296
+ - Prefer project-scoped package managers/tools over global system modifications."""
111
297
 
112
298
 
113
299
  def _bash_tool_schema() -> ToolSchema:
114
300
  return ToolSchema(
115
301
  name="bash",
116
- description=(
117
- "Execute a bash command and return its stdout, stderr and exit code."
118
- ),
302
+ description=_BASH_DESCRIPTION,
119
303
  parameters={
120
304
  "type": "object",
121
305
  "properties": {
122
306
  "command": {
123
307
  "type": "string",
124
- "description": "The bash command to execute.",
308
+ "description": "Shell command to execute via bash -c.",
309
+ },
310
+ "timeout_seconds": {
311
+ "type": "integer",
312
+ "description": "Maximum runtime in seconds before timeout.",
313
+ },
314
+ "call_reason": {
315
+ "type": "string",
316
+ "description": (
317
+ "One-sentence reason for calling this tool (max 120 chars)."
318
+ ),
125
319
  },
126
320
  },
127
321
  "required": ["command"],
128
322
  "additionalProperties": False,
129
323
  },
130
324
  )
131
-
132
-
133
- def _resolve_builtin_bash_tool(mocks: dict[str, Any], evals_root: Path) -> ToolSchema:
134
- mock_tools = mocks.setdefault("tools", {})
135
- if not isinstance(mock_tools, dict):
136
- raise CollectionError("mocks.tools must be an object")
137
- cli_raw = mocks.pop("cli", {})
138
- fs_raw = mocks.pop("fs", None)
139
- if cli_raw and fs_raw is not None:
140
- raise CollectionError("mocks.cli cannot be combined with mocks.fs")
141
- try:
142
- cli = normalize_cli_config(cli_raw, base_dir=evals_root, root=evals_root.parent)
143
- except MockConfigurationError as exc:
144
- raise CollectionError(str(exc)) from exc
145
- fs_normalized: dict[str, Any] | None = None
146
- if fs_raw is not None:
147
- try:
148
- fs_normalized = normalize_fs_config(
149
- fs_raw, base_dir=evals_root, root=evals_root.parent
150
- )
151
- except MockConfigurationError as exc:
152
- raise CollectionError(str(exc)) from exc
153
- if "bash" in mock_tools:
154
- # Check the raw pre-normalization values: normalize_cli_config always
155
- # returns a non-empty dict (passthrough defaults), so testing the
156
- # normalized `cli` here would flag every custom handler as conflicting
157
- # even when the case never declared mocks.cli/mocks.fs at all.
158
- if cli_raw or fs_raw is not None:
159
- raise CollectionError(
160
- "mocks.cli/mocks.fs cannot be combined with a custom "
161
- "mocks.tools.bash handler"
162
- )
163
- else:
164
- handler_with: dict[str, Any] = (
165
- {"fs": fs_normalized} if fs_normalized is not None else {"cli": cli}
166
- )
167
- mock_tools["bash"] = {
168
- "handler": {
169
- "python": "yama.tools.bash.bash:run_bash",
170
- "with": handler_with,
171
- },
172
- }
173
- return _bash_tool_schema()
yama/models.py CHANGED
@@ -63,6 +63,7 @@ class LLMResponse:
63
63
  content: str = ""
64
64
  tool_calls: list[ToolCall] = field(default_factory=list)
65
65
  raw: Any = None
66
+ usage: Json | None = None
66
67
 
67
68
  def assistant_message(self) -> Json:
68
69
  message: Json = {"role": "assistant", "content": self.content or ""}
yama/report.py CHANGED
@@ -8,13 +8,32 @@ from pathlib import Path
8
8
  from typing import Any, Sequence
9
9
 
10
10
  from .models import ResolvedCase, StepResult
11
- from .runner import CaseResult, RunResult, _tool_result_content
11
+ from .runner import CaseResult, RunResult, _tool_result_content, combine_usage
12
12
 
13
13
 
14
14
  def _text(value: Any) -> str:
15
15
  return escape(str(value), quote=True)
16
16
 
17
17
 
18
+ def _usage_split(usage: dict[str, int]) -> str:
19
+ return (
20
+ f"{usage.get('prompt_tokens', 0):,} in"
21
+ f" · {usage.get('completion_tokens', 0):,} out"
22
+ )
23
+
24
+
25
+ def _usage_inline(usage: Any) -> str:
26
+ """`12,345 tokens (10,000 in / 2,345 out)` for summary/heading lines;
27
+ empty when the scope carried no usage data."""
28
+ if not isinstance(usage, dict):
29
+ return ""
30
+ return (
31
+ f"{usage.get('total_tokens', 0):,} tokens"
32
+ f" ({usage.get('prompt_tokens', 0):,} in"
33
+ f" / {usage.get('completion_tokens', 0):,} out)"
34
+ )
35
+
36
+
18
37
  def _json(value: Any) -> str:
19
38
  return escape(
20
39
  json.dumps(value, ensure_ascii=False, indent=2, default=str), quote=False
@@ -239,6 +258,8 @@ def _render_assistant_call(request: dict[str, Any]) -> str:
239
258
  error = request.get("error")
240
259
  error_class = " error" if error else ""
241
260
 
261
+ usage_note = _usage_inline(request.get("usage"))
262
+ usage_html = f" · {_text(usage_note)}" if usage_note else ""
242
263
  content = response.get("content", "") if isinstance(response, dict) else ""
243
264
  response_html = (
244
265
  '<div class="assistant-content"><h5>Assistant text content</h5>'
@@ -261,7 +282,7 @@ def _render_assistant_call(request: dict[str, Any]) -> str:
261
282
  '<span class="event-kind">assistant</span>'
262
283
  '<strong>Assistant response</strong>'
263
284
  f'<span class="muted">request {_text(request.get("request_index", "?"))} · '
264
- f'{_text(provider_name)} · {_text(model_name)}</span>'
285
+ f'{_text(provider_name)} · {_text(model_name)}{usage_html}</span>'
265
286
  "</div>"
266
287
  f'<div class="assistant-response">{response_html}{error_html}</div>'
267
288
  '<details class="raw model-input"><summary>LLM request</summary>'
@@ -316,11 +337,18 @@ def _render_judge(judge: dict[str, Any] | None) -> str:
316
337
  f'<p class="muted">Evidence: {_text(item.get("evidence", ""))}</p>'
317
338
  "</div>"
318
339
  )
340
+ judge_usage = _usage_inline(judge.get("usage"))
341
+ usage_html = (
342
+ f'<span class="metric-inline">{_text(judge_usage)}</span>'
343
+ if judge_usage
344
+ else ""
345
+ )
319
346
  return (
320
347
  '<section class="subsection">'
321
348
  '<div class="section-heading"><h4>Judge</h4>'
322
349
  f'{_status(passed, kind="stamp", size="sm", seed="judge")}'
323
350
  f'<span class="metric-inline">Overall {overall_label}</span>'
351
+ f'{usage_html}'
324
352
  "</div>"
325
353
  f'<div class="judge-grid">{"".join(dimensions)}</div>'
326
354
  "</section>"
@@ -407,6 +435,13 @@ def _render_step(
407
435
  )
408
436
  )
409
437
  next_prior_messages = step.messages if step.messages else prior_messages
438
+ step_usage = combine_usage(
439
+ [request.get("usage") for request in step_requests]
440
+ + [step.judge_result.get("usage") if isinstance(step.judge_result, dict) else None]
441
+ )
442
+ tokens_meta = (
443
+ f' · {step_usage["total_tokens"]:,} tokens' if step_usage else ""
444
+ )
410
445
  html = (
411
446
  f'<details class="step" {"open" if not passed else ""}>'
412
447
  "<summary>"
@@ -415,6 +450,7 @@ def _render_step(
415
450
  '<span class="summary-meta">'
416
451
  f'{len(step.tool_calls)} tool calls · '
417
452
  f'{len(step.hard_checks) - failed_checks}/{len(step.hard_checks)} checks passed'
453
+ f'{tokens_meta}'
418
454
  "</span>"
419
455
  "</summary>"
420
456
  '<div class="step-body">'
@@ -440,11 +476,17 @@ def _render_request(request: dict[str, Any]) -> str:
440
476
  if isinstance(resolved_provider, dict)
441
477
  else ""
442
478
  )
479
+ usage = request.get("usage")
480
+ tokens = (
481
+ f' · {usage.get("total_tokens", 0):,} tokens'
482
+ if isinstance(usage, dict)
483
+ else ""
484
+ )
443
485
  return (
444
486
  '<details class="raw request">'
445
487
  "<summary>"
446
488
  f'Request {_text(request.get("request_index", "?"))} · '
447
- f'{_text(request.get("step_id", "unknown step"))}{provider}'
489
+ f'{_text(request.get("step_id", "unknown step"))}{provider}{tokens}'
448
490
  "</summary>"
449
491
  f'{_render_llm_request_details(request)}'
450
492
  "</details>"
@@ -494,16 +536,22 @@ def _render_run(run: RunResult) -> str:
494
536
  steps = "".join(step_htmls)
495
537
  requests = "".join(_render_request(request) for request in run.requests)
496
538
  mocks = "".join(_render_mock_event(event) for event in run.mock_events)
497
- artifact = (
498
- f'<span class="summary-meta">Artifacts: {_text(run.artifact_dir)}</span>'
499
- if run.artifact_dir
539
+ run_usage = run.usage()
540
+ meta_parts = []
541
+ if run_usage:
542
+ meta_parts.append(_usage_inline(run_usage))
543
+ if run.artifact_dir:
544
+ meta_parts.append(f"Artifacts: {run.artifact_dir}")
545
+ meta = (
546
+ f'<span class="summary-meta">{_text(" · ".join(meta_parts))}</span>'
547
+ if meta_parts
500
548
  else ""
501
549
  )
502
550
  return (
503
551
  f'<details class="run" {"open" if not run.passed else ""}>'
504
552
  "<summary>"
505
553
  f'{_status(run.passed, kind="stamp", size="sm", seed=f"run-{run.run_index}")}'
506
- f'<strong>Run {run.run_index}</strong>{artifact}'
554
+ f'<strong>Run {run.run_index}</strong>{meta}'
507
555
  "</summary>"
508
556
  '<div class="run-body">'
509
557
  f"{error}{steps}"
@@ -531,6 +579,12 @@ def _render_case(case: ResolvedCase, result: CaseResult) -> str:
531
579
  tools = ", ".join(tool.name for tool in case.tools) or "none"
532
580
  skills = ", ".join(skill.name for skill in case.skills) or "none"
533
581
  runs = "".join(_render_run(run) for run in result.runs)
582
+ case_usage = result.usage()
583
+ usage_cell = (
584
+ f"{case_usage['total_tokens']:,} · {_usage_split(case_usage)}"
585
+ if case_usage
586
+ else "–"
587
+ )
534
588
  description = (
535
589
  f'<p class="case-description">{_text(case.description)}</p>'
536
590
  if case.description
@@ -553,6 +607,7 @@ def _render_case(case: ResolvedCase, result: CaseResult) -> str:
553
607
  f'<div><span>Model</span><strong>{_text(case.model.get("name", "unknown"))}</strong></div>'
554
608
  f'<div><span>Tools</span><strong>{_text(tools)}</strong></div>'
555
609
  f'<div><span>Skills</span><strong>{_text(skills)}</strong></div>'
610
+ f'<div><span>LLM tokens</span><strong>{_text(usage_cell)}</strong></div>'
556
611
  "</div>"
557
612
  '<details class="case-context"><summary>Resolved Case context</summary>'
558
613
  '<div class="context-grid">'
@@ -589,6 +644,13 @@ def render_html_report(
589
644
  passed_checks = sum(check.get("passed", False) for check in checks)
590
645
  passed_cases = sum(result.passed for result in results)
591
646
  overall_passed = passed_cases == len(results) and bool(results)
647
+ total_usage = combine_usage(result.usage() for result in results)
648
+ usage_card = (
649
+ f'<strong>{total_usage["total_tokens"]:,}</strong>'
650
+ f'<span class="usage-sub">{_text(_usage_split(total_usage))}</span>'
651
+ if total_usage
652
+ else "<strong>–</strong>"
653
+ )
592
654
  generated_at = datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
593
655
  rendered_cases = "".join(
594
656
  _render_case(case, result) for case, result in zip(cases, results, strict=True)
@@ -682,11 +744,12 @@ summary:focus-visible, a:focus-visible, .verdict:focus-visible {{ outline: 2px s
682
744
  .report-header p {{ font-family: var(--font-mono); font-size: 12px; letter-spacing: .02em; }}
683
745
  .overall {{ display: flex; flex-direction: column; align-items: flex-end; gap: 8px; }}
684
746
  .overall span {{ font-family: var(--font-display); text-transform: uppercase; letter-spacing: .12em; font-size: 11px; color: var(--muted); }}
685
- .summary-grid {{ display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); background: var(--surface); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 30px; overflow: clip; }}
747
+ .summary-grid {{ display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); background: var(--surface); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 30px; overflow: clip; }}
686
748
  .summary-card {{ padding: 16px 22px; border-right: 1px solid var(--border); }}
687
749
  .summary-card:last-child {{ border-right: 0; }}
688
750
  .summary-card span {{ display: block; color: var(--muted); font-family: var(--font-display); text-transform: uppercase; letter-spacing: .08em; font-size: 11px; }}
689
751
  .summary-card strong {{ display: block; margin-top: 6px; font-family: var(--font-mono); font-size: 25px; font-weight: 600; }}
752
+ .summary-card .usage-sub {{ margin-top: 4px; font-family: var(--font-mono); font-size: 11px; text-transform: none; letter-spacing: .02em; }}
690
753
 
691
754
  /* Verdicts: quiet ticks for high-frequency rows (checks, mock events);
692
755
  stamped chops for the handful of hierarchical calls per report
@@ -734,7 +797,7 @@ summary:focus-visible, a:focus-visible, .verdict:focus-visible {{ outline: 2px s
734
797
  .eyebrow {{ color: var(--muted); font-family: var(--font-display); text-transform: uppercase; letter-spacing: .12em; font-size: 11px; }}
735
798
  .case-outcome {{ min-width: 130px; display: grid; justify-items: end; align-content: start; gap: 5px; }}
736
799
  .case-outcome strong {{ font-family: var(--font-mono); font-size: 22px; }}
737
- .metadata {{ display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border-bottom: 1px solid var(--border); }}
800
+ .metadata {{ display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-bottom: 1px solid var(--border); }}
738
801
  .metadata > div {{ min-width: 0; padding: 14px 20px; border-right: 1px solid var(--border); }}
739
802
  .metadata > div:last-child {{ border-right: 0; }}
740
803
  .metadata span, .metadata strong {{ display: block; }}
@@ -842,6 +905,7 @@ tr.failed td {{ background: color-mix(in srgb, var(--fail-bg) 45%, transparent);
842
905
  <div class="summary-card"><span>Cases passed</span><strong>{passed_cases}/{len(results)}</strong></div>
843
906
  <div class="summary-card"><span>Runs passed</span><strong>{passed_runs}/{total_runs}</strong></div>
844
907
  <div class="summary-card"><span>Hard checks passed</span><strong>{passed_checks}/{len(checks)}</strong></div>
908
+ <div class="summary-card"><span>LLM tokens</span>{usage_card}</div>
845
909
  </section>
846
910
  {rendered_cases or '<p>No cases were included in this report.</p>'}
847
911
  </main>
yama/runner.py CHANGED
@@ -9,7 +9,7 @@ from copy import deepcopy
9
9
  from dataclasses import dataclass, field
10
10
  from datetime import datetime, timezone
11
11
  from pathlib import Path
12
- from typing import Any, Callable
12
+ from typing import Any, Callable, Iterable
13
13
 
14
14
  import yaml
15
15
 
@@ -51,6 +51,30 @@ def _tool_result_content(result: Any) -> str:
51
51
  return json.dumps(result, ensure_ascii=False)
52
52
 
53
53
 
54
+ _USAGE_KEYS = ("prompt_tokens", "completion_tokens", "total_tokens")
55
+
56
+
57
+ def combine_usage(items: Iterable[Any]) -> dict[str, int] | None:
58
+ """Sum normalized usage dicts (`llm._normalized_usage` shape).
59
+
60
+ Non-dict items (None from runs whose provider reported no usage) are
61
+ skipped, and the sum is None when nothing carried usage at all --
62
+ "no data" must stay distinguishable from "0 tokens" so scripted or
63
+ errored runs don't render as a misleading all-zero consumption.
64
+ """
65
+ total: dict[str, int] | None = None
66
+ for item in items:
67
+ if not isinstance(item, dict):
68
+ continue
69
+ if total is None:
70
+ total = dict.fromkeys(_USAGE_KEYS, 0)
71
+ for key in _USAGE_KEYS:
72
+ value = item.get(key)
73
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
74
+ total[key] += int(value)
75
+ return total
76
+
77
+
54
78
  class MaxToolRoundsExceeded(RuntimeError):
55
79
  def __init__(self, step_id: str, tool_calls: list[ToolCallRecord]) -> None:
56
80
  super().__init__(f"max tool rounds exceeded for step {step_id}")
@@ -70,12 +94,26 @@ class RunResult:
70
94
  requests: list[dict[str, Any]] = field(default_factory=list)
71
95
  artifact_dir: Path | None = None
72
96
 
97
+ def usage(self) -> dict[str, int] | None:
98
+ """Token usage of every LLM call this run made: the step tool-loop
99
+ requests plus judge calls (which bypass `requests` and land their
100
+ usage on the step's `judge_result`)."""
101
+ return combine_usage(
102
+ [request.get("usage") for request in self.requests]
103
+ + [
104
+ step.judge_result.get("usage")
105
+ for step in self.steps
106
+ if isinstance(step.judge_result, dict)
107
+ ]
108
+ )
109
+
73
110
  def to_dict(self) -> dict[str, Any]:
74
111
  return {
75
112
  "run_index": self.run_index,
76
113
  "passed": self.passed,
77
114
  "steps": [step.to_dict() for step in self.steps],
78
115
  "error": self.error,
116
+ "usage": self.usage(),
79
117
  "mock_events": self.mock_events,
80
118
  "mock_state": self.mock_state,
81
119
  "requests": self.requests,
@@ -91,12 +129,16 @@ class CaseResult:
91
129
  pass_rate: float
92
130
  description: str = ""
93
131
 
132
+ def usage(self) -> dict[str, int] | None:
133
+ return combine_usage(run.usage() for run in self.runs)
134
+
94
135
  def to_dict(self) -> dict[str, Any]:
95
136
  return {
96
137
  "case_key": self.case_key,
97
138
  "description": self.description,
98
139
  "passed": self.passed,
99
140
  "pass_rate": self.pass_rate,
141
+ "usage": self.usage(),
100
142
  "runs": [run.to_dict() for run in self.runs],
101
143
  }
102
144
 
@@ -377,6 +419,8 @@ class YamaRunner:
377
419
  request_record["resolved_provider"] = deepcopy(resolved_provider)
378
420
  assistant = response.assistant_message()
379
421
  request_record["response"] = deepcopy(assistant)
422
+ if response.usage is not None:
423
+ request_record["usage"] = deepcopy(response.usage)
380
424
  messages.append(assistant)
381
425
  if not response.tool_calls:
382
426
  return StepResult(
yama/tools/bash/fs.py CHANGED
@@ -508,6 +508,17 @@ async def _get_session(
508
508
  return session
509
509
 
510
510
 
511
+ def _effective_timeout(arguments: Mapping[str, Any], configured: float) -> float:
512
+ # The model may request a shorter timeout via the builtin bash tool's
513
+ # timeout_seconds argument; the case-configured limit stays the ceiling.
514
+ requested = arguments.get("timeout_seconds")
515
+ if isinstance(requested, bool) or not isinstance(requested, (int, float)):
516
+ return configured
517
+ if requested <= 0:
518
+ return configured
519
+ return min(float(requested), configured)
520
+
521
+
511
522
  async def run_bash_fs(
512
523
  arguments: Mapping[str, Any],
513
524
  context: ToolMockContext | None,
@@ -518,7 +529,7 @@ async def run_bash_fs(
518
529
  command = arguments["command"]
519
530
  session = await _get_session(context, fs_config)
520
531
  timeout = fs_config.get("limits", {}).get("timeout_seconds", DEFAULT_TIMEOUT_SECONDS)
521
- return await session.run(command, timeout=timeout)
532
+ return await session.run(command, timeout=_effective_timeout(arguments, timeout))
522
533
 
523
534
 
524
535
  async def run_bash_cli(
@@ -532,7 +543,7 @@ async def run_bash_cli(
532
543
  fs_config = compile_cli_config(cli_config)
533
544
  session = await _get_session(context, fs_config)
534
545
  timeout = cli_config.get("passthrough_timeout_seconds", DEFAULT_TIMEOUT_SECONDS)
535
- return await session.run(command, timeout=timeout)
546
+ return await session.run(command, timeout=_effective_timeout(arguments, timeout))
536
547
 
537
548
 
538
549
  async def cleanup_session(state: dict[str, Any]) -> None:
yama/tools/skill/skill.py CHANGED
@@ -26,10 +26,16 @@ class SkillTool(Tool):
26
26
  entry = str(config.get("skill_entry", "SKILL.md"))
27
27
  skill_root = (context.plugin_root / skills_dir / name).resolve()
28
28
  requested_file = arguments.get("file", entry)
29
- if not isinstance(requested_file, str) or not requested_file.strip():
29
+ if requested_file is None:
30
+ requested_file = entry
31
+ if not isinstance(requested_file, str):
30
32
  raise ToolMockError(
31
- "INVALID_SKILL_FILE", "file must be a non-empty relative path"
33
+ "INVALID_SKILL_FILE", "file must be a relative path string"
32
34
  )
35
+ if not requested_file.strip():
36
+ # The advertised schema defaults file to "" and documents that an
37
+ # empty value reads the Skill entry file.
38
+ requested_file = entry
33
39
 
34
40
  relative = Path(requested_file)
35
41
  if relative.is_absolute():
yama/workspace.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import tomllib
4
4
  from dataclasses import dataclass, field
5
+ from fnmatch import fnmatchcase
5
6
  from pathlib import Path
6
7
  from typing import Any
7
8
 
@@ -92,11 +93,33 @@ def resolve_plugin_root(
92
93
  return root, plugin
93
94
 
94
95
 
96
+ def case_key_for_path(path: Path, plugin_root: Path) -> str:
97
+ """The stable identifier a case is reported and filtered by: its path
98
+ relative to the plugin root (falling back to the bare file name for
99
+ explicit paths outside the plugin)."""
100
+ try:
101
+ return path.resolve().relative_to(plugin_root.resolve()).as_posix()
102
+ except ValueError:
103
+ return path.name
104
+
105
+
106
+ def matches_case_filter(case_key: str, filters: list[str]) -> bool:
107
+ """OR over the filters; each is an fnmatch glob when it contains a
108
+ wildcard character, a plain substring otherwise."""
109
+ return any(
110
+ fnmatchcase(case_key, pattern)
111
+ if any(ch in pattern for ch in "*?[")
112
+ else pattern in case_key
113
+ for pattern in filters
114
+ )
115
+
116
+
95
117
  def collect_case_paths(
96
118
  plugin_root: Path,
97
119
  workspace: WorkspaceConfig,
98
120
  plugin_config: dict[str, Any],
99
121
  explicit_paths: list[Path] | None = None,
122
+ filters: list[str] | None = None,
100
123
  ) -> list[Path]:
101
124
  if explicit_paths:
102
125
  paths = [
@@ -112,4 +135,10 @@ def collect_case_paths(
112
135
  missing = [path for path in paths if not path.is_file()]
113
136
  if missing:
114
137
  raise ConfigurationError(f"case file does not exist: {missing[0]}")
138
+ if filters:
139
+ paths = [
140
+ path
141
+ for path in paths
142
+ if matches_case_filter(case_key_for_path(path, plugin_root), filters)
143
+ ]
115
144
  return paths
@@ -1,27 +0,0 @@
1
- yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
- yama/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
- yama/assertions.py,sha256=0x1r82W2dtAY1mTk4LC86VulD5Q9blS7QeRCTysb4kE,21736
4
- yama/cli.py,sha256=Fsl-GROEQJx9hHs5qSlAtZTkEaeCU2TY6S8IhmJmmzM,23203
5
- yama/llm.py,sha256=XqGE4aKPOimy9n3oNF5rUvqWdJlpi0EVzMlD-FBim6A,13570
6
- yama/mocks.py,sha256=YyiU6Y7NgttxHYJBsqGPILKYlTsM4IMTIilMNRkUuzs,14973
7
- yama/models.py,sha256=FeKOYS4MAQhDPyhAyd4pPvQH015w5hOJqhNzTZHYRgI,3990
8
- yama/report.py,sha256=csceNtljXd--palHhvdVIXsPYs7uF_C1xUkLfoWPZbc,37824
9
- yama/runner.py,sha256=9JXlJPSEFHKrZETdso5BCR_SQZ97lEzpP0ZwyYz5o0g,23823
10
- yama/workspace.py,sha256=rHQ9kQUkAo32gJpqRf7pSd5JhBc05xgxA1wPRC4bOQ8,3618
11
- yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
12
- yama/loaders/case.py,sha256=Kh37rtT30lxkCRZ6wA3fo8_tTxeTeN0d0c-OTqkfSSY,14532
13
- yama/loaders/common.py,sha256=Fg71_vcnu5339QI_itvYPvRbk9LtBgEnzoA3t4Krb4U,754
14
- yama/loaders/tool_loader.py,sha256=BubcplVYKiJxgNsMKGRfiRiK1qVo0EvJfLOJzQEx9js,6388
15
- yama/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
- yama/tools/base.py,sha256=ONFuGzTSWVsA0k4-UUREncqAHmyQI2uHpVOU2Dh_XiQ,446
17
- yama/tools/bash/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
- yama/tools/bash/_cli_shim.py,sha256=f3Rom5UipW0dA0KRYavqIa9HJDKT336ssDZGWeVmkvo,2494
19
- yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
20
- yama/tools/bash/fs.py,sha256=ncLZf4_gErRP3HHXinLEQeN6chrf7JaSiaTuadVl8MY,21314
21
- yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- yama/tools/skill/skill.py,sha256=P2rDz6VqRLfhiabWjOU3ZBaWLw30Eywf3o_OxVfFbPI,1992
23
- python_yama-0.3.0.dist-info/METADATA,sha256=GK8pJCJR0KCRpRfc5FQ0YvAZ2Pym-HSGGnsSn8U30l8,5830
24
- python_yama-0.3.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
25
- python_yama-0.3.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
26
- python_yama-0.3.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
27
- python_yama-0.3.0.dist-info/RECORD,,