544 lines
28 KiB
Python
Executable File
544 lines
28 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Dump what the sidecar would launch: spawn / resume / fork × every harness.
|
||
|
||
Calls the real route handlers (``routes_runs.spawn`` / ``resume``,
|
||
``fork.fork`` — so ``_claude_args`` (harness-claude's ``claude_launch`` since 2026-11-26), the inline pi branch,
|
||
``_opencode_launch`` / ``_agy_launch`` and ``launch._launch`` itself all run)
|
||
over a matrix of request bodies (claude, pi, opencode, agy; with / without
|
||
model, effort, thinking, account, scope, lean, extras, Code Mode, compact) and
|
||
prints, per request, the answer and every process it would start:
|
||
|
||
argv, cwd, the sorted environment KEYS, stdin
|
||
|
||
Nothing is launched: ``subprocess.Popen`` / ``subprocess.run`` are recorders,
|
||
the network is off, and the sidecar runs in a throw-away ``HOME`` holding
|
||
synthetic accounts (a work Claude login, two opencode accounts — one keyless —
|
||
and an agy account), so nothing of the real machine is read. Environment
|
||
VALUES are never printed: a key the sidecar set or changed carries a short
|
||
hash of its value (``KEY#1a2b3c4d``), enough to see a change.
|
||
|
||
scripts/ab/launch-dump.py # print the working tree's dump
|
||
scripts/ab/launch-dump.py --base HEAD # diff base ref vs working tree
|
||
|
||
Each tree runs under ``uv run --with-requirements <tree>/sidecar/requirements.txt``.
|
||
|
||
The harnesses: a tree from before the strict plugin-only cutover (it still has
|
||
``sidecar/harness_builtin.py``) runs its built-in bridges — its live plugin
|
||
dirs point nowhere; a newer tree runs the real ``harness-*`` / ``provider-*``
|
||
plugins of ``SIDECAR_SEED_PLUGINS_DIR`` (default
|
||
``~/projects/ai-agent-plugins/plugins``), through a live index naming them in
|
||
place. Both see the same environment keys. No *provider* plugin is live on
|
||
either side: provider-evox2's manifest is input data (the EVOX2's real
|
||
servers and models), which the opencode driver lays over ``models.json`` —
|
||
with it the two sides would differ by that input, not by their code.
|
||
|
||
Exit codes: 0 = identical (or plain dump), 1 = a difference, 2 = setup error.
|
||
"""
|
||
|
||
import argparse
|
||
import atexit
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import shutil
|
||
import sqlite3
|
||
import sys
|
||
import tempfile
|
||
import uuid
|
||
|
||
HERE = pathlib.Path(__file__).resolve().parent
|
||
sys.path.insert(0, str(HERE))
|
||
import _common as ab # noqa: E402
|
||
|
||
TOKEN = "ab-launch-dump-token"
|
||
NS = uuid.UUID("0b1f0c5e-2d0a-4a53-9a57-3a6f7a1d9c10")
|
||
# The one clock-dependent value in a launch: a lean run's system prompt names
|
||
# the current date (launch.lean_prompt) — frozen to this instant, UTC.
|
||
FROZEN_TIME = (2026, 1, 2, 3, 4, 5, 4, 2, 0)
|
||
|
||
|
||
def runner(tree: pathlib.Path) -> list[str]:
|
||
return ["uv", "run", "--quiet", "--no-project", "--with", "httpx",
|
||
"--with-requirements", str(tree / "sidecar" / "requirements.txt"), "python"]
|
||
|
||
|
||
def sid_for(name: str) -> str:
|
||
return str(uuid.uuid5(NS, name))
|
||
|
||
|
||
# ── the matrix ───────────────────────────────────────────────────────────────
|
||
|
||
def scenarios(home: pathlib.Path) -> list[tuple[str, str, dict]]:
|
||
"""(name, route, body) — ``sessionId`` is filled in from the name."""
|
||
proj = str(home / "projects" / "demo")
|
||
scope = {"writeDirs": [proj], "readDirs": [str(home / "shared")],
|
||
"denyRead": [str(home / "secrets")],
|
||
"systemPrompt": "You work for the guest Ada, in their project only.",
|
||
"remoteControl": False, "git": {"user": "ada", "email": "ada@example.org"}}
|
||
nobash = {**scope, "noBash": True}
|
||
lean = {"allow": ["git", "curl"], "tools": ["Bash", "Read", "Grep"]}
|
||
agents = {"clarifier": {"description": "asks the user", "prompt": "Ask one question."}}
|
||
S: list[tuple[str, str, dict]] = []
|
||
|
||
def add(name, route, **body):
|
||
S.append((name, route, body))
|
||
|
||
# claude
|
||
add("claude spawn plain", "spawn", prompt="Say hi")
|
||
add("claude spawn model", "spawn", prompt="Say hi", model="sonnet")
|
||
add("claude spawn pinned model + effort", "spawn", prompt="Say hi",
|
||
model="claude-opus-4-8", effort="xhigh")
|
||
add("claude spawn thinking off", "spawn", prompt="Say hi", thinking=False)
|
||
add("claude spawn account work", "spawn", prompt="Say hi", account="work", effort="low")
|
||
add("claude spawn cwd", "spawn", prompt="Say hi", cwd=proj)
|
||
add("claude spawn scope", "spawn", prompt="Say hi", cwd=proj, scope=scope)
|
||
add("claude spawn scope noBash", "spawn", prompt="Say hi", cwd=proj, scope=nobash)
|
||
add("claude spawn lean", "spawn", prompt="Run the job", lean=lean)
|
||
add("claude spawn lean default", "spawn", prompt="Run the job", lean={})
|
||
add("claude spawn lean + scope", "spawn", prompt="Run the job", cwd=proj,
|
||
lean=lean, scope=nobash, model="haiku")
|
||
add("claude spawn extras", "spawn", prompt="Say hi",
|
||
appendSystemPrompt="Answer in French.", agents=agents)
|
||
add("claude spawn chrome", "spawn", prompt="Open the page", chrome=True)
|
||
add("claude spawn code mode", "spawn", prompt="--dash first", codeMode=True, chrome=True)
|
||
add("claude spawn code mode + lean", "spawn", prompt="Run the job", codeMode=True, lean={})
|
||
add("claude spawn bad effort", "spawn", prompt="Say hi", effort="ludicrous")
|
||
add("claude spawn unknown account", "spawn", prompt="Say hi", account="nobody")
|
||
add("claude spawn empty prompt", "spawn", prompt=" ")
|
||
add("claude resume plain", "resume", prompt="And then?")
|
||
add("claude resume model + effort", "resume", prompt="And then?", model="opus",
|
||
effort="high", thinking=False)
|
||
add("claude resume account work", "resume", prompt="And then?", account="work")
|
||
add("claude resume scope", "resume", prompt="And then?", cwd=proj, scope=scope)
|
||
add("claude resume extras + chrome", "resume", prompt="And then?",
|
||
appendSystemPrompt="Answer in French.", agents=agents, chrome=True)
|
||
add("claude resume compact", "resume", prompt="And then?", model="opus",
|
||
compact={"model": "haiku", "instructions": "Keep the\n decisions."})
|
||
add("claude resume compact + scope", "resume", prompt="And then?", cwd=proj,
|
||
scope=scope, compact={"instructions": "Keep the decisions."})
|
||
add("claude resume code mode", "resume", prompt="And then?", codeMode=True,
|
||
compact={"instructions": "dropped in code mode"})
|
||
add("claude fork plain", "fork", prompt="Edited turn", cutLine=2, cutText="second question")
|
||
add("claude fork model", "fork", prompt="Edited turn", cutLine=2, model="sonnet")
|
||
add("claude fork account work", "fork", prompt="Edited turn", cutLine=2, account="work")
|
||
add("claude fork scope + extras", "fork", prompt="Edited turn", cutLine=2, scope=scope,
|
||
cwd=proj, appendSystemPrompt="Answer in French.", agents=agents)
|
||
add("claude fork canary mismatch", "fork", prompt="Edited turn", cutLine=2,
|
||
cutText="not what the record says")
|
||
add("claude fork out of range", "fork", prompt="Edited turn", cutLine=99)
|
||
|
||
# pi
|
||
add("pi spawn plain", "spawn", harness="pi", prompt="Say hi")
|
||
add("pi spawn model", "spawn", harness="pi", prompt="Say hi", model="qwen/qwen3-coder")
|
||
add("pi spawn thinking off + effort", "spawn", harness="pi", prompt="Say hi",
|
||
thinking=False, effort="high")
|
||
add("pi spawn account ignored", "spawn", harness="pi", prompt="Say hi", account="work")
|
||
add("pi spawn scope", "spawn", harness="pi", prompt="Say hi", cwd=proj, scope=scope)
|
||
add("pi spawn scope noBash", "spawn", harness="pi", prompt="Say hi", cwd=proj, scope=nobash)
|
||
add("pi spawn lean", "spawn", harness="pi", prompt="Run the job",
|
||
lean={"allow": ["git"], "tools": ["Bash", "Read", "WebSearch", "Glob"]})
|
||
add("pi spawn lean + scope", "spawn", harness="pi", prompt="Run the job", cwd=proj,
|
||
lean=lean, scope=nobash)
|
||
add("pi resume plain", "resume", harness="pi", prompt="And then?")
|
||
add("pi resume keeps the session's model", "resume", harness="pi", prompt="And then?",
|
||
_sid=sid_for("pi-own-model"))
|
||
add("pi resume model + thinking off", "resume", harness="pi", prompt="And then?",
|
||
model="ggml-org/qwen3.8-27b", thinking=False)
|
||
add("pi resume scope", "resume", harness="pi", prompt="And then?", cwd=proj, scope=scope)
|
||
add("pi fork plain", "fork", harness="pi", prompt="Edited turn", cutLine=7, cutUserOrd=2)
|
||
add("pi fork cut text + model", "fork", harness="pi", prompt="Edited turn", cutLine=7,
|
||
cutText="second question", model="inkling-2-mini")
|
||
add("pi fork keeps the source's model", "fork", harness="pi", prompt="Edited turn",
|
||
cutLine=3, _src=sid_for("pi-own-model"))
|
||
add("pi fork scope refused", "fork", harness="pi", prompt="Edited turn", cutLine=3,
|
||
scope=scope)
|
||
|
||
# opencode
|
||
add("opencode spawn plain", "spawn", harness="opencode", prompt="Say hi")
|
||
add("opencode spawn model + effort", "spawn", harness="opencode", prompt="Say hi",
|
||
model="gpt-5.5-fast", effort="xhigh")
|
||
add("opencode spawn effort default word", "spawn", harness="opencode", prompt="Say hi",
|
||
effort="default")
|
||
add("opencode spawn local model on the login account", "spawn", harness="opencode",
|
||
prompt="Say hi", model="evox2/qwen3.6-35b-a3b", effort="think")
|
||
add("opencode spawn keyless account", "spawn", harness="opencode", prompt="Say hi",
|
||
account="opencode-lab")
|
||
add("opencode spawn keyless + local model", "spawn", harness="opencode", prompt="Say hi",
|
||
account="opencode-lab", model="evox2-inkling/inkling-2-mini", effort="low")
|
||
add("opencode spawn keyless + GPT refused", "spawn", harness="opencode", prompt="Say hi",
|
||
account="opencode-lab", model="gpt-6-sol")
|
||
add("opencode spawn not logged in", "spawn", harness="opencode", prompt="Say hi",
|
||
account="chatgpt-out")
|
||
add("opencode spawn scope refused", "spawn", harness="opencode", prompt="Say hi",
|
||
scope=scope)
|
||
add("opencode spawn bad effort", "spawn", harness="opencode", prompt="Say hi",
|
||
effort="ludicrous")
|
||
add("opencode spawn thinking off + cwd", "spawn", harness="opencode", prompt=" Say hi ",
|
||
thinking=False, cwd=proj)
|
||
add("opencode resume plain", "resume", harness="opencode", prompt="And then?")
|
||
add("opencode resume keeps the session's model", "resume", harness="opencode",
|
||
prompt="And then?", _sid=sid_for("opencode-own-model"))
|
||
add("opencode resume own model, new effort", "resume", harness="opencode",
|
||
prompt="And then?", effort="low", _sid=sid_for("opencode-own-model"))
|
||
add("opencode resume new model drops own effort", "resume", harness="opencode",
|
||
prompt="And then?", model="gpt-6-luna", _sid=sid_for("opencode-own-model"))
|
||
add("opencode resume scope refused", "resume", harness="opencode", prompt="And then?",
|
||
scope=scope)
|
||
add("opencode fork plain", "fork", harness="opencode", prompt="Edited turn", cutLine=4,
|
||
cutUserOrd=1, _src=sid_for("opencode-own-model"))
|
||
add("opencode fork by key + model", "fork", harness="opencode", prompt="Edited turn",
|
||
cutLine=4, cutKey="user:msg_2", cutText="second question", model="gpt-6-sol",
|
||
effort="medium", _src=sid_for("opencode-own-model"))
|
||
add("opencode fork scope refused", "fork", harness="opencode", prompt="Edited turn",
|
||
cutLine=4, scope=scope)
|
||
|
||
# agy
|
||
add("agy spawn plain", "spawn", harness="agy", prompt="Say hi")
|
||
add("agy spawn model + effort", "spawn", harness="agy", prompt="Say hi",
|
||
model="gemini-4-hydrogen", effort="low")
|
||
add("agy spawn effort-suffixed model", "spawn", harness="agy", prompt="Say hi",
|
||
model="gemini-4-neon-xhigh")
|
||
add("agy spawn cwd with CLAUDE.md", "spawn", harness="agy", prompt="Say hi", cwd=proj)
|
||
add("agy spawn scope", "spawn", harness="agy", prompt="Say hi", cwd=proj, scope=scope)
|
||
add("agy spawn scope noBash", "spawn", harness="agy", prompt="Say hi", cwd=proj,
|
||
scope=nobash)
|
||
add("agy spawn bad effort", "spawn", harness="agy", prompt="Say hi", effort="none")
|
||
add("agy spawn unknown account", "spawn", harness="agy", prompt="Say hi", account="nobody")
|
||
add("agy resume never started", "resume", harness="agy", prompt="And then?")
|
||
add("agy resume plain", "resume", harness="agy", prompt="And then?",
|
||
_sid=sid_for("agy-started"))
|
||
add("agy resume keeps the conversation's model", "resume", harness="agy",
|
||
prompt="And then?", _sid=sid_for("agy-own-model"))
|
||
add("agy resume model + effort", "resume", harness="agy", prompt="And then?",
|
||
model="gemini-4-argon", effort="medium", _sid=sid_for("agy-own-model"))
|
||
add("agy resume scope", "resume", harness="agy", prompt="And then?", cwd=proj,
|
||
scope=scope, _sid=sid_for("agy-started"))
|
||
add("agy fork refused", "fork", harness="agy", prompt="Edited turn", cutLine=3)
|
||
|
||
add("unknown harness", "spawn", harness="codex", prompt="Say hi")
|
||
return S
|
||
|
||
|
||
# ── the sandbox ──────────────────────────────────────────────────────────────
|
||
|
||
def build_home(home: pathlib.Path) -> None:
|
||
"""The synthetic machine: dirs, logins, sessions. No real content."""
|
||
for d in ("homelab", "projects/demo", "shared", "secrets", "logs", ".claude/projects",
|
||
".claude-work/projects", "oc-chatgpt", "oc-lab", "oc-out", "agy-home",
|
||
".pi/agent/sessions", ".pi/agent"):
|
||
(home / d).mkdir(parents=True, exist_ok=True)
|
||
(home / "projects/demo/CLAUDE.md").write_text("# demo\n\nA synthetic project.\n")
|
||
(home / "projects/demo/.git").mkdir(exist_ok=True)
|
||
(home / ".claude/CLAUDE.md").write_text("# global\n\nSynthetic global instructions.\n")
|
||
(home / ".claude-work/.credentials.json").write_text("{}")
|
||
# pi's model registry: one local provider (what opencode's twins read)
|
||
(home / ".pi/agent/models.json").write_text(json.dumps({"providers": {"evox2": {
|
||
"name": "EVOX2", "baseUrl": "http://evox2.invalid:8090/v1", "apiKey": "synthetic",
|
||
"models": [{"id": "qwen3.6-35b-a3b", "name": "Qwen", "reasoning": True,
|
||
"contextWindow": 131072, "maxTokens": 16384}]}}}))
|
||
# a pi session that answered on a model of its own
|
||
(home / ".pi/agent/sessions" / f"2026-01-01T00-00-00_{sid_for('pi-own-model')}.jsonl"
|
||
).write_text(json.dumps({"type": "model_change", "modelId": "qwen/qwen3-coder"}) + "\n")
|
||
# claude source sessions to fork, per account
|
||
lines = [
|
||
{"type": "user", "sessionId": "SRC", "message": {"role": "user", "content": "first question"}},
|
||
{"type": "assistant", "sessionId": "SRC", "message": {"role": "assistant", "content": [
|
||
{"type": "text", "text": "first answer"}]}},
|
||
{"type": "user", "sessionId": "SRC", "message": {"role": "user", "content": "second question"}},
|
||
{"type": "assistant", "sessionId": "SRC", "message": {"role": "assistant", "content": [
|
||
{"type": "text", "text": "second answer"}]}},
|
||
]
|
||
for cfg in (".claude", ".claude-work"):
|
||
d = home / cfg / "projects" / "-synthetic-homelab"
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
(d / f"{sid_for('claude-src')}.jsonl").write_text(
|
||
"".join(json.dumps(o).replace("SRC", sid_for("claude-src")) + "\n" for o in lines))
|
||
# opencode: a logged-in account with one session that has a model of its own
|
||
for name, logged in (("oc-chatgpt", True), ("oc-lab", False), ("oc-out", False)):
|
||
db = sqlite3.connect(home / name / "opencode.db")
|
||
db.executescript(
|
||
"CREATE TABLE credential (id TEXT, label TEXT, value TEXT, active INTEGER,"
|
||
" time_updated INTEGER, integration_id TEXT);"
|
||
"CREATE TABLE session_v2 (id TEXT, parent_id TEXT, model TEXT);"
|
||
"CREATE TABLE session_message (id TEXT, session_id TEXT, type TEXT, seq INTEGER,"
|
||
" data TEXT);")
|
||
if logged:
|
||
db.execute("INSERT INTO credential VALUES ('cred_1','synthetic',?,1,1,'openai')",
|
||
(json.dumps({"type": "oauth"}),))
|
||
ses = f"ses_{sid_for('opencode-own-model')}"
|
||
db.execute("INSERT INTO session_v2 VALUES (?,NULL,?)", (ses, json.dumps(
|
||
{"providerID": "openai", "id": "gpt-5.5", "variant": "medium"})))
|
||
for i, text in enumerate(("first question", "second question", "third question")):
|
||
db.execute("INSERT INTO session_message VALUES (?,?,?,?,?)",
|
||
(f"msg_{i + 1}", ses, "user", i, json.dumps({"text": text})))
|
||
db.commit()
|
||
db.close()
|
||
|
||
|
||
PLUGINS = pathlib.Path(os.path.expanduser(
|
||
os.environ.get("SIDECAR_SEED_PLUGINS_DIR") or "~/projects/ai-agent-plugins/plugins"))
|
||
|
||
|
||
def live_dirs(home: pathlib.Path, tree: pathlib.Path) -> dict[str, str]:
|
||
"""The loaders' dirs: the plugins in place for a plugin-only tree, nothing
|
||
for a tree that still has its built-in bridges."""
|
||
out = {"SIDECAR_LIVE_HARNESSES_DIR": str(home / "live-harnesses"),
|
||
"SIDECAR_LIVE_PROVIDERS_DIR": str(home / "live-providers"),
|
||
"SIDECAR_SEED_PLUGINS_DIR": str(home / "no-seed")}
|
||
if (tree / "sidecar" / "harness_builtin.py").is_file():
|
||
return out
|
||
if not PLUGINS.is_dir():
|
||
raise SystemExit(f"launch-dump: no plugins at {PLUGINS} (SIDECAR_SEED_PLUGINS_DIR)")
|
||
(home / "live-providers").mkdir(parents=True, exist_ok=True)
|
||
(home / "live-providers" / "index.json").write_text('{"version": 1, "providers": {}}')
|
||
for kind, plural, key, id_key, code in (
|
||
("harness", "harnesses", "harness", "harnessId", "sidecar"),):
|
||
d = pathlib.Path(out[f"SIDECAR_LIVE_{plural.upper()}_DIR"])
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
items = {}
|
||
for pdir in sorted(PLUGINS.glob(f"{kind}-*")):
|
||
try:
|
||
man = json.loads((pdir / "plugin.json").read_text())
|
||
except (OSError, ValueError):
|
||
continue
|
||
obj = man.get(key) or {}
|
||
if not isinstance(obj.get(id_key), str):
|
||
continue
|
||
items[obj[id_key]] = {"pluginId": man.get("id") or pdir.name, "dir": str(pdir),
|
||
"entry": (obj.get(code) or {}).get("entry"),
|
||
"guestAllowed": bool(obj.get("guestAllowed"))}
|
||
(d / "index.json").write_text(json.dumps({"version": 1, plural: items}))
|
||
return out
|
||
|
||
|
||
def sandbox_env(home: pathlib.Path) -> dict[str, str]:
|
||
return {
|
||
"HOME": str(home), "PATH": "/usr/local/bin:/usr/bin:/bin", "LANG": "C.UTF-8",
|
||
"TZ": "UTC", "USER": "ab", "TERM": "xterm",
|
||
"SIDECAR_TOKEN": TOKEN, "SIDECAR_LOG_DIR": str(home / "logs"),
|
||
"SIDECAR_CWD": str(home / "homelab"),
|
||
"SIDECAR_LAUNCH_PROBE_S": "0", "SIDECAR_CODE_MODE_BANNER_S": "0",
|
||
"SIDECAR_ACCOUNTS": f"work={home}/.claude-work",
|
||
"SIDECAR_OPENCODE_ACCOUNTS": (f"chatgpt-work={home}/oc-chatgpt,"
|
||
f"opencode-lab={home}/oc-lab,chatgpt-out={home}/oc-out"),
|
||
"SIDECAR_OPENCODE_KEYLESS": "opencode-lab",
|
||
"SIDECAR_AGY_ACCOUNTS": f"google-personal={home}/agy-home",
|
||
"CLAUDE_BIN": "claude", "OPENCODE_BIN": "opencode", "AGY_BIN": "agy",
|
||
# things a run must NOT inherit, to see them stripped
|
||
"ANTHROPIC_API_KEY": "synthetic-api-key", "OPENAI_API_KEY": "synthetic-openai-key",
|
||
"SSH_AUTH_SOCK": "/synthetic/ssh.sock", "DBUS_SESSION_BUS_ADDRESS": "unix:synthetic",
|
||
"CLAUDE_CONFIG_DIR": "/synthetic/stray-config-dir",
|
||
}
|
||
|
||
|
||
# ── one tree's dump ──────────────────────────────────────────────────────────
|
||
|
||
def dump(tree: pathlib.Path) -> None:
|
||
import subprocess
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
|
||
home = pathlib.Path(tempfile.mkdtemp(prefix="ab-launch-")).resolve()
|
||
atexit.register(shutil.rmtree, home, ignore_errors=True)
|
||
build_home(home)
|
||
python = sys.executable
|
||
tree = tree.resolve()
|
||
os.environ.clear()
|
||
os.environ.update(sandbox_env(home))
|
||
os.environ.update(live_dirs(home, tree))
|
||
time.tzset()
|
||
base_env = dict(os.environ)
|
||
|
||
def norm(s: str) -> str:
|
||
return (s.replace(str(tree), "<TREE>").replace(str(home), "<HOME>")
|
||
.replace(python, "<PYTHON>").replace(sys.prefix, "<VENV>"))
|
||
|
||
calls: list[dict] = []
|
||
|
||
def env_keys(env) -> list[str]:
|
||
if env is None:
|
||
return ["<inherits the sidecar's environment>"]
|
||
out = []
|
||
for k in sorted(env):
|
||
v = str(env[k])
|
||
if base_env.get(k) == v:
|
||
out.append(k)
|
||
else: # set or changed by the sidecar: the key and a hash, never the value
|
||
out.append(f"{k}#{hashlib.sha256(norm(v).encode()).hexdigest()[:8]}")
|
||
return out
|
||
|
||
def read_stdin(stdin) -> str:
|
||
if stdin is None:
|
||
return "<inherited>"
|
||
if stdin == subprocess.DEVNULL:
|
||
return "<devnull>"
|
||
if stdin == subprocess.PIPE:
|
||
return "<pipe>"
|
||
try:
|
||
pos = stdin.tell()
|
||
data = stdin.read()
|
||
stdin.seek(pos)
|
||
return json.dumps(data.decode("utf-8", "replace"), ensure_ascii=False)
|
||
except Exception as e: # noqa: BLE001
|
||
return f"<unreadable: {type(e).__name__}>"
|
||
|
||
class FakePopen:
|
||
pid = 4242
|
||
returncode = None
|
||
stdin = stdout = stderr = None
|
||
|
||
def __init__(self, args, **kw):
|
||
self.args = args
|
||
calls.append({"kind": "Popen", "argv": [str(a) for a in args],
|
||
"cwd": kw.get("cwd"), "env": env_keys(kw.get("env")),
|
||
"stdin": read_stdin(kw.get("stdin")),
|
||
"newSession": bool(kw.get("start_new_session"))})
|
||
|
||
def poll(self):
|
||
return None
|
||
|
||
def wait(self, timeout=None):
|
||
return 0
|
||
|
||
def communicate(self, *a, **k):
|
||
return b"", b""
|
||
|
||
def kill(self):
|
||
pass
|
||
terminate = send_signal = kill
|
||
|
||
def fake_run(args, **kw):
|
||
argv = [str(a) for a in args]
|
||
out, rc = "", 1
|
||
if argv[1:2] == ["--version"]:
|
||
out, rc = "2.1.999 (Claude Code)\n", 0
|
||
elif "api" in argv and any("/fork" in a for a in argv):
|
||
out, rc = json.dumps({"data": {"id": "ses_ab_fork_minted"}}), 0
|
||
calls.append({"kind": "run", "argv": argv, "cwd": kw.get("cwd"),
|
||
"env": env_keys(kw.get("env")), "stdin": read_stdin(kw.get("stdin")),
|
||
"newSession": False})
|
||
text = bool(kw.get("text") or kw.get("universal_newlines"))
|
||
return subprocess.CompletedProcess(args, rc, out if text else out.encode(),
|
||
"" if text else b"")
|
||
|
||
real_strftime = time.strftime
|
||
|
||
def frozen_strftime(fmt, t=None):
|
||
return real_strftime(fmt, time.struct_time(FROZEN_TIME) if t is None else t)
|
||
|
||
def no_network(*a, **k):
|
||
raise urllib.error.URLError("launch-dump: the network is off")
|
||
|
||
subprocess.Popen = FakePopen
|
||
subprocess.run = fake_run
|
||
time.strftime = frozen_strftime
|
||
urllib.request.urlopen = no_network
|
||
|
||
sys.path.insert(0, str(tree / "sidecar"))
|
||
if (tree / "sidecar" / "agy_cli.py").is_file():
|
||
import agy_cli # noqa: E402
|
||
import agy_mirror # noqa: E402
|
||
else:
|
||
# the harness-agy plugin's modules, loaded as the sidecar loads them
|
||
import harness_loader # noqa: E402
|
||
harness_loader.LOADER._ensure()
|
||
assert set(harness_loader.ids()) >= {"claude", "pi", "opencode", "agy"}, \
|
||
harness_loader.public()
|
||
agy_cli = sys.modules["sidecar_ext.harness.harness_agy.cli"]
|
||
agy_mirror = sys.modules["sidecar_ext.harness.harness_agy.mirror"]
|
||
import config # noqa: E402
|
||
import fork as fork_mod # noqa: E402
|
||
if (tree / "sidecar" / "local_room.py").is_file():
|
||
import local_room # noqa: E402
|
||
else:
|
||
# provider-evox2's module since 2026-11-26, loaded as the sidecar loads it
|
||
import usage_loader # noqa: E402
|
||
usage_loader.LOADER._ensure()
|
||
local_room = sys.modules.get("sidecar_ext.provider.provider_evox2.local_room") \
|
||
or type("NoRoom", (), {})()
|
||
import routes_runs # noqa: E402
|
||
from fastapi import HTTPException # noqa: E402
|
||
assert pathlib.Path(routes_runs.__file__).resolve().is_relative_to(tree)
|
||
assert str(config.LOG_DIR).startswith(str(home)), config.LOG_DIR
|
||
|
||
# the only product functions replaced: two fire-and-forget side effects
|
||
local_room.make_room_async = lambda harness, model: calls.append(
|
||
{"kind": "make_room", "argv": [str(harness), str(model)]})
|
||
agy_mirror.kick = lambda *a, **k: calls.append({"kind": "agy_mirror.kick", "argv": []})
|
||
|
||
# agy: a signed-in account, one started conversation, one with its own model
|
||
tok = agy_cli.token_path("google-personal")
|
||
tok.parent.mkdir(parents=True, exist_ok=True)
|
||
tok.write_text("synthetic")
|
||
agy_cli.record(sid_for("agy-started"), agy="agy-conv-started", account="google-personal")
|
||
agy_cli.record(sid_for("agy-own-model"), agy="agy-conv-own", account="google-personal")
|
||
tp = agy_cli.transcript_path("google-personal", "agy-conv-own")
|
||
tp.parent.mkdir(parents=True, exist_ok=True)
|
||
tp.write_text(json.dumps({"type": "PLANNER_RESPONSE", "model": "gemini-4-hydrogen-low"}) + "\n")
|
||
|
||
handlers = {"spawn": (routes_runs.spawn, routes_runs.SpawnBody),
|
||
"resume": (routes_runs.resume, routes_runs.ResumeBody),
|
||
"fork": (fork_mod.fork, fork_mod.ForkBody)}
|
||
auth = f"Bearer {TOKEN}"
|
||
out = sys.stdout
|
||
todo = scenarios(home)
|
||
out.write(f"# {len(todo)} request(s); sidecar as the lab's host (SIDECAR_TOKEN set)\n")
|
||
out.write(f"# sidecar env keys: {' '.join(sorted(base_env))}\n")
|
||
for name, route, body in todo:
|
||
body = dict(body)
|
||
sid = body.pop("_sid", None) or sid_for(name)
|
||
src = body.pop("_src", None) or sid_for("claude-src")
|
||
body["sessionId"] = sid
|
||
if route == "fork":
|
||
body["srcSessionId"] = src
|
||
calls.clear()
|
||
fn, model = handlers[route]
|
||
out.write(f"\n=== {name}\nPOST /{route} "
|
||
f"{norm(json.dumps(body, sort_keys=True, ensure_ascii=False))}\n")
|
||
try:
|
||
res = fn(model(**body), authorization=auth)
|
||
out.write(f"-> 200 {norm(json.dumps(res, sort_keys=True, ensure_ascii=False))}\n")
|
||
except HTTPException as e:
|
||
out.write(f"-> HTTP {e.status_code} "
|
||
f"{norm(json.dumps(e.detail, sort_keys=True, ensure_ascii=False))}\n")
|
||
except Exception as e: # noqa: BLE001 — a crash is behaviour too
|
||
out.write(f"-> !{type(e).__name__}: {norm(str(e))}\n")
|
||
for c in calls:
|
||
if c["kind"] not in ("Popen", "run"):
|
||
out.write(f"{c['kind']}: {' '.join(c['argv'])}\n")
|
||
continue
|
||
out.write(f"{c['kind']}: cwd={norm(str(c['cwd']))} stdin={c['stdin']} "
|
||
f"newSession={c['newSession']}\n")
|
||
for i, a in enumerate(c["argv"]):
|
||
out.write(f" argv[{i}] {norm(json.dumps(a, ensure_ascii=False))}\n")
|
||
out.write(f" env: {' '.join(c['env'])}\n")
|
||
# the next request starts from a clean runner: no pid record left
|
||
for p in config.LOG_DIR.glob("*"):
|
||
if p.is_file():
|
||
p.unlink()
|
||
routes_runs.pids._procs.clear()
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
ap.add_argument("--base", metavar="REF", help="diff this git ref against the working tree")
|
||
ap.add_argument("--keep", action="store_true", help="keep the scratch dir")
|
||
ap.add_argument("--tree", type=pathlib.Path, help=argparse.SUPPRESS)
|
||
args = ap.parse_args()
|
||
if args.tree: # internal: one tree's dump (already under uv)
|
||
dump(args.tree)
|
||
return 0
|
||
me = pathlib.Path(__file__).resolve()
|
||
if args.base:
|
||
return ab.dump_ab(me, args.base, [], runner=runner, keep=args.keep)
|
||
with ab.workdir() as work:
|
||
ab.run_pool([([*runner(ab.REPO), str(me), "--tree", str(ab.REPO)],
|
||
ab.frozen_env(work), None)], 1)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|