2025-10-06 03:17:58 +00:00
|
|
|
|
#!/usr/bin/env python3
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Batch Agent Runner — run the agent over a JSONL prompt dataset in parallel.
|
|
|
|
|
|
|
|
|
|
|
|
Batches are processed by a multiprocessing pool with per-batch ``batch_N.jsonl`` output,
|
|
|
|
|
|
checkpointing for ``--resume``, trajectories in from/value format, and tool-usage
|
|
|
|
|
|
statistics aggregated across all batches. See ``main`` (fire CLI) for usage.
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"""
|
|
|
|
|
|
|
2026-09-02 18:23:51 -07:00
|
|
|
|
# hermes_bootstrap must be the very first import — UTF-8 stdio on Windows, no-op on POSIX.
|
fix(entry-points): guard hermes_bootstrap import so partial updates don't brick hermes (#22091)
teknium1 hit ModuleNotFoundError: No module named 'hermes_bootstrap' after
a code update, on both his Windows machine AND his Linux workstation. The
failure mode is real and affects every user who updates hermes by any path
OTHER than a fully-successful ``hermes update``.
## What happens
hermes_bootstrap.py is a top-level module registered via pyproject.toml's
``py-modules`` list (added by Brooklyn's Windows UTF-8 stdio work). It
must be registered in the venv's editable-install .pth file before Python
can find it as a bare ``import hermes_bootstrap``.
``hermes update`` handles this correctly: (1) git reset --hard, (2) clear
__pycache__, (3) uv pip install -e . (re-registers the package including
the new py-modules list), (4) restart.
BUT if any step AFTER (1) fails — network blip during pip install, PEP 668
on a system Python, venv locked, uv not in PATH, a crash mid-update — the
user is left with new code that references hermes_bootstrap and a venv
that doesn't know about it. Every hermes invocation after that crashes
with ModuleNotFoundError, including ``hermes update`` itself. No recovery
path without manual `uv pip install -e .`.
Also affects users who ``git pull`` the repo directly without running
hermes update — relatively common for developers.
## Fix
Wrap ``import hermes_bootstrap`` in a try/except ModuleNotFoundError
across all 6 entry points (hermes_cli/main, run_agent, gateway/run,
acp_adapter/entry, cli, batch_runner). On Windows, missing bootstrap
means the UTF-8 stdio setup doesn't run — degraded behavior (Unicode
chars may fail to print) but NOT a crash. POSIX is unaffected either way
since the bootstrap is a no-op there.
Once hermes is running again, the user can ``hermes update`` to fully
recover.
## Test update
tests/test_hermes_bootstrap.py::test_entry_point_imports_bootstrap
scans for the first top-level import in each entry point and asserts it
is hermes_bootstrap. Extended the check to accept a Try block whose body
is a lone Import of hermes_bootstrap — that's the recovery-friendly form
we just introduced.
Verified behavior by ``mv hermes_bootstrap.py hermes_bootstrap.py.bak``
and confirming ``python -c "import hermes_cli.main"`` succeeds. 82/82
tests pass (hermes_bootstrap + windows-native + windows-compat).
2026-05-08 14:43:13 -07:00
|
|
|
|
try:
|
2026-10-08 17:22:54 +02:00
|
|
|
|
import hermes_bootstrap
|
2026-09-23 14:15:29 -04:00
|
|
|
|
except ModuleNotFoundError as exc:
|
|
|
|
|
|
# Partial ``hermes update`` (git reset landed, ``uv pip install -e .`` did not).
|
|
|
|
|
|
if exc.name != "hermes_bootstrap":
|
|
|
|
|
|
raise # the bootstrap exists but cannot load: skipping it would skip PM activation
|
hermes_bootstrap: Windows-only UTF-8 stdio shim for all entry points
Codebase-wide fix for Python-on-Windows UTF-8 footguns, complementing
the earlier execute_code sandbox fixes (which remain load-bearing for
when the sandbox explicitly scrubs child env).
Problem: Python on Windows has two long-standing text-encoding pitfalls:
1. sys.stdout/stderr are bound to the console code page (cp1252 on
US-locale installs) — print('café') crashes with UnicodeEncodeError.
2. Subprocess children don't know to use UTF-8 unless PYTHONUTF8 and/or
PYTHONIOENCODING are set in their env — so any Python we spawn
(linters, sandbox children, delegation workers) hits the same bug.
Solution: A tiny bootstrap module (hermes_bootstrap.py) imported as the
first statement of every Hermes entry point:
- hermes_cli/main.py (hermes / hermes-agent console_script)
- run_agent.py (hermes-agent direct)
- acp_adapter/entry.py (hermes-acp)
- gateway/run.py (messaging gateway)
- batch_runner.py (parallel batch mode)
- cli.py (legacy direct-launch CLI)
On Windows, the bootstrap:
- os.environ.setdefault('PYTHONUTF8', '1') (PEP 540 UTF-8 mode)
- os.environ.setdefault('PYTHONIOENCODING', 'utf-8')
- sys.stdout/stderr/stdin.reconfigure(encoding='utf-8', errors='replace')
Children inherit the env vars → they run in UTF-8 mode.
Current process's stdio is reconfigured → print('café') works now.
On POSIX (Linux/macOS), the bootstrap is a complete no-op. We don't
touch LANG, LC_*, or anything else — users who have intentionally
configured a non-UTF-8 locale aren't affected. POSIX systems are
already UTF-8 by default in 99% of modern setups, so there's nothing
to fix.
setdefault() (not overwrite) means users who explicitly set PYTHONUTF8=0
or PYTHONIOENCODING=cp1252 in their environment are respected.
What this does NOT fix: bare open(path, 'w') calls in the *parent*
process still default to locale encoding because PYTHONUTF8 is only
read at interpreter init. A ruff PLW1514 sweep (separate follow-up)
will add explicit encoding='utf-8' at those ~219 call sites for
belt-and-suspenders.
Tests (17): 16 passed, 1 skipped on Windows.
- Windows: env vars set, stdio reconfigured, child inherits UTF-8 mode
- POSIX: complete no-op (verified on fake POSIX + skipped on real
POSIX since we don't have a Linux box in this session)
- Idempotence: multiple calls safe
- Graceful degradation: non-reconfigurable streams don't crash
- User opt-out: explicit PYTHONUTF8=0 is respected
- Load order: every entry point's FIRST top-level import is
hermes_bootstrap, enforced by an AST-level parametrized test
pyproject.toml: added hermes_bootstrap to py-modules so it ships with
pip installs.
2026-05-07 19:09:40 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
import json
|
|
|
|
|
|
import logging
|
2026-09-25 12:27:39 -05:00
|
|
|
|
import contextlib
|
2025-10-06 03:17:58 +00:00
|
|
|
|
import os
|
|
|
|
|
|
import time
|
|
|
|
|
|
import traceback
|
2026-09-02 18:23:51 -07:00
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
from multiprocessing import Lock, Pool
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
refactor: codebase-wide lint cleanup — unused imports, dead code, and inefficient patterns (#5821)
Comprehensive cleanup across 80 files based on automated (ruff, pyflakes, vulture)
and manual analysis of the entire codebase.
Changes by category:
Unused imports removed (~95 across 55 files):
- Removed genuinely unused imports from all major subsystems
- agent/, hermes_cli/, tools/, gateway/, plugins/, cron/
- Includes imports in try/except blocks that were truly unused
(vs availability checks which were left alone)
Unused variables removed (~25):
- Removed dead variables: connected, inner, channels, last_exc,
source, new_server_names, verify, pconfig, default_terminal,
result, pending_handled, temperature, loop
- Dropped unused argparse subparser assignments in hermes_cli/main.py
(12 instances of add_parser() where result was never used)
Dead code removed:
- run_agent.py: Removed dead ternary (None if False else None) and
surrounding unreachable branch in identity fallback
- run_agent.py: Removed write-only attribute _last_reported_tool
- hermes_cli/providers.py: Removed dead @property decorator on
module-level function (decorator has no effect outside a class)
- gateway/run.py: Removed unused MCP config load before reconnect
- gateway/platforms/slack.py: Removed dead SessionSource construction
Undefined name bugs fixed (would cause NameError at runtime):
- batch_runner.py: Added missing logger = logging.getLogger(__name__)
- tools/environments/daytona.py: Added missing Dict and Path imports
Unnecessary global statements removed (14):
- tools/terminal_tool.py: 5 functions declared global for dicts
they only mutated via .pop()/[key]=value (no rebinding)
- tools/browser_tool.py: cleanup thread loop only reads flag
- tools/rl_training_tool.py: 4 functions only do dict mutations
- tools/mcp_oauth.py: only reads the global
- hermes_time.py: only reads cached values
Inefficient patterns fixed:
- startswith/endswith tuple form: 15 instances of
x.startswith('a') or x.startswith('b') consolidated to
x.startswith(('a', 'b'))
- len(x)==0 / len(x)>0: 13 instances replaced with pythonic
truthiness checks (not x / bool(x))
- in dict.keys(): 5 instances simplified to in dict
- Redefined unused name: removed duplicate _strip_mdv2 import in
send_message_tool.py
Other fixes:
- hermes_cli/doctor.py: Replaced undefined logger.debug() with pass
- hermes_cli/config.py: Consolidated chained .endswith() calls
Test results: 3934 passed, 17 failed (all pre-existing on main),
19 skipped. Zero regressions.
2026-04-07 10:25:31 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
import fire
|
2026-09-02 18:23:51 -07:00
|
|
|
|
from rich.console import Console
|
|
|
|
|
|
from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn, TimeRemainingColumn
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
2026-09-02 18:23:51 -07:00
|
|
|
|
from model_tools import TOOL_TO_TOOLSET_MAP
|
2025-10-06 03:17:58 +00:00
|
|
|
|
from run_agent import AIAgent
|
|
|
|
|
|
from toolset_distributions import (
|
2026-09-02 18:23:51 -07:00
|
|
|
|
list_distributions,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
sample_toolsets_from_distribution,
|
2026-09-02 18:23:51 -07:00
|
|
|
|
validate_distribution,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-09-02 18:23:51 -07:00
|
|
|
|
logger = logging.getLogger(__name__)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
2026-09-02 18:23:51 -07:00
|
|
|
|
# Auto-derived from model_tools so it stays in sync as tools are added. Gives every
|
|
|
|
|
|
# trajectory a consistent tool_stats schema (Arrow/Parquet for HF datasets) and filters
|
|
|
|
|
|
# corrupted entries (hallucinated tool names) when combining trajectories.
|
2026-02-08 20:19:14 +00:00
|
|
|
|
ALL_POSSIBLE_TOOLS = set(TOOL_TO_TOOLSET_MAP.keys())
|
2026-01-14 13:40:10 +00:00
|
|
|
|
|
|
|
|
|
|
DEFAULT_TOOL_STATS = {'count': 0, 'success': 0, 'failure': 0}
|
2026-09-02 18:23:51 -07:00
|
|
|
|
_REASONING_KEYS = ("total_assistant_turns", "turns_with_reasoning", "turns_without_reasoning")
|
2026-01-14 13:40:10 +00:00
|
|
|
|
|
2026-09-02 18:44:40 -07:00
|
|
|
|
# BatchRunner.__init__ parameters stored as same-named attributes.
|
|
|
|
|
|
_RUNNER_FIELDS = (
|
|
|
|
|
|
"batch_size", "run_name", "distribution", "max_iterations", "base_url", "api_key", "model",
|
|
|
|
|
|
"num_workers", "verbose", "ephemeral_system_prompt", "log_prefix_chars", "providers_allowed",
|
|
|
|
|
|
"providers_ignored", "providers_order", "provider_sort", "openrouter_min_coding_score",
|
2026-09-07 03:32:37 -07:00
|
|
|
|
"reasoning_config", "prefill_messages", "max_samples",
|
2026-09-02 18:44:40 -07:00
|
|
|
|
)
|
2026-09-02 18:34:38 -07:00
|
|
|
|
# BatchRunner attributes forwarded verbatim to every AIAgent in the worker config.
|
|
|
|
|
|
_AGENT_PASSTHROUGH = (
|
|
|
|
|
|
"base_url", "api_key", "ephemeral_system_prompt", "providers_allowed", "providers_ignored",
|
2026-09-07 03:32:37 -07:00
|
|
|
|
"providers_order", "provider_sort", "openrouter_min_coding_score",
|
2026-09-02 18:34:38 -07:00
|
|
|
|
"reasoning_config", "prefill_messages",
|
fix(observability): attribute ACP and batch execution surfaces
Fleet telemetry showed "unknown" as the single largest execution_surface
bucket. Two construction paths were mis-attributed, both silently:
1. ACP editor sessions (VS Code / Zed / JetBrains) declare platform="acp",
but "acp" was absent from EXECUTION_SURFACES, so the contract's
closed-schema fallback folded every editor session into "other" --
the bucket meant for genuinely unclassifiable traffic.
2. batch_runner built agents from _AGENT_PASSTHROUGH, which omitted
"platform" entirely, so every batch task run reported "unknown"
despite "batch" already being a first-class surface.
Neither is a reporting bug in the exporter: both are declaration gaps at
the construction site. "unknown" must mean "this run genuinely could not
be attributed", not "a construction site forgot to say who it was".
Changes:
- add "acp" to EXECUTION_SURFACES and map it to the "interactive"
entrypoint alongside cli/desktop/tui
- add "acp" to the v2 wire schema enum (kept in sync by an existing test)
- pass platform through batch_runner: added to _AGENT_PASSTHROUGH, set
self.platform = "batch" on the runner, and defaulted at the worker call
site so callers that build a config without it stay attributable
Wire compatibility: the ingest service validates the envelope only and
stores metric bodies verbatim, so packages carrying the new value are
accepted by the already-deployed server. No coordinated deploy needed.
Tests: 12 new behavioural tests. Verified red before the fix (4 failed),
green after. Three fix-mutants confirmed killed:
M1 revert acp from EXECUTION_SURFACES -> 3 failed
M2 revert acp entrypoint mapping only -> 1 failed
M3 revert batch passthrough -> 1 failed
No source-text assertions; every test is a contract between the surfaces
the schema accepts and the surface each path declares. A guard test pins
that a genuinely undeclared run still reports "unknown", so attribution
cannot be "fixed" by inventing a default that hides real gaps.
2026-09-09 11:27:36 +10:00
|
|
|
|
# Without this, every batch task run is attributed to the "unknown" execution
|
|
|
|
|
|
# surface in shared metrics even though "batch" is a first-class surface.
|
|
|
|
|
|
"platform",
|
2026-09-02 18:34:38 -07:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-01-14 13:40:10 +00:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _normalize_tool_stats(tool_stats: dict[str, dict[str, int]]) -> dict[str, dict[str, int]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""All possible tools with zero defaults (consistent HF schema), plus any unexpected tools."""
|
|
|
|
|
|
normalized = {
|
|
|
|
|
|
tool: tool_stats[tool].copy() if tool in tool_stats else DEFAULT_TOOL_STATS.copy()
|
|
|
|
|
|
for tool in ALL_POSSIBLE_TOOLS
|
|
|
|
|
|
}
|
2026-01-14 13:40:10 +00:00
|
|
|
|
for tool, stats in tool_stats.items():
|
|
|
|
|
|
if tool not in normalized:
|
|
|
|
|
|
normalized[tool] = stats.copy()
|
|
|
|
|
|
return normalized
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _normalize_tool_error_counts(tool_error_counts: dict[str, int]) -> dict[str, int]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""All possible tools with zero defaults, plus any unexpected tools."""
|
|
|
|
|
|
normalized = {tool: tool_error_counts.get(tool, 0) for tool in ALL_POSSIBLE_TOOLS}
|
2026-01-14 13:40:10 +00:00
|
|
|
|
for tool, count in tool_error_counts.items():
|
|
|
|
|
|
if tool not in normalized:
|
|
|
|
|
|
normalized[tool] = count
|
|
|
|
|
|
return normalized
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _merge_tool_stats(total: dict[str, dict[str, int]], tool_stats: dict[str, dict[str, int]]) -> None:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Add per-tool count/success/failure from *tool_stats* into *total* in place."""
|
|
|
|
|
|
for tool_name, stats in tool_stats.items():
|
|
|
|
|
|
agg = total.setdefault(tool_name, DEFAULT_TOOL_STATS.copy())
|
|
|
|
|
|
agg["count"] += stats["count"]
|
|
|
|
|
|
agg["success"] += stats["success"]
|
|
|
|
|
|
agg["failure"] += stats["failure"]
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _merge_reasoning_stats(total: dict[str, int], reasoning_stats: dict[str, Any]) -> None:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Add the turn counters from *reasoning_stats* into *total* in place."""
|
|
|
|
|
|
for key in total:
|
|
|
|
|
|
total[key] += reasoning_stats.get(key, 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _tool_call_succeeded(content) -> bool:
|
|
|
|
|
|
"""Judge a tool response: JSON with a non-null ``error`` / ``success: false`` fails;
|
|
|
|
|
|
non-JSON fails only when empty or starting with ``Error:`` (no substring matching, to
|
|
|
|
|
|
avoid false positives). Non-zero exit codes are NOT failures — the model self-corrects."""
|
|
|
|
|
|
try:
|
|
|
|
|
|
content_json = json.loads(content) if isinstance(content, str) else content
|
|
|
|
|
|
except (json.JSONDecodeError, ValueError, TypeError):
|
|
|
|
|
|
return bool(content) and not content.strip().lower().startswith("error:")
|
|
|
|
|
|
if not isinstance(content_json, dict):
|
|
|
|
|
|
return True
|
|
|
|
|
|
if content_json.get("error") is not None:
|
|
|
|
|
|
return False
|
|
|
|
|
|
# Terminal wraps its response in a "content" field.
|
|
|
|
|
|
inner_content = content_json.get("content")
|
|
|
|
|
|
if isinstance(inner_content, dict) and inner_content.get("error") is not None:
|
|
|
|
|
|
return False
|
|
|
|
|
|
return content_json.get("success") is not False
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _extract_tool_stats(messages: list[dict[str, Any]]) -> dict[str, dict[str, int]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Per-tool call counts and success/failure tallies from a message history."""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
tool_stats = {}
|
2026-09-02 18:23:51 -07:00
|
|
|
|
tool_calls_map = {} # tool_call_id -> tool name
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
for msg in messages:
|
|
|
|
|
|
if msg["role"] == "assistant" and "tool_calls" in msg and msg["tool_calls"]:
|
|
|
|
|
|
for tool_call in msg["tool_calls"]:
|
2026-03-21 07:20:41 -07:00
|
|
|
|
if not tool_call or not isinstance(tool_call, dict): continue
|
2025-10-06 03:17:58 +00:00
|
|
|
|
tool_name = tool_call["function"]["name"]
|
2026-09-02 18:23:51 -07:00
|
|
|
|
tool_stats.setdefault(tool_name, DEFAULT_TOOL_STATS.copy())["count"] += 1
|
|
|
|
|
|
tool_calls_map[tool_call["id"]] = tool_name
|
2025-10-06 03:17:58 +00:00
|
|
|
|
elif msg["role"] == "tool":
|
|
|
|
|
|
tool_call_id = msg.get("tool_call_id", "")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
is_success = _tool_call_succeeded(msg.get("content", ""))
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if tool_call_id in tool_calls_map:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
tool_stats[tool_calls_map[tool_call_id]]["success" if is_success else "failure"] += 1
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
return tool_stats
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _turn_has_reasoning(msg: dict[str, Any]) -> bool:
|
2026-09-02 18:44:40 -07:00
|
|
|
|
"""``<REASONING_SCRATCHPAD>`` in content, or a non-empty native ``reasoning`` field."""
|
|
|
|
|
|
if "<REASONING_SCRATCHPAD>" in (msg.get("content", "") or ""):
|
|
|
|
|
|
return True
|
|
|
|
|
|
return bool(msg.get("reasoning", "").strip()) if msg.get("reasoning") else False
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _extract_reasoning_stats(messages: list[dict[str, Any]]) -> dict[str, int]:
|
2026-09-02 18:44:40 -07:00
|
|
|
|
"""Count assistant turns with reasoning vs without."""
|
|
|
|
|
|
assistant_turns = [msg for msg in messages if msg.get("role") == "assistant"]
|
|
|
|
|
|
total = len(assistant_turns)
|
|
|
|
|
|
with_reasoning = sum(1 for msg in assistant_turns if _turn_has_reasoning(msg))
|
2026-02-08 20:19:14 +00:00
|
|
|
|
return {
|
|
|
|
|
|
"total_assistant_turns": total,
|
|
|
|
|
|
"turns_with_reasoning": with_reasoning,
|
|
|
|
|
|
"turns_without_reasoning": total - with_reasoning,
|
|
|
|
|
|
"has_any_reasoning": with_reasoning > 0,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _failure_result(prompt_index: int, batch_num: int, error: str) -> dict[str, Any]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Result dict for a prompt that produced no trajectory."""
|
|
|
|
|
|
return {
|
|
|
|
|
|
"success": False,
|
|
|
|
|
|
"prompt_index": prompt_index,
|
|
|
|
|
|
"error": error,
|
|
|
|
|
|
"trajectory": None,
|
|
|
|
|
|
"tool_stats": {},
|
|
|
|
|
|
"toolsets_used": [],
|
|
|
|
|
|
"metadata": {"batch_num": batch_num, "timestamp": datetime.now().isoformat()},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _prepare_container_image(
|
2026-10-08 17:22:54 +02:00
|
|
|
|
prompt_index: int, prompt_data: dict[str, Any], batch_num: int, task_id: str, config: dict[str, Any]
|
|
|
|
|
|
) -> Optional[dict[str, Any]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Register the dataset row's per-prompt container image (``image``/``docker_image``)
|
2026-10-21 05:57:43 -07:00
|
|
|
|
for this task's sandbox (Docker, Modal, Daytona, or a plugin backend such as Singularity).
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
For Docker the image is verified (local cache, then pull) before spending tokens on the
|
|
|
|
|
|
agent loop; Modal pulls server-side so no local check. Returns a failure result when the
|
|
|
|
|
|
pull fails, else ``None``.
|
|
|
|
|
|
"""
|
|
|
|
|
|
container_image = prompt_data.get("image") or prompt_data.get("docker_image")
|
|
|
|
|
|
if not container_image:
|
|
|
|
|
|
return None
|
|
|
|
|
|
env_type = os.getenv("TERMINAL_ENV", "local")
|
|
|
|
|
|
if env_type == "docker":
|
|
|
|
|
|
import subprocess as _sp
|
|
|
|
|
|
try:
|
|
|
|
|
|
probe = _sp.run(
|
|
|
|
|
|
["docker", "image", "inspect", container_image],
|
|
|
|
|
|
capture_output=True, timeout=10,
|
2026-10-09 01:25:59 +02:00
|
|
|
|
check=False,
|
2026-09-02 18:23:51 -07:00
|
|
|
|
)
|
|
|
|
|
|
if probe.returncode != 0:
|
|
|
|
|
|
if config.get("verbose"):
|
|
|
|
|
|
print(f" Prompt {prompt_index}: Pulling docker image {container_image}...", flush=True)
|
|
|
|
|
|
pull = _sp.run(
|
|
|
|
|
|
["docker", "pull", container_image],
|
|
|
|
|
|
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=600,
|
2026-10-09 01:25:59 +02:00
|
|
|
|
check=False,
|
2026-09-02 18:23:51 -07:00
|
|
|
|
)
|
|
|
|
|
|
if pull.returncode != 0:
|
|
|
|
|
|
return _failure_result(
|
|
|
|
|
|
prompt_index, batch_num,
|
|
|
|
|
|
f"Docker image not available: {container_image}\n{pull.stderr[:500]}",
|
|
|
|
|
|
)
|
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
|
pass # Docker CLI not installed — skip check (e.g., Modal backend)
|
|
|
|
|
|
except Exception as img_err:
|
|
|
|
|
|
if config.get("verbose"):
|
|
|
|
|
|
print(f" Prompt {prompt_index}: Docker image check failed: {img_err}", flush=True)
|
|
|
|
|
|
from tools.terminal_tool import register_task_env_overrides
|
|
|
|
|
|
overrides = {
|
|
|
|
|
|
"docker_image": container_image,
|
|
|
|
|
|
"modal_image": container_image,
|
|
|
|
|
|
"daytona_image": container_image,
|
2026-10-21 05:57:43 -07:00
|
|
|
|
# A plugin backend reads its own ``<backend>_image`` override (tools.terminal_tool._select_image).
|
|
|
|
|
|
f"{env_type}_image": container_image,
|
2026-09-02 18:23:51 -07:00
|
|
|
|
}
|
|
|
|
|
|
if prompt_data.get("cwd"):
|
|
|
|
|
|
overrides["cwd"] = prompt_data["cwd"]
|
|
|
|
|
|
register_task_env_overrides(task_id, overrides)
|
|
|
|
|
|
if config.get("verbose"):
|
|
|
|
|
|
print(f" Prompt {prompt_index}: Using container image {container_image}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
def _process_single_prompt(
|
|
|
|
|
|
prompt_index: int,
|
2026-10-08 17:22:54 +02:00
|
|
|
|
prompt_data: dict[str, Any],
|
2025-10-06 03:17:58 +00:00
|
|
|
|
batch_num: int,
|
2026-10-08 17:22:54 +02:00
|
|
|
|
config: dict[str, Any]
|
|
|
|
|
|
) -> dict[str, Any]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Run the agent on one prompt; returns trajectory, stats and metadata (or a failure result)."""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
prompt = prompt_data["prompt"]
|
2026-03-01 16:14:36 -08:00
|
|
|
|
task_id = f"task_{prompt_index}"
|
2026-09-02 18:23:51 -07:00
|
|
|
|
failure = _prepare_container_image(prompt_index, prompt_data, batch_num, task_id, config)
|
|
|
|
|
|
if failure is not None:
|
|
|
|
|
|
return failure
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
try:
|
|
|
|
|
|
selected_toolsets = sample_toolsets_from_distribution(config["distribution"])
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if config.get("verbose"):
|
|
|
|
|
|
print(f" Prompt {prompt_index}: Using toolsets {selected_toolsets}")
|
|
|
|
|
|
agent = AIAgent(
|
|
|
|
|
|
model=config["model"],
|
|
|
|
|
|
max_iterations=config["max_iterations"],
|
|
|
|
|
|
enabled_toolsets=selected_toolsets,
|
|
|
|
|
|
save_trajectories=False, # We handle saving ourselves
|
2025-10-08 02:33:58 +00:00
|
|
|
|
verbose_logging=config.get("verbose", False),
|
2026-01-08 08:57:51 +00:00
|
|
|
|
log_prefix_chars=config.get("log_prefix_chars", 100),
|
2026-09-02 18:23:51 -07:00
|
|
|
|
log_prefix=f"[B{batch_num}:P{prompt_index}]",
|
2026-02-16 22:40:31 -08:00
|
|
|
|
skip_context_files=True, # Don't pollute trajectories with SOUL.md/AGENTS.md
|
2026-02-19 00:57:31 -08:00
|
|
|
|
skip_memory=True, # Don't use persistent memory in batch runs
|
fix(observability): attribute ACP and batch execution surfaces
Fleet telemetry showed "unknown" as the single largest execution_surface
bucket. Two construction paths were mis-attributed, both silently:
1. ACP editor sessions (VS Code / Zed / JetBrains) declare platform="acp",
but "acp" was absent from EXECUTION_SURFACES, so the contract's
closed-schema fallback folded every editor session into "other" --
the bucket meant for genuinely unclassifiable traffic.
2. batch_runner built agents from _AGENT_PASSTHROUGH, which omitted
"platform" entirely, so every batch task run reported "unknown"
despite "batch" already being a first-class surface.
Neither is a reporting bug in the exporter: both are declaration gaps at
the construction site. "unknown" must mean "this run genuinely could not
be attributed", not "a construction site forgot to say who it was".
Changes:
- add "acp" to EXECUTION_SURFACES and map it to the "interactive"
entrypoint alongside cli/desktop/tui
- add "acp" to the v2 wire schema enum (kept in sync by an existing test)
- pass platform through batch_runner: added to _AGENT_PASSTHROUGH, set
self.platform = "batch" on the runner, and defaulted at the worker call
site so callers that build a config without it stay attributable
Wire compatibility: the ingest service validates the envelope only and
stores metric bodies verbatim, so packages carrying the new value are
accepted by the already-deployed server. No coordinated deploy needed.
Tests: 12 new behavioural tests. Verified red before the fix (4 failed),
green after. Three fix-mutants confirmed killed:
M1 revert acp from EXECUTION_SURFACES -> 3 failed
M2 revert acp entrypoint mapping only -> 1 failed
M3 revert batch passthrough -> 1 failed
No source-text assertions; every test is a contract between the surfaces
the schema accepts and the surface each path declares. A guard test pins
that a genuinely undeclared run still reports "unknown", so attribution
cannot be "fixed" by inventing a default that hides real gaps.
2026-09-09 11:27:36 +10:00
|
|
|
|
**{key: config.get(key) for key in _AGENT_PASSTHROUGH if key != "platform"},
|
|
|
|
|
|
# Batch is a first-class execution surface. Defaulting here (rather than
|
|
|
|
|
|
# relying on the caller's config dict) keeps task-run telemetry attributable
|
|
|
|
|
|
# even for callers that build a config without it.
|
|
|
|
|
|
platform=config.get("platform") or "batch",
|
2025-10-06 03:17:58 +00:00
|
|
|
|
)
|
2026-09-25 12:27:39 -05:00
|
|
|
|
try:
|
|
|
|
|
|
# task_id ensures each task gets its own isolated VM
|
|
|
|
|
|
result = agent.run_conversation(prompt, task_id=task_id)
|
|
|
|
|
|
|
|
|
|
|
|
# Stats before conversion — keep the original evaluation order.
|
|
|
|
|
|
tool_stats = _extract_tool_stats(result["messages"])
|
|
|
|
|
|
reasoning_stats = _extract_reasoning_stats(result["messages"])
|
|
|
|
|
|
trajectory = agent._convert_to_trajectory_format(result["messages"], prompt, result["completed"])
|
|
|
|
|
|
finally:
|
|
|
|
|
|
# One agent per prompt, N prompts per batch process: an unclosed
|
|
|
|
|
|
# agent per prompt leaks terminals/VMs/httpx clients for the
|
|
|
|
|
|
# batch's whole run (#50197).
|
|
|
|
|
|
with contextlib.suppress(Exception):
|
|
|
|
|
|
agent.close()
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
return {
|
|
|
|
|
|
"success": True,
|
|
|
|
|
|
"prompt_index": prompt_index,
|
|
|
|
|
|
"trajectory": trajectory,
|
|
|
|
|
|
"tool_stats": tool_stats,
|
2026-02-08 20:19:14 +00:00
|
|
|
|
"reasoning_stats": reasoning_stats,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"completed": result["completed"],
|
2026-09-03 09:44:26 -07:00
|
|
|
|
# Sibling of the non-empty-response return below (#64686): the classifier's failure_reason must
|
|
|
|
|
|
# survive the empty-response normalization path too, or downstream consumers (TUI billing
|
|
|
|
|
|
# surface, transient-failure persistence) lose the structured reason exactly when the run
|
|
|
|
|
|
# produced no text.
|
2026-01-10 05:56:26 +00:00
|
|
|
|
"partial": result.get("partial", False),
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"api_calls": result["api_calls"],
|
|
|
|
|
|
"toolsets_used": selected_toolsets,
|
2026-09-02 18:34:38 -07:00
|
|
|
|
"metadata": {"batch_num": batch_num, "timestamp": datetime.now().isoformat(), "model": config["model"]},
|
2025-10-06 03:17:58 +00:00
|
|
|
|
}
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"❌ Error processing prompt {prompt_index}: {e}")
|
|
|
|
|
|
if config.get("verbose"):
|
|
|
|
|
|
traceback.print_exc()
|
2026-09-02 18:23:51 -07:00
|
|
|
|
return _failure_result(prompt_index, batch_num, str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _append_jsonl(path: Path, row: dict[str, Any]) -> None:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Append one JSON row and fsync so a crash never loses an acknowledged prompt."""
|
|
|
|
|
|
with open(path, 'a', encoding='utf-8') as f:
|
|
|
|
|
|
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
|
|
|
|
f.flush()
|
|
|
|
|
|
os.fsync(f.fileno())
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _process_batch_worker(args: tuple) -> dict[str, Any]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Pool worker: process one batch of ``(index, prompt_data)`` sequentially.
|
|
|
|
|
|
|
|
|
|
|
|
``args`` is ``(batch_num, batch_data, output_dir, completed_prompts, config)``.
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"""
|
|
|
|
|
|
batch_num, batch_data, output_dir, completed_prompts_set, config = args
|
|
|
|
|
|
output_dir = Path(output_dir)
|
|
|
|
|
|
print(f"\n🔄 Batch {batch_num}: Starting ({len(batch_data)} prompts)")
|
|
|
|
|
|
batch_output_file = output_dir / f"batch_{batch_num}.jsonl"
|
2026-09-02 18:55:16 -07:00
|
|
|
|
prompts_to_process = [(idx, data) for idx, data in batch_data if idx not in completed_prompts_set]
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if not prompts_to_process:
|
|
|
|
|
|
print(f"✅ Batch {batch_num}: Already completed (skipping)")
|
2026-09-02 18:34:38 -07:00
|
|
|
|
return {"batch_num": batch_num, "processed": 0, "skipped": len(batch_data), "tool_stats": {}, "completed_prompts": []}
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f" Processing {len(prompts_to_process)} prompts (skipping {len(batch_data) - len(prompts_to_process)} already completed)")
|
|
|
|
|
|
batch_tool_stats = {}
|
2026-09-02 18:23:51 -07:00
|
|
|
|
batch_reasoning_stats = dict.fromkeys(_REASONING_KEYS, 0)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
completed_in_batch = []
|
2026-02-08 20:19:14 +00:00
|
|
|
|
discarded_no_reasoning = 0
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
for prompt_index, prompt_data in prompts_to_process:
|
2026-09-02 18:34:38 -07:00
|
|
|
|
result = _process_single_prompt(prompt_index, prompt_data, batch_num, config)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if result["success"] and result["trajectory"]:
|
2026-02-08 20:19:14 +00:00
|
|
|
|
reasoning = result.get("reasoning_stats", {})
|
|
|
|
|
|
if not reasoning.get("has_any_reasoning", True):
|
|
|
|
|
|
print(f" 🚫 Prompt {prompt_index} discarded (no reasoning in any turn)")
|
|
|
|
|
|
discarded_no_reasoning += 1
|
2026-04-20 04:55:21 -07:00
|
|
|
|
completed_in_batch.append(prompt_index)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
# Tombstone row (#93527): resume filters by scanning batch_*.jsonl
|
|
|
|
|
|
# rows for prompt content, so a discarded sample without a row would
|
|
|
|
|
|
# be re-run at full cost on every restart. The merge step excludes
|
|
|
|
|
|
# tombstones from trajectories.jsonl.
|
|
|
|
|
|
_append_jsonl(batch_output_file, {
|
2026-08-24 00:09:37 -07:00
|
|
|
|
"prompt_index": prompt_index,
|
|
|
|
|
|
"discarded": "no_reasoning",
|
|
|
|
|
|
"prompt": _entry_prompt_text(prompt_data),
|
2026-09-02 18:23:51 -07:00
|
|
|
|
})
|
2026-02-08 20:19:14 +00:00
|
|
|
|
continue
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
# Normalize for a consistent schema across all entries.
|
2026-01-14 13:40:10 +00:00
|
|
|
|
raw_tool_stats = result.get("tool_stats", {})
|
|
|
|
|
|
raw_error_counts = {
|
2026-09-02 18:23:51 -07:00
|
|
|
|
tool_name: stats.get("failure", 0)
|
2026-01-14 13:40:10 +00:00
|
|
|
|
for tool_name, stats in raw_tool_stats.items()
|
2026-01-10 05:56:26 +00:00
|
|
|
|
}
|
2026-09-02 18:23:51 -07:00
|
|
|
|
_append_jsonl(batch_output_file, {
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"prompt_index": prompt_index,
|
|
|
|
|
|
"conversations": result["trajectory"],
|
|
|
|
|
|
"metadata": result["metadata"],
|
|
|
|
|
|
"completed": result["completed"],
|
2026-01-10 05:56:26 +00:00
|
|
|
|
"partial": result.get("partial", False), # True if stopped due to invalid tool calls
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"api_calls": result["api_calls"],
|
2026-01-10 05:56:26 +00:00
|
|
|
|
"toolsets_used": result["toolsets_used"],
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"tool_stats": _normalize_tool_stats(raw_tool_stats), # {tool: {count, success, failure}}
|
|
|
|
|
|
"tool_error_counts": _normalize_tool_error_counts(raw_error_counts) # {tool: failure_count}
|
|
|
|
|
|
})
|
|
|
|
|
|
_merge_tool_stats(batch_tool_stats, result.get("tool_stats", {}))
|
|
|
|
|
|
_merge_reasoning_stats(batch_reasoning_stats, result.get("reasoning_stats", {}))
|
|
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
# Only mark as completed if successfully saved (failed prompts can be retried on resume)
|
|
|
|
|
|
if result["success"] and result["trajectory"]:
|
|
|
|
|
|
completed_in_batch.append(prompt_index)
|
|
|
|
|
|
status = "⚠️ partial" if result.get("partial") else "✅"
|
|
|
|
|
|
print(f" {status} Prompt {prompt_index} completed")
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(f" ❌ Prompt {prompt_index} failed (will retry on resume)")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f"✅ Batch {batch_num}: Completed ({len(prompts_to_process)} prompts processed)")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
return {
|
|
|
|
|
|
"batch_num": batch_num,
|
|
|
|
|
|
"processed": len(prompts_to_process),
|
|
|
|
|
|
"skipped": len(batch_data) - len(prompts_to_process),
|
|
|
|
|
|
"tool_stats": batch_tool_stats,
|
2026-02-08 20:19:14 +00:00
|
|
|
|
"reasoning_stats": batch_reasoning_stats,
|
|
|
|
|
|
"discarded_no_reasoning": discarded_no_reasoning,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"completed_prompts": completed_in_batch
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _entry_prompt_text(entry: dict) -> str:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Human prompt text from a dataset/trajectory entry: flat ``prompt``, ShareGPT
|
|
|
|
|
|
``conversations`` (from/value), chat ``conversations``/``messages`` (role/content),
|
|
|
|
|
|
or a no-reasoning discard tombstone."""
|
2026-08-24 00:09:37 -07:00
|
|
|
|
if not isinstance(entry, dict):
|
|
|
|
|
|
return ""
|
|
|
|
|
|
text = str(entry.get("prompt") or "").strip()
|
|
|
|
|
|
if text:
|
|
|
|
|
|
return text
|
|
|
|
|
|
for key in ("conversations", "messages"):
|
|
|
|
|
|
for msg in entry.get(key, []) or []:
|
|
|
|
|
|
if not isinstance(msg, dict):
|
|
|
|
|
|
continue
|
|
|
|
|
|
role = msg.get("role") or msg.get("from")
|
|
|
|
|
|
if role in {"user", "human"}:
|
|
|
|
|
|
text = str(msg.get("content") or msg.get("value") or "").strip()
|
|
|
|
|
|
if text:
|
|
|
|
|
|
return text
|
|
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-02 18:44:40 -07:00
|
|
|
|
def _banner(title: str) -> None:
|
|
|
|
|
|
print("\n" + "=" * 70)
|
|
|
|
|
|
print(title)
|
|
|
|
|
|
print("=" * 70)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _chunk(entries: list[tuple[int, dict[str, Any]]], size: int) -> list[list[tuple[int, dict[str, Any]]]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Split ``(index, entry)`` tuples into batches of *size*, preserving original indices."""
|
|
|
|
|
|
return [entries[i:i + size] for i in range(0, len(entries), size)]
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
class BatchRunner:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Manages batch processing of agent prompts with checkpointing and statistics."""
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
dataset_file: str,
|
|
|
|
|
|
batch_size: int,
|
|
|
|
|
|
run_name: str,
|
|
|
|
|
|
distribution: str = "default",
|
|
|
|
|
|
max_iterations: int = 10,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
base_url: str | None = None,
|
|
|
|
|
|
api_key: str | None = None,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
model: str = "claude-opus-4-20250514",
|
|
|
|
|
|
num_workers: int = 4,
|
2025-10-08 02:33:58 +00:00
|
|
|
|
verbose: bool = False,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
ephemeral_system_prompt: str | None = None,
|
2025-11-07 14:43:44 -05:00
|
|
|
|
log_prefix_chars: int = 100,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
providers_allowed: list[str] | None = None,
|
|
|
|
|
|
providers_ignored: list[str] | None = None,
|
|
|
|
|
|
providers_order: list[str] | None = None,
|
|
|
|
|
|
provider_sort: str | None = None,
|
feat(openrouter): wire Pareto Code router with min_coding_score knob (#22838)
Pick openrouter/pareto-code as your model and OpenRouter auto-routes each
request to the cheapest model meeting your coding-quality bar (ranked by
Artificial Analysis). The new openrouter.min_coding_score config key (0.0-1.0,
default 0.65) tunes the floor.
- hermes_cli/models.py: add openrouter/pareto-code to OPENROUTER_MODELS so
it shows up in the picker with a description
- hermes_cli/config.py: add openrouter.min_coding_score (default 0.65 — lands
on a mid-tier coder on the current Pareto frontier)
- plugins/model-providers/openrouter: emit extra_body.plugins =
[{id: pareto-router, min_coding_score: X}] when model is openrouter/pareto-code
AND the score is a valid float in [0.0, 1.0]
- agent/transports/chat_completions.py: same emission on the legacy flag
path (when no provider profile is loaded)
- run_agent.py: openrouter_min_coding_score kwarg + storage; plumbed into
both build_kwargs() invocations and the context-summary extra_body path
- cli.py: read openrouter.min_coding_score once at init, validate float in
[0,1], pass to AIAgent constructions (CLI + background-task paths)
- cron/scheduler.py, batch_runner.py, tools/delegate_tool.py,
tui_gateway/server.py: propagate the kwarg (mirrors providers_order
plumbing — subagents inherit, cron/batch read from config)
- tests: profile-level + transport-level coverage of the model gating,
unset/empty/out-of-range handling, and the legacy flag path
- docs: new 'OpenRouter Pareto Code Router' section in providers.md
Verified end-to-end against api.openrouter.ai: at score=0.65 we land on a
mid-tier coder, at omission we get the strongest. Score is silently dropped
on any model other than openrouter/pareto-code, so it's safe to leave set.
2026-05-09 14:47:00 -07:00
|
|
|
|
openrouter_min_coding_score: Optional[float] = None,
|
2026-09-07 03:32:37 -07:00
|
|
|
|
|
2026-10-08 21:29:48 +02:00
|
|
|
|
reasoning_config: dict[str, Any] | None = None,
|
|
|
|
|
|
prefill_messages: list[dict[str, Any]] | None = None,
|
|
|
|
|
|
max_samples: int | None = None,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
):
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Load the dataset (truncated to *max_samples*), validate *distribution*, create batches.
|
|
|
|
|
|
|
|
|
|
|
|
``ephemeral_system_prompt`` is used during execution but NOT saved to trajectories.
|
|
|
|
|
|
``prefill_messages`` are prepended as few-shot context; Anthropic Sonnet/Opus 4.6+
|
|
|
|
|
|
reject a trailing assistant-role prefill (400) — use user-role priming for those.
|
2025-10-06 03:17:58 +00:00
|
|
|
|
"""
|
2026-09-02 18:44:40 -07:00
|
|
|
|
params = dict(locals())
|
2025-10-06 03:17:58 +00:00
|
|
|
|
self.dataset_file = Path(dataset_file)
|
2026-09-02 18:44:40 -07:00
|
|
|
|
for name in _RUNNER_FIELDS:
|
|
|
|
|
|
setattr(self, name, params[name])
|
fix(observability): attribute ACP and batch execution surfaces
Fleet telemetry showed "unknown" as the single largest execution_surface
bucket. Two construction paths were mis-attributed, both silently:
1. ACP editor sessions (VS Code / Zed / JetBrains) declare platform="acp",
but "acp" was absent from EXECUTION_SURFACES, so the contract's
closed-schema fallback folded every editor session into "other" --
the bucket meant for genuinely unclassifiable traffic.
2. batch_runner built agents from _AGENT_PASSTHROUGH, which omitted
"platform" entirely, so every batch task run reported "unknown"
despite "batch" already being a first-class surface.
Neither is a reporting bug in the exporter: both are declaration gaps at
the construction site. "unknown" must mean "this run genuinely could not
be attributed", not "a construction site forgot to say who it was".
Changes:
- add "acp" to EXECUTION_SURFACES and map it to the "interactive"
entrypoint alongside cli/desktop/tui
- add "acp" to the v2 wire schema enum (kept in sync by an existing test)
- pass platform through batch_runner: added to _AGENT_PASSTHROUGH, set
self.platform = "batch" on the runner, and defaulted at the worker call
site so callers that build a config without it stay attributable
Wire compatibility: the ingest service validates the envelope only and
stores metric bodies verbatim, so packages carrying the new value are
accepted by the already-deployed server. No coordinated deploy needed.
Tests: 12 new behavioural tests. Verified red before the fix (4 failed),
green after. Three fix-mutants confirmed killed:
M1 revert acp from EXECUTION_SURFACES -> 3 failed
M2 revert acp entrypoint mapping only -> 1 failed
M3 revert batch passthrough -> 1 failed
No source-text assertions; every test is a contract between the surfaces
the schema accepts and the surface each path declares. A guard test pins
that a genuinely undeclared run still reports "unknown", so attribution
cannot be "fixed" by inventing a default that hides real gaps.
2026-09-09 11:27:36 +10:00
|
|
|
|
# Batch runs are their own execution surface; declaring it here keeps every
|
|
|
|
|
|
# worker's task-run telemetry attributable instead of falling back to "unknown".
|
|
|
|
|
|
self.platform = "batch"
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if not validate_distribution(distribution):
|
|
|
|
|
|
raise ValueError(f"Unknown distribution: {distribution}. Available: {list(list_distributions().keys())}")
|
|
|
|
|
|
self.output_dir = Path("data") / run_name
|
|
|
|
|
|
self.output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
self.checkpoint_file = self.output_dir / "checkpoint.json"
|
|
|
|
|
|
self.stats_file = self.output_dir / "statistics.json"
|
|
|
|
|
|
self.dataset = self._load_dataset()
|
2026-02-08 20:19:14 +00:00
|
|
|
|
if self.max_samples and self.max_samples < len(self.dataset):
|
|
|
|
|
|
full_count = len(self.dataset)
|
|
|
|
|
|
self.dataset = self.dataset[:self.max_samples]
|
|
|
|
|
|
print(f"✂️ Truncated dataset from {full_count} to {self.max_samples} samples (--max_samples)")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
self.batches = self._create_batches()
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print("📊 Batch Runner Initialized")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f" Dataset: {self.dataset_file} ({len(self.dataset)} prompts)")
|
|
|
|
|
|
print(f" Batch size: {self.batch_size}")
|
|
|
|
|
|
print(f" Total batches: {len(self.batches)}")
|
|
|
|
|
|
print(f" Run name: {self.run_name}")
|
|
|
|
|
|
print(f" Distribution: {self.distribution}")
|
|
|
|
|
|
print(f" Output directory: {self.output_dir}")
|
|
|
|
|
|
print(f" Workers: {self.num_workers}")
|
2025-10-08 02:33:58 +00:00
|
|
|
|
if self.ephemeral_system_prompt:
|
|
|
|
|
|
prompt_preview = self.ephemeral_system_prompt[:60] + "..." if len(self.ephemeral_system_prompt) > 60 else self.ephemeral_system_prompt
|
|
|
|
|
|
print(f" 🔒 Ephemeral system prompt: '{prompt_preview}'")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _load_dataset(self) -> list[dict[str, Any]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Load JSONL entries that have a ``prompt`` field; skip blank/invalid lines."""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if not self.dataset_file.exists():
|
|
|
|
|
|
raise FileNotFoundError(f"Dataset file not found: {self.dataset_file}")
|
|
|
|
|
|
dataset = []
|
|
|
|
|
|
with open(self.dataset_file, 'r', encoding='utf-8') as f:
|
|
|
|
|
|
for line_num, line in enumerate(f, 1):
|
|
|
|
|
|
line = line.strip()
|
|
|
|
|
|
if not line:
|
|
|
|
|
|
continue
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
try:
|
|
|
|
|
|
entry = json.loads(line)
|
|
|
|
|
|
except json.JSONDecodeError as e:
|
|
|
|
|
|
print(f"⚠️ Warning: Invalid JSON on line {line_num}: {e}")
|
|
|
|
|
|
continue
|
fix(tools,tui_gateway,cli,plugins): parseable non-dict JSON no longer crashes the remaining file scans
Same class as the Bot Chat drain wedge already on this branch: every JSON-file
scan guarded "did it parse?" and then assumed the value was a dict. A file
holding `42`, `"oops"` or `[1,2,3]` (corruption, truncated write, foreign tool)
passed the guard and raised AttributeError/TypeError at the first `.get()`,
usually before a single healthy sibling was processed. Each site now treats a
non-object payload like a corrupt file under that subsystem's existing policy:
- tools/bot_relay.py::_expire_if_stale / claim_pending_envelopes — the
envelope is skipped by the sweep and not claimed (same as unparseable).
- tools/browser_lightpanda.py::reap_orphaned_lightpanda — record unlinked,
scan continues.
- tools/write_approval.py::list_pending / get_pending — record skipped with
the existing "unreadable pending record" warning / None.
- tui_gateway/methods_session.py::_legacy_spawn_tree_entry / spawn_tree.load —
scalar snapshot reads as empty / returns the existing 5000 error instead of
violating the SpawnTreeLoadResult contract.
- hermes_cli/local_runtime/binaries.py::manifest_verified — False.
- plugins/platforms/a2a/protocol.py::load_conversation — non-dict lines are
dropped, keeping the declared list[dict] return.
- batch_runner.py::_load_dataset / _scan_completed_prompts_by_content /
_combine_batch_files — line skipped and counted as filtered.
- trajectory_compressor.py::process_entry_async — scalar entry passed through
unchanged.
Ported from the source hunks of PR #114241; its gateway/shutdown_flush.py
drain_transcript_spool hunk is left to open PR #84785, and its
recover_pending_to_db / cron / bot_live_delivery / bot_mode_dm hunks are
already on this branch or on main.
(cherry picked from commit d4b54568887e69b3ee3d363ebe4dcd657ccf64f9)
2026-09-18 01:35:01 -07:00
|
|
|
|
if not isinstance(entry, dict) or 'prompt' not in entry:
|
|
|
|
|
|
print(f"⚠️ Warning: Line {line_num} missing 'prompt' field, skipping")
|
|
|
|
|
|
continue
|
|
|
|
|
|
dataset.append(entry)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if not dataset:
|
|
|
|
|
|
raise ValueError(f"No valid entries found in dataset file: {self.dataset_file}")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
return dataset
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _create_batches(self) -> list[list[tuple[int, dict[str, Any]]]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Split the dataset into batches of ``(index, entry)`` tuples."""
|
|
|
|
|
|
return _chunk(list(enumerate(self.dataset)), self.batch_size)
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _empty_checkpoint(self) -> dict[str, Any]:
|
2026-09-02 18:55:16 -07:00
|
|
|
|
return {"run_name": self.run_name, "completed_prompts": [], "batch_stats": {}, "last_updated": None}
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _load_checkpoint(self) -> dict[str, Any]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Checkpoint data (completed prompt indices), or an empty one if missing/unreadable."""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if not self.checkpoint_file.exists():
|
2026-09-02 18:23:51 -07:00
|
|
|
|
return self._empty_checkpoint()
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
try:
|
|
|
|
|
|
with open(self.checkpoint_file, 'r', encoding='utf-8') as f:
|
|
|
|
|
|
return json.load(f)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"⚠️ Warning: Failed to load checkpoint: {e}")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
return self._empty_checkpoint()
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _save_checkpoint(self, checkpoint_data: dict[str, Any], lock: Optional[Lock] = None):
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Atomically write *checkpoint_data* (stamped ``last_updated``), under *lock* if given."""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
checkpoint_data["last_updated"] = datetime.now().isoformat()
|
refactor: extract atomic_json_write helper, add 24 checkpoint tests
Extract the duplicated temp-file + fsync + os.replace pattern from
batch_runner.py (1 instance) and process_registry.py (2 instances) into
a shared utils.atomic_json_write() function.
Add 12 tests for atomic_json_write covering: valid JSON, parent dir
creation, overwrite, crash safety (original preserved on error), no temp
file leaks, string paths, unicode, custom indent, concurrent writes.
Add 12 tests for batch_runner checkpoint behavior covering:
_save_checkpoint (valid JSON, last_updated, overwrite, lock/no-lock,
parent dirs, no temp leaks), _load_checkpoint (missing file, existing
data, corrupt JSON), and resume logic (preserves prior progress,
different run_name starts fresh).
2026-03-06 05:50:12 -08:00
|
|
|
|
from utils import atomic_json_write
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if lock:
|
|
|
|
|
|
with lock:
|
refactor: extract atomic_json_write helper, add 24 checkpoint tests
Extract the duplicated temp-file + fsync + os.replace pattern from
batch_runner.py (1 instance) and process_registry.py (2 instances) into
a shared utils.atomic_json_write() function.
Add 12 tests for atomic_json_write covering: valid JSON, parent dir
creation, overwrite, crash safety (original preserved on error), no temp
file leaks, string paths, unicode, custom indent, concurrent writes.
Add 12 tests for batch_runner checkpoint behavior covering:
_save_checkpoint (valid JSON, last_updated, overwrite, lock/no-lock,
parent dirs, no temp leaks), _load_checkpoint (missing file, existing
data, corrupt JSON), and resume logic (preserves prior progress,
different run_name starts fresh).
2026-03-06 05:50:12 -08:00
|
|
|
|
atomic_json_write(self.checkpoint_file, checkpoint_data)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
else:
|
refactor: extract atomic_json_write helper, add 24 checkpoint tests
Extract the duplicated temp-file + fsync + os.replace pattern from
batch_runner.py (1 instance) and process_registry.py (2 instances) into
a shared utils.atomic_json_write() function.
Add 12 tests for atomic_json_write covering: valid JSON, parent dir
creation, overwrite, crash safety (original preserved on error), no temp
file leaks, string paths, unicode, custom indent, concurrent writes.
Add 12 tests for batch_runner checkpoint behavior covering:
_save_checkpoint (valid JSON, last_updated, overwrite, lock/no-lock,
parent dirs, no temp leaks), _load_checkpoint (missing file, existing
data, corrupt JSON), and resume logic (preserves prior progress,
different run_name starts fresh).
2026-03-06 05:50:12 -08:00
|
|
|
|
atomic_json_write(self.checkpoint_file, checkpoint_data)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
def _scan_completed_prompts_by_content(self) -> set:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Prompt texts already processed, scanned from every ``batch_*.jsonl``.
|
|
|
|
|
|
|
|
|
|
|
|
Matching on content rather than index lets resume recover even when indices
|
|
|
|
|
|
don't line up. Failed entries are skipped (retried); discard tombstones count
|
|
|
|
|
|
as completed (#93527) — re-running would just re-discard.
|
2026-01-18 10:11:59 +00:00
|
|
|
|
"""
|
|
|
|
|
|
completed_prompts = set()
|
|
|
|
|
|
batch_files = sorted(self.output_dir.glob("batch_*.jsonl"))
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
if not batch_files:
|
|
|
|
|
|
return completed_prompts
|
|
|
|
|
|
print(f"📂 Scanning {len(batch_files)} batch files for completed prompts...")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
for batch_file in batch_files:
|
|
|
|
|
|
try:
|
|
|
|
|
|
with open(batch_file, 'r', encoding='utf-8') as f:
|
|
|
|
|
|
for line in f:
|
|
|
|
|
|
try:
|
|
|
|
|
|
entry = json.loads(line.strip())
|
fix(tools,tui_gateway,cli,plugins): parseable non-dict JSON no longer crashes the remaining file scans
Same class as the Bot Chat drain wedge already on this branch: every JSON-file
scan guarded "did it parse?" and then assumed the value was a dict. A file
holding `42`, `"oops"` or `[1,2,3]` (corruption, truncated write, foreign tool)
passed the guard and raised AttributeError/TypeError at the first `.get()`,
usually before a single healthy sibling was processed. Each site now treats a
non-object payload like a corrupt file under that subsystem's existing policy:
- tools/bot_relay.py::_expire_if_stale / claim_pending_envelopes — the
envelope is skipped by the sweep and not claimed (same as unparseable).
- tools/browser_lightpanda.py::reap_orphaned_lightpanda — record unlinked,
scan continues.
- tools/write_approval.py::list_pending / get_pending — record skipped with
the existing "unreadable pending record" warning / None.
- tui_gateway/methods_session.py::_legacy_spawn_tree_entry / spawn_tree.load —
scalar snapshot reads as empty / returns the existing 5000 error instead of
violating the SpawnTreeLoadResult contract.
- hermes_cli/local_runtime/binaries.py::manifest_verified — False.
- plugins/platforms/a2a/protocol.py::load_conversation — non-dict lines are
dropped, keeping the declared list[dict] return.
- batch_runner.py::_load_dataset / _scan_completed_prompts_by_content /
_combine_batch_files — line skipped and counted as filtered.
- trajectory_compressor.py::process_entry_async — scalar entry passed through
unchanged.
Ported from the source hunks of PR #114241; its gateway/shutdown_flush.py
drain_transcript_spool hunk is left to open PR #84785, and its
recover_pending_to_db / cron / bot_live_delivery / bot_mode_dm hunks are
already on this branch or on main.
(cherry picked from commit d4b54568887e69b3ee3d363ebe4dcd657ccf64f9)
2026-09-18 01:35:01 -07:00
|
|
|
|
if not isinstance(entry, dict) or entry.get("failed", False):
|
2026-01-18 10:11:59 +00:00
|
|
|
|
continue
|
2026-08-24 00:09:37 -07:00
|
|
|
|
prompt_text = _entry_prompt_text(entry)
|
|
|
|
|
|
if prompt_text:
|
|
|
|
|
|
completed_prompts.add(prompt_text)
|
2026-01-18 10:11:59 +00:00
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
|
continue
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f" ⚠️ Warning: Error reading {batch_file.name}: {e}")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
return completed_prompts
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _filter_dataset_by_completed(self, completed_prompts: set) -> tuple[list[dict], list[int]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Return ``([(index, entry)] not yet completed, [skipped indices])``."""
|
2026-01-18 10:11:59 +00:00
|
|
|
|
filtered_dataset = []
|
|
|
|
|
|
skipped_indices = []
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
for idx, entry in enumerate(self.dataset):
|
|
|
|
|
|
prompt_text = entry.get("prompt", "").strip()
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
# Also check conversations format
|
|
|
|
|
|
if not prompt_text:
|
|
|
|
|
|
conversations = entry.get("conversations", [])
|
|
|
|
|
|
for msg in conversations:
|
|
|
|
|
|
role = msg.get("role") or msg.get("from")
|
2026-05-11 11:13:25 -07:00
|
|
|
|
if role in {"user", "human"}:
|
2026-01-18 10:11:59 +00:00
|
|
|
|
prompt_text = (msg.get("content") or msg.get("value", "")).strip()
|
|
|
|
|
|
break
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
if prompt_text in completed_prompts:
|
|
|
|
|
|
skipped_indices.append(idx)
|
|
|
|
|
|
else:
|
|
|
|
|
|
filtered_dataset.append((idx, entry))
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
return filtered_dataset, skipped_indices
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
def _apply_resume(self) -> bool:
|
|
|
|
|
|
"""Rebuild ``self.batches`` from unprocessed prompts. False when nothing is left to run."""
|
|
|
|
|
|
completed_prompt_texts = self._scan_completed_prompts_by_content()
|
|
|
|
|
|
if not completed_prompt_texts:
|
|
|
|
|
|
return True
|
|
|
|
|
|
print(f" Found {len(completed_prompt_texts)} already-completed prompts by content matching")
|
|
|
|
|
|
filtered_entries, skipped_indices = self._filter_dataset_by_completed(completed_prompt_texts)
|
|
|
|
|
|
|
|
|
|
|
|
if not filtered_entries:
|
|
|
|
|
|
print("\n✅ All prompts have already been processed!")
|
|
|
|
|
|
return False
|
|
|
|
|
|
self.batches = _chunk(filtered_entries, self.batch_size)
|
2026-09-02 18:44:40 -07:00
|
|
|
|
_banner("📊 RESUME SUMMARY")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
print(f" Original dataset size: {len(self.dataset):,} prompts")
|
|
|
|
|
|
print(f" Already completed: {len(skipped_indices):,} prompts")
|
|
|
|
|
|
print(" ─────────────────────────────────────────")
|
|
|
|
|
|
print(f" 🎯 RESUMING WITH: {len(filtered_entries):,} prompts")
|
|
|
|
|
|
print(f" New batches created: {len(self.batches)}")
|
|
|
|
|
|
print("=" * 70 + "\n")
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _worker_config(self) -> dict[str, Any]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Picklable agent configuration for worker processes.
|
|
|
|
|
|
|
|
|
|
|
|
``self.api_key`` may be a zero-arg callable (Azure Foundry Entra ID bearer provider
|
|
|
|
|
|
from ``agent.azure_identity_adapter``), which is not safely picklable across the
|
|
|
|
|
|
Pool boundary. Drop it and let each worker rebuild its own provider via
|
|
|
|
|
|
``resolve_runtime_provider()`` from ``model.auth_mode`` in config.yaml
|
|
|
|
|
|
(azure-identity caches in-process, so each worker gets its own short-lived cache).
|
|
|
|
|
|
"""
|
2026-05-15 14:36:18 -07:00
|
|
|
|
if callable(self.api_key) and not isinstance(self.api_key, str):
|
|
|
|
|
|
worker_api_key = None
|
|
|
|
|
|
print(
|
|
|
|
|
|
"ℹ️ Detected Entra ID bearer provider — workers will rebuild "
|
|
|
|
|
|
"credentials from config.yaml in each process.",
|
|
|
|
|
|
flush=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
worker_api_key = self.api_key
|
2026-09-02 18:34:38 -07:00
|
|
|
|
config = {key: getattr(self, key) for key in _AGENT_PASSTHROUGH}
|
|
|
|
|
|
config["api_key"] = worker_api_key
|
|
|
|
|
|
for key in ("distribution", "model", "max_iterations", "verbose", "log_prefix_chars"):
|
|
|
|
|
|
config[key] = getattr(self, key)
|
|
|
|
|
|
return config
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _run_pool(self, config, checkpoint_data, completed_prompts_set, checkpoint_lock) -> list[dict[str, Any]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Process all batches in a worker pool, checkpointing after each result."""
|
2026-01-08 08:57:51 +00:00
|
|
|
|
print(f"\n🔧 Initializing {self.num_workers} worker processes...")
|
2026-03-03 01:43:07 +03:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
with Pool(processes=self.num_workers) as pool:
|
2026-09-02 18:34:38 -07:00
|
|
|
|
# output_dir as str for pickling
|
2025-10-06 03:17:58 +00:00
|
|
|
|
tasks = [
|
2026-09-02 18:34:38 -07:00
|
|
|
|
(batch_num, batch_data, str(self.output_dir), completed_prompts_set, config)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
for batch_num, batch_data in enumerate(self.batches)
|
|
|
|
|
|
]
|
2026-01-08 08:57:51 +00:00
|
|
|
|
print(f"✅ Created {len(tasks)} batch tasks")
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print("🚀 Starting parallel batch processing...\n")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
# rich Progress gives a persistent bottom bar; stdout/stderr are NOT
|
|
|
|
|
|
# redirected so worker prints stay visible.
|
2026-01-14 14:02:59 +00:00
|
|
|
|
results = []
|
|
|
|
|
|
console = Console(force_terminal=True)
|
|
|
|
|
|
with Progress(
|
2026-09-02 18:34:38 -07:00
|
|
|
|
SpinnerColumn(), TextColumn("[bold blue]📦 Batches"), BarColumn(bar_width=40),
|
|
|
|
|
|
MofNCompleteColumn(), TextColumn("•"), TimeRemainingColumn(),
|
|
|
|
|
|
console=console, refresh_per_second=2, transient=False,
|
|
|
|
|
|
redirect_stdout=False, redirect_stderr=False,
|
2026-01-14 14:02:59 +00:00
|
|
|
|
) as progress:
|
|
|
|
|
|
task = progress.add_task("Processing", total=len(tasks))
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-14 14:02:59 +00:00
|
|
|
|
# Temporarily suppress DEBUG logging to avoid bar interference
|
|
|
|
|
|
root_logger = logging.getLogger()
|
|
|
|
|
|
original_level = root_logger.level
|
|
|
|
|
|
root_logger.setLevel(logging.WARNING)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-14 14:02:59 +00:00
|
|
|
|
try:
|
|
|
|
|
|
for result in pool.imap_unordered(_process_batch_worker, tasks):
|
|
|
|
|
|
results.append(result)
|
|
|
|
|
|
progress.update(task, advance=1)
|
2026-03-03 01:43:07 +03:00
|
|
|
|
|
|
|
|
|
|
# Incremental checkpoint update (so resume works after crash)
|
|
|
|
|
|
try:
|
|
|
|
|
|
batch_num = result.get('batch_num')
|
|
|
|
|
|
completed = result.get('completed_prompts', []) or []
|
|
|
|
|
|
completed_prompts_set.update(completed)
|
|
|
|
|
|
|
|
|
|
|
|
if isinstance(batch_num, int):
|
|
|
|
|
|
checkpoint_data.setdefault('batch_stats', {})[str(batch_num)] = {
|
2026-09-02 18:34:38 -07:00
|
|
|
|
key: result.get(key, 0) for key in ('processed', 'skipped', 'discarded_no_reasoning')
|
2026-03-03 01:43:07 +03:00
|
|
|
|
}
|
|
|
|
|
|
checkpoint_data['completed_prompts'] = sorted(completed_prompts_set)
|
|
|
|
|
|
self._save_checkpoint(checkpoint_data, lock=checkpoint_lock)
|
|
|
|
|
|
except Exception as ckpt_err:
|
|
|
|
|
|
# Don't fail the run if checkpoint write fails
|
2026-03-06 05:16:31 -08:00
|
|
|
|
print(f"⚠️ Warning: Failed to save incremental checkpoint: {ckpt_err}")
|
2026-08-01 14:10:29 +05:30
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
|
|
print("\n⚠️ Interrupted — terminating batch workers...")
|
|
|
|
|
|
pool.terminate()
|
|
|
|
|
|
pool.join()
|
|
|
|
|
|
raise
|
2026-03-02 12:16:07 +03:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error("Batch worker failed: %s", e, exc_info=True)
|
2026-08-01 14:10:29 +05:30
|
|
|
|
pool.terminate()
|
|
|
|
|
|
pool.join()
|
2026-03-02 12:16:07 +03:00
|
|
|
|
raise
|
2026-01-14 14:02:59 +00:00
|
|
|
|
finally:
|
|
|
|
|
|
root_logger.setLevel(original_level)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
return results
|
2026-04-24 13:33:56 +01:00
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _combine_batch_files(self) -> tuple[int, int]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Merge ALL ``batch_*.jsonl`` (old runs + resume) into ``trajectories.jsonl``.
|
|
|
|
|
|
|
|
|
|
|
|
Drops corrupted entries (hallucinated tool names, invalid JSON) and discard
|
|
|
|
|
|
tombstones (#93527, resume bookkeeping only). Returns ``(kept, files_found)``.
|
|
|
|
|
|
"""
|
2025-10-06 03:17:58 +00:00
|
|
|
|
combined_file = self.output_dir / "trajectories.jsonl"
|
2026-01-18 10:11:59 +00:00
|
|
|
|
print(f"\n📦 Combining ALL batch files into {combined_file.name}...")
|
2026-01-10 05:56:26 +00:00
|
|
|
|
total_entries = 0
|
|
|
|
|
|
filtered_entries = 0
|
2026-08-24 00:09:37 -07:00
|
|
|
|
tombstone_entries = 0
|
2026-01-18 10:11:59 +00:00
|
|
|
|
batch_files_found = 0
|
|
|
|
|
|
all_batch_files = sorted(self.output_dir.glob("batch_*.jsonl"))
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
with open(combined_file, 'w', encoding='utf-8') as outfile:
|
2026-01-18 10:11:59 +00:00
|
|
|
|
for batch_file in all_batch_files:
|
|
|
|
|
|
batch_files_found += 1
|
|
|
|
|
|
batch_num = batch_file.stem.split("_")[1] # Extract batch number for logging
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
with open(batch_file, 'r', encoding='utf-8') as infile:
|
|
|
|
|
|
for line in infile:
|
|
|
|
|
|
total_entries += 1
|
|
|
|
|
|
try:
|
|
|
|
|
|
data = json.loads(line)
|
2026-08-24 00:09:15 -07:00
|
|
|
|
|
fix(tools,tui_gateway,cli,plugins): parseable non-dict JSON no longer crashes the remaining file scans
Same class as the Bot Chat drain wedge already on this branch: every JSON-file
scan guarded "did it parse?" and then assumed the value was a dict. A file
holding `42`, `"oops"` or `[1,2,3]` (corruption, truncated write, foreign tool)
passed the guard and raised AttributeError/TypeError at the first `.get()`,
usually before a single healthy sibling was processed. Each site now treats a
non-object payload like a corrupt file under that subsystem's existing policy:
- tools/bot_relay.py::_expire_if_stale / claim_pending_envelopes — the
envelope is skipped by the sweep and not claimed (same as unparseable).
- tools/browser_lightpanda.py::reap_orphaned_lightpanda — record unlinked,
scan continues.
- tools/write_approval.py::list_pending / get_pending — record skipped with
the existing "unreadable pending record" warning / None.
- tui_gateway/methods_session.py::_legacy_spawn_tree_entry / spawn_tree.load —
scalar snapshot reads as empty / returns the existing 5000 error instead of
violating the SpawnTreeLoadResult contract.
- hermes_cli/local_runtime/binaries.py::manifest_verified — False.
- plugins/platforms/a2a/protocol.py::load_conversation — non-dict lines are
dropped, keeping the declared list[dict] return.
- batch_runner.py::_load_dataset / _scan_completed_prompts_by_content /
_combine_batch_files — line skipped and counted as filtered.
- trajectory_compressor.py::process_entry_async — scalar entry passed through
unchanged.
Ported from the source hunks of PR #114241; its gateway/shutdown_flush.py
drain_transcript_spool hunk is left to open PR #84785, and its
recover_pending_to_db / cron / bot_live_delivery / bot_mode_dm hunks are
already on this branch or on main.
(cherry picked from commit d4b54568887e69b3ee3d363ebe4dcd657ccf64f9)
2026-09-18 01:35:01 -07:00
|
|
|
|
if not isinstance(data, dict):
|
|
|
|
|
|
filtered_entries += 1
|
|
|
|
|
|
continue
|
2026-08-24 00:09:15 -07:00
|
|
|
|
if data.get("discarded"):
|
2026-08-24 00:09:37 -07:00
|
|
|
|
tombstone_entries += 1
|
2026-08-24 00:09:15 -07:00
|
|
|
|
continue
|
2026-01-18 10:11:59 +00:00
|
|
|
|
tool_stats = data.get('tool_stats', {})
|
2026-09-02 18:23:51 -07:00
|
|
|
|
invalid_tools = [k for k in tool_stats if k not in ALL_POSSIBLE_TOOLS]
|
|
|
|
|
|
|
2026-01-18 10:11:59 +00:00
|
|
|
|
if invalid_tools:
|
2026-01-10 05:56:26 +00:00
|
|
|
|
filtered_entries += 1
|
2026-01-18 10:11:59 +00:00
|
|
|
|
invalid_preview = invalid_tools[0][:50] + "..." if len(invalid_tools[0]) > 50 else invalid_tools[0]
|
|
|
|
|
|
print(f" ⚠️ Filtering corrupted entry (batch {batch_num}): invalid tool '{invalid_preview}'")
|
|
|
|
|
|
continue
|
|
|
|
|
|
outfile.write(line)
|
|
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
|
filtered_entries += 1
|
|
|
|
|
|
print(f" ⚠️ Filtering invalid JSON entry (batch {batch_num})")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-01-10 05:56:26 +00:00
|
|
|
|
if filtered_entries > 0:
|
|
|
|
|
|
print(f"⚠️ Filtered {filtered_entries} corrupted entries out of {total_entries} total")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
kept = total_entries - filtered_entries - tombstone_entries
|
|
|
|
|
|
print(f"✅ Combined {batch_files_found} batch files into trajectories.jsonl ({kept} entries)")
|
|
|
|
|
|
return kept, batch_files_found
|
|
|
|
|
|
|
|
|
|
|
|
def _print_summary(self, results, total_tool_stats, total_reasoning_stats, kept, batch_files_found, start_time) -> None:
|
2026-09-02 18:44:40 -07:00
|
|
|
|
_banner("📊 BATCH PROCESSING COMPLETE")
|
2026-01-18 10:11:59 +00:00
|
|
|
|
print(f"✅ Prompts processed this run: {sum(r.get('processed', 0) for r in results)}")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
print(f"✅ Total trajectories in merged file: {kept}")
|
2026-01-18 10:11:59 +00:00
|
|
|
|
print(f"✅ Total batch files merged: {batch_files_found}")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f"⏱️ Total duration: {round(time.time() - start_time, 2)}s")
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print("\n📈 Tool Usage Statistics:")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print("-" * 70)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
if total_tool_stats:
|
2026-09-02 18:34:38 -07:00
|
|
|
|
sorted_tools = sorted(total_tool_stats.items(), key=lambda x: x[1]["count"], reverse=True)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f"{'Tool Name':<25} {'Count':<10} {'Success':<10} {'Failure':<10} {'Success Rate':<12}")
|
|
|
|
|
|
print("-" * 70)
|
|
|
|
|
|
for tool_name, stats in sorted_tools:
|
2026-09-02 18:34:38 -07:00
|
|
|
|
print(f"{tool_name:<25} {stats['count']:<10} {stats['success']:<10} {stats['failure']:<10} {stats['success_rate']:.1f}%")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
else:
|
|
|
|
|
|
print("No tool calls were made during this run.")
|
2026-02-08 20:19:14 +00:00
|
|
|
|
total_discarded = sum(r.get("discarded_no_reasoning", 0) for r in results)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print("\n🧠 Reasoning Coverage:")
|
2026-02-08 20:19:14 +00:00
|
|
|
|
print("-" * 70)
|
|
|
|
|
|
total_turns = total_reasoning_stats["total_assistant_turns"]
|
|
|
|
|
|
with_reasoning = total_reasoning_stats["turns_with_reasoning"]
|
|
|
|
|
|
without_reasoning = total_reasoning_stats["turns_without_reasoning"]
|
|
|
|
|
|
if total_turns > 0:
|
|
|
|
|
|
pct_with = round(with_reasoning / total_turns * 100, 1)
|
|
|
|
|
|
pct_without = round(without_reasoning / total_turns * 100, 1)
|
|
|
|
|
|
print(f" Total assistant turns: {total_turns:,}")
|
|
|
|
|
|
print(f" With reasoning: {with_reasoning:,} ({pct_with}%)")
|
|
|
|
|
|
print(f" Without reasoning: {without_reasoning:,} ({pct_without}%)")
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(" No assistant turns recorded.")
|
|
|
|
|
|
if total_discarded > 0:
|
|
|
|
|
|
print(f" 🚫 Samples discarded (zero reasoning): {total_discarded:,}")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f"\n💾 Results saved to: {self.output_dir}")
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print(" - Trajectories: trajectories.jsonl (combined)")
|
|
|
|
|
|
print(" - Individual batches: batch_*.jsonl (for debugging)")
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print(f" - Statistics: {self.stats_file.name}")
|
|
|
|
|
|
print(f" - Checkpoint: {self.checkpoint_file.name}")
|
|
|
|
|
|
|
2026-09-02 18:23:51 -07:00
|
|
|
|
def run(self, resume: bool = False):
|
|
|
|
|
|
"""Run the batch pipeline; with *resume*, skip prompts already present in batch files."""
|
2026-09-02 18:44:40 -07:00
|
|
|
|
_banner("🚀 Starting Batch Processing")
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
|
|
|
|
|
if resume and not self._apply_resume():
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# Load existing checkpoint (so resume doesn't clobber prior progress)
|
|
|
|
|
|
checkpoint_data = self._load_checkpoint()
|
|
|
|
|
|
if checkpoint_data.get("run_name") != self.run_name:
|
|
|
|
|
|
checkpoint_data = self._empty_checkpoint()
|
|
|
|
|
|
config = self._worker_config()
|
|
|
|
|
|
|
|
|
|
|
|
# Index tracking is secondary to content matching (backward compatibility).
|
|
|
|
|
|
completed_prompts_set = set(checkpoint_data.get("completed_prompts", []))
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
# Checkpoint writes happen in the parent process; keep a lock for safety.
|
|
|
|
|
|
checkpoint_lock = Lock()
|
|
|
|
|
|
results = self._run_pool(config, checkpoint_data, completed_prompts_set, checkpoint_lock)
|
|
|
|
|
|
total_tool_stats = {}
|
|
|
|
|
|
total_reasoning_stats = dict.fromkeys(_REASONING_KEYS, 0)
|
|
|
|
|
|
for batch_result in results:
|
|
|
|
|
|
_merge_tool_stats(total_tool_stats, batch_result.get("tool_stats", {}))
|
|
|
|
|
|
_merge_reasoning_stats(total_reasoning_stats, batch_result.get("reasoning_stats", {}))
|
|
|
|
|
|
|
|
|
|
|
|
# Final checkpoint is best-effort; incremental writes already happened.
|
|
|
|
|
|
try:
|
|
|
|
|
|
checkpoint_data["completed_prompts"] = sorted(completed_prompts_set)
|
|
|
|
|
|
self._save_checkpoint(checkpoint_data, lock=checkpoint_lock)
|
|
|
|
|
|
except Exception as ckpt_err:
|
|
|
|
|
|
print(f"⚠️ Warning: Failed to save final checkpoint: {ckpt_err}")
|
|
|
|
|
|
|
|
|
|
|
|
for stats in total_tool_stats.values():
|
|
|
|
|
|
total_calls = stats["success"] + stats["failure"]
|
2026-09-02 18:34:38 -07:00
|
|
|
|
stats["success_rate"] = round(stats["success"] / total_calls * 100, 2) if total_calls > 0 else 0.0
|
|
|
|
|
|
stats["failure_rate"] = round(stats["failure"] / total_calls * 100, 2) if total_calls > 0 else 0.0
|
2026-09-02 18:23:51 -07:00
|
|
|
|
kept, batch_files_found = self._combine_batch_files()
|
|
|
|
|
|
final_stats = {
|
|
|
|
|
|
"run_name": self.run_name,
|
|
|
|
|
|
"distribution": self.distribution,
|
|
|
|
|
|
"total_prompts": len(self.dataset),
|
|
|
|
|
|
"total_batches": len(self.batches),
|
|
|
|
|
|
"batch_size": self.batch_size,
|
2026-09-03 09:44:26 -07:00
|
|
|
|
# Snapshot the CLI-level credential/runtime fields BEFORE mutating them so a failed in-place
|
|
|
|
|
|
# agent swap can roll the whole CLI back to the old working model. Otherwise the broken
|
|
|
|
|
|
# credentials staged below leak into the next turn's resolution even though the agent itself
|
|
|
|
|
|
# rolled back (#50163).
|
|
|
|
|
|
# Snapshot CLI-level fields before mutation so a failed in-place swap rolls the whole CLI back
|
|
|
|
|
|
# to the old working model (#50163).
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"model": self.model,
|
|
|
|
|
|
"completed_at": datetime.now().isoformat(),
|
|
|
|
|
|
"duration_seconds": round(time.time() - start_time, 2),
|
|
|
|
|
|
"tool_statistics": total_tool_stats,
|
|
|
|
|
|
"reasoning_statistics": total_reasoning_stats,
|
2026-09-02 18:34:38 -07:00
|
|
|
|
"discarded_no_reasoning": sum(r.get("discarded_no_reasoning", 0) for r in results),
|
2026-09-02 18:23:51 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
with open(self.stats_file, 'w', encoding='utf-8') as f:
|
|
|
|
|
|
json.dump(final_stats, f, indent=2, ensure_ascii=False)
|
|
|
|
|
|
self._print_summary(results, total_tool_stats, total_reasoning_stats, kept, batch_files_found, start_time)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
|
def _split_csv(value: Optional[str]) -> Optional[list[str]]:
|
2026-09-02 18:23:51 -07:00
|
|
|
|
"""Comma-separated CLI string to a list of stripped items; ``None`` when empty."""
|
|
|
|
|
|
return [p.strip() for p in value.split(",")] if value else None
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
|
|
|
|
|
def main(
|
2026-10-08 21:29:48 +02:00
|
|
|
|
dataset_file: str | None = None,
|
|
|
|
|
|
batch_size: int | None = None,
|
|
|
|
|
|
run_name: str | None = None,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
distribution: str = "default",
|
2026-03-07 09:06:37 -08:00
|
|
|
|
model: str = "anthropic/claude-sonnet-4.6",
|
2026-10-08 21:29:48 +02:00
|
|
|
|
api_key: str | None = None,
|
2026-01-29 06:10:24 +00:00
|
|
|
|
base_url: str = "https://openrouter.ai/api/v1",
|
2025-10-06 03:17:58 +00:00
|
|
|
|
max_turns: int = 10,
|
|
|
|
|
|
num_workers: int = 4,
|
|
|
|
|
|
resume: bool = False,
|
|
|
|
|
|
verbose: bool = False,
|
2025-10-08 02:33:58 +00:00
|
|
|
|
list_distributions: bool = False,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
ephemeral_system_prompt: str | None = None,
|
2025-11-07 14:43:44 -05:00
|
|
|
|
log_prefix_chars: int = 100,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
providers_allowed: str | None = None,
|
|
|
|
|
|
providers_ignored: str | None = None,
|
|
|
|
|
|
providers_order: str | None = None,
|
|
|
|
|
|
provider_sort: str | None = None,
|
2026-09-07 03:32:37 -07:00
|
|
|
|
|
2026-10-08 21:29:48 +02:00
|
|
|
|
reasoning_effort: str | None = None,
|
2026-02-08 10:49:24 +00:00
|
|
|
|
reasoning_disabled: bool = False,
|
2026-10-08 21:29:48 +02:00
|
|
|
|
prefill_messages_file: str | None = None,
|
|
|
|
|
|
max_samples: int | None = None,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
):
|
|
|
|
|
|
"""
|
|
|
|
|
|
Run batch processing of agent prompts from a dataset.
|
2025-11-07 14:43:44 -05:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
Args:
|
|
|
|
|
|
dataset_file (str): Path to JSONL file with 'prompt' field in each entry
|
|
|
|
|
|
batch_size (int): Number of prompts per batch
|
|
|
|
|
|
run_name (str): Name for this run (used for output and checkpointing)
|
|
|
|
|
|
distribution (str): Toolset distribution to use (default: "default")
|
|
|
|
|
|
model (str): Model name to use (default: "claude-opus-4-20250514")
|
|
|
|
|
|
api_key (str): API key for model authentication
|
|
|
|
|
|
base_url (str): Base URL for model API
|
|
|
|
|
|
max_turns (int): Maximum number of tool calling iterations per prompt (default: 10)
|
|
|
|
|
|
num_workers (int): Number of parallel worker processes (default: 4)
|
|
|
|
|
|
resume (bool): Resume from checkpoint if run was interrupted (default: False)
|
|
|
|
|
|
verbose (bool): Enable verbose logging (default: False)
|
|
|
|
|
|
list_distributions (bool): List available toolset distributions and exit
|
2025-10-08 02:33:58 +00:00
|
|
|
|
ephemeral_system_prompt (str): System prompt used during agent execution but NOT saved to trajectories (optional)
|
2025-11-07 14:43:44 -05:00
|
|
|
|
log_prefix_chars (int): Number of characters to show in log previews for tool calls/responses (default: 20)
|
2026-01-08 08:57:51 +00:00
|
|
|
|
providers_allowed (str): Comma-separated list of OpenRouter providers to allow (e.g. "anthropic,openai")
|
|
|
|
|
|
providers_ignored (str): Comma-separated list of OpenRouter providers to ignore (e.g. "together,deepinfra")
|
|
|
|
|
|
providers_order (str): Comma-separated list of OpenRouter providers to try in order (e.g. "anthropic,openai,google")
|
|
|
|
|
|
provider_sort (str): Sort providers by "price", "throughput", or "latency" (OpenRouter only)
|
2026-09-07 03:32:37 -07:00
|
|
|
|
|
2026-07-12 00:26:49 -07:00
|
|
|
|
reasoning_effort (str): Reasoning effort: "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra" (default: "medium")
|
2026-02-08 10:49:24 +00:00
|
|
|
|
reasoning_disabled (bool): Completely disable reasoning/thinking tokens (default: False)
|
|
|
|
|
|
prefill_messages_file (str): Path to JSON file containing prefill messages (list of {role, content} dicts)
|
2026-02-08 20:19:14 +00:00
|
|
|
|
max_samples (int): Only process the first N samples from the dataset (optional, processes all if not set)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
|
|
# Basic usage
|
|
|
|
|
|
python batch_runner.py --dataset_file=data.jsonl --batch_size=10 --run_name=my_run
|
|
|
|
|
|
|
|
|
|
|
|
# Resume interrupted run
|
|
|
|
|
|
python batch_runner.py --dataset_file=data.jsonl --batch_size=10 --run_name=my_run --resume
|
|
|
|
|
|
|
|
|
|
|
|
# Use specific distribution
|
|
|
|
|
|
python batch_runner.py --dataset_file=data.jsonl --batch_size=10 --run_name=image_test --distribution=image_gen
|
|
|
|
|
|
|
2026-09-07 03:32:37 -07:00
|
|
|
|
# With disabled reasoning
|
2025-10-08 02:33:58 +00:00
|
|
|
|
python batch_runner.py --dataset_file=data.jsonl --batch_size=10 --run_name=my_run \\
|
2026-09-07 03:32:37 -07:00
|
|
|
|
--reasoning_disabled
|
2026-02-08 10:49:24 +00:00
|
|
|
|
|
|
|
|
|
|
# With prefill messages from file
|
|
|
|
|
|
python batch_runner.py --dataset_file=data.jsonl --batch_size=10 --run_name=my_run \\
|
|
|
|
|
|
--prefill_messages_file=configs/prefill_opus.json
|
2025-10-08 02:33:58 +00:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
# List available distributions
|
|
|
|
|
|
python batch_runner.py --list_distributions
|
|
|
|
|
|
"""
|
|
|
|
|
|
if list_distributions:
|
refactor: remove remaining redundant local imports (comprehensive sweep)
Full AST-based scan of all .py files to find every case where a module
or name is imported locally inside a function body but is already
available at module level. This is the second pass — the first commit
handled the known cases from the lint report; this one catches
everything else.
Files changed (19):
cli.py — 16 removals: time as _time/_t/_tmod (×10),
re / re as _re (×2), os as _os, sys,
partial os from combo import,
from model_tools import get_tool_definitions
gateway/run.py — 8 removals: MessageEvent as _ME /
MessageType as _MT (×3), os as _os2,
MessageEvent+MessageType (×2), Platform,
BasePlatformAdapter as _BaseAdapter
run_agent.py — 6 removals: get_hermes_home as _ghh,
partial (contextlib, os as _os),
cleanup_vm, cleanup_browser,
set_interrupt as _sif (×2),
partial get_toolset_for_tool
hermes_cli/main.py — 4 removals: get_hermes_home, time as _time,
logging as _log, shutil
hermes_cli/config.py — 1 removal: get_hermes_home as _ghome
hermes_cli/runtime_provider.py
— 1 removal: load_config as _load_bedrock_config
hermes_cli/setup.py — 2 removals: importlib.util (×2)
hermes_cli/nous_subscription.py
— 1 removal: from hermes_cli.config import load_config
hermes_cli/tools_config.py
— 1 removal: from hermes_cli.config import load_config, save_config
cron/scheduler.py — 3 removals: concurrent.futures, json as _json,
from hermes_cli.config import load_config
batch_runner.py — 1 removal: list_distributions as get_all_dists
(kept print_distribution_info, not at top level)
tools/send_message_tool.py
— 2 removals: import os (×2)
tools/skills_tool.py — 1 removal: logging as _logging
tools/browser_camofox.py
— 1 removal: from hermes_cli.config import load_config
tools/image_generation_tool.py
— 1 removal: import fal_client
environments/tool_context.py
— 1 removal: concurrent.futures
gateway/platforms/bluebubbles.py
— 1 removal: httpx as _httpx
gateway/platforms/whatsapp.py
— 1 removal: import asyncio
tui_gateway/server.py — 2 removals: from datetime import datetime,
import time
All alias references (_time, _t, _tmod, _re, _os, _os2, _json, _ghh,
_ghome, _sif, _ME, _MT, _BaseAdapter, _load_bedrock_config, _httpx,
_logging, _log, get_all_dists) updated to use the top-level names.
2026-04-21 12:46:31 +05:30
|
|
|
|
from toolset_distributions import print_distribution_info
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print("📊 Available Toolset Distributions")
|
|
|
|
|
|
print("=" * 70)
|
refactor: remove remaining redundant local imports (comprehensive sweep)
Full AST-based scan of all .py files to find every case where a module
or name is imported locally inside a function body but is already
available at module level. This is the second pass — the first commit
handled the known cases from the lint report; this one catches
everything else.
Files changed (19):
cli.py — 16 removals: time as _time/_t/_tmod (×10),
re / re as _re (×2), os as _os, sys,
partial os from combo import,
from model_tools import get_tool_definitions
gateway/run.py — 8 removals: MessageEvent as _ME /
MessageType as _MT (×3), os as _os2,
MessageEvent+MessageType (×2), Platform,
BasePlatformAdapter as _BaseAdapter
run_agent.py — 6 removals: get_hermes_home as _ghh,
partial (contextlib, os as _os),
cleanup_vm, cleanup_browser,
set_interrupt as _sif (×2),
partial get_toolset_for_tool
hermes_cli/main.py — 4 removals: get_hermes_home, time as _time,
logging as _log, shutil
hermes_cli/config.py — 1 removal: get_hermes_home as _ghome
hermes_cli/runtime_provider.py
— 1 removal: load_config as _load_bedrock_config
hermes_cli/setup.py — 2 removals: importlib.util (×2)
hermes_cli/nous_subscription.py
— 1 removal: from hermes_cli.config import load_config
hermes_cli/tools_config.py
— 1 removal: from hermes_cli.config import load_config, save_config
cron/scheduler.py — 3 removals: concurrent.futures, json as _json,
from hermes_cli.config import load_config
batch_runner.py — 1 removal: list_distributions as get_all_dists
(kept print_distribution_info, not at top level)
tools/send_message_tool.py
— 2 removals: import os (×2)
tools/skills_tool.py — 1 removal: logging as _logging
tools/browser_camofox.py
— 1 removal: from hermes_cli.config import load_config
tools/image_generation_tool.py
— 1 removal: import fal_client
environments/tool_context.py
— 1 removal: concurrent.futures
gateway/platforms/bluebubbles.py
— 1 removal: httpx as _httpx
gateway/platforms/whatsapp.py
— 1 removal: import asyncio
tui_gateway/server.py — 2 removals: from datetime import datetime,
import time
All alias references (_time, _t, _tmod, _re, _os, _os2, _json, _ghh,
_ghome, _sif, _ME, _MT, _BaseAdapter, _load_bedrock_config, _httpx,
_logging, _log, get_all_dists) updated to use the top-level names.
2026-04-21 12:46:31 +05:30
|
|
|
|
all_dists = list_distributions()
|
2025-10-06 03:17:58 +00:00
|
|
|
|
for dist_name in sorted(all_dists.keys()):
|
|
|
|
|
|
print_distribution_info(dist_name)
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
print("\n💡 Usage:")
|
|
|
|
|
|
print(" python batch_runner.py --dataset_file=data.jsonl --batch_size=10 \\")
|
|
|
|
|
|
print(" --run_name=my_run --distribution=<name>")
|
|
|
|
|
|
return
|
2026-09-02 18:23:51 -07:00
|
|
|
|
|
2026-09-02 18:34:38 -07:00
|
|
|
|
for invalid, message in (
|
|
|
|
|
|
(not dataset_file, "--dataset_file is required"),
|
|
|
|
|
|
(not batch_size or batch_size < 1, "--batch_size must be a positive integer"),
|
|
|
|
|
|
(not run_name, "--run_name is required"),
|
|
|
|
|
|
):
|
|
|
|
|
|
if invalid:
|
|
|
|
|
|
print(f"❌ Error: {message}")
|
|
|
|
|
|
raise SystemExit(1)
|
2026-08-15 03:47:34 +02:00
|
|
|
|
|
2026-03-07 10:14:19 -08:00
|
|
|
|
# --reasoning_disabled takes priority, then --reasoning_effort, then default (medium)
|
2026-02-08 10:49:24 +00:00
|
|
|
|
reasoning_config = None
|
|
|
|
|
|
if reasoning_disabled:
|
|
|
|
|
|
reasoning_config = {"effort": "none"}
|
|
|
|
|
|
print("🧠 Reasoning: DISABLED (effort=none)")
|
|
|
|
|
|
elif reasoning_effort:
|
2026-07-12 00:26:49 -07:00
|
|
|
|
valid_efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]
|
2026-02-08 10:49:24 +00:00
|
|
|
|
if reasoning_effort not in valid_efforts:
|
|
|
|
|
|
print(f"❌ Error: --reasoning_effort must be one of: {', '.join(valid_efforts)}")
|
2026-08-15 03:47:34 +02:00
|
|
|
|
raise SystemExit(1)
|
2026-02-08 10:49:24 +00:00
|
|
|
|
reasoning_config = {"enabled": True, "effort": reasoning_effort}
|
|
|
|
|
|
print(f"🧠 Reasoning effort: {reasoning_effort}")
|
|
|
|
|
|
prefill_messages = None
|
|
|
|
|
|
if prefill_messages_file:
|
|
|
|
|
|
try:
|
|
|
|
|
|
with open(prefill_messages_file, 'r', encoding='utf-8') as f:
|
|
|
|
|
|
prefill_messages = json.load(f)
|
|
|
|
|
|
if not isinstance(prefill_messages, list):
|
2026-03-07 17:08:09 +00:00
|
|
|
|
print("❌ Error: prefill_messages_file must contain a JSON array of messages")
|
2026-08-15 03:47:34 +02:00
|
|
|
|
raise SystemExit(1)
|
2026-02-08 10:49:24 +00:00
|
|
|
|
print(f"💬 Loaded {len(prefill_messages)} prefill messages from {prefill_messages_file}")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"❌ Error loading prefill messages: {e}")
|
2026-08-15 03:47:34 +02:00
|
|
|
|
raise SystemExit(1)
|
|
|
|
|
|
|
2025-10-06 03:17:58 +00:00
|
|
|
|
try:
|
|
|
|
|
|
runner = BatchRunner(
|
|
|
|
|
|
dataset_file=dataset_file,
|
|
|
|
|
|
batch_size=batch_size,
|
|
|
|
|
|
run_name=run_name,
|
|
|
|
|
|
distribution=distribution,
|
|
|
|
|
|
max_iterations=max_turns,
|
|
|
|
|
|
base_url=base_url,
|
|
|
|
|
|
api_key=api_key,
|
|
|
|
|
|
model=model,
|
|
|
|
|
|
num_workers=num_workers,
|
2025-10-08 02:33:58 +00:00
|
|
|
|
verbose=verbose,
|
2025-11-07 14:43:44 -05:00
|
|
|
|
ephemeral_system_prompt=ephemeral_system_prompt,
|
2026-01-08 08:57:51 +00:00
|
|
|
|
log_prefix_chars=log_prefix_chars,
|
2026-09-02 18:23:51 -07:00
|
|
|
|
providers_allowed=_split_csv(providers_allowed),
|
|
|
|
|
|
providers_ignored=_split_csv(providers_ignored),
|
|
|
|
|
|
providers_order=_split_csv(providers_order),
|
2026-01-08 08:57:51 +00:00
|
|
|
|
provider_sort=provider_sort,
|
2026-09-07 03:32:37 -07:00
|
|
|
|
|
2026-02-08 10:49:24 +00:00
|
|
|
|
reasoning_config=reasoning_config,
|
|
|
|
|
|
prefill_messages=prefill_messages,
|
2026-02-08 20:19:14 +00:00
|
|
|
|
max_samples=max_samples,
|
2025-10-06 03:17:58 +00:00
|
|
|
|
)
|
|
|
|
|
|
runner.run(resume=resume)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"\n❌ Fatal error: {e}")
|
|
|
|
|
|
if verbose:
|
|
|
|
|
|
traceback.print_exc()
|
2026-08-15 03:47:34 +02:00
|
|
|
|
raise SystemExit(1)
|
2025-10-06 03:17:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
fire.Fire(main)
|