#!/usr/bin/env python3 """ roundtable — put one question to a panel of independent models, in parallel. Each lane is a different model, answering the same brief without seeing the others. The product is *disagreement*: where independently-trained models land in the same place, that convergence means something; where they split, that is where you look. Design notes worth reading before changing anything: * There are no long-lived processes. A lane is one HTTP request or one short-lived subprocess. An abandoned run cannot keep billing, because there is nothing left running to bill. * There is no delivery step. Answers come back in the response or the lane failed. Nothing can "succeed" into a place nobody reads. * `harness`, not `model`, decides cost. See CLI lanes below. Usage: roundtable "the brief" cat brief.md | roundtable - roundtable --lanes Auditor,Builder "the brief" roundtable --list roundtable --list --json roster as JSON for tools (no secret refs) roundtable --version roundtable --json > answers.json roundtable --each --run-id ID "..." tag every transcript of this run with ID roundtable --each --revise latest-run round 2 over the newest run, found by run_id rather than by counting files roundtable --synthesize latest:12 --diff readers over a finished run's transcripts; no lane is re-asked roundtable --config DB another store instead of the default roundtable --max-spend 0.50 cat brief.md | roundtable --each -j 8 - eight lanes at a time, each still its own process and its own deadline roundtable --each --revise latest:12 optional second round: each lane sees the locked round-1 answers and may HOLD or REVISE roundtable --discuss latest:12 shared-context discussion seeded from that round: lanes take turns in ONE thread, one lane in flight at a time, then each closes with HOLD or REVISE roundtable --discuss latest:12 --discuss-rounds 3 "focus on the cost claims" cat brief.md | roundtable --discuss new - start cold, no blind round roundtable --converse latest:12 the same flag, by its other name roundtable --each --dry-run - priced pre-flight: per-lane and panel worst-case cost without dispatching (may dial out to load prices; #81). Add --diff and you get the readers too; multiply by discuss-rounds+1 under --discuss. Refuses --dry-run --list and --dry-run --synthesize. Store (#105): the only configuration. Runs read lanes and secrets from it; YAML is retired, and `import-yaml` moves an old config in once. roundtable db init | migrate | doctor [--config DB] roundtable secrets set NAME [--stdin] value from stdin or a no-echo prompt, never argv roundtable secrets check [NAME...] | list | rotate NAME | rm NAME [--force] roundtable secrets rekey roundtable lanes list [--all] | show NAME [--json] | history NAME roundtable lanes add NAME --harness http|cli|acp [--set k=v ...] [--key-entry S] roundtable lanes edit NAME [--set k=v] [--unset k] [--key-entry S] [--notes T] roundtable lanes enable|disable|retire NAME | clone SRC NEW | rename OLD NEW roundtable defaults|globals show | set k=v ... | unset k ... roundtable db export [--out FILE] | import FILE [--merge|--replace] roundtable db backup [--dir DIR] [--keep N] | restore FILE [--force] roundtable import-yaml PATH [--dry-run] [--pull-secrets] one-time move off YAML * Round 1 is blind by construction — a lane cannot see the others because their answers do not exist yet in its process. `--revise` and `--discuss` are the only paths to cross-lane visibility: both replay a *finished* run's transcript(s), so the openings each lane receives are locked before any lane reads them. Answers after either are not independent and the report says so; convergence there is persuasion, not evidence. """ from __future__ import annotations import argparse import concurrent.futures as cf import contextlib import datetime as dt import email.utils import getpass import hashlib import json import os import re import shutil import signal import socket import sqlite3 import ssl import subprocess import tempfile import sys import threading import time import urllib.error import urllib.parse import urllib.request import uuid from pathlib import Path # Semantic version. Bump it in the PR that changes behaviour: patch for a fix, # minor for a new flag or mode, major for a change that breaks a caller. __version__ = "1.4.0" TRANSCRIPT_DIR = Path.home() / ".local" / "share" / "flatline-roundtable" / "transcripts" RUN_ID_RE = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}") def safe_route(base_url: str | None) -> str: """A base_url fit for --list --json: scheme, host, port and path only. Config forbids secrets in base_url, but nothing enforces it; a token in userinfo or the query string must not ride out through tool-facing JSON. """ if not base_url: return "" parts = urllib.parse.urlsplit(str(base_url)) host = parts.hostname or "" if ":" in host: host = f"[{host}]" try: port = parts.port except ValueError: port = None netloc = host + (f":{port}" if port else "") return urllib.parse.urlunsplit((parts.scheme, netloc, parts.path, "", "")) def new_run_id() -> str: """A run id that sorts by time and cannot collide across same-second runs.""" return dt.datetime.now().strftime("%Y%m%d-%H%M%S-") + os.urandom(4).hex() # Honours XDG_CACHE_HOME, which is both correct on Linux and what lets the tests # point the caches somewhere disposable instead of writing to a real one. CACHE_DIR = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "flatline-roundtable" PRICING_CACHE = CACHE_DIR / "pricing.json" TOKENIZER_CACHE = CACHE_DIR / "tokens.json" PRICING_TTL = 24 * 3600 OPENROUTER_MODELS = "https://openrouter.ai/api/v1/models" # Fallback when a model has never been measured. Deliberately pessimistic: # ~4 chars/token overestimates for English prose, which is the safe direction # for a budget check. # # Shipping a real tokenizer was considered and rejected. tiktoken only covers # OpenAI, and this roster spans DeepSeek, Mistral, Gemini, Qwen, Cohere and # MiniMax -- each with its own vocabulary, so one tokenizer would be wrong for # almost every lane while adding a dependency. Instead the tool measures itself: # every http response reports usage.prompt_tokens for a prompt whose length we # know exactly, so the real ratio is observable for free. Same principle as # load_pricing -- prefer measured reality to a hand-maintained constant. CHARS_PER_TOKEN = 4 # A measured ratio is shrunk by this before use, so the estimate keeps erring # high. The budget check exists to refuse a run that would overspend; an # estimate that came in under the truth would defeat it. CALIBRATION_SAFETY = 0.9 # One run of one lane is not a ratio. Below this, keep using the constant. MIN_CALIBRATION_SAMPLES = 3 # Keys a lane's `extra_body` must never set: they define the request itself, and # silently overwriting them turns a config typo into a call you did not intend. EXTRA_BODY_DENY = {"model", "messages", "stream", "max_tokens"} # Ceiling on a vendor-supplied Retry-After, in seconds. Free tiers advertise 60s # windows; a cap below that sleeps, wakes inside the window that has not # reopened, and burns the retry. The old value was 30, which made "honour # Retry-After" a no-op for precisely the lanes that depend on it. RETRY_AFTER_CAP = 90 # Base for linear backoff when the vendor gives us nothing to go on. RETRY_BACKOFF = 3 # Scrubbed from every CLI lane's environment. # # THIS IS LOAD-BEARING. `claude -p` authenticates against a Max/Pro subscription # via OAuth and costs nothing -- but ONLY if ANTHROPIC_API_KEY is unset. If it is # present in the ambient shell, the CLI bills prepaid console credits instead, # which are billed separately from the subscription. A free lane silently becomes # a paid one, with no error and no visible difference in the output. # # The same shape applies to the other vendors' CLIs. # # An API key is NOT the only way a subscription lane becomes metered, which is # why the patterns below exist alongside this list. CLAUDE_CODE_USE_BEDROCK and # CLAUDE_CODE_USE_VERTEX route `claude` to AWS/GCP metered billing using ambient # cloud credentials, with no API key involved at all -- a key-only denylist does # nothing about them. A *_BASE_URL points the CLI at an arbitrary proxy. # CSI sequences (colour, cursor moves) and the OSC form used for titles and # hyperlinks. NO_COLOR=1 covers most CLIs; this covers the ones it does not. ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)") SCRUB_ENV = ( "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "OPENAI_API_KEY", "OPENAI_BASE_URL", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", ) # An explicit list goes stale the moment a vendor adds a billing route, and the # roster already spans vendors whose variables are not named here at all. These # catch the shapes rather than the names. # # Over-scrubbing makes a lane fail loudly; under-scrubbing costs money silently. # In this tool that trade is not close, so the patterns are deliberately broad. SCRUB_ENV_PATTERNS = ( re.compile(r"_API_KEY$"), re.compile(r"_AUTH_TOKEN$"), re.compile(r"_BASE_URL$"), re.compile(r"^CLAUDE_CODE_USE_"), ) def child_env(lane: dict) -> dict: """The environment a subprocess lane runs in. Shared by the cli and acp harnesses -- they carried byte-identical copies of this, which is one more place for the two to drift apart on a rule where drifting costs money. A lane may name extra variables via `scrub_env:`, so adding a lane for a new vendor's CLI does not require editing this file to stay safe. """ drop = set(SCRUB_ENV) | set(lane.get("scrub_env") or ()) env = { k: v for k, v in os.environ.items() if k not in drop and not any(p.search(k) for p in SCRUB_ENV_PATTERNS) } env["NO_COLOR"] = "1" return env def die(msg: str) -> "NoReturn": # noqa: F821 sys.exit(f"roundtable: {msg}") # --------------------------------------------------------------------------- # # pricing # --------------------------------------------------------------------------- # def load_pricing(lanes: list[dict]) -> dict[str, tuple[float, float]]: """Per-token (prompt, completion) prices, keyed by model id. Hand-maintained prices in config go stale silently the moment a vendor changes them, and a stale number is worse than none because it reads as authoritative. Pull the real table instead, cached for a day so a run does not depend on the network. Config `price_per_mtok` still wins if set — it is the escape hatch for vendors with no price endpoint. """ if not any(l.get("vendor") == "openrouter" for l in lanes): return {} try: if PRICING_CACHE.exists() and time.time() - PRICING_CACHE.stat().st_mtime < PRICING_TTL: raw = json.loads(PRICING_CACHE.read_text()) else: with urllib.request.urlopen(OPENROUTER_MODELS, timeout=20) as r: raw = json.load(r) PRICING_CACHE.parent.mkdir(parents=True, exist_ok=True) PRICING_CACHE.write_text(json.dumps(raw)) except Exception: # Never fail a run over pricing. Estimates degrade to config values. return {} out = {} for m in raw.get("data", []): pr = m.get("pricing") or {} try: out[m["id"]] = (float(pr.get("prompt", 0)), float(pr.get("completion", 0))) except (TypeError, ValueError): continue return out def load_calibration() -> dict: """Observed chars-per-token per model, accumulated across past runs.""" try: return json.loads(TOKENIZER_CACHE.read_text()) except Exception: # A missing or corrupt cache must never fail a run: the constant is a # perfectly serviceable fallback, it is just wider than it needs to be. return {} def chars_per_token(model: str | None, calib: dict) -> float: """Measured ratio for this model, or the pessimistic constant.""" rec = calib.get(model or "") if not rec or rec.get("samples", 0) < MIN_CALIBRATION_SAMPLES: return CHARS_PER_TOKEN tokens = rec.get("tokens", 0) if tokens <= 0: return CHARS_PER_TOKEN # Shrink toward more-tokens-per-char so the estimate stays on the safe side. return max(1.0, (rec["chars"] / tokens) * CALIBRATION_SAFETY) def record_calibration(results: list[dict], prompt: str, lanes: list[dict]) -> None: """Fold this run's real prompt_tokens back into the cache. Only http lanes report usage, and only the prompt side is measurable this way -- the completion side is already bounded by max_tokens, which is the worst case the budget check needs anyway. """ by_name = {l["name"]: l for l in lanes} calib = load_calibration() touched = False for r in results: usage = r.get("usage") or {} ptok = usage.get("prompt_tokens") model = r.get("model") lane = by_name.get(r.get("lane")) if not (ptok and model and lane): continue chars = len(prompt) + len(lane.get("personality") or "") if chars <= 0: continue rec = calib.setdefault(model, {"chars": 0, "tokens": 0, "samples": 0}) rec["chars"] += chars rec["tokens"] += int(ptok) rec["samples"] += 1 touched = True if not touched: return try: TOKENIZER_CACHE.parent.mkdir(parents=True, exist_ok=True) TOKENIZER_CACHE.write_text(json.dumps(calib, indent=2, sort_keys=True)) except OSError: pass # a cache we cannot write is a slightly wider estimate, nothing more def lane_prices(lane: dict, table: dict) -> tuple[float, float]: """(prompt, completion) per-token price for a lane, or (0, 0) if free/unknown.""" if lane.get("price_per_mtok") is not None: # explicit override p = float(lane["price_per_mtok"]) / 1_000_000 return (p, p) if lane["harness"] in ("cli", "acp"): # subscription — no marginal cost return (0.0, 0.0) return table.get(lane.get("model"), (0.0, 0.0)) def spend_report(spent: float, estimate: float, budget, lanes: list[dict], table: dict) -> dict: """The run's spend, machine-readable (#79): what the human summary prints, plus the lanes whose cost could not be priced. When `unpriced` is non-empty, `actual` is a lower bound, not the bill.""" return {"actual": round(spent, 6), "estimated_worst_case": round(estimate, 6), "budget": budget, "unpriced": [l["name"] for l in lanes if not lane_price_known(l, table)]} def cmd_dry_run(a, cfg, lanes, est_prompt, prices, calib, defaults, estimate, brief_on_record) -> int: """Priced pre-flight (issue #81). Exit 0 without dispatching anything. `estimate` is whatever `estimate_run` (+ synthesis, *discuss passes) just produced for the budget gate above. The dry-run path uses the same number, so the gate and the human/JSON report never disagree; only the disposition differs (the gate dies, the dry-run reports). `spend_report` already carries the same `estimated_worst_case` key for post-run (#79), so dry-run shares that name rather than a parallel `panel_total` (#131 dry-run / post-run shape compat). `--list` was the offline roster view before this existed; it still is. A `--each --diff` refusal (issue #74) inherits from main(): the synthesis step is folded in here as elsewhere, but `--each --diff` is still refused. """ retries = int(cfg.get("retries", 1)) attempts = 1 + max(0, retries) discuss_factor = (a.discuss_rounds + 1) if a.discuss else 1 # Per-lane breakdown. `estimate_run` collapses to a total; the dry-run # user wants to see which lane is the driver and whether any are unpriced. per_lane = [] for l in lanes: pin, pout = lane_prices(l, prices) priced = lane_price_known(l, prices) in_tok = ((len(est_prompt) + len(l.get("personality") or "")) / chars_per_token(l.get("model"), calib)) out_tok = float(l.get("max_tokens", defaults.get("max_tokens", 2000))) p_cost = in_tok * pin * attempts c_cost = out_tok * pout cost = p_cost + c_cost # `free` requires being priced at (0, 0). An unknown price that # happens to fall through to (0, 0) is fail-open (#72) — call it # unpriced, not free, so the UI can render it as unknown. free = priced and pin == 0.0 and pout == 0.0 # `--discuss` already has each lane speak once per pass and once to # close, so per-lane cost is multiplied here so the JSON sum equals # the panel total. The gate does the same on `estimate` above; here # we mirror it on each entry to keep `sum(lanes[].cost)` honest. per_lane.append({ "name": l["name"], "model": l.get("model") or "", "vendor": l.get("vendor") or "", "harness": l["harness"], "route": safe_route(l.get("base_url")) or l.get("command") or "", "prompt_tokens": int(round(in_tok * attempts * discuss_factor)), "completion_tokens": int(round(out_tok * discuss_factor)), "prompt_cost": round(p_cost * discuss_factor, 6), "completion_cost": round(c_cost * discuss_factor, 6), "cost": round(cost * discuss_factor, 6), "free": free, "priced": priced, }) if a.diff: # Same fold the budget gate applied; kept here so the JSON shape and # human output include the readers and their cost. Synthesis is # priced against the ORIGINAL brief on record, not the focus text in # a revision round — same rule the gate already uses. synth_cost = estimate_synthesis( lanes, brief_on_record, prices, defaults, calib, cfg.get("synthesizer"), int(cfg.get("synthesizers", 2))) readers = [r["name"] for r in pick_synthesizers( lanes, cfg.get("synthesizer"), int(cfg.get("synthesizers", 2)))] # `--discuss` again: the readers participate in the discussion too, # so their cost is folded by the same pass count to keep the total # honest. `--panel --diff` alone (no --discuss) leaves `discuss_factor` # at 1. synthesis = {"cost": round(synth_cost * discuss_factor, 6), "readers": readers} else: synthesis = None passes = (a.discuss_rounds + 1) if a.discuss else None budget = a.max_spend if a.max_spend is not None else cfg.get("budget_usd") unpriced = [l["name"] for l in lanes if not lane_price_known(l, prices)] # `would_exceed_budget` is the same comparison the gate dies on: priced # estimate vs budget. Under unpriced+budget we cannot tell (#72), so # `null` rather than a misleading `false` that would read as "safe". if unpriced and budget is not None: would_exceed = None else: would_exceed = budget is not None and estimate > budget if a.json: out = { "mode": ("discuss" if a.discuss else "revise" if a.revise else "panel" if a.panel else "each"), "lanes": per_lane, "estimated_worst_case": round(estimate, 6), "synthesis": synthesis, "discuss_passes": passes, "budget": budget, "would_exceed_budget": would_exceed, "unpriced": unpriced, "currency": "USD", } print(json.dumps(out, indent=2, sort_keys=True)) return 0 # Human output. Match the column widths of `roundtable --list` so the two # read side by side; the cost lives in a fourth column to the right. label_map = {"http": "http", "cli": "cli ", "acp": "acp "} print(f"Pre-flight estimate for {len(lanes)} lane(s) — no dispatch.") for r in per_lane: route_h = label_map.get(r["harness"], r["harness"]) if not r["priced"]: tag = "unpriced" elif r["free"]: tag = "free" else: tag = f"${r['cost']:.4f}" print(f" [{route_h:<4}] {r['name']:<18} {str(r['model'] or '-'):<42} {tag}") print(f"\n panel worst case: ${estimate:.4f}") if synthesis is not None: n = len(synthesis["readers"]) s = "reader" if n == 1 else "readers" print(f" synthesis ({n} {s}): ${synthesis['cost']:.4f}") if passes is not None: print(f" discuss passes: {passes}") if budget is not None: if would_exceed is None: verdict = "cannot tell — unpriced lanes; budget not yet binding" elif would_exceed: verdict = "would exceed budget — dispatch would refuse" else: verdict = "within budget on dispatch" print(f" budget ${budget:.2f}: {verdict}") if unpriced: print("\n unpriced lanes (estimate is a lower bound, not the bill): " + ", ".join(unpriced)) print(" set price_per_mtok on the lane or add vendor: openrouter " "so the price table covers it") # `load_pricing` can fail (offline, catalog stale) and return {}. http lanes # without an explicit price then report unpriced. if not prices and any(l["harness"] == "http" for l in lanes): print("\n prices not loaded (offline?); http lanes are unpriced") return 0 def fill_costs(results: list[dict], lanes: list[dict], table: dict) -> None: """Give every result a `cost` (#79). ask() sets it only when it priced a usage block. A lane that is free or on a subscription is 0.0. Anything else is null, meaning unknown: an unpriced model, or no usage returned. Null is the honest value there. A zero would read as free.""" for r, l in zip(results, lanes): if r is None or "cost" in r: continue free = lane_price_known(l, table) and lane_prices(l, table) == (0.0, 0.0) r["cost"] = 0.0 if free else None def lane_price_known(lane: dict, table: dict) -> bool: """Whether lane_prices' (0, 0) would mean "free" rather than "no idea" (#72). lane_prices collapses both to zero, which is fine for reporting but is fail-open for the budget gate: an http lane whose model id is missing from the table -- every direct Mistral/DeepSeek/local endpoint, or a typo -- estimated to $0.00 and so could never trip --max-spend. Free has three legitimate shapes; anything else on a metered harness is unknown. """ if lane.get("price_per_mtok") is not None: # explicit, including 0 return True if lane["harness"] in ("cli", "acp"): # subscription return True model = str(lane.get("model") or "") return model.endswith(":free") or model in table def estimate_run(lanes: list[dict], prompt: str, table: dict, defaults: dict, calib: dict | None = None, retries: int = 0) -> float: """Worst-case cost BEFORE dispatch (issue #4). Enforcing a budget only after responses return reports an overrun rather than preventing one -- the money is already spent by then. Assume every lane answers to its full max_tokens, which is the ceiling a run can actually hit. The prompt is charged (1 + retries) times, because http_lane re-issues on a 200-carrying-an-error and on an empty answer, and both bill the prompt. This was previously ignored entirely: with the shipped default of retries: 3 the estimate could understate that term by 300%, while CALIBRATION_SAFETY shaved a further 10% off it in the name of staying conservative. Only the prompt side multiplies. A retry happens precisely when no usable completion came back, so the completion ceiling is still one max_tokens. """ calib = calib or {} attempts = 1 + max(0, int(retries)) total = 0.0 for l in lanes: pin, pout = lane_prices(l, table) if not (pin or pout): continue in_tok = (len(prompt) + len(l.get("personality") or "")) / chars_per_token( l.get("model"), calib) out_tok = float(l.get("max_tokens", defaults.get("max_tokens", 2000))) total += in_tok * pin * attempts + out_tok * pout return total # --------------------------------------------------------------------------- # # config # --------------------------------------------------------------------------- # # The store load_config() last read. fetch_keys() decrypts from the same file, # so `--config` names one store for both halves of a run, and for its --each # children, which are handed the same --config. DB_PATH: Path | None = None def load_config(path: Path) -> dict: """The live roster from the store at `path`, validated (#109). YAML is retired: the store is the only configuration. A YAML path is refused with the one command that moves it in. """ global DB_PATH if path.suffix.lower() in (".yaml", ".yml"): die(f"{path} is a YAML config, and YAML is retired — the store is the config now.\n" f" Move it in once with: roundtable import-yaml {path}") if not path.exists(): die(f"no store at {path}\n" f" create one with: roundtable db init\n" f" then add lanes: roundtable import-yaml OLD.yaml | db import FILE | lanes add") conn = open_roster(path) try: cfg = store_roster(conn) finally: conn.close() DB_PATH = path return validate_config(cfg, str(path)) def read_yaml_config(path: Path) -> tuple[dict, str]: """The retired YAML reader, kept for `import-yaml` only. PyYAML is imported here and nowhere else: a run never needs it, and a host that has already imported its YAML does not need it installed at all. """ try: import yaml except ImportError: die("import-yaml needs PyYAML for this one-time import — pip install pyyaml") if not path.exists(): die(f"no YAML at {path}") text = path.read_text() try: cfg = yaml.safe_load(text) or {} except yaml.YAMLError as e: die(f"{path} is not valid YAML: {e}") return cfg, text def validate_config(cfg: dict, where: str) -> dict: """Validate a roster dict and apply `defaults` to each lane. Kept apart from the read so a roster from any source -- the store, a YAML file on its way in through import-yaml, a `db import` file -- passes through exactly one set of rules. `where` names the source in errors. """ if not isinstance(cfg, dict): die(f"{where} is not a mapping") if not isinstance(cfg.get("lanes"), list) or not cfg["lanes"]: die(f"{where} defines no lanes") defaults = cfg.get("defaults") or {} # Turning verification off has to be a per-lane decision someone typed. As a # default it would quietly cover every lane, OpenRouter included -- the # global bypass #78 exists to make unnecessary. if "insecure" in defaults: die("insecure may not be a default — set it on the one lane that needs it") seen: set[str] = set() lanes = [] for i, raw in enumerate(cfg["lanes"]): if not isinstance(raw, dict): die(f"lane #{i + 1} is not a mapping") lane = {**defaults, **raw} name = lane.get("name") # YAML 1.1 reads Off/No as False and Yes/On as True, so an unquoted # lane called `Off` arrives here as a boolean and the truthiness check # below reported "has no name" -- an error naming neither the cause nor # the fix, for a plausible name for a parked lane. if name is not None and not isinstance(name, str): # The original text is already gone -- the parser handed us a bool -- # so name the rule rather than echoing a useless {name!r}. die(f"lane #{i + 1}: name must be a string, got the boolean {name!r}. " f"YAML reads Off/No as false and Yes/On as true; " f"quote the name to keep it a string.") if not name: die(f"lane #{i + 1} has no name") if name in seen: die(f"duplicate lane name {name!r} — names must be unique") seen.add(name) harness = lane.get("harness") if harness not in ("http", "cli", "acp"): die(f"{name}: harness must be 'http', 'cli' or 'acp', got {harness!r}") if harness == "http": for req in ("model", "base_url"): if not lane.get(req): die(f"{name}: http lane needs {req}") elif harness == "acp": if not lane.get("command"): die(f"{name}: acp lane needs a command") else: if not lane.get("command"): die(f"{name}: cli lane needs a command") if not lane.get("args"): die(f"{name}: cli lane needs args (use '{{prompt}}' or stdin: true)") # The line above only proved args is non-empty. Without one of these # two, the brief is never delivered: cmd carries no prompt, stdin is # DEVNULL, and the personality-prepend finds nothing to attach to. # The dangerous outcome is not the CLI erroring -- that fails loudly. # It is a CLI that answers an empty prompt with something plausible, # producing a lane that counts as a vote without having seen the # question. if "{prompt}" not in lane["args"] and not lane.get("stdin"): die(f"{name}: cli lane would send no prompt — " f"put '{{prompt}}' in args, or set stdin: true") if lane.get("lineage") is not None and not isinstance(lane["lineage"], str): die(f"{name}: lineage must be a string naming a model family") if lane.get("rpm") is not None: try: rpm = float(lane["rpm"]) except (TypeError, ValueError): die(f"{name}: rpm must be a number, got {lane['rpm']!r}") if rpm <= 0: die(f"{name}: rpm must be greater than 0 (omit it for no pacing)") bad = EXTRA_BODY_DENY & set((lane.get("extra_body") or {}).keys()) if bad: die(f"{name}: extra_body may not set {', '.join(sorted(bad))}") # TLS (#78). A default ca_bundle is fine -- a cli/acp lane simply has no # TLS to apply it to -- but naming one on the lane itself is a no-op the # operator meant to do something, so it fails. if harness != "http": for k in ("ca_bundle", "insecure"): if k in raw: die(f"{name}: {k} applies to http lanes only") if lane.get("ca_bundle") is not None and ( not isinstance(lane["ca_bundle"], str) or not lane["ca_bundle"]): die(f"{name}: ca_bundle must be a path to a PEM file") if lane.get("insecure") is not None and not isinstance(lane["insecure"], bool): die(f"{name}: insecure must be true or false, got {lane['insecure']!r}") if lane.get("insecure") and lane.get("ca_bundle"): die(f"{name}: set ca_bundle or insecure, not both") lanes.append(lane) cfg["lanes"] = lanes return cfg # --------------------------------------------------------------------------- # # secrets # --------------------------------------------------------------------------- # def fetch_keys(lanes: list[dict]) -> dict[str, str]: """Resolve every secret ONCE, before fan-out. Doing this inside the worker threads instead means N concurrent reads, and -- because the DB key lives in `pass` -- N `pass show` calls against one gpg-agent, which either serialise behind a single pinentry or, in a non-tty context, storm and fail. Resolve up front, deduped, while still single-threaded, so one clear error replaces N identical ones. Values come from the store (#109), decrypted in memory only. `pass` is now needed for one thing, the DB key: one `pass show` per process, where there used to be one per distinct entry. The first-line rule that kept `pass` metadata out of an Authorization header is applied when a value is stored (`secrets set`, `import-yaml --pull-secrets`). """ entries = {l["key_entry"] for l in lanes if l.get("key_entry")} if not entries: return {} from cryptography.exceptions import InvalidTag conn, key = open_store(DB_PATH or DEFAULT_DB) keys: dict[str, str] = {} try: for entry in sorted(entries): row = conn.execute("SELECT ciphertext, nonce, key_id FROM secrets WHERE name = ?", (entry,)).fetchone() if row is None: die(f"no secret {entry!r} in the store\n" f" create it with: roundtable secrets set {entry}") try: value = decrypt_secret(key, entry, *row) except InvalidTag: die(f"secret {entry!r} does not decrypt — `roundtable secrets check` " f"lists the damaged rows") if not value: die(f"secret {entry!r} is empty") keys[entry] = value finally: conn.close() return keys # --------------------------------------------------------------------------- # # store (#105) # # One SQLite file per host holding the lane roster (#108), the lane secrets # (#107) and, later, metrics. It is the only configuration: load_config() # reads the roster from it and fetch_keys() decrypts from it (#109). # # Encryption is column-level: secrets.ciphertext is AES-256-GCM, everything else # is plain SQLite so `sqlite3` can still query it. SQLCipher was rejected -- it # needs a compiled binding on every host and in CI, and its key would live in # `pass` anyway (epic #105, decision 7). # --------------------------------------------------------------------------- # DATA_DIR = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") / "flatline-roundtable" DEFAULT_DB = DATA_DIR / "roundtable.db" # The name callers already use (skill/toolpanel.py) for "the config a run reads". DEFAULT_CONFIG = DEFAULT_DB DB_KEY_ENTRY = "flatline-roundtable/db-key" # Tests and CI have no gpg-agent. This names a FILE holding the key, never the # key itself: an env var carrying the value would leak into every child process # and every `ps e`. DB_KEY_FILE_ENV = "ROUNDTABLE_DB_KEY_FILE" KCV_PLAINTEXT = b"flatline-roundtable-kcv" SECRET_NAME_RE = re.compile(r"^[A-Za-z0-9._@+/-]+$") # Migration N takes user_version N-1 to N. Append, never edit a shipped one: a # host that already ran it will not run it again. # # SQLite 3.34 is the floor (pluto), so no STRICT, RETURNING or DROP COLUMN. # # lanes.key_entry deliberately has no REFERENCES secrets(name). A lane can be # imported before its secret is set -- `db doctor` reports that case -- and a # foreign key would refuse the lane instead. `secrets rm` checks references # itself. MIGRATIONS = [ """ CREATE TABLE meta (key TEXT PRIMARY KEY, value BLOB); CREATE TABLE globals (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE defaults (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE secrets ( name TEXT PRIMARY KEY, ciphertext BLOB NOT NULL, nonce BLOB NOT NULL, key_id TEXT NOT NULL, vendor TEXT, notes TEXT, created_at TEXT NOT NULL, rotated_at TEXT, last_used_at TEXT ); CREATE TABLE lanes ( lane_id TEXT PRIMARY KEY, name TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1, retired_at TEXT, notes TEXT, key_entry TEXT, config TEXT NOT NULL DEFAULT '{}', harness TEXT GENERATED ALWAYS AS (json_extract(config, '$.harness')) VIRTUAL, vendor TEXT GENERATED ALWAYS AS (json_extract(config, '$.vendor')) VIRTUAL, model TEXT GENERATED ALWAYS AS (json_extract(config, '$.model')) VIRTUAL, version INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE UNIQUE INDEX lanes_live_name ON lanes(lower(name)) WHERE retired_at IS NULL; CREATE TABLE lane_versions ( id INTEGER PRIMARY KEY, lane_id TEXT NOT NULL REFERENCES lanes(lane_id), version INTEGER NOT NULL, config TEXT NOT NULL, config_sha256 TEXT NOT NULL, key_entry TEXT, changed_at TEXT NOT NULL, changed_by TEXT, reason TEXT, UNIQUE (lane_id, version) ); CREATE TABLE lane_aliases ( old_name TEXT PRIMARY KEY, lane_id TEXT NOT NULL REFERENCES lanes(lane_id), renamed_at TEXT NOT NULL ); """, # 2 (#108): roster order. YAML order is the order --list shows and lanes run # in. rowid is not a substitute: VACUUM may renumber the rowids of a table # without an INTEGER PRIMARY KEY. """ ALTER TABLE lanes ADD COLUMN position INTEGER """, ] SCHEMA_VERSION = len(MIGRATIONS) def _now() -> str: return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds") def _aesgcm(): # Imported here, not at the top: a run whose lanes name no secret -- cli and # acp lanes, a local llama.cpp -- must still work on a host without it. try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: die("the store needs the `cryptography` package — pip install cryptography") return AESGCM def key_id(key: bytes) -> str: """A public fingerprint of the DB key: safe to print, store and compare.""" return hashlib.sha256(key).hexdigest()[:16] def _secret_aad(name: str, kid: str) -> bytes: # Binding the name means a ciphertext copied onto another row fails to # decrypt rather than handing lane B lane A's key. Binding the key id means # a row that missed a rekey fails loudly instead of decrypting as garbage. return f"secret\0{name}\0{kid}".encode() def _kcv_aad(kid: str) -> bytes: return f"kcv\0{kid}".encode() def _check_private(path: Path, what: str) -> None: mode = path.stat().st_mode & 0o777 if mode & 0o077: die(f"{what} {path} is mode {mode:04o}; it must be 0600 — chmod 600 {path}") def _parse_key(text: str, where: str) -> bytes: raw = text.strip().splitlines()[0].strip() if text.strip() else "" try: key = bytes.fromhex(raw) except ValueError: key = b"" if len(key) != 32: die(f"{where} does not hold a DB key (expected 64 hex characters)") return key def _pass_store_dir() -> Path: return Path(os.environ.get("PASSWORD_STORE_DIR") or Path.home() / ".password-store") def _pass_show(entry: str) -> str | None: """First-line-safe `pass show`; None when the entry is absent or pass is.""" if not shutil.which("pass"): return None try: p = subprocess.run(["pass", "show", entry], capture_output=True, text=True, timeout=30) except subprocess.TimeoutExpired: die(f"`pass show {entry}` timed out — is gpg-agent waiting on a passphrase?") return p.stdout if p.returncode == 0 else None def load_db_key() -> bytes: """The DB key: $ROUNDTABLE_DB_KEY_FILE, else `pass`, else die. One `pass show` per process -- the same reason fetch_keys() resolves before fan-out -- and never an interactive passphrase, which would hang a non-tty `--each` child. """ kf = os.environ.get(DB_KEY_FILE_ENV) if kf: path = Path(kf) if not path.exists(): die(f"${DB_KEY_FILE_ENV} names {path}, which does not exist") _check_private(path, "DB key file") return _parse_key(path.read_text(), str(path)) out = _pass_show(DB_KEY_ENTRY) if out is None: if not shutil.which("pass"): die(f"no DB key: `pass` is not installed and ${DB_KEY_FILE_ENV} is unset") die(f"no DB key in pass entry {DB_KEY_ENTRY!r}\n" f" create the store (and its key) with: roundtable db init") return _parse_key(out, f"pass entry {DB_KEY_ENTRY!r}") def store_db_key(key: bytes, entry: str = DB_KEY_ENTRY) -> None: """Write a key where load_db_key() will find it. The value goes on stdin, never argv.""" kf = os.environ.get(DB_KEY_FILE_ENV) if kf: path = Path(kf + entry[len(DB_KEY_ENTRY):]) # `.prev` rides along as a suffix fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as f: f.write(key.hex() + "\n") os.chmod(path, 0o600) return if not shutil.which("pass"): die(f"cannot store the DB key: `pass` is not installed and ${DB_KEY_FILE_ENV} is unset") p = subprocess.run(["pass", "insert", "-m", "-f", entry], input=key.hex() + "\n", capture_output=True, text=True, timeout=60) if p.returncode != 0: die(f"`pass insert {entry}` failed: {p.stderr.strip() or p.returncode}") def open_db(path: Path, create: bool = False) -> sqlite3.Connection: """Open the store with the settings every caller relies on. WAL + busy_timeout is what lets `--each -j N` children share one file: a reader never blocks a writer, and a writer waits rather than failing. """ if not path.exists(): if not create: die(f"no store at {path}\n create it with: roundtable db init") path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) # Create the file 0600 before SQLite touches it. SQLite gives -wal and # -shm the database file's mode, so this one call covers all three. os.close(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)) _check_private(path, "store") # timeout= installs the busy handler before the first statement; the PRAGMA # below comes too late to cover `journal_mode=WAL`, which takes a lock and # races when `--each -j N` children open the store together. conn = sqlite3.connect(path, isolation_level=None, timeout=30) conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA synchronous=NORMAL") conn.execute("PRAGMA foreign_keys=ON") conn.execute("PRAGMA busy_timeout=30000") return conn def schema_version(conn: sqlite3.Connection) -> int: return conn.execute("PRAGMA user_version").fetchone()[0] def migrate(conn: sqlite3.Connection) -> tuple[int, int]: """Apply pending migrations, each in its own transaction. Idempotent, also against a concurrent migrator: the version is read under the write lock, so a caller that waited on another one's migration skips it rather than re-running CREATE TABLE.""" before = None while True: conn.execute("BEGIN IMMEDIATE") n = schema_version(conn) if before is None: before = n # as seen under the lock, so the report is honest too if n > SCHEMA_VERSION: conn.execute("ROLLBACK") die(f"store is at schema {n}, newer than this roundtable ({SCHEMA_VERSION}) — " f"update roundtable before touching it") if n == SCHEMA_VERSION: conn.execute("COMMIT") break try: # Not executescript(): it COMMITs first, which would split a # migration across transactions. for stmt in (s.strip() for s in MIGRATIONS[n].split(";")): if stmt: conn.execute(stmt) conn.execute(f"PRAGMA user_version = {n + 1}") conn.execute("COMMIT") except BaseException: conn.execute("ROLLBACK") raise return before, schema_version(conn) def _meta(conn: sqlite3.Connection, key: str): row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone() return row[0] if row else None def _write_kcv(conn: sqlite3.Connection, key: bytes) -> None: kid = key_id(key) nonce = os.urandom(12) ct = _aesgcm()(key).encrypt(nonce, KCV_PLAINTEXT, _kcv_aad(kid)) conn.executemany("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", [("key_id", kid), ("kcv", ct), ("kcv_nonce", nonce)]) def verify_db_key(conn: sqlite3.Connection, key: bytes) -> None: """Die unless `key` is the one this store was written with. Runs before any secret row is read, so a wrong key produces one clear message instead of N authentication failures that look like corruption. """ want = _meta(conn, "key_id") if want is None: die("store has no key-check value — was it created with `roundtable db init`?") have = key_id(key) if have != want: die(f"DB key (id {have}) does not unlock this store (id {want})") from cryptography.exceptions import InvalidTag try: pt = _aesgcm()(key).decrypt(_meta(conn, "kcv_nonce"), _meta(conn, "kcv"), _kcv_aad(want)) except InvalidTag: pt = None if pt != KCV_PLAINTEXT: die(f"DB key id {have} matches, but the key-check value does not decrypt — " f"the store's meta table is damaged") def open_store(path: Path) -> tuple[sqlite3.Connection, bytes]: """An initialised, migrated store plus its verified key.""" conn = open_roster(path) try: key = load_db_key() verify_db_key(conn, key) except BaseException: # die() is a SystemExit; without this the caller never gets the # connection to close, and a bad or missing key leaks it (#90). conn.close() raise return conn, key def encrypt_secret(key: bytes, name: str, value: str) -> tuple[bytes, bytes, str]: kid = key_id(key) nonce = os.urandom(12) return _aesgcm()(key).encrypt(nonce, value.encode(), _secret_aad(name, kid)), nonce, kid def decrypt_secret(key: bytes, name: str, ciphertext: bytes, nonce: bytes, kid: str) -> str: return _aesgcm()(key).decrypt(nonce, ciphertext, _secret_aad(name, kid)).decode() def _read_secret_value(name: str, use_stdin: bool) -> str: if use_stdin: data = sys.stdin.read() else: data = getpass.getpass(f"value for {name} (not echoed): ") # Same rule as fetch_keys(): the secret is the first line. That makes # `pass show X | roundtable secrets set X --stdin` do the right thing. value = data.splitlines()[0].strip() if data.strip() else "" if not value: die(f"empty value for {name} — nothing stored") return value def _referencing_lanes(conn: sqlite3.Connection, name: str) -> list[str]: return [r[0] for r in conn.execute( "SELECT name FROM lanes WHERE key_entry = ? AND retired_at IS NULL ORDER BY name", (name,))] # --------------------------------------------------------------------------- # # store admin commands # --------------------------------------------------------------------------- # ADMIN_VERBS = { "db": ("init", "migrate", "doctor", "export", "import", "backup", "restore"), "secrets": ("set", "check", "list", "rotate", "rm", "rekey"), "lanes": ("list", "show", "add", "edit", "enable", "disable", "retire", "clone", "rename", "history"), "defaults": ("show", "set", "unset"), "globals": ("show", "set", "unset"), } def is_admin_argv(argv: list[str]) -> bool: """True when argv is a store command rather than a brief. The brief is positional and free text, so `roundtable "db is slow"` must stay a brief. Only a known group followed by nothing, a known verb or a flag counts. """ if argv and argv[0] == "import-yaml": # Takes a path, not a verb: `import-yaml is broken` stays a brief. return len(argv) == 1 or argv[1].startswith("-") or \ argv[1].lower().endswith((".yaml", ".yml", ".example")) if not argv or argv[0] not in ADMIN_VERBS: return False return len(argv) == 1 or argv[1] in ADMIN_VERBS[argv[0]] or argv[1].startswith("-") def cmd_db_init(a) -> int: _aesgcm() # before a key is created, not after path = a.config if path.exists() and schema_version(open_db(path)) > 0: die(f"{path} is already a store — `roundtable db doctor` checks it") kf = os.environ.get(DB_KEY_FILE_ENV) if kf and not Path(kf).exists(): key = os.urandom(32) store_db_key(key) print(f"DB key created in {kf}") elif kf: key = load_db_key() print(f"DB key reused from {kf}") elif _pass_show(DB_KEY_ENTRY) is not None: # A second host, or a re-init after deleting the file: keep the key so a # `db import` from another host's export can be read here. key = load_db_key() print(f"DB key reused from pass entry {DB_KEY_ENTRY}") else: # `pass insert -f` overwrites. If the entry file exists but `pass show` # failed, that is a gpg-agent problem, not an absent key -- overwriting # would destroy the only key to an existing store. if (_pass_store_dir() / f"{DB_KEY_ENTRY}.gpg").exists(): die(f"pass entry {DB_KEY_ENTRY} exists but could not be read — " f"unlock gpg-agent and retry; refusing to overwrite it") key = os.urandom(32) store_db_key(key) print(f"DB key created in pass entry {DB_KEY_ENTRY}") conn = open_db(path, create=True) migrate(conn) conn.execute("BEGIN IMMEDIATE") _write_kcv(conn, key) conn.executemany("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", [("host_id", socket.gethostname()), ("created_at", _now())]) conn.execute("COMMIT") print(f"store created at {path} (schema {SCHEMA_VERSION}, key id {key_id(key)})") return 0 def cmd_db_migrate(a) -> int: before, after = migrate(open_db(a.config)) if before == after: print(f"schema {after} — already current") else: print(f"schema {before} -> {after}") return 0 def cmd_db_doctor(a) -> int: path = a.config conn = open_db(path) problems = 0 mode = path.stat().st_mode & 0o777 ver = schema_version(conn) print(f"store {path}") print(f"mode {mode:04o}") print(f"schema {ver} (this roundtable: {SCHEMA_VERSION})") if ver != SCHEMA_VERSION: problems += 1 integrity = conn.execute("PRAGMA integrity_check").fetchone()[0] print(f"integrity {integrity}") if integrity != "ok": problems += 1 if ver < 1: return 1 want = _meta(conn, "key_id") try: key = load_db_key() except SystemExit as e: print(f"key store id {want}; key unavailable: {e}") return 1 have = key_id(key) if have == want: verify_db_key(conn, key) print(f"key id {have} — unlocks this store") else: print(f"key id {have} does NOT unlock this store (id {want})") problems += 1 n = conn.execute("SELECT count(*) FROM secrets").fetchone()[0] print(f"secrets {n}") if ver >= 2: live, on = conn.execute("SELECT count(*), coalesce(sum(active), 0) FROM lanes " "WHERE retired_at IS NULL").fetchone() print(f"lanes {live} live, {on} active") orphans = conn.execute( "SELECT l.name, l.key_entry FROM lanes l LEFT JOIN secrets s ON s.name = l.key_entry " "WHERE l.key_entry IS NOT NULL AND l.retired_at IS NULL AND s.name IS NULL " "ORDER BY l.name").fetchall() for lane, entry in orphans: print(f"MISSING lane {lane} names secret {entry!r}, which is not in the store") problems += len(orphans) return 1 if problems else 0 def cmd_secrets_set(a) -> int: if a.value: die("refusing a secret value on the command line — argv is readable by any\n" " local user via `ps` and lands in shell history. Use --stdin, or omit\n" " the value to be prompted without echo.") if not SECRET_NAME_RE.match(a.name): die(f"secret name {a.name!r} may use only letters, digits and . _ @ + / -") conn, key = open_store(a.config) if conn.execute("SELECT 1 FROM secrets WHERE name = ?", (a.name,)).fetchone(): die(f"secret {a.name!r} already exists — use: roundtable secrets rotate {a.name}") ct, nonce, kid = encrypt_secret(key, a.name, _read_secret_value(a.name, a.stdin)) conn.execute( "INSERT INTO secrets (name, ciphertext, nonce, key_id, vendor, notes, created_at) " "VALUES (?, ?, ?, ?, ?, ?, ?)", (a.name, ct, nonce, kid, a.vendor, a.notes, _now())) print(f"stored {a.name} (key id {kid})") return 0 def cmd_secrets_rotate(a) -> int: conn, key = open_store(a.config) if not conn.execute("SELECT 1 FROM secrets WHERE name = ?", (a.name,)).fetchone(): die(f"no secret {a.name!r} — create it with: roundtable secrets set {a.name}") ct, nonce, kid = encrypt_secret(key, a.name, _read_secret_value(a.name, a.stdin)) conn.execute("UPDATE secrets SET ciphertext = ?, nonce = ?, key_id = ?, rotated_at = ? " "WHERE name = ?", (ct, nonce, kid, _now(), a.name)) print(f"rotated {a.name} (key id {kid})") return 0 def cmd_secrets_check(a) -> int: from cryptography.exceptions import InvalidTag conn, key = open_store(a.config) names = a.names or sorted( {r[0] for r in conn.execute("SELECT name FROM secrets")} | {r[0] for r in conn.execute( "SELECT key_entry FROM lanes WHERE key_entry IS NOT NULL AND retired_at IS NULL")}) bad = 0 for name in names: row = conn.execute("SELECT ciphertext, nonce, key_id FROM secrets WHERE name = ?", (name,)).fetchone() if row is None: print(f"{name}\tMISSING") bad += 1 continue try: # The length is the only property of the value ever printed: enough # to spot a truncated paste, useless to anyone reading the terminal. n = len(decrypt_secret(key, name, *row)) except InvalidTag: print(f"{name}\tCORRUPT\tkey id {row[2]}") bad += 1 continue print(f"{name}\tpresent\t{n} chars\tkey id {row[2]}") return 1 if bad else 0 def cmd_secrets_list(a) -> int: conn = open_db(a.config) rows = conn.execute( "SELECT s.name, s.vendor, s.created_at, s.rotated_at, s.key_id, " "(SELECT count(*) FROM lanes l WHERE l.key_entry = s.name AND l.retired_at IS NULL) " "FROM secrets s ORDER BY s.name").fetchall() if not rows: print("no secrets stored") for name, vendor, created, rotated, kid, used in rows: print(f"{name}\tvendor={vendor or '-'}\tcreated={created}\t" f"rotated={rotated or '-'}\tkey id {kid}\tlanes={used}") return 0 def cmd_secrets_rm(a) -> int: conn = open_db(a.config) if not conn.execute("SELECT 1 FROM secrets WHERE name = ?", (a.name,)).fetchone(): die(f"no secret {a.name!r}") users = _referencing_lanes(conn, a.name) if users and not a.force: die(f"secret {a.name!r} is used by {', '.join(users)} — those lanes would fail\n" f" at run time. Point them elsewhere first, or pass --force.") conn.execute("DELETE FROM secrets WHERE name = ?", (a.name,)) print(f"removed {a.name}") return 0 def cmd_secrets_rekey(a) -> int: """Re-encrypt every secret under a fresh key. Order matters, because the failure worth fearing is a store whose key is nowhere: the old key is stashed as `.prev` first, the rows are re-encrypted inside an open transaction, the new key is written, and only then does the transaction commit. If the key write fails the transaction rolls back; if the commit fails the old key is put back. """ conn, old = open_store(a.config) new = os.urandom(32) store_db_key(old, DB_KEY_ENTRY + ".prev") conn.execute("BEGIN IMMEDIATE") try: rows = conn.execute("SELECT name, ciphertext, nonce, key_id FROM secrets").fetchall() for name, ct, nonce, kid in rows: value = decrypt_secret(old, name, ct, nonce, kid) conn.execute("UPDATE secrets SET ciphertext = ?, nonce = ?, key_id = ? WHERE name = ?", (*encrypt_secret(new, name, value), name)) _write_kcv(conn, new) store_db_key(new) except BaseException: conn.execute("ROLLBACK") raise try: conn.execute("COMMIT") except BaseException: store_db_key(old) raise print(f"rekeyed {len(rows)} secret(s): key id {key_id(old)} -> {key_id(new)}\n" f" the old key is kept as {DB_KEY_ENTRY}.prev until you remove it") return 0 # --------------------------------------------------------------------------- # # lane roster in the store (#108) # # A YAML lane dict is split four ways on the way in: `name`, `active`, `notes` # and `key_entry` are columns, everything else is the `config` JSON. Only a # change to config or key_entry is a new version -- the record a lane's track # record will hang on (#89) -- so renaming, parking or annotating a lane does # not reset its history. store_roster() puts the pieces back together in the # shape yaml.safe_load() returns, so validate_config() is the one rule set for # both sources, and load_config() is what a run reads (#109). # --------------------------------------------------------------------------- # LANE_COLUMNS = { "name": "roundtable lanes rename OLD NEW", "active": "roundtable lanes enable|disable NAME", "notes": "--notes", "key_entry": "--key-entry", } GLOBAL_KEYS = ("budget_usd", "concurrency", "deadline_seconds", "retries", "synthesizer", "synthesizers") ROSTER_FORMAT = "flatline-roundtable/roster" LANE_SELECT = ("SELECT lane_id, name, active, notes, key_entry, config, version, " "retired_at, created_at, updated_at FROM lanes") # NULL positions (rows written before migration 2) sort last, oldest first. LANE_ORDER = " ORDER BY position IS NULL, position, created_at, lane_id" @contextlib.contextmanager def _tx(conn: sqlite3.Connection): """One write transaction. die() raises SystemExit, which rolls back too: a lane that fails validation is never left half-written.""" conn.execute("BEGIN IMMEDIATE") try: yield except BaseException: conn.execute("ROLLBACK") raise conn.execute("COMMIT") def _canon(obj) -> str: # One spelling per config, so a version bump means the config changed and # never that a dict happened to iterate in another order. return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False) def _actor() -> str: try: user = getpass.getuser() except Exception: # noqa: BLE001 -- no passwd entry in some containers user = "?" return f"{user}@{socket.gethostname()}" def open_roster(path: Path) -> sqlite3.Connection: """A migrated store, without the DB key: lanes, defaults and globals hold no secret, so reading or editing them must not need gpg-agent.""" conn = open_db(path) if schema_version(conn) < SCHEMA_VERSION: die(f"store is at schema {schema_version(conn)}, this roundtable needs " f"{SCHEMA_VERSION} — run: roundtable db migrate") return conn def _lane(r) -> dict: keys = ("lane_id", "name", "active", "notes", "key_entry", "config", "version", "retired_at", "created_at", "updated_at") lane = dict(zip(keys, r)) lane["active"] = bool(lane["active"]) lane["config"] = json.loads(lane["config"]) return lane def _live_lanes(conn: sqlite3.Connection) -> list[dict]: return [_lane(r) for r in conn.execute(LANE_SELECT + " WHERE retired_at IS NULL" + LANE_ORDER)] def _find_lane(conn: sqlite3.Connection, name: str, retired: bool = False) -> dict: """The live lane called `name`, case-insensitively like --lanes. With retired=True an old name also resolves -- through lane_aliases, or to the most recently retired lane of that name -- so `lanes history` and `lanes show` still answer for a lane that is gone. """ r = conn.execute(LANE_SELECT + " WHERE lower(name) = lower(?) AND retired_at IS NULL", (name,)).fetchone() if r is None and retired: r = conn.execute(LANE_SELECT + " WHERE lane_id = (SELECT lane_id FROM lane_aliases " "WHERE lower(old_name) = lower(?))", (name,)).fetchone() r = r or conn.execute(LANE_SELECT + " WHERE lower(name) = lower(?) " "ORDER BY retired_at DESC", (name,)).fetchone() if r is None: die(f"no lane {name!r} — `roundtable lanes list --all` shows every lane") return _lane(r) def _kv(conn: sqlite3.Connection, table: str) -> dict: assert table in ("globals", "defaults") return {k: json.loads(v) for k, v in conn.execute(f"SELECT key, value FROM {table} ORDER BY key")} def _lane_dict(lane: dict) -> dict: """A stored lane as the YAML lane dict it came from.""" d = {"name": lane["name"], "active": lane["active"]} if lane["key_entry"] is not None: d["key_entry"] = lane["key_entry"] if lane["notes"] is not None: d["notes"] = lane["notes"] return {**d, **lane["config"]} def store_roster(conn: sqlite3.Connection) -> dict: """The live roster in the shape yaml.safe_load() returns, so the same validate_config() call accepts either.""" cfg = _kv(conn, "globals") defaults = _kv(conn, "defaults") if defaults: cfg["defaults"] = defaults cfg["lanes"] = [_lane_dict(l) for l in _live_lanes(conn)] return cfg def validate_store(conn: sqlite3.Connection) -> None: """Die, inside the caller's transaction, unless the live roster would pass load_config(). Run after every write, so the messages are load_config()'s own and the store never holds a roster a run would refuse.""" roster = store_roster(conn) if not roster["lanes"]: return validate_config(roster, "the store") # validate_config() compares names exactly, but --lanes matches them # case-insensitively, so `Skeptic` and `skeptic` would be one lane to a run. seen: set[str] = set() for lane in roster["lanes"]: if lane["name"].lower() in seen: die(f"duplicate lane name {lane['name']!r} — names must be unique") seen.add(lane["name"].lower()) def _check_config_keys(keys) -> None: for k in keys: if k in LANE_COLUMNS: die(f"{k} is not part of a lane's config — use: {LANE_COLUMNS[k]}") def _check_key_entry(name: str | None) -> None: if name is not None and not SECRET_NAME_RE.match(name): die(f"key_entry {name!r} may use only letters, digits and . _ @ + / -") def _check_global(key: str, value) -> None: if key not in GLOBAL_KEYS: die(f"unknown global {key!r} — one of: {', '.join(GLOBAL_KEYS)}") num = isinstance(value, (int, float)) and not isinstance(value, bool) whole = num and float(value).is_integer() ok = { "concurrency": whole and value >= 1, "retries": whole and value >= 0, "synthesizers": whole and value >= 1, "deadline_seconds": num and value > 0, "budget_usd": num and value >= 0, "synthesizer": isinstance(value, str) and value != "", }[key] if not ok: die(f"{key}: {value!r} is not a valid value") def _parse_sets(items) -> dict: """`--set k=v`: v is JSON when it parses (300, true, ["-p"]), else a string.""" out = {} for item in items or []: k, sep, v = item.partition("=") if not sep or not k: die(f"expected KEY=VALUE, got {item!r}") try: out[k] = json.loads(v) except ValueError: out[k] = v return out def _record_version(conn, lane_id: str, version: int, config: dict, key_entry: str | None, reason: str | None) -> None: text = _canon(config) conn.execute( "INSERT INTO lane_versions (lane_id, version, config, config_sha256, key_entry, " "changed_at, changed_by, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (lane_id, version, text, hashlib.sha256(text.encode()).hexdigest(), key_entry, _now(), _actor(), reason)) def _next_position(conn) -> int: return conn.execute("SELECT coalesce(max(position), -1) + 1 FROM lanes").fetchone()[0] def _insert_lane(conn, name: str, config: dict, key_entry: str | None, notes: str | None, active: bool, reason: str | None, lane_id: str | None = None, position: int | None = None) -> str: lane_id = lane_id or uuid.uuid4().hex now = _now() try: conn.execute( "INSERT INTO lanes (lane_id, name, active, notes, key_entry, config, version, " "position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)", (lane_id, name, int(active), notes, key_entry, _canon(config), _next_position(conn) if position is None else position, now, now)) except sqlite3.IntegrityError: # The live-name index is case-insensitive; the message is load_config()'s. die(f"duplicate lane name {name!r} — names must be unique") _record_version(conn, lane_id, 1, config, key_entry, reason) return lane_id def _update_config(conn, lane: dict, config: dict, key_entry: str | None, reason: str | None) -> bool: """New version only if config or key_entry really changed.""" if _canon(config) == _canon(lane["config"]) and key_entry == lane["key_entry"]: return False version = lane["version"] + 1 conn.execute("UPDATE lanes SET config = ?, key_entry = ?, version = ?, updated_at = ? " "WHERE lane_id = ?", (_canon(config), key_entry, version, _now(), lane["lane_id"])) _record_version(conn, lane["lane_id"], version, config, key_entry, reason) lane.update(config=config, key_entry=key_entry, version=version) return True def _rename(conn, lane: dict, new: str) -> None: try: conn.execute("UPDATE lanes SET name = ?, updated_at = ? WHERE lane_id = ?", (new, _now(), lane["lane_id"])) except sqlite3.IntegrityError: die(f"duplicate lane name {new!r} — names must be unique") # So a transcript written under the old name stays attributable. A name # reused and renamed again later points at its latest owner. conn.execute("INSERT OR REPLACE INTO lane_aliases (old_name, lane_id, renamed_at) " "VALUES (?, ?, ?)", (lane["name"], lane["lane_id"], _now())) lane["name"] = new def _warn_missing_secret(conn, key_entry: str | None) -> None: if key_entry and not conn.execute("SELECT 1 FROM secrets WHERE name = ?", (key_entry,)).fetchone(): print(f" note: secret {key_entry!r} is not in the store yet — " f"roundtable secrets set {key_entry}") def cmd_lanes_list(a) -> int: conn = open_roster(a.config) where = "" if a.all else " WHERE retired_at IS NULL" lanes = [_lane(r) for r in conn.execute(LANE_SELECT + where + LANE_ORDER)] if not lanes: print("no lanes stored") for l in lanes: state = "retired" if l["retired_at"] else ("active" if l["active"] else "inactive") c = l["config"] print(f"{l['name']}\t{state}\t{c.get('harness', '-')}\t{c.get('vendor') or '-'}\t" f"{c.get('model') or '-'}\tv{l['version']}\tkey={l['key_entry'] or '-'}") return 0 def cmd_lanes_show(a) -> int: conn = open_roster(a.config) lane = _find_lane(conn, a.name, retired=True) lane["aliases"] = [r[0] for r in conn.execute( "SELECT old_name FROM lane_aliases WHERE lane_id = ? ORDER BY renamed_at", (lane["lane_id"],))] if a.json: print(json.dumps(lane, indent=2, sort_keys=True, ensure_ascii=False)) return 0 for k in ("name", "lane_id", "active", "retired_at", "version", "key_entry", "notes", "aliases", "created_at", "updated_at"): v = lane[k] print(f"{k:<11}{', '.join(v) if isinstance(v, list) else ('-' if v is None else v)}") print("config") for line in json.dumps(lane["config"], indent=2, sort_keys=True, ensure_ascii=False).splitlines(): print(f" {line}") return 0 def cmd_lanes_add(a) -> int: config = {"harness": a.harness, **_parse_sets(a.set)} _check_config_keys(config) _check_key_entry(a.key_entry) conn = open_roster(a.config) with _tx(conn): lane_id = _insert_lane(conn, a.name, config, a.key_entry, a.notes, True, a.reason or "added") validate_store(conn) print(f"added {a.name} (lane id {lane_id}, version 1)") _warn_missing_secret(conn, a.key_entry) return 0 def cmd_lanes_edit(a) -> int: sets = _parse_sets(a.set) _check_config_keys(sets) _check_config_keys(u for u in a.unset if u != "key_entry") _check_key_entry(a.key_entry) conn = open_roster(a.config) with _tx(conn): lane = _find_lane(conn, a.name) config = {**lane["config"], **sets} for k in a.unset: if k != "key_entry" and k not in config: die(f"{lane['name']} has no {k} to unset") config.pop(k, None) key_entry = None if "key_entry" in a.unset else (a.key_entry or lane["key_entry"]) before = lane["version"] changed = _update_config(conn, lane, config, key_entry, a.reason) if a.notes is not None: conn.execute("UPDATE lanes SET notes = ?, updated_at = ? WHERE lane_id = ?", (a.notes or None, _now(), lane["lane_id"])) validate_store(conn) if changed: print(f"{lane['name']}: version {before} -> {lane['version']}") elif a.notes is not None: print(f"{lane['name']}: notes updated (version {before}, unchanged)") else: print(f"{lane['name']}: no change (version {before})") if changed: _warn_missing_secret(conn, key_entry) return 0 def _set_active(a, active: bool) -> int: conn = open_roster(a.config) with _tx(conn): lane = _find_lane(conn, a.name) conn.execute("UPDATE lanes SET active = ?, updated_at = ? WHERE lane_id = ?", (int(active), _now(), lane["lane_id"])) word = "active" if active else "inactive" print(f"{lane['name']}: {'already ' if lane['active'] == active else ''}{word}") return 0 def cmd_lanes_retire(a) -> int: conn = open_roster(a.config) with _tx(conn): lane = _find_lane(conn, a.name) conn.execute("UPDATE lanes SET retired_at = ?, updated_at = ? WHERE lane_id = ?", (_now(), _now(), lane["lane_id"])) print(f"retired {lane['name']} (lane id {lane['lane_id']}, version {lane['version']}); " f"the name is free and its history is kept") return 0 def cmd_lanes_clone(a) -> int: conn = open_roster(a.config) with _tx(conn): src = _find_lane(conn, a.src) # Inactive on purpose: once runs read the store (#109), an active clone # would join the next --each run and bill alongside its original. lane_id = _insert_lane(conn, a.new, src["config"], src["key_entry"], None, False, f"cloned from {src['name']} v{src['version']} ({src['lane_id']})") validate_store(conn) print(f"cloned {src['name']} as {a.new} (lane id {lane_id}, version 1, inactive — " f"roundtable lanes enable {a.new})") return 0 def cmd_lanes_rename(a) -> int: conn = open_roster(a.config) with _tx(conn): lane = _find_lane(conn, a.old) old = lane["name"] if old == a.new: die(f"{old} is already called {a.new}") _rename(conn, lane, a.new) validate_store(conn) print(f"renamed {old} -> {a.new} (lane id {lane['lane_id']}, version {lane['version']}; " f"{old} stays as an alias)") return 0 def cmd_lanes_history(a) -> int: conn = open_roster(a.config) lane = _find_lane(conn, a.name, retired=True) print(f"{lane['name']} (lane id {lane['lane_id']})") for v, at, by, sha, ke, why in conn.execute( "SELECT version, changed_at, changed_by, config_sha256, key_entry, reason " "FROM lane_versions WHERE lane_id = ? ORDER BY version", (lane["lane_id"],)): print(f"v{v}\t{at}\t{by or '-'}\tsha {sha[:12]}\tkey={ke or '-'}\t{why or ''}") for old, at in conn.execute("SELECT old_name, renamed_at FROM lane_aliases " "WHERE lane_id = ? ORDER BY renamed_at", (lane["lane_id"],)): print(f"renamed from {old} at {at}") if lane["retired_at"]: print(f"retired at {lane['retired_at']}") return 0 def _kv_cmd(table: str): def show(a) -> int: rows = _kv(open_roster(a.config), table) if not rows: print(f"no {table} set") for k, v in rows.items(): print(f"{k}\t{json.dumps(v, ensure_ascii=False)}") return 0 def set_(a) -> int: items = _parse_sets(a.items) for k, v in items.items(): if table == "globals": _check_global(k, v) elif k == "name": die("defaults cannot set a lane's name") conn = open_roster(a.config) with _tx(conn): conn.executemany(f"INSERT OR REPLACE INTO {table} (key, value, updated_at) " f"VALUES (?, ?, ?)", [(k, _canon(v), _now()) for k, v in items.items()]) validate_store(conn) print(f"{table}: set {', '.join(items)}") return 0 def unset(a) -> int: conn = open_roster(a.config) with _tx(conn): for k in a.keys: if conn.execute(f"DELETE FROM {table} WHERE key = ?", (k,)).rowcount == 0: die(f"{table} has no {k}") validate_store(conn) print(f"{table}: unset {', '.join(a.keys)}") return 0 return show, set_, unset def export_roster(conn: sqlite3.Connection) -> dict: """Everything a second host needs to run the same panel, except values. lane_id rides along so a lane keeps one identity -- and one track record -- on every host it is imported to. Versions and timestamps do not: they describe this host's edit history, and leaving them out is what lets export -> import --replace -> export come back byte-identical. """ return { "format": ROSTER_FORMAT, "format_version": 1, "globals": _kv(conn, "globals"), "defaults": _kv(conn, "defaults"), "lanes": [{"lane_id": l["lane_id"], "name": l["name"], "active": l["active"], "key_entry": l["key_entry"], "notes": l["notes"], "config": l["config"]} for l in _live_lanes(conn)], } def dump_roster(doc: dict) -> str: return json.dumps(doc, indent=2, sort_keys=True, ensure_ascii=False) + "\n" def _check_roster_doc(doc, where: str) -> None: if not isinstance(doc, dict) or doc.get("format") != ROSTER_FORMAT: die(f"{where} is not a roster export (no \"format\": \"{ROSTER_FORMAT}\")") if doc.get("format_version") != 1: die(f"{where} is roster format {doc.get('format_version')!r}; this roundtable reads 1") for k in ("globals", "defaults"): if not isinstance(doc.get(k, {}), dict): die(f"{where}: {k} must be a mapping") if not isinstance(doc.get("lanes"), list): die(f"{where}: lanes must be a list") for i, l in enumerate(doc["lanes"]): if not isinstance(l, dict) or not isinstance(l.get("config"), dict): die(f"{where}: lane #{i + 1} needs a config mapping") if not isinstance(l.get("name"), str) or not l["name"]: die(f"{where}: lane #{i + 1} has no name") _check_config_keys(l["config"]) # Checked, not coerced: bool("false") is True, and once runs read the # store an "inactive" lane that is really active joins runs and bills. if not isinstance(l.get("active", True), bool): die(f"{where}: lane #{i + 1}: active must be true or false, got {l['active']!r}") for k in ("key_entry", "notes", "lane_id"): if l.get(k) is not None and not isinstance(l[k], str): die(f"{where}: lane #{i + 1}: {k} must be a string, got {l[k]!r}") _check_key_entry(l.get("key_entry")) def apply_roster(conn: sqlite3.Connection, doc: dict, replace: bool, reason: str) -> dict: """Make the store hold `doc`, inside the caller's transaction. A lane is matched by lane_id, else by live name. replace retires every live lane the document does not mention and makes globals and defaults exactly the document's; merge only adds and updates. Returns counts for the report. """ counts = {"added": 0, "updated": 0, "unchanged": 0, "retired": 0} for table in ("globals", "defaults"): if replace: conn.execute(f"DELETE FROM {table}") for k, v in doc.get(table, {}).items(): if table == "globals": _check_global(k, v) conn.execute(f"INSERT OR REPLACE INTO {table} (key, value, updated_at) " f"VALUES (?, ?, ?)", (k, _canon(v), _now())) ids = {l.get("lane_id") for l in doc["lanes"]} - {None} names = {l["name"].lower() for l in doc["lanes"] if not l.get("lane_id")} if replace: # Before any insert: a lane the document drops may hold a name that one # of its own lanes is about to take. for l in _live_lanes(conn): if l["lane_id"] not in ids and l["name"].lower() not in names: conn.execute("UPDATE lanes SET retired_at = ?, updated_at = ? WHERE lane_id = ?", (_now(), _now(), l["lane_id"])) counts["retired"] += 1 for pos, d in enumerate(doc["lanes"]): r = None if d.get("lane_id"): r = conn.execute(LANE_SELECT + " WHERE lane_id = ?", (d["lane_id"],)).fetchone() else: r = conn.execute(LANE_SELECT + " WHERE lower(name) = lower(?) AND retired_at IS NULL", (d["name"],)).fetchone() active = bool(d.get("active", True)) if r is None: _insert_lane(conn, d["name"], d["config"], d.get("key_entry"), d.get("notes"), active, reason, lane_id=d.get("lane_id"), position=pos if replace else None) counts["added"] += 1 continue lane = _lane(r) changed = _update_config(conn, lane, d["config"], d.get("key_entry"), reason) if lane["name"] != d["name"]: _rename(conn, lane, d["name"]) try: conn.execute("UPDATE lanes SET active = ?, notes = ?, retired_at = NULL, " "position = coalesce(?, position), updated_at = ? WHERE lane_id = ?", (int(active), d.get("notes"), pos if replace else None, _now(), lane["lane_id"])) except sqlite3.IntegrityError: # A retired lane coming back while a newer live lane holds its name. die(f"duplicate lane name {d['name']!r} — names must be unique " f"(lane id {lane['lane_id']} is retired here and its name is taken)") counts["updated" if changed else "unchanged"] += 1 validate_store(conn) return counts def _report(counts: dict) -> str: return ", ".join(f"{n} {k}" for k, n in counts.items()) def cmd_db_export(a) -> int: text = dump_roster(export_roster(open_roster(a.config))) if a.out is None: sys.stdout.write(text) return 0 # Holds no secret value, but a base_url can carry credentials (safe_route # exists for that reason), so the file is private like everything else. fd = os.open(a.out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) os.fchmod(fd, 0o600) # O_CREAT's mode applies only to a NEW file with os.fdopen(fd, "w") as f: f.write(text) print(f"exported to {a.out}") return 0 def cmd_db_import(a) -> int: try: doc = json.loads(a.file.read_text()) except (OSError, ValueError) as e: die(f"cannot read {a.file}: {e}") _check_roster_doc(doc, str(a.file)) conn = open_roster(a.config) with _tx(conn): counts = apply_roster(conn, doc, a.replace, f"db import {a.file.name}") print(f"imported {a.file} ({'replace' if a.replace else 'merge'}): {_report(counts)}") return 0 # --------------------------------------------------------------------------- # # import-yaml: the one-time move off YAML # --------------------------------------------------------------------------- # _DECORATION = re.compile(r"^[-=*#~_ ]+|[-=*#~_ ]+$") _TRAILING = re.compile(r"^\s*(?:-\s+)?(?:active|key_entry)\s*:\s*[^#\n]*?\s#\s?(.*)$") def _comment_text(line: str) -> tuple[str, bool]: text = line.strip().lstrip("#").strip() return _DECORATION.sub("", text), bool(re.search(r"[-=]{3,}", text)) def yaml_lane_comments(text: str, n: int) -> list[list[str]] | None: """The comments that explain each lane, as a list of notes per lane. Comments in this YAML are load-bearing ("keep it off: answers were incoherent"), and the store has no comments, so they move into `notes`: the full-line comment block directly above a lane (no blank line between) and a trailing `# ...` on its `active:` or `key_entry:` line. Which comment belongs to which lane is a guess -- a section banner lands on the first lane under it -- so `import-yaml --dry-run` prints the result for review. None when the lanes cannot be lined up with the parsed list. """ lines = text.splitlines() start = next((i for i, l in enumerate(lines) if re.match(r"lanes\s*:\s*(#.*)?$", l)), None) if start is None: return None items, indent, stop = [], None, len(lines) for i in range(start + 1, len(lines)): l = lines[i] if l.strip() and not l[0].isspace() and l[0] not in "#-": stop = i # the next top-level key break m = re.match(r"( *)-(\s|$)", l) if m and (indent is None or len(m.group(1)) == indent): indent = len(m.group(1)) items.append(i) if len(items) != n: return None notes = [] for k, at in enumerate(items): pieces: list[str] = [] block = [] j = at - 1 # Only comments at or left of the item's dash: a deeper `# ...` is the # tail of the previous lane's block scalar, not a comment. while j > start and lines[j].strip().startswith("#") \ and len(lines[j]) - len(lines[j].lstrip()) <= indent: block.append(lines[j]) j -= 1 para: list[str] = [] for line in reversed(block): t, banner = _comment_text(line) if banner: pieces += [" ".join(para)] if para else [] para = [] pieces += [t] if t else [] elif t: para.append(t) pieces += [" ".join(para)] if para else [] end = items[k + 1] if k + 1 < len(items) else stop for line in lines[at:end]: m = _TRAILING.match(line) if m and m.group(1).strip(): pieces.append(m.group(1).strip()) notes.append(pieces) return notes def roster_from_cfg(raw: dict, where: str, text: str | None = None) -> dict: """A YAML-shaped config dict as a roster document `db import` accepts. validate_config() runs first, so a config a run would refuse -- the YAML 1.1 `Off` lane name (#29), a cli lane with no prompt -- is refused with the same message before anything is written. With the YAML `text`, the lanes' comments become their notes. """ validate_config(dict(raw), where) defaults = raw.get("defaults") or {} globals_ = {k: v for k, v in raw.items() if k not in ("lanes", "defaults")} for k in sorted(set(globals_) - set(GLOBAL_KEYS)): print(f" note: top-level {k!r} is not a setting roundtable reads — not imported", file=sys.stderr) globals_.pop(k) comments = yaml_lane_comments(text, len(raw["lanes"])) if text is not None else None if comments is None: if text is not None: print(" note: could not line comments up with lanes — only `notes:` values are kept", file=sys.stderr) comments = [[] for _ in raw["lanes"]] lanes = [] for l, extra in zip(raw["lanes"], comments): config = {k: v for k, v in l.items() if k not in LANE_COLUMNS} try: _canon(config) except TypeError as e: die(f"{l['name']}: a value is not plain data ({e}) — quote it in the YAML") pieces = ([str(l["notes"])] if l.get("notes") else []) + extra lanes.append({ "lane_id": None, "name": l["name"], # Same truthiness the run path applies: l.get("active", True). "active": bool(l.get("active", defaults.get("active", True))), "key_entry": l.get("key_entry"), "notes": " | ".join(pieces) or None, "config": config, }) try: _canon([globals_, defaults]) except TypeError as e: die(f"{where}: a default or global is not plain data ({e}) — quote it") return {"format": ROSTER_FORMAT, "format_version": 1, "globals": globals_, "defaults": defaults, "lanes": lanes} def yaml_to_roster(path: Path) -> dict: raw, text = read_yaml_config(path) return roster_from_cfg(raw, str(path), text) def read_pass_entries(entries: list[str]) -> dict[str, str]: """Each entry's value from `pass`, for --pull-secrets: the retired run-path reader, kept for the one-time move. Sequential, one `pass show` at a time, for the same gpg-agent reason fetch_keys() resolves before fan-out.""" if not entries: return {} if not shutil.which("pass"): die("--pull-secrets reads `pass`, which is not installed") out: dict[str, str] = {} for entry in sorted(entries): try: p = subprocess.run(["pass", "show", entry], capture_output=True, text=True, timeout=30) except subprocess.TimeoutExpired: die(f"`pass show {entry}` timed out — is gpg-agent waiting on a passphrase?") if p.returncode != 0: die(f"no pass entry {entry!r} — nothing imported") # pass returns the whole file; the secret is the first line. Storing the # blob would put trailing metadata into an Authorization header. first = p.stdout.splitlines()[0].strip() if p.stdout.strip() else "" if not first: die(f"pass entry {entry!r} is empty — nothing imported") out[entry] = first return out def cmd_import_yaml(a) -> int: doc = yaml_to_roster(a.path) _check_roster_doc(doc, str(a.path)) entries = sorted({l["key_entry"] for l in doc["lanes"] if l["key_entry"]} | ({doc["defaults"]["key_entry"]} if doc["defaults"].get("key_entry") else set())) if a.dry_run: for l in doc["lanes"]: print(f"{l['name']}\t{'active' if l['active'] else 'inactive'}\t" f"{l['config'].get('harness')}\tnotes: {l['notes'] or '-'}") print(f"{len(doc['lanes'])} lane(s), globals {sorted(doc['globals']) or '-'}, " f"defaults {sorted(doc['defaults']) or '-'}, {len(entries)} key entr" f"{'y' if len(entries) == 1 else 'ies'}. Nothing written (--dry-run).") return 0 if a.pull_secrets: conn, key = open_store(a.config) have = {r[0] for r in conn.execute("SELECT name FROM secrets")} # Every value is read before anything is written, so a locked # gpg-agent fails the import cleanly instead of half-way through. pulled = read_pass_entries([e for e in entries if e not in have]) else: conn, pulled = open_roster(a.config), {} vendor = {} for l in doc["lanes"]: vendor.setdefault(l["key_entry"], l["config"].get("vendor")) with _tx(conn): counts = apply_roster(conn, doc, False, f"import-yaml {a.path.name}") for name, value in pulled.items(): ct, nonce, kid = encrypt_secret(key, name, value) conn.execute( "INSERT INTO secrets (name, ciphertext, nonce, key_id, vendor, notes, created_at) " "VALUES (?, ?, ?, ?, ?, ?, ?)", (name, ct, nonce, kid, vendor.get(name), f"pulled from pass {name}", _now())) print(f"imported {a.path}: {_report(counts)}") if a.pull_secrets: kept = [e for e in entries if e not in pulled] print(f"secrets: {len(pulled)} pulled from pass" + (f", {len(kept)} already in the store" if kept else "")) else: for e in entries: _warn_missing_secret(conn, e) return 0 # --------------------------------------------------------------------------- # # backup and restore (#110) # # A backup is a self-contained copy taken with SQLite's online backup API, so # it is consistent even while a run holds the store open in WAL mode -- a file # copy of roundtable.db alone would miss whatever still sits in -wal. The copy # is useless without the DB key, which lives in `pass`; scripts/backup-telesto.sh # ships both. # --------------------------------------------------------------------------- # def _sqlite_copy(src: sqlite3.Connection, dest: Path) -> None: """Write `src` to a new, private `dest` as a rollback-journal database, so the copy is one file with no -wal or -shm beside it.""" os.close(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)) dst = sqlite3.connect(dest, isolation_level=None) try: src.backup(dst) dst.execute("PRAGMA journal_mode=DELETE") finally: dst.close() def _integrity(path: Path) -> str: try: c = sqlite3.connect(f"file:{path}?mode=ro", uri=True) try: return c.execute("PRAGMA integrity_check").fetchone()[0] finally: c.close() except sqlite3.DatabaseError as e: return str(e) def cmd_db_backup(a) -> int: conn = open_db(a.config) out_dir = a.dir or a.config.parent / "backups" out_dir.mkdir(parents=True, exist_ok=True, mode=0o700) host = re.sub(r"[^A-Za-z0-9.-]", "_", socket.gethostname().split(".")[0]) stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") dest = out_dir / f"roundtable-{host}-{stamp}.db" n = 1 while dest.exists(): # two backups in one second dest = out_dir / f"roundtable-{host}-{stamp}-{n}.db" n += 1 try: _sqlite_copy(conn, dest) finally: conn.close() result = _integrity(dest) if result != "ok": dest.unlink() die(f"backup copy failed integrity_check ({result}) — nothing kept") # Newest first: by stamp, then by the -N a same-second backup gets. Plain # name order would put "...Z-1.db" before "...Z.db", which is backwards. pat = re.compile(rf"roundtable-{re.escape(host)}-(\d{{8}}T\d{{6}}Z)(?:-(\d+))?\.db") mine = sorted((p for p in out_dir.iterdir() if pat.fullmatch(p.name)), key=lambda p: (pat.fullmatch(p.name)[1], int(pat.fullmatch(p.name)[2] or 0)), reverse=True) pruned = mine[a.keep:] if a.keep > 0 else [] for old in pruned: old.unlink() print(f"backup {dest} (integrity ok, kept {min(len(mine), a.keep)}" + (f", pruned {len(pruned)}" if pruned else "") + ")") return 0 def cmd_db_restore(a) -> int: src_path = a.file if not src_path.exists(): die(f"no backup at {src_path}") result = _integrity(src_path) if result != "ok": die(f"{src_path} fails integrity_check ({result}) — refusing to restore it") src = sqlite3.connect(f"file:{src_path}?mode=ro", uri=True) try: ver = schema_version(src) kid = src.execute("SELECT value FROM meta WHERE key = 'key_id'").fetchone() except sqlite3.DatabaseError: kid = None if kid is None: src.close() die(f"{src_path} is not a roundtable store (no key id in its meta table)") # --force exists for this check only. A newer schema may hold tables this # code does not know, which is a choice; a corrupt file never is. if ver > SCHEMA_VERSION and not a.force: src.close() die(f"{src_path} is at schema {ver}, newer than this roundtable ({SCHEMA_VERSION}) — " f"update roundtable, or pass --force") target = a.config kept = None if target.exists(): live = open_db(target) # Fold -wal into the main file so the copy kept aside is complete. live.execute("PRAGMA wal_checkpoint(TRUNCATE)") live.close() stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") kept = target.with_name(f"{target.name}.pre-restore-{stamp}") target.rename(kept) for side in ("-wal", "-shm"): Path(f"{target}{side}").unlink(missing_ok=True) else: target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) try: _sqlite_copy(src, target) except BaseException: if kept is not None and not target.exists(): kept.rename(target) raise finally: src.close() restored = open_db(target) restored.execute("PRAGMA journal_mode=WAL") restored.close() print(f"restored {src_path} -> {target} (schema {ver}, key id {kid[0]})") if kept is not None: print(f" the store it replaced is kept as {kept}") print(" check it with: roundtable db doctor && roundtable secrets check") return 0 def admin_main(argv: list[str]) -> int: common = argparse.ArgumentParser(add_help=False) common.add_argument("--config", type=Path, default=DEFAULT_DB, help=f"the store (default {DEFAULT_DB})") ap = argparse.ArgumentParser(prog="roundtable", description="store administration") groups = ap.add_subparsers(dest="group", required=True) db = groups.add_parser("db", help="create, migrate and check the store") dbv = db.add_subparsers(dest="verb", required=True) dbv.add_parser("init", parents=[common], help="create the store and its DB key") \ .set_defaults(fn=cmd_db_init) dbv.add_parser("migrate", parents=[common], help="apply pending schema migrations") \ .set_defaults(fn=cmd_db_migrate) dbv.add_parser("doctor", parents=[common], help="check mode, schema, integrity and key") \ .set_defaults(fn=cmd_db_doctor) p = dbv.add_parser("export", parents=[common], help="roster as JSON: globals, defaults, lanes; never a secret value") p.add_argument("--out", type=Path, help="write here (0600) instead of stdout") p.set_defaults(fn=cmd_db_export) p = dbv.add_parser("import", parents=[common], help="load a `db export` file") p.add_argument("file", type=Path) mode = p.add_mutually_exclusive_group() mode.add_argument("--merge", action="store_true", help="add and update lanes, keep the rest (default)") mode.add_argument("--replace", action="store_true", help="make the roster exactly the file; unlisted lanes are retired") p.set_defaults(fn=cmd_db_import) p = dbv.add_parser("backup", parents=[common], help="integrity-checked 0600 copy, safe while the store is in use") p.add_argument("--dir", type=Path, help="where to write (default: backups/ beside the store)") p.add_argument("--keep", type=int, default=14, help="newest copies to keep (default 14)") p.set_defaults(fn=cmd_db_backup) p = dbv.add_parser("restore", parents=[common], help="replace the store with a backup; the old one is kept aside") p.add_argument("file", type=Path) p.add_argument("--force", action="store_true", help="restore a backup from a newer schema (never a corrupt one)") p.set_defaults(fn=cmd_db_restore) ln = groups.add_parser("lanes", help="the lane roster in the store") lv = ln.add_subparsers(dest="verb", required=True) p = lv.add_parser("list", parents=[common], help="live lanes, in roster order") p.add_argument("--all", action="store_true", help="include retired lanes") p.set_defaults(fn=cmd_lanes_list) p = lv.add_parser("show", parents=[common], help="one lane; the secret's name only") p.add_argument("name") p.add_argument("--json", action="store_true") p.set_defaults(fn=cmd_lanes_show) p = lv.add_parser("add", parents=[common], help="a new lane, validated like load_config") p.add_argument("name") p.add_argument("--harness", required=True) p.add_argument("--set", action="append", metavar="KEY=VALUE", help="config key; VALUE is JSON when it parses, else a string") p.add_argument("--key-entry", help="the NAME of the secret this lane uses") p.add_argument("--notes") p.add_argument("--reason") p.set_defaults(fn=cmd_lanes_add) p = lv.add_parser("edit", parents=[common], help="change config; a real change is a new version") p.add_argument("name") p.add_argument("--set", action="append", metavar="KEY=VALUE") p.add_argument("--unset", action="append", default=[], metavar="KEY") p.add_argument("--key-entry") p.add_argument("--notes", help="replace the notes ('' clears); no new version") p.add_argument("--reason", help="recorded with the new version") p.set_defaults(fn=cmd_lanes_edit) for verb, on in (("enable", True), ("disable", False)): p = lv.add_parser(verb, parents=[common], help=f"set active {str(on).lower()}; no new version") p.add_argument("name") p.set_defaults(fn=lambda a, on=on: _set_active(a, on)) p = lv.add_parser("retire", parents=[common], help="free the name, keep the history") p.add_argument("name") p.set_defaults(fn=cmd_lanes_retire) p = lv.add_parser("clone", parents=[common], help="copy a lane's config under a new name (inactive)") p.add_argument("src") p.add_argument("new") p.set_defaults(fn=cmd_lanes_clone) p = lv.add_parser("rename", parents=[common], help="new name, same lane; the old name stays an alias") p.add_argument("old") p.add_argument("new") p.set_defaults(fn=cmd_lanes_rename) p = lv.add_parser("history", parents=[common], help="every version of a lane") p.add_argument("name") p.set_defaults(fn=cmd_lanes_history) for table, what in (("defaults", "applied under every lane"), ("globals", f"run settings: {', '.join(GLOBAL_KEYS)}")): show, set_, unset = _kv_cmd(table) g = groups.add_parser(table, help=what) gv = g.add_subparsers(dest="verb", required=True) gv.add_parser("show", parents=[common]).set_defaults(fn=show) p = gv.add_parser("set", parents=[common]) p.add_argument("items", nargs="+", metavar="KEY=VALUE") p.set_defaults(fn=set_) p = gv.add_parser("unset", parents=[common]) p.add_argument("keys", nargs="+", metavar="KEY") p.set_defaults(fn=unset) p = groups.add_parser("import-yaml", parents=[common], help="one-time: move a YAML config's lanes into the store") p.add_argument("path", type=Path) p.add_argument("--dry-run", action="store_true", help="print each lane and the notes taken from its comments; write nothing") p.add_argument("--pull-secrets", action="store_true", help="also copy each key_entry's value from pass into the store") p.set_defaults(fn=cmd_import_yaml) sec = groups.add_parser("secrets", help="lane secrets, encrypted in the store") sv = sec.add_subparsers(dest="verb", required=True) p = sv.add_parser("set", parents=[common], help="store a new secret (stdin or prompt)") p.add_argument("name") # Captured only so it can be refused with a reason, rather than argparse's # "unrecognized arguments" -- which reads like a typo, not a policy. p.add_argument("value", nargs="*", help=argparse.SUPPRESS) p.add_argument("--stdin", action="store_true", help="read the value from stdin") p.add_argument("--vendor") p.add_argument("--notes") p.set_defaults(fn=cmd_secrets_set) p = sv.add_parser("check", parents=[common], help="present/MISSING, length, key id") p.add_argument("names", nargs="*") p.set_defaults(fn=cmd_secrets_check) sv.add_parser("list", parents=[common], help="names and metadata, never values") \ .set_defaults(fn=cmd_secrets_list) p = sv.add_parser("rotate", parents=[common], help="replace a secret's value") p.add_argument("name") p.add_argument("--stdin", action="store_true") p.set_defaults(fn=cmd_secrets_rotate) p = sv.add_parser("rm", parents=[common], help="delete a secret") p.add_argument("name") p.add_argument("--force", action="store_true", help="even if a lane uses it") p.set_defaults(fn=cmd_secrets_rm) sv.add_parser("rekey", parents=[common], help="re-encrypt every secret under a new DB key") \ .set_defaults(fn=cmd_secrets_rekey) a = ap.parse_args(argv) # Checked before any verb runs: `db init` would otherwise create a DB key # before discovering it was pointed at the wrong file. if a.config.suffix.lower() in (".yaml", ".yml"): die(f"{a.config} is a YAML file; store commands take the database path.\n" f" To move a YAML config into the store: roundtable import-yaml PATH") return a.fn(a) class Pacer: """Spread one vendor's request *starts* to at least `interval` apart. The semaphore in `ask` bounds how many requests are in flight at once. That is a different quantity from how fast they arrive, and vendors meter the second one. Ten lanes dispatched together are ten requests in the same second even at concurrency 1, because each finishes and immediately frees the slot -- so a per-minute cap can be tripped before any 429 comes back to tell us about it. Retrying after a 429 is the reactive half and already exists. This is the proactive half: it costs a few seconds of wall clock and avoids burning a lane's retries on a limit we could have simply not hit. Bookkeeping happens under the lock; the sleep deliberately does not, so waiting threads do not serialise behind each other's sleeps. """ def __init__(self, interval: float): self.interval = max(0.0, interval) self._lock = threading.Lock() self._next = 0.0 def wait(self) -> float: """Block until this vendor's next slot. Returns seconds actually waited.""" if not self.interval: return 0.0 with self._lock: now = time.monotonic() start = max(now, self._next) self._next = start + self.interval delay = start - now if delay > 0: time.sleep(delay) return delay def build_semaphores(lanes: list[dict], default_cc: int) -> dict[str, threading.Semaphore]: """One semaphore per vendor group, sized by the SMALLEST cap in the group. A single-slot local llama.cpp will queue every concurrent request past its own timeout if we fan out against it blindly, so the cap is load-bearing. Smallest, not first: this used to be a `setdefault`, which took whichever lane for that vendor appeared first in the YAML. A `concurrency: 1` lane listed second was silently ignored and the group ran at the default -- reintroducing the exact failure the cap exists to prevent, decided by roster order. build_pacers already resolves rpm by minimum; this agrees with it. """ caps: dict[str, int] = {} for l in lanes: gid = l.get("vendor") or l["name"] cc = int(l.get("concurrency", default_cc)) caps[gid] = min(caps.get(gid, cc), cc) return {gid: threading.Semaphore(cc) for gid, cc in caps.items()} def lineage_collisions(results: list[dict], lanes: list[dict]) -> list[dict]: """Lanes that answered from the same place, and so do not vote independently. The product claim is that convergence between independently-trained models is evidence. Every other guard in this tool protects the plumbing of that claim -- the cost gates, the orphan kills, the partial-delivery exit -- while nothing protected the claim itself. A gateway routes one model string to whatever provider is cheapest at that moment, and a roster can name the same model twice by accident. When either happens the panel reports agreement and the agreement is an echo. Two lanes collide when they resolved to the same (served_by, model), or when they declare the same `lineage:`. Reported, never fatal: a deliberate duplicate is a legitimate thing to want, it just must not be silent. """ by_name = {l["name"]: l for l in lanes} groups: dict[tuple, list[str]] = {} for r in results: if not r.get("answer"): continue lane = by_name.get(r.get("lane")) or {} lineage = lane.get("lineage") # A declared lineage is the operator's own claim and outranks whatever # the gateway happened to report. key = (("lineage", lineage) if lineage else ("served", r.get("served_by"), r.get("model"))) if key[1] is None: continue groups.setdefault(key, []).append(r["lane"]) out = [] for key, names in groups.items(): if len(names) < 2: continue out.append({ "lanes": sorted(names), "kind": key[0], "detail": key[1] if key[0] == "lineage" else f"{key[1]} / {key[2]}", }) return sorted(out, key=lambda c: c["lanes"]) def build_pacers(lanes: list[dict]) -> dict[str, Pacer]: """One Pacer per vendor group, keyed the same way the semaphores are. Where lanes in a group disagree on `rpm`, the smallest wins: the cap belongs to the vendor, not the lane, so the most conservative number is the only one that can be correct for all of them. """ rpms: dict[str, float] = {} for l in lanes: rpm = l.get("rpm") if not rpm: continue gid = l.get("vendor") or l["name"] rpms[gid] = min(rpms.get(gid, float("inf")), float(rpm)) return {gid: Pacer(60.0 / rpm) for gid, rpm in rpms.items()} # --------------------------------------------------------------------------- # # transport # --------------------------------------------------------------------------- # def parse_retry_after(value: str | None) -> float | None: """Seconds to wait, from a Retry-After header, or None if it says nothing. The header has two legal forms and the previous `.isdigit()` test accepted neither reliably: "1.5" is not all digits, and the HTTP-date form is not either, so both silently fell back to the default backoff -- under a comment promising the vendor's own number would be honoured. """ if not value: return None value = value.strip() try: return max(0.0, float(value)) except ValueError: pass try: when = email.utils.parsedate_to_datetime(value) except (TypeError, ValueError): return None if when is None: return None if when.tzinfo is None: when = when.replace(tzinfo=dt.timezone.utc) return max(0.0, (when - dt.datetime.now(dt.timezone.utc)).total_seconds()) def tls_context(lane: dict) -> ssl.SSLContext | None: """The SSL context for one http lane, or None for urllib's default (#78). `ca_bundle` trusts that PEM file *instead of* the system roots, for this lane only: a private CA should not also be able to vouch for OpenRouter. `insecure: true` turns verification off for this lane only, and says so on every call. Neither touches any other lane, which a global PYTHONHTTPSVERIFY=0 would. """ if lane.get("insecure"): print(f"warning: {lane.get('name', '?')}: TLS verification is OFF (insecure: true)", file=sys.stderr) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE return ctx if lane.get("ca_bundle"): path = os.path.expanduser(lane["ca_bundle"]) try: return ssl.create_default_context(cafile=path) except (OSError, ssl.SSLError) as e: raise RuntimeError(f"ca_bundle {path}: {e}") from None return None def http_lane(lane: dict, prompt: str, key: str | None, retries: int) -> dict: body = { "model": lane["model"], "max_tokens": lane.get("max_tokens", 2000), "messages": ( ([{"role": "system", "content": lane["personality"]}] if lane.get("personality") else []) + [{"role": "user", "content": prompt}] ), } if lane.get("temperature") is not None: body["temperature"] = lane["temperature"] body.update(lane.get("extra_body") or {}) url = lane["base_url"].rstrip("/") + "/chat/completions" headers = {"Content-Type": "application/json"} if key: # In-process only. Never argv -- argv is world-readable via ps. headers["Authorization"] = f"Bearer {key}" ctx = tls_context(lane) attempt = 0 while True: req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers) try: with urllib.request.urlopen(req, timeout=lane.get("timeout", 300), context=ctx) as r: data = json.load(r) # A 200 carrying an error body is how an upstream failure arrives when # the gateway itself succeeded -- "Upstream error from Nvidia" on a # free endpoint under load. No completion was produced, so nothing # billed and another attempt is safe. Previously this raised straight # out of the retry loop, so the single most common free-lane failure # was the one failure that never got a second try. if "error" in data: if attempt < retries: attempt += 1 time.sleep(RETRY_BACKOFF * attempt) continue raise RuntimeError(str(data["error"])[:300]) choice = data["choices"][0] answer = (choice["message"].get("content") or "").strip() finish = choice.get("finish_reason") # An empty body is worth another attempt, whatever the finish # reason. Free endpoints return one under load (measured: 1 call in 6 # on one provider, 1 completion token, finish_reason "stop"), and a # reasoning model returns one when that run's thinking overshot the # budget before it reached any answer. # # That second case was briefly treated as deterministic and not # retried at all. It is not: reasoning usage is a distribution, not a # constant. The same lane, same brief, same max_tokens came back # empty 5 times in 10, reasoning ranging 167-353 within those ten # runs -- and 28-4126 across longer ones. A retry is another draw, # and at the margin it wins about half the time. Refusing to retry # threw away a recovery that works. # # It IS a second charge on a metered lane, so it stays bounded by # `retries` exactly like every other path here. if not answer and attempt < retries: attempt += 1 time.sleep(RETRY_BACKOFF * attempt) continue # Out of attempts. Name which failure this was: "empty answer" points # at the vendor, when the number the operator can actually change is # max_tokens. if not answer and finish == "length": raise RuntimeError( "no answer — every attempt spent its whole token budget on " "reasoning; raise max_tokens for this lane" ) return { "answer": answer, "finish_reason": finish, "served_by": data.get("provider"), "usage": data.get("usage"), } except urllib.error.HTTPError as e: retry_after = e.headers.get("Retry-After") if e.headers else None transient = e.code >= 500 or e.code == 429 # urllib builds the HTTPError around the open response, so it holds a # socket until closed. Nothing outside this handler can close it, and # a 13-lane panel retrying 429s would leak one fd per attempt (#90). # Read the body for the message first, then close on every path. try: err_body = b"" if transient and attempt < retries else e.read()[:200] finally: e.close() if transient and attempt < retries: attempt += 1 # Honour Retry-After rather than hammering a rate-limited vendor. wait = parse_retry_after(retry_after) time.sleep(min(wait, RETRY_AFTER_CAP) if wait is not None else RETRY_BACKOFF * attempt) continue raise RuntimeError(f"HTTP {e.code}: {err_body.decode(errors='replace')}") from None except urllib.error.URLError as e: if attempt < retries: attempt += 1 time.sleep(RETRY_BACKOFF * attempt) continue raise RuntimeError(f"connection failed: {e.reason}") from None except TimeoutError: # Deliberately NOT retried. The request may well have completed and # billed on the vendor side; a blind retry double-charges a metered # lane to produce an answer we already paid for. raise RuntimeError(f"timed out after {lane.get('timeout', 300)}s") from None def cli_lane(lane: dict, prompt: str) -> dict: """Run a subscription-backed CLI in one-shot mode. Two things here are not decoration: 1. The child gets a scrubbed environment (see SCRUB_ENV) so an API key in the ambient shell cannot silently convert this free lane into a billed one. 2. start_new_session=True puts the child in its own process group so a timeout can kill the whole tree. A plain subprocess timeout leaves a hung CLI (or one sitting at a login prompt) orphaned and running -- which is precisely the failure this tool was built to eliminate. """ env = child_env(lane) cmd, stdin_text = [], None for arg in lane["args"]: if arg == "{prompt}": cmd.append(prompt) elif arg == "{personality}": cmd.append(lane.get("personality", "")) else: cmd.append(arg) if lane.get("stdin"): stdin_text = prompt cmd = [a for a in cmd if a != prompt] if lane.get("personality") and not any("{personality}" in a for a in lane["args"]): text = f"{lane['personality']}\n\n---\n\n{prompt}" if stdin_text is not None: stdin_text = text else: cmd = [lane["personality"] + "\n\n---\n\n" + a if a == prompt else a for a in cmd] proc = subprocess.Popen( [lane["command"], *cmd], stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, start_new_session=True, ) # `with` closes the pipes on every exit path. communicate() closes them on # success, but not when it times out, so the kill path leaked them (#90). with proc: try: out, err = proc.communicate(stdin_text, timeout=lane.get("timeout", 300)) except subprocess.TimeoutExpired: try: os.killpg(os.getpgid(proc.pid), signal.SIGKILL) except (ProcessLookupError, PermissionError): pass proc.wait(timeout=10) raise RuntimeError(f"timed out after {lane.get('timeout', 300)}s (process group killed)") from None if proc.returncode != 0: raise RuntimeError(f"{lane['command']} exit {proc.returncode}: {err.strip()[:200]}") # Shell profiles and CLI banners pollute stdout with escape sequences. Strip # them rather than dropping whole lines: deleting an answer line to dodge a # banner is the wrong trade in a tool that treats a clipped answer as a # failure worth surfacing. # # There used to be a hardcoded clock emoji here too -- one machine's # shell-hook banner, baked into a general-purpose tool, silently deleting any # answer line that happened to begin with that glyph. A per-CLI quirk belongs # in that lane's config, which is what `strip_prefixes` is for, and the # general rule belongs here. text = ANSI_RE.sub("", out) drop = tuple(lane.get("strip_prefixes") or ()) if drop: text = "\n".join(l for l in text.splitlines() if not l.strip().startswith(drop)) text = text.strip() if not text: raise RuntimeError("produced no output") return {"answer": text, "finish_reason": "stop", "served_by": lane["command"], "usage": None} # --------------------------------------------------------------------------- # # run # --------------------------------------------------------------------------- # def acp_lane(lane: dict, prompt: str) -> dict: """Drive an ACP (Agent Client Protocol) agent for exactly one turn. Some assistants expose no one-shot print mode -- only JSON-RPC over stdio. This does the minimum exchange to get one answer: initialize -> session/new -> session/prompt -> collect updates -> kill The process is created for this turn and killed at the end of it, in its own process group. That is the whole point: an ACP agent is a SERVER and will sit there indefinitely if you let it, which is precisely the long-lived-process failure this tool exists to avoid. Do not "optimise" this by reusing a session across lanes or keeping the process warm. """ env = child_env(lane) # An empty directory, not the caller's cwd. # # ACP agents are overwhelmingly coding agents with their own filesystem # tools. clientCapabilities.fs below declares what *this client* offers; it # does not disable theirs, and mcpServers: [] only means "no extra servers". # Handing over os.getcwd() therefore contradicted "lanes have no tools and # no file access" -- and worse for the panel, it let one lane see context # the others could not, which is the independence claim quietly breaking. workdir = tempfile.mkdtemp(prefix="roundtable-acp-") proc = subprocess.Popen( [lane["command"], *(lane.get("args") or [])], stdin=subprocess.PIPE, stdout=subprocess.PIPE, # NOT a PIPE. Nothing reads stderr, so a chatty agent fills the buffer, # blocks on write, and the lane dies at "timed out waiting for # session/prompt" -- pointing the diagnosis at the protocol rather than # at a full pipe. cli_lane escapes this only because communicate() # pumps both streams. stderr=subprocess.DEVNULL, text=True, bufsize=1, env=env, cwd=workdir, start_new_session=True, ) lk, wlk, replies, chunks = threading.Lock(), threading.Lock(), {}, [] thoughts = [0] def send(msg): with wlk: proc.stdin.write(json.dumps(msg) + "\n") proc.stdin.flush() def reader(): try: for line in proc.stdout: try: m = json.loads(line) except (ValueError, TypeError): continue # agents emit non-JSON banners on stdout if "id" in m and ("result" in m or "error" in m): with lk: replies[m["id"]] = m elif "id" in m and "method" in m: # ACP is bidirectional: the agent can call US, and it BLOCKS # its turn until we respond. Ignoring these (the old # behaviour) stalls the turn forever while generation keeps # streaming -- the answer is produced, billed, and never # delivered (#56). Lanes have no tools, so the honest # answers are "no" and "no such method". if m["method"] == "session/request_permission": # "cancelled" means the USER cancelled the whole turn, # and agents honour it: Laguna's first delivered # full-brief turn ended after one sentence on exactly # that reply (#62). The no-tools answer is to SELECT a # reject option -- "denied, carry on" -- and fall back # to cancelled only when the request offers no options. opts = ((m.get("params") or {}).get("options")) or [] rej = next((o for o in opts if str(o.get("kind", "")).startswith("reject")), None) or next( (o for o in opts if any(w in str(o.get("name", "")).lower() for w in ("reject", "deny"))), None) if rej is not None and rej.get("optionId") is not None: send({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": { "outcome": "selected", "optionId": rej["optionId"]}}}) else: send({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": {"outcome": "cancelled"}}}) else: send({"jsonrpc": "2.0", "id": m["id"], "error": {"code": -32601, "message": f"{m['method']} not supported"}}) elif m.get("method") == "session/update": u = (m.get("params") or {}).get("update") or {} if u.get("sessionUpdate") == "agent_message_chunk": t = (u.get("content") or {}).get("text") if t: chunks.append(t) elif u.get("sessionUpdate") == "agent_thought_chunk": thoughts[0] += 1 # diagnostics only, never the answer except (ValueError, OSError): pass # stream closed under us on kill threading.Thread(target=reader, daemon=True).start() deadline = time.time() + lane.get("timeout", 300) def call(rid, method, params): send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) while time.time() < deadline: with lk: if rid in replies: return replies[rid] if proc.poll() is not None: raise RuntimeError(f"{lane['command']} exited during {method}") time.sleep(0.05) # Say what WAS seen: "31733 thought chunks, 0 answer chunks" is a model # still reasoning at the deadline; "0 and 0" is a dead handshake. The # bare message made those look identical for four days. raise RuntimeError( f"timed out waiting for {method} " f"({len(chunks)} answer chunks, {thoughts[0]} thought chunks streamed)") try: call(0, "initialize", {"protocolVersion": lane.get("protocol_version", 1), "clientCapabilities": {"fs": {"readTextFile": False, "writeTextFile": False}}}) r = call(1, "session/new", {"cwd": workdir, "mcpServers": []}) sid = (r.get("result") or {}).get("sessionId") if not sid: raise RuntimeError(f"session/new returned no sessionId: {str(r)[:150]}") # Per-lane session config, applied before the prompt. ACP agents expose # tunables (thought level, mode, model) only as session/set_config_option # calls after session/new -- pool's --settings flag does NOT reach them # (measured 2026-09-04: thought_level stayed "max" under every --settings # spelling). A rejected value is a hard failure, not a silent fallback: # a lane that quietly ran at the wrong thought level is a mislabeled # answer, which is worse than no answer. for rid, (cid, val) in enumerate( sorted((lane.get("config_options") or {}).items()), start=100): r = call(rid, "session/set_config_option", {"sessionId": sid, "configId": cid, "value": val}) if "error" in r: raise RuntimeError( f"set_config_option {cid}={val!r} rejected: {str(r['error'])[:150]}") got = next((o.get("currentValue") for o in (r.get("result") or {}).get("configOptions") or [] if o.get("id") == cid), val) if got != val: raise RuntimeError( f"set_config_option {cid}: asked {val!r}, agent reports {got!r}") text = prompt if lane.get("personality"): text = f"{lane['personality']}\n\n---\n\n{prompt}" try: r = call(2, "session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]}) except RuntimeError as e: # The turn's deadline passed, but answer text already streamed in. # Discarding it is the project's cardinal sin inverted: a billed # generation delivered to nobody (#56). Return what arrived, marked # truncated -- the summary must not read it as complete. if str(e).startswith("timed out") and chunks: return {"answer": "".join(chunks).strip(), "finish_reason": "timeout", "served_by": lane["command"], "usage": None} raise if "error" in r: raise RuntimeError(str(r["error"])[:200]) stop = (r.get("result") or {}).get("stopReason") answer = "".join(chunks).strip() if not answer: raise RuntimeError(f"no agent_message_chunk received (stopReason={stop})") return {"answer": answer, "finish_reason": "length" if stop == "max_tokens" else "stop", "served_by": lane["command"], "usage": None} finally: try: os.killpg(os.getpgid(proc.pid), signal.SIGKILL) except (ProcessLookupError, PermissionError, OSError): pass # killpg only signals. Without a wait the child stays a zombie in the # process table for the life of the run -- one per acp lane. cli_lane # already reaps; this now matches it. try: proc.wait(timeout=10) except (subprocess.TimeoutExpired, OSError): pass # The pipes outlive the process unless closed here: one leaked pair per # acp lane (#90). The reader thread may still hold stdout; closing it # under the thread ends its loop, which it already tolerates. for f in (proc.stdin, proc.stdout): try: f.close() except (OSError, ValueError): pass shutil.rmtree(workdir, ignore_errors=True) def ask(lane, prompt, keys, retries, deadline, sems, lock, spent, prices, pacers=None): started = time.time() result = { "lane": lane["name"], "model": lane.get("model"), "vendor": lane.get("vendor"), "harness": lane["harness"], "answer": None, "error": None, "finish_reason": None, } # A vendor with no configured semaphore must not crash the lane -- ask() is # called from synthesize() as well as the fan-out, and a reader's vendor may # not be in `sems`. This was a nullcontext until the deadline work replaced # `with sem:` by an explicit acquire/release, which nullcontext does not # have. None is the honest value, and every use below already guards for it. sem = sems.get(lane.get("vendor") or lane["name"]) try: if deadline and time.time() > deadline: raise RuntimeError("global deadline passed before dispatch") pacer = (pacers or {}).get(lane.get("vendor") or lane["name"]) if pacer: result["paced_s"] = round(pacer.wait(), 2) # Pacing can push a lane past a deadline that it was inside when the # run started. Re-check rather than dispatching a request whose # answer we have already decided not to wait for. if deadline and time.time() > deadline: raise RuntimeError("global deadline passed while pacing") # Waiting for a vendor slot is unbounded without this, and both checks # above have already passed by then -- which is how deadline_seconds # came to bound nothing at all. Every thread reached them at t=0. if sem is not None: slot_wait = (deadline - time.time()) if deadline else None if slot_wait is not None and slot_wait <= 0: raise RuntimeError("global deadline passed before dispatch") if not (sem.acquire(timeout=slot_wait) if slot_wait is not None else sem.acquire()): raise RuntimeError("global deadline passed waiting for a vendor slot") try: # The lane's own timeout, further capped by whatever is left of the # run. "whole-run wall clock" has to actually bound the wall clock, # or it reads as a guarantee it does not give. budget_s = lane.get("timeout", 300) if deadline: budget_s = min(budget_s, deadline - time.time()) if budget_s <= 0: raise RuntimeError("global deadline passed before dispatch") bounded = {**lane, "timeout": budget_s} if lane["harness"] == "acp": out = acp_lane(bounded, prompt) elif lane["harness"] == "cli": out = cli_lane(bounded, prompt) else: key = keys.get(lane["key_entry"]) if lane.get("key_entry") else None out = http_lane(bounded, prompt, key, retries) finally: if sem is not None: sem.release() result.update(out) if not result["answer"]: result["error"] = "empty answer" # A clipped answer is a silent failure: it reads as complete and is not. if result.get("finish_reason") in ("length", "timeout"): result["truncated"] = True # Charge prompt and completion separately: completion is typically 2-4x # the prompt rate, so a blended per-token figure understates a long answer. pin, pout = prices u = out.get("usage") or {} if (pin or pout) and u: cost = (u.get("prompt_tokens") or 0) * pin + (u.get("completion_tokens") or 0) * pout result["cost"] = round(cost, 6) with lock: spent[0] += cost except Exception as e: # noqa: BLE001 — a lane failing must never kill the run result["error"] = str(e) result["seconds"] = round(time.time() - started, 1) return result SYNTH_PROMPT = """Below are {n} independent answers to the same question, each from a different model that could not see the others. Report ONLY: 1. AGREED — points where they independently land in the same place. 2. SPLIT — points of genuine disagreement. For each, say WHO takes which side and WHY they differ (different assumption, different priority, different reading). 3. LONE CLAIMS — anything asserted by exactly one lane that the others neither support nor contradict. Flag any that look like invented specifics. Do not summarise the answers. Do not add your own opinion on the question. If they substantially agree, say so in one line rather than manufacturing a split. --- THE QUESTION --- {brief} --- THE ANSWERS --- {answers}""" SYNTH_SECTIONS = ("AGREED", "SPLIT", "LONE CLAIMS") # A section header, and only at the start of a line. # # Matching the bare word anywhere used to be enough to relocate every finding: a # reader that opens with "I will report AGREED, SPLIT and LONE CLAIMS below" # put all three markers in its preamble, so every lane fell into whichever # section came last. Restating the instructions is the common case, not an # exotic one, and the result was a THE READERS DISAGREE block listing lanes that # both readers had in fact classified identically. # # Tolerates the shapes models actually emit: `AGREED`, `## AGREED`, `**AGREED**`, # `1. AGREED`, `### 2) SPLIT`. SECTION_RE = re.compile( r"^[ \t]{0,3}(?:#{1,6}[ \t]*)?(?:\*\*)?(?:\d+[.)][ \t]*)?(?:\*\*)?" r"(AGREED|SPLIT|LONE[ \t]+CLAIMS)\b", re.IGNORECASE | re.MULTILINE, ) def pick_synthesizers(lanes, want, n): """Choose up to n readers, preferring free lanes from *different* vendors. Vendor spread is the point: two readings from one lineage share the priors that make a single reading untrustworthy, so they would agree for the same reason rather than independently. """ named = [l for l in lanes if l["name"] == want] if want else [] pool = [l for l in lanes if l["name"] != want] def rank(l): # cli and acp ride a subscription; :free costs nothing; the rest bill. # acp used to rank alongside metered http, which made reader choice # roster-order dependent and contradicted "prefers free lanes". # lane_prices already treats acp as free -- this now agrees with it. return (0 if l["harness"] in ("cli", "acp") else 1 if str(l.get("model", "")).endswith(":free") else 2) chosen, used_vendors = list(named), {l.get("vendor") for l in named} for lane in sorted(pool, key=rank): if len(chosen) >= n: break if lane.get("vendor") in used_vendors: continue chosen.append(lane) used_vendors.add(lane.get("vendor")) # Only if vendor spread could not fill the quota, allow a repeat vendor -- # two readings still beat one, even correlated ones. for lane in sorted(pool, key=rank): if len(chosen) >= n: break if lane not in chosen: chosen.append(lane) return chosen[:n] def classify_mentions(text, lane_names): """Which section of a reading each lane is named under. Deliberately mechanical. Comparing two readings with a third model would reintroduce exactly the problem this is meant to expose -- another single model's priors deciding what counts as a difference. """ if not text: return {} marks = [ (m.start(), " ".join(m.group(1).upper().split())) for m in SECTION_RE.finditer(text) ] if not marks: return {} # Segment on every header in document order. A section that appears twice # contributes both of its spans rather than only the first. bounds = [ (sec, text[pos:(marks[i + 1][0] if i + 1 < len(marks) else len(text))]) for i, (pos, sec) in enumerate(marks) ] out = {} for name in lane_names: # Word-bounded: substring matching let a lane called `Chair` be claimed # by the word "Chairman", and `Local` by the word "local". pat = re.compile(rf"\b{re.escape(name)}\b", re.IGNORECASE) hits = {sec for sec, chunk in bounds if pat.search(chunk)} if hits: out[name] = sorted(hits) return out def compare_readings(readings, lane_names): """Where the readers genuinely disagree about a lane's classification. Disjoint placements, not merely unequal ones. Readers differ in how liberally they name lanes: one writes "all four land on the same core" and so names every lane in every section, another describes the sections without attribution and names lanes only under LONE CLAIMS. Comparing sets for equality flags every lane on a panel the readers agreed about -- observed on a live four-lane run where one reader's own summary was "no genuine disagreement". Overlap means they put the lane in at least one of the same buckets, which is not a disagreement. A block that fires on an agreeing panel teaches the reader to skip it, which is worse than not printing it. """ if len(readings) < 2: return [] maps = [(r["by"], classify_mentions(r.get("text"), lane_names)) for r in readings] conflicts = [] for name in lane_names: placements = {by: m.get(name) for by, m in maps} sets = [set(v) for v in placements.values() if v] # Fewer than two readers placed it at all: nothing to disagree about. if len(sets) < 2: continue common = set.intersection(*sets) if not common: conflicts.append({"lane": name, "placements": placements}) return conflicts def estimate_synthesis(lanes, brief, table, defaults, calib, want, count): """Worst-case cost of the --diff readers. This used to be invisible to the budget. Each reader is sent the brief plus *every* lane's answer, so it is the largest single request of the run -- and since two readers became the default, it is sent twice. Gating the panel and ignoring the synthesis made `--max-spend` a check on the cheap half. Bounded before dispatch the same way the panel is: assume every lane fills its max_tokens, which is the ceiling its answer can reach. """ readers = pick_synthesizers(lanes, want, count) if not readers: return 0.0 body_chars = sum( float(l.get("max_tokens", defaults.get("max_tokens", 2000))) * chars_per_token(l.get("model"), calib) for l in lanes ) prompt_chars = min(len(brief), 4000) + body_chars + len(SYNTH_PROMPT) total = 0.0 for r in readers: pin, pout = lane_prices(r, table) if not (pin or pout): continue in_tok = prompt_chars / chars_per_token(r.get("model"), calib) # synthesize() raises a reader's ceiling to at least 1500; match it. out_tok = max(float(r.get("max_tokens", defaults.get("max_tokens", 2000))), 1500) total += in_tok * pin + out_tok * pout return total def synthesize(results, brief, cfg, lanes, keys, prices, count=2, sems=None, lock=None, spent=None, deadline=None, pacers=None, retries=1): """Ask N lanes to report where the others diverged (issues #6, #8). Reading N full answers does not scale, and disagreement is the actual product. This is opt-in because it is NOT neutral: a synthesizer is itself one model with its own priors deciding what counts as a disagreement. It is a reading aid, not a verdict -- which is why the raw answers are still written to the transcript. Two readers rather than one, because a single reading hides its own bias: with one you cannot tell a real split from that model's taste in splits. Where two independent readers place the same lane differently, the reading is doing the work rather than the evidence. That comparison is mechanical on purpose -- handing it to a third model would just move the problem. Prefers free lanes so the convenience does not quietly cost money. """ answered = [r for r in results if r.get("answer")] if len(answered) < 2: return None, "need at least 2 answers to compare" chosen = pick_synthesizers(lanes, cfg.get("synthesizer"), max(1, int(count))) if not chosen: return None, "no lane available to synthesize" body = "\n\n".join(f"### {r['lane']} ({r['model'] or r['harness']})\n{r['answer']}" for r in answered) ask_text = SYNTH_PROMPT.format(n=len(answered), brief=brief.strip()[:4000], answers=body) # Route readers through ask() rather than calling the transports directly. # Going around it meant synthesis ignored the per-vendor semaphore (so it # could overrun a single-slot local server), ignored rpm pacing, ignored the # deadline, and -- worst -- never added its tokens to `spent`, so the run's # reported cost omitted its largest request. def read(lane): synth_lane = {**lane, "max_tokens": max(int(lane.get("max_tokens", 2000)), 1500), "personality": None} return ask(synth_lane, ask_text, keys, retries, deadline, sems if sems is not None else {}, lock or threading.Lock(), spent if spent is not None else [0.0], lane_prices(lane, prices), pacers) # Collect via as_completed rather than calling .result() in dispatch order # (#83): the old loop blocked on reader 1 before it would look at reader 2, # so anything done per lane inside the loop serialised behind the slowest # early reader. Gather into a dict first, then assemble in `chosen` order so # the output is identical regardless of which reader finished first. replies = {} with cf.ThreadPoolExecutor(max_workers=len(chosen)) as pool: futs = {pool.submit(read, l): i for i, l in enumerate(chosen)} for fut in cf.as_completed(futs): replies[futs[fut]] = fut.result() # ask() never raises; it reports via "error" readings, errors = [], [] for i, lane in enumerate(chosen): r = replies[i] if r.get("answer"): readings.append({"by": lane["name"], "text": r["answer"]}) else: errors.append(f"{lane['name']}: {r.get('error') or 'empty answer'}") if not readings: return None, f"synthesis failed ({'; '.join(errors)})" names = [r["lane"] for r in answered] return { "readings": readings, "conflicts": compare_readings(readings, names), "errors": errors, }, None # --------------------------------------------------------------------------- # # revision round # --------------------------------------------------------------------------- # REVISE_PROMPT = """This is round {round} of a panel. In round {prev} you answered the brief below in isolation. Now — and only now — the full panel's answers are in front of you, anonymised as PANELIST letters. Yours is marked. Open your reply with exactly one word on its own line: HOLD or REVISE. Then give your full current answer. It REPLACES your round-{prev} answer, so it must stand alone. If you REVISE, name the specific argument that moved you and the panelist letter it came from. If you HOLD, engage the strongest point made against your position instead of restating yourself. Do not converge for politeness, and do not defer to the majority or to any model you think you recognise in an answer's style. Move only for a reason you can state. {extra} --- THE BRIEF --- {brief} --- ROUND {prev} ANSWERS --- {answers}""" # The verdict the lane was told to open with. Tolerates the same decoration # models actually emit around SECTION_RE's headers: `HOLD`, `**REVISE**`, # `## HOLD`, `> REVISE`. Searched only near the top so a lane *quoting* the # instructions mid-answer is not misread as a verdict. VERDICT_RE = re.compile(r"^[ \t>#*]*(?:\*\*)?(HOLD|REVISE|NEW)\b", re.MULTILINE) def parse_verdict(answer: str | None) -> str | None: m = VERDICT_RE.search((answer or "")[:400]) return m.group(1) if m else None # Children of one pre-run_id --each fan-out start minutes apart, never half an # hour: the same rule the UI uses to group them. LATEST_RUN_GAP = 30 * 60 def transcript_time(p: Path) -> float: m = re.match(r"(\d{8}-\d{6})", p.name) if m: try: return dt.datetime.strptime(m.group(1), "%Y%m%d-%H%M%S").timestamp() except ValueError: pass return p.stat().st_mtime def latest_run_paths(flag: str) -> list[Path]: """`latest-run`: every transcript of the most recent round (#80). `latest:N` counts lanes (#75), so it is right only when N happens to equal the run's lane count, and it reaches past the run boundary otherwise -- the brief and round guards in load_transcripts exist to catch exactly that. A round now has an identity (run_id, #116), so this resolves it directly: the newest lane transcript names the run, and every transcript carrying the same run_id is in it. Synthesis transcripts (#118) are not lanes and are skipped. Transcripts written before run_id fall back to "same brief and round, walking back until a 30-minute gap". Scans newest-first and stops one gap past the earliest match, so it reads a handful of files rather than the whole history. """ files = sorted(TRANSCRIPT_DIR.glob("*.json"), key=lambda p: p.name, reverse=True) newest = None found: list[Path] = [] earliest = None for p in files: t = transcript_time(p) if earliest is not None and t < earliest - LATEST_RUN_GAP: break try: d = json.loads(p.read_text()) except (OSError, ValueError): continue if not isinstance(d, dict) or "results" not in d or d.get("mode") == "synthesis": continue if newest is None: newest = d elif newest.get("run_id"): if d.get("run_id") != newest["run_id"]: continue elif d.get("run_id") or (str(d.get("brief", "")).strip(), int(d.get("round") or 1)) != \ (str(newest.get("brief", "")).strip(), int(newest.get("round") or 1)): break # pre-run_id: one contiguous stretch of the same question if d.get("partial"): die(f"{flag} latest-run: {p.name} is partial (a run still going, or one that " "was killed).\n Name the transcripts explicitly to use what it has.") found.append(p) earliest = t if earliest is None else min(earliest, t) if not found: die(f"{flag} latest-run: no lane transcripts in {TRANSCRIPT_DIR}") return found def latest_lane_paths(flag: str, spec: str, n: int) -> list[Path]: """`latest:N`: the newest transcripts that together cover N distinct lanes (#75). N used to count files. That matched the docs ("N = the run's lane count") only for `--each`, which writes one file per lane: a `--panel` round is ONE file holding every lane, so `latest:12` refused a 12-lane panel round, and a lane retried in its own file was counted twice. Counting lanes makes N mean the same thing for both modes. Synthesis transcripts (#118) carry no lanes and are skipped; unreadable files are left for an explicit path to report. """ files = sorted(TRANSCRIPT_DIR.glob("*.json"), key=lambda p: p.name, reverse=True) picked: list[Path] = [] lanes: set[str] = set() for p in files: try: d = json.loads(p.read_text()) except (OSError, ValueError): continue if not isinstance(d, dict) or not isinstance(d.get("results"), list) \ or d.get("mode") == "synthesis": continue got = {r["lane"] for r in d["results"] if isinstance(r, dict) and r.get("lane")} if not got: continue picked.append(p) lanes |= got if len(lanes) >= n: return picked die(f"{flag} {spec}: N counts lanes, and the transcripts in {TRANSCRIPT_DIR} cover " f"only {len(lanes)} distinct lane(s) across {len(picked)} file(s).\n" " A --panel round is one file holding every lane; an --each round is one file " "per lane.\n Use latest-run for the newest whole run, or name the files.") def load_transcripts(arg: str, flag: str = "--revise") -> tuple[list[Path], dict]: """Resolve --revise's (or --synthesize's) argument into one merged prior round. Accepts explicit paths (comma-separated), `latest`, `latest:N`, and `latest-run` (every transcript of the newest round, by run_id). The multi-file forms exist because `--each` — the recommended way to run a panel — writes ONE TRANSCRIPT PER LANE by design, so "the previous round" of a 12-lane run is 12 files, and `latest:12` is how you name them without listing them. N counts lanes, not files (#75), so `latest:12` also names a 12-lane `--panel` round, which is one file. Briefs must match across the files: mixing transcripts of different questions is only ever an accident (a `latest:N` that reached past the run boundary into someone else's transcripts), and the merge would silently hand every lane a packet half about the wrong question. """ paths: list[Path] = [] for spec in (s.strip() for s in arg.split(",")): if not spec: continue if spec == "latest-run": paths.extend(latest_run_paths(flag)) continue if spec == "latest" or spec.startswith("latest:"): # Parse N defensively (#76): a bare int() here was the one place # the tool leaked a raw traceback where every other bad input # die()s with a message naming the fix. Zero and negatives are # refused too — cands[-0:] would silently mean "all of them". n_str = spec.split(":", 1)[1] if ":" in spec else "1" if not n_str.isdecimal() or int(n_str) < 1: die(f"{flag} latest:N needs a positive integer (e.g. latest:12)") paths.extend(latest_lane_paths(flag, spec, int(n_str))) else: paths.append(Path(spec).expanduser()) # Dedupe, then chronological order: transcript names begin with a timestamp # (then lane/pid for uniqueness), so sorting by name is sorting by time. This # makes the later answer win below when the same lane appears twice. paths = sorted(set(paths), key=lambda p: p.name) if not paths: die(f"{flag}: no transcript named") briefs: set[str] = set() by_lane: dict[str, dict] = {} round_no = 1 rounds_seen: set[int] = set() for p in paths: try: data = json.loads(p.read_text()) except (OSError, json.JSONDecodeError) as e: die(f"cannot read transcript {p}: {e}") if not isinstance(data, dict) or "brief" not in data or "results" not in data: die(f"{p} is not a roundtable transcript (needs brief + results)") briefs.add(data["brief"].strip()) round_no = max(round_no, int(data.get("round") or 1)) rounds_seen.add(int(data.get("round") or 1)) for r in data["results"]: # A panel transcript written mid-run holds None for the lanes that # had not answered yet; r.get() on one was a raw traceback (#118). if not isinstance(r, dict): continue # An answer never loses to a later failure of the same lane. if r.get("answer") or r["lane"] not in by_lane: by_lane[r["lane"]] = r if len(briefs) > 1: die(f"{flag}: transcripts answer different briefs — refusing to mix them.\n" " name the files explicitly, or use latest:N with N = that run's lane count") if len(rounds_seen) > 1: # Found in first live use: retrying one failed lane of a revision round # with latest:N swept in the siblings' round-2 transcripts. The brief # guard cannot catch that — a revision round records the SAME brief — # and the merge would hand the lane its peers' round-2 answers labelled # as the round it is trying to redo. die(f"{flag}: transcripts span rounds {{}} — refusing to mix them.\n" " name the files of ONE round explicitly".format(sorted(rounds_seen))) merged = {"brief": briefs.pop(), "results": list(by_lane.values()), "round": round_no} if not any(r.get("answer") for r in merged["results"]): die(f"{flag}: no answers in the named transcript(s)") return paths, merged def print_synthesis(synth: dict | None, synth_err: str | None) -> None: """Print a --diff synthesis: each reader's reading, then where the readers disagree.""" if synth: for r in synth["readings"]: print(f"\n{'=' * 74}\nWHERE THEY DIVERGE (read by {r['by']})\n{'=' * 74}") print(r["text"]) # Two readers exist so the reading's own bias is visible. Where they # place the same lane differently, that is the synthesizer talking, # not the panel -- go read that lane's raw answer. if synth["conflicts"]: print(f"\n{'=' * 74}\nTHE READERS DISAGREE\n{'=' * 74}") for c in synth["conflicts"]: where = " ".join( f"{by}={'/'.join(sec) if sec else 'unmentioned'}" for by, sec in c["placements"].items() ) print(f" {c['lane']:<18} {where}") print("\n These are classification disputes between the readers, not\n" " findings. Read those lanes' raw answers in the transcript.") elif len(synth["readings"]) > 1: print(f"\n Both readers classified every lane the same way.") for e in synth.get("errors") or []: print(f"\n !! reader failed — {e}", file=sys.stderr) n = len(synth["readings"]) print(f"\n -- {n} lane{'s' if n != 1 else ''} reading the others, not a verdict." f" raw answers in the transcript.") else: print(f"\n !! {synth_err}", file=sys.stderr) def synthesize_run(a, cfg: dict, lanes: list[dict]) -> int: """--synthesize: run only the --diff readers over a FINISHED run (#118). `--each --diff` is refused (#74) because synthesis needs every answer in one process, and its refusal said to "synthesize the transcripts afterwards" -- but nothing did. This is that step. The answers are locked: they are read from the transcripts, no lane is re-queried, and the run's independence is untouched, because the readers see the answers only after every lane has given one. The only requests are the readers' own, and they go through the same budget gate, pricing, semaphores and pacing as a --diff run. The result is written as its own transcript carrying the parent run's run_id, with `results` empty so nothing that merges transcripts counts an answer twice. """ paths, prior = load_transcripts(a.synthesize, flag="--synthesize") answered = [r for r in prior["results"] if r.get("answer")] if len(answered) < 2: die("--synthesize: need at least 2 answers to compare") ids = set() for p in paths: try: ids.add(json.loads(p.read_text()).get("run_id")) except (OSError, ValueError): pass # Same run as the answers it reads, so a reader of runs (the UI) shows the # synthesis on that run. An explicit --run-id wins; a mixed set gets a new one. run_id = a.run_id or (ids.pop() if len(ids) == 1 and None not in ids else new_run_id()) count = int(cfg.get("synthesizers", 2)) readers = pick_synthesizers(lanes, cfg.get("synthesizer"), count) if not readers: die("--synthesize: no active lane is available to read") budget = a.max_spend if a.max_spend is not None else cfg.get("budget_usd") prices = load_pricing(readers) if budget is not None: unpriced = [l for l in readers if not lane_price_known(l, prices)] if unpriced: die("a budget is set but these readers have no known price, so it cannot bind:\n" + "".join(f" {l['name']} (model {l.get('model') or '-'})\n" for l in unpriced) + " set price_per_mtok on the lane, or pick a reader with --lanes") # The answers are known, so the estimate is exact on the input side rather # than the max_tokens ceiling estimate_synthesis has to assume before a run. calib = load_calibration() defaults = cfg.get("defaults") or {} body_chars = sum(len(r["answer"]) + len(r["lane"]) + 40 for r in answered) prompt_chars = min(len(prior["brief"]), 4000) + body_chars + len(SYNTH_PROMPT) estimate = 0.0 for r in readers: pin, pout = lane_prices(r, prices) in_tok = prompt_chars / chars_per_token(r.get("model"), calib) out_tok = max(float(r.get("max_tokens", defaults.get("max_tokens", 2000))), 1500) estimate += in_tok * pin + out_tok * pout if budget is not None and estimate > budget: die(f"estimated worst case ${estimate:.4f} exceeds budget ${budget:.2f} — refusing to dispatch\n" f" raise --max-spend or pick cheaper readers with --lanes") keys = fetch_keys(readers) sems = build_semaphores(readers, int(cfg.get("concurrency", 8))) pacers = build_pacers(readers) lock, spent = threading.Lock(), [0.0] deadline = time.time() + cfg["deadline_seconds"] if cfg.get("deadline_seconds") else None synth, synth_err = synthesize(answered, prior["brief"], cfg, readers, keys, prices, count=count, sems=sems, lock=lock, spent=spent, deadline=deadline, pacers=pacers, retries=int(cfg.get("retries", 1))) path = None if not a.no_transcript: private_transcript_dir() stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S") path = TRANSCRIPT_DIR / f"{stamp}-synthesis-{os.getpid()}.json" save_transcript({"run_id": run_id, "brief": prior["brief"], "results": [], "synthesis": synth, "synthesis_error": synth_err, "mode": "synthesis", "round": int(prior.get("round") or 1), "parent": [str(p) for p in paths], "cost": round(spent[0], 6), "spend": spend_report(spent[0], estimate, budget, readers, prices)}, path) if a.json: print(json.dumps({"run_id": run_id, "synthesis": synth, "error": synth_err, "cost": round(spent[0], 6), "spend": spend_report(spent[0], estimate, budget, readers, prices)}, indent=2)) else: print(f"SYNTHESIS of {len(answered)} answers from {len(paths)} transcript(s)") print_synthesis(synth, synth_err) if spent[0] or estimate: print(f"spend: ${spent[0]:.4f} actual (est. worst case ${estimate:.4f})") if path: print(f"transcript: {path}") return 0 if synth else 1 def private_transcript_dir() -> Path: """Make TRANSCRIPT_DIR exist and be private to the user (0700). A transcript holds the full brief and every lane's answer, and briefs are routinely confidential. The default umask leaves the directory world-listable, which hands the filenames -- and, with 0644 files, the contents -- to any local user, including a `cli` lane's vendor agent, which runs with full tool access (#73). The chmod on an existing dir is for transcript dirs created before this fix. """ TRANSCRIPT_DIR.mkdir(mode=0o700, parents=True, exist_ok=True) TRANSCRIPT_DIR.chmod(0o700) return TRANSCRIPT_DIR def save_transcript(record: dict, path: Path) -> Path: """Write one transcript at `path`, private to the user (dir 0700, file 0600). Atomic via write-then-replace: a kill during the write leaves the previous good transcript rather than a truncated one (#58). The staging file is a UNIQUE mkstemp in the same directory (same filesystem, so the replace is still atomic): a name derived from `path` made two writers colliding on one transcript also collide on one .json.tmp and race before either rename (#70). The 0600 goes on the staging file BEFORE the replace, so there is no window in which the transcript is readable by anyone else (#73). """ private_transcript_dir() fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".json.tmp") try: os.fchmod(fd, 0o600) with os.fdopen(fd, "w") as fh: fh.write(json.dumps(record, indent=2)) os.replace(tmp, path) except BaseException: # Never leave a half-written temp behind if the write or rename fails. try: os.unlink(tmp) except OSError: pass raise return path def alias_map(results: list[dict]) -> dict[str, str]: """Stable anonymous letters for every lane that answered. Anonymised because attribution invites authority-weighting — "the Anthropic lane said so" is exactly the deference the revision instructions forbid. One global map rather than per-viewer letters, so a lane writing "Panelist C's cost argument moved me" means the same C in every packet and in the transcript's audit record. """ answered = [r["lane"] for r in results if r.get("answer")] return {name: (chr(ord("A") + i) if i < 26 else f"P{i + 1}") for i, name in enumerate(answered)} def build_revision_prompt(lane_name: str, prior: dict, aliases: dict[str, str], round_no: int, focus: str = "") -> str: own = next((r for r in prior["results"] if r["lane"] == lane_name and r.get("answer")), None) sections = [] if own: sections.append(f"YOUR ROUND-{round_no - 1} ANSWER " f"(you are PANELIST {aliases[lane_name]} to the others):\n" f"{own['answer']}") else: sections.append(f"YOU GAVE NO ROUND-{round_no - 1} ANSWER (your lane failed or " f"was absent). Treat this as your first answer, and open with " f"the word NEW instead of HOLD or REVISE.") for r in prior["results"]: if not r.get("answer") or r["lane"] == lane_name: continue sections.append(f"PANELIST {aliases[r['lane']]}:\n{r['answer']}") extra = f"\n--- ADDITIONAL FOCUS FOR THIS ROUND ---\n{focus}\n" if focus else "" return REVISE_PROMPT.format(round=round_no, prev=round_no - 1, brief=prior["brief"], extra=extra, answers="\n\n".join(sections)) # --------------------------------------------------------------------------- # # discussion mode # --------------------------------------------------------------------------- # # --discuss: the panel shares ONE context and takes turns in it, one lane in # flight at a time. # # Buzz (the standing fleet) gives lanes a conversation by keeping a resident # agent runtime per lane and a message bus between them, and that is exactly # what made it too heavy to keep around. Here the "shared context space" is a # string: the brief, the anonymised opening positions, and every turn said so # far, in order. A turn is one ordinary ask() with that string as the prompt, # so the process holds one request at a time -- a cli lane's agent runtime # exists only for its turn -- and nothing outlives the run, which keeps the # no-long-lived-process guarantee the rest of the tool is built on. # # The thread is O(N^2) in prompt tokens: turn k re-sends the k-1 turns before # it. DISCUSS_WORDS caps what one turn adds and --discuss-rounds caps the # passes; the budget gate prices the longest packet times the requests per lane. # # A shared thread has a failure mode a blind round cannot have: one lane's # invention becomes everyone's premise. In the first live run (#98) a lane # asserted a "default 24 h" expiry that does not exist and the next three # turns cited it as evidence. Both prompts therefore say that a fact first # introduced in the thread is a claim until its source is cited. That lowers # the rate; the reader's verification pass is still the control. # # Every turn is appended to the transcript as soon as it returns, so a run that # dies at turn 17 leaves 16 turns on disk. The closings are saved as `results`, # which makes a discussion transcript a valid parent for --revise, --diff # synthesis or another --discuss. DISCUSS_WORDS = 300 DISCUSS_PROMPT = """This is a live panel discussion between {n} independent models. You are PANELIST {me}. It is your turn: turn {turn} of {total}, pass {pas} of {passes}. Everything below is shared context: the brief, each panelist's opening position (written in isolation), and the discussion so far in the order it was said. Every panelist sees exactly this. Speak to the panel, not to a moderator. Address panelists by letter. Do at least one of: concede a specific point that was right; challenge a specific claim and say why; answer a question that was put to you; ask one question whose answer would settle a dispute. Do not restate your opening and do not summarise the discussion. Do not defer to the majority or to any model you think you recognise. If nothing has been said yet, open the discussion with the point you most want tested. Stay under {words} words. A fact first introduced in this discussion -- not in the brief, not in an opening -- is a claim, not evidence, until its source is cited: a file and line, a command that was run, a document. Do not build on one; ask for its source. If you rely on one anyway, say that you have not verified it. {extra} --- THE BRIEF --- {brief} --- OPENING POSITIONS --- {openings} --- DISCUSSION SO FAR --- {thread}""" CLOSING_PROMPT = """The discussion is over. You are PANELIST {me}. Give your closing position on the brief. Open your reply with exactly one word on its own line: HOLD or REVISE, relative to your opening position (NEW if you gave none). Your closing REPLACES your opening, so it must stand alone. If you REVISE, name the argument that moved you and the panelist letter it came from. If you HOLD, answer the strongest point made against you instead of restating yourself. Move only for a reason you can state. A fact first introduced in this discussion -- not in the brief, not in an opening -- is a claim, not evidence, until its source is cited: a file and line, a command that was run, a document. Do not let one carry your closing; if it does, say that you have not verified it. {extra} --- THE BRIEF --- {brief} --- OPENING POSITIONS --- {openings} --- THE DISCUSSION --- {thread}""" def discussion_aliases(lanes: list[dict], prior: dict | None) -> dict[str, str]: """Letters for everyone in the room. Prior-round lanes keep the letters alias_map would give them, so a lane that opened as PANELIST C is still C when it speaks; roster lanes with no opening (a cold start, or a lane that failed in round 1) are lettered after. A prior lane not on this roster keeps its letter too -- its opening is still shown, it just never gets a turn. """ aliases = alias_map(prior["results"]) if prior else {} for l in lanes: if l["name"] not in aliases: i = len(aliases) aliases[l["name"]] = chr(ord("A") + i) if i < 26 else f"P{i + 1}" return aliases def render_openings(prior: dict | None, aliases: dict[str, str]) -> str: if not prior: return "(none -- this discussion starts cold)" return "\n\n".join(f"PANELIST {aliases[r['lane']]}:\n{r['answer']}" for r in prior["results"] if r.get("answer")) def render_thread(thread: list[dict]) -> str: # A turn that failed is kept in the transcript but not read to the panel: # "[no answer]" is noise to argue with. The turn numbers stay as spoken. said = [f"PANELIST {t['alias']} (turn {t['turn']}):\n{t['answer']}" for t in thread if t.get("answer")] return "\n\n".join(said) if said else "(nothing yet -- you speak first)" def build_discussion_prompt(me: str, brief: str, prior: dict | None, aliases: dict[str, str], thread: list[dict], turn: int, total: int, pas: int, passes: int, n: int, focus: str = "") -> str: extra = f"\n--- ADDITIONAL FOCUS ---\n{focus}\n" if focus else "" return DISCUSS_PROMPT.format(n=n, me=me, turn=turn, total=total, pas=pas, passes=passes, words=DISCUSS_WORDS, extra=extra, brief=brief, openings=render_openings(prior, aliases), thread=render_thread(thread)) def build_closing_prompt(me: str, brief: str, prior: dict | None, aliases: dict[str, str], thread: list[dict], focus: str = "") -> str: extra = f"\n--- ADDITIONAL FOCUS ---\n{focus}\n" if focus else "" return CLOSING_PROMPT.format(me=me, extra=extra, brief=brief, openings=render_openings(prior, aliases), thread=render_thread(thread)) def run_discussion(lanes: list[dict], brief: str, prior: dict | None, aliases: dict[str, str], rounds: int, focus: str, ask_one, on_turn, on_closing) -> tuple[list[dict], list[dict]]: """Drive the thread: `rounds` passes over the roster, then one closing each. Strictly sequential -- the next turn cannot be built until this one has been said, and one-at-a-time is the memory property the mode exists for. `ask_one(lane, packet)` is ask() with the run's plumbing applied; the two callbacks fire after every turn and every closing so the caller can stream and persist without this function knowing about terminals or transcripts. """ n = len(lanes) total = rounds * n thread: list[dict] = [] for pas in range(rounds): # Rotate the opener each pass so no lane always speaks first (anchoring # the pass) or last (getting the final word for free). order = lanes[pas % n:] + lanes[:pas % n] for l in order: turn = len(thread) + 1 packet = build_discussion_prompt(aliases[l["name"]], brief, prior, aliases, thread, turn, total, pas + 1, rounds, n, focus) r = ask_one(l, packet) thread.append({"turn": turn, "pass": pas + 1, "alias": aliases[l["name"]], **r}) on_turn(thread[-1], thread) closings: list = [None] * n for i, l in enumerate(lanes): closings[i] = ask_one(l, build_closing_prompt(aliases[l["name"]], brief, prior, aliases, thread, focus)) on_closing(closings) return thread, closings def main() -> int: # Store commands (`db ...`, `secrets ...`) get their own parser. This must # run before argparse sees argv: the brief is free-text positional, so the # guard decides, narrowly, which argv is a command and which is a question. if is_admin_argv(sys.argv[1:]): return admin_main(sys.argv[1:]) ap = argparse.ArgumentParser(add_help=False) ap.add_argument("brief", nargs="*") ap.add_argument("--config", type=Path, default=DEFAULT_CONFIG) ap.add_argument("--lanes") ap.add_argument("--each", action="store_true") ap.add_argument("-j", "--concurrency", type=int, default=None, help="with --each, run up to N lanes at once (default 1). " "Per-lane and per-vendor caps still apply.") ap.add_argument("--panel", action="store_true") ap.add_argument("--version", action="version", version=f"roundtable {__version__}") ap.add_argument("--list", action="store_true") ap.add_argument("--json", action="store_true") ap.add_argument("--max-spend", type=float) ap.add_argument("--no-transcript", action="store_true") ap.add_argument("--diff", action="store_true") ap.add_argument("--revise", metavar="TRANSCRIPT") # --converse is the same flag under the name CJ uses for it; argparse # binds both spellings to `discuss`, so nothing downstream knows which # one was typed. ap.add_argument("--discuss", "--converse", dest="discuss", metavar="TRANSCRIPT|new", help="shared-context discussion, one lane speaking at a time: " "seeded from a blind round's transcript(s), or `new` to " "start cold from the brief") ap.add_argument("--discuss-rounds", type=int, default=2, help="passes over the roster before closings (default 2)") ap.add_argument("--synthesize", metavar="TRANSCRIPT", help="run only the --diff readers over a finished run's " "transcripts (paths, latest, latest:N); no lane is re-asked") ap.add_argument("--run-id", metavar="ID", help="tag every transcript of this run with ID (default: generated)") ap.add_argument("--dry-run", "--estimate", dest="dry_run", action="store_true", help="priced pre-flight: resolve config + lanes, fetch prices, " "print the per-lane and panel worst-case cost, exit 0. " "Combines with --each, --panel, --diff, --revise, --discuss. " "Refuses --list and --synthesize. --json emits a machine shape " "(#81). May dial out to load prices; --list stays the offline " "route view.") ap.add_argument("-h", "--help", action="store_true") a = ap.parse_args() if a.help: print(__doc__.strip()) return 0 # One id for the whole run, forwarded to every --each child. Before this, # a fan-out left N transcripts with nothing tying them together, and a # reader (the UI, `--revise latest:N`) could only guess which belonged to # one run from timestamps (#116). Validated because it reaches a filename # reader and a URL in the UI: refuse anything but a plain token. if a.run_id is not None and not RUN_ID_RE.fullmatch(a.run_id): die("--run-id must be 1-64 characters of A-Z a-z 0-9 . _ - (not starting with .)") run_id = a.run_id or new_run_id() if a.synthesize and (a.each or a.panel or a.revise or a.discuss or a.diff): die("--synthesize reads a finished run; it does not start one.\n" " Drop --each/--panel/--revise/--discuss/--diff.") if a.dry_run and a.synthesize: die("--dry-run prices a fresh dispatch; --synthesize reads a finished one.\n" " Drop --synthesize.") if a.dry_run and a.list: die("--dry-run and --list are two different pre-flights; pick one.\n" " --list roster + route, no network, no cost\n" " --dry-run [...] --json priced worst-case panel cost (may dial out for prices)") if a.discuss: if a.revise: die("--discuss and --revise are two different second rounds; pick one") if a.each or a.panel: die("--discuss already runs the lanes one at a time, in one process:\n" " each turn is built from the turns before it, so there is nothing\n" " to fan out. Drop --each/--panel.") if a.discuss_rounds < 1: die("--discuss-rounds needs a positive integer") cfg = load_config(a.config) lanes = [l for l in cfg["lanes"] if l.get("active", True)] # `0/0 lanes answered` used to exit 0, reporting success for a run that # asked nobody anything. len(answered) == len(results) is true of two empty # lists. That is the same shape as partial delivery -- a lane that silently # did not run -- and in a cron or CI context the exit code is the only # signal anyone sees. --list is exempt: showing an empty roster is a fair # answer to "what is configured". if not lanes and not a.list: die(f"{a.config} has lanes, but none are active — " f"enable one with: roundtable lanes enable NAME") if a.lanes: want = {n.strip().lower() for n in a.lanes.split(",")} lanes = [l for l in lanes if l["name"].lower() in want] if not lanes: die(f"--lanes matched nothing in {a.config}") if a.synthesize and not a.list: return synthesize_run(a, cfg, lanes) # Resolve `latest`/`latest:N` to concrete paths HERE, before --each fans # out. Children run sequentially and each writes a transcript, so a child # resolving "latest" for itself would pick up a sibling's round-2 output — # the exact self-echo this feature must not create. prior = None prior_paths: list[Path] = [] if a.revise and not a.list: prior_paths, prior = load_transcripts(a.revise) a.revise = ",".join(str(p) for p in prior_paths) # A discussion seeded from a blind round keeps round 1's epistemic claim # intact; `new` starts cold, and its transcript is round 1 -- a dependent one. if a.discuss and a.discuss != "new" and not a.list: prior_paths, prior = load_transcripts(a.discuss) if a.discuss and len(lanes) < 2 and not a.list: die("--discuss needs at least two lanes; one lane is a monologue") # ONE RUN PER LANE. # # A single invocation finishes when its SLOWEST lane finishes, which couples # every lane's fate to the worst one: one slow lane sets the wall-clock for # all of them, raising its timeout pushes the run past a caller's timeout, and # a lane that dies cannot be retried without rerunning everything. Lanes are # meant to be independent; sharing a deadline makes their failures dependent. # # Measured 2026-08-30: the poolside/ACP lane needs ~400s alone on a 110KB # brief and exceeded 780s under 12-lane contention, losing its answer in four # consecutive rounds. Every one of those losses was avoidable. # # So multi-lane runs must say which they want. --each is the right answer and # is what the refusal points at; --panel is the escape hatch for anyone who # genuinely wants the old shared-deadline behaviour. # --discuss is exempt: it is sequential by construction (see run_discussion), # so no lane ever waits on another's deadline. if len(lanes) > 1 and not a.list and not (a.each or a.panel or a.discuss): die("refusing to run {n} lanes in one invocation.\n" " A shared deadline makes independent lanes fail together: the run is\n" " only as fast as its slowest lane, and one death costs every answer.\n" "\n" " --each run each lane as its own process (what you want)\n" " --each -j N the same, up to N lanes at once\n" " --lanes NAME one lane\n" " --panel the old shared-deadline behaviour, if you mean it" .format(n=len(lanes))) # #74: --diff used to evaporate under --each. The children's argv forwarded # --json/--no-transcript/--revise but not --diff, so the flag was accepted, # ignored, and the run exited 0 with no synthesis. Forwarding it would not # fix that: synthesis compares every lane's answer, and under --each each # answer lives in its own process -- a child with one lane has nothing to # compare. Refuse here, before any child is spawned and before any spend. if a.each and a.diff and not a.list: die("--each --diff: synthesis needs every answer in one process, and\n" " --each gives each lane its own. Either:\n" "\n" " --panel --diff one shared deadline, then synthesis\n" " --each, then --synthesize latest:N readers over the finished run") if a.list: if a.json: # For tools (the UI's lane picker). Names the route, never a secret # or the `pass` entry holding one: a lane's key ref is config, not # something a caller of --list needs. print(json.dumps([{"name": l["name"], "harness": l["harness"], "vendor": l.get("vendor"), "model": l.get("model"), "route": safe_route(l.get("base_url")) or l.get("command") or ""} for l in lanes], indent=2)) return 0 for l in lanes: route = l["harness"] where = l.get("base_url") or l.get("command") or "" print(f" [{route:<4}] {l['name']:<18} {str(l.get('vendor') or '-'):<14} " f"{str(l.get('model') or '-'):<42} {where}") print(f"\n {len(lanes)} active lane(s). No calls made.") return 0 prompt = sys.stdin.read() if a.brief[:1] == ["-"] else " ".join(a.brief) if not prompt.strip() and not a.revise and not prior: die("empty brief") # In a revision round the brief on record stays the ORIGINAL question; any # brief text passed alongside --revise rides in the packet as extra focus. prompts = aliases = None round_no = 1 brief_on_record = prompt est_prompt = prompt if a.revise: aliases = alias_map(prior["results"]) round_no = int(prior.get("round") or 1) + 1 prompts = {l["name"]: build_revision_prompt(l["name"], prior, aliases, round_no, focus=prompt.strip()) for l in lanes} brief_on_record = prior["brief"] # Packets differ per lane only by which answer is marked YOURS; the # longest one is the honest worst case for the budget gate. est_prompt = max(prompts.values(), key=len) focus = "" if a.discuss: aliases = discussion_aliases(lanes, prior) if prior: round_no = int(prior.get("round") or 1) + 1 brief_on_record = prior["brief"] focus = prompt.strip() # The budget gate's worst case: the last closing packet, i.e. the full # context plus every turn at the word cap (~7 chars a word with the # PANELIST headers). Multiplied by requests-per-lane below. est_prompt = build_closing_prompt( "A", brief_on_record, prior, aliases, [{"turn": i + 1, "alias": "A", "answer": "x" * (DISCUSS_WORDS * 7)} for i in range(a.discuss_rounds * len(lanes))], focus) budget = a.max_spend if a.max_spend is not None else cfg.get("budget_usd") deadline = time.time() + cfg["deadline_seconds"] if cfg.get("deadline_seconds") else None prices = load_pricing(lanes) # A budget can only bind on lanes it can price. An unpriced http lane used # to estimate to $0 and slip past the gate unseen (#72) -- fail-open on the # one check whose job is to fail closed. No default rate either: a guessed # number reads as authoritative and is wrong for almost every vendor. if budget is not None and not a.dry_run: unpriced = [l for l in lanes if not lane_price_known(l, prices)] if unpriced: die( "a budget is set but these lanes have no known price, so it cannot bind:\n" + "".join(f" {l['name']} (model {l.get('model') or '-'})\n" for l in unpriced) + " set price_per_mtok on the lane or add vendor: openrouter so the " "price table covers it" ) # Refuse BEFORE spending, not after. A budget checked only on the way out # reports an overrun; it does not prevent one. # # This gate must also sit BEFORE the --each fan-out below (issue #71). It # used to sit after that branch returned, so the parent never ran it: each # child gated only its own lane, and a roster where no single lane is # expensive but the panel total is walked through N cheap gates and spent # N× what any one estimate implied. The whole-panel estimate is the one the # README promises, so it runs here over the full selected set; the child's # own gate stays as a backstop, not the only check. calib = load_calibration() defaults = cfg.get("defaults") or {} estimate = estimate_run(lanes, est_prompt, prices, defaults, calib, retries=int(cfg.get("retries", 1))) if a.diff: # The readers are dispatched from inside this run, so their cost belongs # in the gate that decides whether to dispatch at all. estimate += estimate_synthesis(lanes, brief_on_record, prices, defaults, calib, cfg.get("synthesizer"), int(cfg.get("synthesizers", 2))) if a.discuss: # Each lane speaks once per pass and once to close. estimate *= a.discuss_rounds + 1 # Dry-run reports the same estimate the gate just computed (the human and # JSON numbers MUST match the gate for the UI to rely on it, #81). Skipping # the gate's `die` below is on purpose: a dry-run exists to *show* a number # that may exceed the budget, not to refuse to compute it. The unpriced # --budget die above is gated by `not a.dry_run` so dry-run under a budget # with an unpriced lane reports instead of refusing — same #72 information # the gate would have died with, minus the failure mode the dry-run exists # to avoid. if a.dry_run: return cmd_dry_run(a, cfg, lanes, est_prompt, prices, calib, defaults, estimate, brief_on_record) if budget is not None and estimate > budget: die( f"estimated worst case ${estimate:.4f} exceeds budget ${budget:.2f} — refusing to dispatch\n" f" raise --max-spend, drop lanes with --lanes, or lower max_tokens" ) if a.each: # Re-invoke ourselves once per lane. Separate processes, separate # deadlines, separate transcripts: a lane can be slow, or die, alone. # The panel-wide budget gate above has already passed; a child re-runs # it for its single lane only as a backstop (issue #71). # # Serial by DEFAULT, still: the measurement in the block above is why, # and a config that predates this flag must not silently start fanning # out. `--concurrency N` is the opt-in, and it is the only way to get # parallel lanes without the shared deadline --panel imposes. # # Before this flag existed there was no such way: this loop was a # blocking subprocess.run, so --each was always serial, and anyone who # wanted lanes in parallel had to reach for --panel and give up the # per-lane deadlines that are the entire point of --each. The `concurrency:` # key in the config is deliberately NOT read here -- it is documented as # the panel-mode default, the shipped example sets it to 8, and quietly # honouring it would flip every existing caller from serial to eight-way. # # The per-vendor cap IS applied, by the same smallest-in-group rule # build_semaphores uses, so a `concurrency: 1` local lane still cannot be # run beside its neighbour on the same GPU while the API lanes fan out. # # Output stays in roster order: a lane's block is printed whole, once # every lane before it has been printed, so a concurrent run reads # exactly like a serial one instead of interleaving. At -j1 the child # keeps the terminal directly, so the familiar live streaming is intact. # # --diff is deliberately not forwarded: --each --diff was refused above # (#74), so it cannot reach this point. default_cc = max(int(a.concurrency or 1), 1) caps: dict[str, int] = {} for l in lanes: gid = l.get("vendor") or l["name"] cc = int(l.get("concurrency", default_cc)) caps[gid] = min(caps.get(gid, cc), cc) vendor_sems = {gid: threading.Semaphore(cc) for gid, cc in caps.items()} overall = threading.Semaphore(max(default_cc, 1)) def child_argv(l: dict) -> list[str]: argv = [sys.executable, str(Path(__file__).resolve()), "--lanes", l["name"], "--config", str(a.config), "--run-id", run_id] if a.json: argv.append("--json") if a.no_transcript: argv.append("--no-transcript") if a.revise: argv += ["--revise", a.revise] argv.append("-") return argv def run_one(l: dict) -> tuple[int, str]: gid = l.get("vendor") or l["name"] with overall, vendor_sems[gid]: r = subprocess.run(child_argv(l), input=prompt, text=True, capture_output=True) return r.returncode, (r.stdout or "") + (r.stderr or "") rc = 0 if default_cc == 1: # Unchanged path: the child inherits this terminal and streams. for l in lanes: print(f"\n=== {l['name']} " + "=" * (66 - len(l['name'])), flush=True) r = subprocess.run(child_argv(l), input=prompt, text=True) rc = rc or r.returncode return rc with cf.ThreadPoolExecutor(max_workers=max(len(lanes), 1)) as pool: futures = [pool.submit(run_one, l) for l in lanes] for l, fut in zip(lanes, futures): print(f"\n=== {l['name']} " + "=" * (66 - len(l['name'])), flush=True) try: code, out = fut.result() except Exception as exc: # noqa: BLE001 code, out = 1, f" !! lane crashed: {exc}\n" sys.stdout.write(out) sys.stdout.flush() rc = rc or code return rc # Keys are resolved after the fan-out decision so the --each parent, which # never queries anything itself, does not hit `pass` once for every lane # its children are about to hit it for again. keys = fetch_keys(lanes) sems = build_semaphores(lanes, int(cfg.get("concurrency", 8))) # Concurrency bounds how many are in flight; rpm bounds how fast they start. pacers = build_pacers(lanes) lock, spent = threading.Lock(), [0.0] t0 = time.time() # The transcript path is claimed BEFORE the fan-out, not after it, so that a # run which dies mid-flight still leaves its finished lanes on disk. This # used to be `list(pool.map(...))` followed by a single write at the end: # every completed answer was held in memory until the last lane returned, so # a SIGKILL, a closed terminal, a harness timeout or a Ctrl-C anywhere in the # fan-out threw away every answer already collected -- including paid http # lanes that had billed for tokens nobody would ever read. The symptom is a # run that "randomly dies" with zero output and no transcript. path = None if not a.no_transcript: private_transcript_dir() stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S") # One lane per process (the --each contract), so the lane name makes the # path unique across a fan-out. The second-resolution timestamp alone was # NOT unique: `--each -j N` starts lanes within the same second, and every # child computed its own stamp independently — so they collided on one path # and overwrote each other's answers while exiting 0 (#70). pid covers two # runs of the SAME lane in the same second (a retry, or a bare single-lane # call), which is otherwise still possible. suffix = f"-{lanes[0]['name']}" if len(lanes) == 1 else "" if a.discuss: suffix = "-discuss" path = TRANSCRIPT_DIR / f"{stamp}{suffix}-{os.getpid()}.json" thread: list[dict] = [] def save(results_so_far, synthesis=None, collisions=None, partial=True, spend=None): """Write the transcript. Called after every lane, and again at the end. Atomic via write-then-replace: a kill during the write leaves the previous good transcript rather than a truncated one. """ if path is None: return # brief_on_record stays the ORIGINAL question in a revision round; in a # first round it is just `prompt`. A revision transcript also records the # round number, its parents, and the alias map, exactly as a completed # round does -- so a partial revision transcript reads like a full one. payload = {"run_id": run_id, "brief": brief_on_record, "results": results_so_far, "synthesis": synthesis, "collisions": collisions} if spend is not None: payload["spend"] = spend if prompts or a.discuss: payload.update({"round": round_no, "parent": [str(p) for p in prior_paths], "aliases": aliases}) if a.discuss: # The thread is the product; `results` (the closings) is what makes # this file a round another mode can build on. payload.update({"mode": "discuss", "discuss_rounds": a.discuss_rounds, "discussion": thread}) if partial: payload["partial"] = True payload["note"] = ("run did not finish — these are the lanes that had " "answered when the transcript was last written") # Staged to a unique temp, chmod 0600, then replaced: see save_transcript. save_transcript(payload, path) ordered = [None] * len(lanes) if a.discuss: retries = int(cfg.get("retries", 1)) def ask_one(l: dict, packet: str) -> dict: # deadline_seconds bounds ONE turn here, not the run: a discussion # is rounds * lanes dependent requests, and a whole-run clock sized # for a single fan-out would cut every discussion off mid-thread. turn_deadline = (time.time() + cfg["deadline_seconds"] if cfg.get("deadline_seconds") else None) return ask(l, packet, keys, retries, turn_deadline, sems, lock, spent, lane_prices(l, prices), pacers) def on_turn(t: dict, so_far: list[dict]) -> None: thread[:] = so_far save(ordered) if a.json: return print(f"\n--- pass {t['pass']} · turn {t['turn']}/{a.discuss_rounds * len(lanes)}" f" · {t['lane']} (PANELIST {t['alias']}) · {t['seconds']}s") print(t["answer"] if t["answer"] else f" !! {t['error']}", flush=True) def on_closing(closings: list) -> None: for i, c in enumerate(closings): ordered[i] = c save(ordered) if not a.json: print(f"DISCUSSION — {len(lanes)} lanes, {a.discuss_rounds} pass(es), one at a time", flush=True) run_discussion(lanes, brief_on_record, prior, aliases, a.discuss_rounds, focus, ask_one, on_turn, on_closing) results = ordered else: with cf.ThreadPoolExecutor(max_workers=max(len(lanes), 1)) as pool: # In a revision round each lane gets its own packet (prompts[name]); # otherwise every lane gets the same brief. futures = { pool.submit(ask, l, prompts[l["name"]] if prompts else prompt, keys, int(cfg.get("retries", 1)), deadline, sems, lock, spent, lane_prices(l, prices), pacers): i for i, l in enumerate(lanes) } for fut in cf.as_completed(futures): i = futures[fut] try: ordered[i] = fut.result() except Exception as e: # noqa: BLE001 — mirror ask()'s own contract ordered[i] = {"lane": lanes[i]["name"], "model": lanes[i].get("model"), "vendor": lanes[i].get("vendor"), "harness": lanes[i]["harness"], "answer": None, "error": str(e), "finish_reason": None} # Persist after every lane. Order is preserved by writing into the # slot the lane was dispatched from, so a partial transcript reads # the same way a complete one does, with `null` for lanes still out. save(ordered) results = ordered answered = [r for r in results if r["answer"]] # Fold this run's real prompt_tokens back in, so the next pre-flight # estimate is measured rather than assumed. # Calibration pairs one prompt length with each lane's measured # prompt_tokens; in a revision round every lane got a different packet, so # feeding any single length would poison the ratio for the next estimate. if not prompts and not a.discuss: record_calibration(results, prompt, lanes) # Convergence between lanes that turn out to be the same model is an echo, # not evidence. Never fatal -- a deliberate duplicate is a legitimate thing # to want -- but it must not be silent, because it is invisible in the # answers themselves. collisions = lineage_collisions(results, lanes) synth = None if a.diff: synth, synth_err = synthesize(results, brief_on_record, cfg, lanes, keys, prices, count=int(cfg.get("synthesizers", 2)), sems=sems, lock=lock, spent=spent, deadline=deadline, pacers=pacers, retries=int(cfg.get("retries", 1))) # Final write: same file the fan-out has been updating, now complete and with # the synthesis attached. Clears the `partial` marker. Revision metadata # (round/parent/aliases) is folded in by save() when this is a revision round. fill_costs(results, lanes, prices) # spent[0] includes the --diff readers, which are picked from these lanes. spend = spend_report(spent[0], estimate, budget, lanes, prices) save(results, synthesis=synth, collisions=collisions, partial=False, spend=spend) if a.json: if a.discuss: out = {"discussion": thread, "results": results, "spend": spend} if a.diff: out["synthesis"] = synth else: # The no-flag form stays a bare list: wrapping it would break every # caller indexing into it. Each result carries its own `cost`. out = {"results": results, "synthesis": synth, "spend": spend} if a.diff else results print(json.dumps(out, indent=2)) elif a.diff: print_synthesis(synth, synth_err) if spent[0] or estimate: print(f"spend: ${spent[0]:.4f} actual (est. worst case ${estimate:.4f})") else: if a.discuss: print(f"\n{'=' * 74}\nCLOSINGS — each lane's position after the discussion") for r in results: # served_by was captured on every http response and never shown. # Who actually answered is the evidence for the independence claim. via = f" via {r['served_by']}" if r.get("served_by") else "" print(f"\n{'=' * 74}\n{r['lane']} ({r['model'] or r['harness']})" f"{via} {r['seconds']}s") print("=" * 74) print(r["answer"] if r["answer"] else f" !! {r['error']}") if r.get("truncated"): print("\n !! TRUNCATED — salvaged at the lane timeout; the turn never finished" if r.get("finish_reason") == "timeout" else "\n !! TRUNCATED — hit max_tokens; raise it for this lane") if prompts or a.discuss: moves = [(r["lane"], parse_verdict(r["answer"]) or "?") for r in results if r["answer"]] held = sum(1 for _, v in moves if v == "HOLD") unparsed = sum(1 for _, v in moves if v == "?") print(f"\n{'=' * 74}") if a.discuss: spoke = sum(1 for t in thread if t.get("answer")) print(f"ROUND {round_no} — closings after a shared discussion" f" ({spoke}/{len(thread)} turns spoken, {a.discuss_rounds} pass(es))." f" Agreement here is persuasion, not independent convergence.") else: print(f"ROUND {round_no} — lanes saw the round-{round_no - 1} answers." f" Agreement here is persuasion, not independent convergence.") # A closing with no verdict word is not a move; say so rather than # folding it into the moved count. tail = f", {unparsed} gave no verdict" if unparsed else "" print(f" {held} HOLD, {len(moves) - held - unparsed} moved{tail}:") for lane, v in moves: print(f" {lane:<18} {v}") print(f"\n{'=' * 74}") print(f"{len(answered)}/{len(results)} lanes answered in {time.time() - t0:.1f}s") if spent[0] or estimate: print(f"spend: ${spent[0]:.4f} actual (est. worst case ${estimate:.4f})") if not a.no_transcript: print(f"transcript: {path}") for r in results: if not r["answer"]: print(f" FAILED {r['lane']}: {r['error']}") # Next to the summary rather than above the answers: a warning printed # before the reader has seen anything is a warning they scroll past. if collisions: print(f"\n LANES THAT ARE NOT INDEPENDENT", file=sys.stderr) for c in collisions: how = "declared lineage" if c["kind"] == "lineage" else "answered from" print(f" {', '.join(c['lanes'])} — {how} {c['detail']}", file=sys.stderr) print(" Agreement between these is an echo, not convergence.", file=sys.stderr) # Backstop only -- the pre-flight gate above is what actually protects the # budget. This catches an estimate that was too optimistic. if budget is not None and spent[0] > budget: print(f"\n!! spend ${spent[0]:.4f} exceeded budget ${budget:.2f}", file=sys.stderr) return 2 # A silent lane is the bug this tool exists to eliminate, so partial # delivery is a failure, not a pass. return 0 if len(answered) == len(results) else 1 if __name__ == "__main__": sys.exit(main())